gt
stringclasses
1 value
context
stringlengths
2.49k
119k
# python imports from copy import deepcopy import json # django imports from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template.loader import render_to_string from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ # lfs imports import lfs.core.utils import lfs.discounts.utils import lfs.order.utils import lfs.payment.settings import lfs.payment.utils import lfs.shipping.utils import lfs.voucher.utils from lfs.addresses.utils import AddressManagement from lfs.addresses.settings import CHECKOUT_NOT_REQUIRED_ADDRESS from lfs.cart import utils as cart_utils from lfs.core.models import Country from lfs.checkout.settings import CHECKOUT_TYPE_ANON, CHECKOUT_TYPE_AUTH, ONE_PAGE_CHECKOUT_FORM from lfs.customer import utils as customer_utils from lfs.customer.utils import create_unique_username from lfs.customer.forms import CreditCardForm, CustomerAuthenticationForm from lfs.customer.forms import BankAccountForm from lfs.customer.forms import RegisterForm from lfs.payment.models import PaymentMethod from lfs.voucher.models import Voucher from lfs.voucher.settings import MESSAGES def login(request, template_name="lfs/checkout/login.html"): """Displays a form to login or register/login the user within the check out process. The form's post request goes to lfs.customer.views.login where all the logic happens - see there for more. """ # If the user is already authenticate we don't want to show this view at all if request.user.is_authenticated(): return HttpResponseRedirect(reverse("lfs_checkout")) shop = lfs.core.utils.get_default_shop(request) # If only anonymous checkout allowed we don't want to show this view at all. if shop.checkout_type == CHECKOUT_TYPE_ANON: return HttpResponseRedirect(reverse("lfs_checkout")) # Using Djangos default AuthenticationForm login_form = CustomerAuthenticationForm() register_form = RegisterForm() if request.POST.get("action") == "login": login_form = CustomerAuthenticationForm(data=request.POST) login_form.fields["username"].label = _(u"E-Mail") if login_form.is_valid(): from django.contrib.auth import login login(request, login_form.get_user()) return lfs.core.utils.set_message_cookie(reverse("lfs_checkout"), msg=_(u"You have been logged in.")) elif request.POST.get("action") == "register": register_form = RegisterForm(data=request.POST) if register_form.is_valid(): email = register_form.data.get("email") password = register_form.data.get("password_1") # Create user user = User.objects.create_user( username=create_unique_username(email), email=email, password=password) # Notify lfs.core.signals.customer_added.send(sender=user) # Log in user from django.contrib.auth import authenticate user = authenticate(username=email, password=password) from django.contrib.auth import login login(request, user) return lfs.core.utils.set_message_cookie(reverse("lfs_checkout"), msg=_(u"You have been registered and logged in.")) return render_to_response(template_name, RequestContext(request, { "login_form": login_form, "register_form": register_form, "anonymous_checkout": shop.checkout_type != CHECKOUT_TYPE_AUTH, })) def checkout_dispatcher(request): """Dispatcher to display the correct checkout form """ shop = lfs.core.utils.get_default_shop(request) cart = cart_utils.get_cart(request) if cart is None or not cart.get_items(): return empty_page_checkout(request) if request.user.is_authenticated() or \ shop.checkout_type == CHECKOUT_TYPE_ANON: return HttpResponseRedirect(reverse("lfs_checkout")) else: return HttpResponseRedirect(reverse("lfs_checkout_login")) def cart_inline(request, template_name="lfs/checkout/checkout_cart_inline.html"): """Displays the cart items of the checkout page. Factored out to be reusable for the starting request (which renders the whole checkout page and subsequent ajax requests which refresh the cart items. """ cart = cart_utils.get_cart(request) # Shipping selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(request) shipping_costs = lfs.shipping.utils.get_shipping_costs(request, selected_shipping_method) # Payment selected_payment_method = lfs.payment.utils.get_selected_payment_method(request) payment_costs = lfs.payment.utils.get_payment_costs(request, selected_payment_method) # Cart costs cart_price = 0 cart_tax = 0 if cart is not None: cart_price = cart.get_price_gross(request) + shipping_costs["price_gross"] + payment_costs["price"] cart_tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"] discounts = lfs.discounts.utils.get_valid_discounts(request) for discount in discounts: cart_price = cart_price - discount["price_gross"] cart_tax = cart_tax - discount["tax"] # Voucher voucher_number = '' display_voucher = False voucher_value = 0 voucher_tax = 0 voucher_message = MESSAGES[6] if cart is not None: try: voucher_number = lfs.voucher.utils.get_current_voucher_number(request) voucher = Voucher.objects.get(number=voucher_number) except Voucher.DoesNotExist: pass else: lfs.voucher.utils.set_current_voucher_number(request, voucher_number) is_voucher_effective, voucher_message = voucher.is_effective(request, cart) if is_voucher_effective: display_voucher = True voucher_value = voucher.get_price_gross(request, cart) cart_price = cart_price - voucher_value voucher_tax = voucher.get_tax(request, cart) cart_tax = cart_tax - voucher_tax else: display_voucher = False voucher_value = 0 voucher_tax = 0 if cart_price < 0: cart_price = 0 if cart_tax < 0: cart_tax = 0 cart_items = [] if cart: for cart_item in cart.get_items(): product = cart_item.product quantity = product.get_clean_quantity(cart_item.amount) cart_items.append({ "obj": cart_item, "quantity": quantity, "product": product, "product_price_net": cart_item.get_price_net(request), "product_price_gross": cart_item.get_price_gross(request), "product_tax": cart_item.get_tax(request), }) return render_to_string(template_name, RequestContext(request, { "cart": cart, "cart_items": cart_items, "cart_price": cart_price, "cart_tax": cart_tax, "display_voucher": display_voucher, "discounts": discounts, "voucher_value": voucher_value, "voucher_tax": voucher_tax, "shipping_costs": shipping_costs, "payment_price": payment_costs["price"], "selected_shipping_method": selected_shipping_method, "selected_payment_method": selected_payment_method, "voucher_number": voucher_number, "voucher_message": voucher_message, })) def one_page_checkout(request, template_name="lfs/checkout/one_page_checkout.html"): """ One page checkout form. """ OnePageCheckoutForm = lfs.core.utils.import_symbol(ONE_PAGE_CHECKOUT_FORM) cart = lfs.cart.utils.get_cart(request) if cart is None: return HttpResponseRedirect(reverse('lfs_cart')) initial_address = {} shop = lfs.core.utils.get_default_shop(request) if request.user.is_anonymous(): if shop.checkout_type == CHECKOUT_TYPE_AUTH: return HttpResponseRedirect(reverse("lfs_checkout_login")) else: initial_address['email'] = request.user.email customer = lfs.customer.utils.get_or_create_customer(request) invoice_address = customer.selected_invoice_address shipping_address = customer.selected_shipping_address bank_account = customer.selected_bank_account credit_card = customer.selected_credit_card if request.method == "POST": checkout_form = OnePageCheckoutForm(data=request.POST) iam = AddressManagement(customer, invoice_address, "invoice", request.POST, initial=initial_address) sam = AddressManagement(customer, shipping_address, "shipping", request.POST, initial=initial_address) bank_account_form = BankAccountForm(instance=bank_account, data=request.POST) credit_card_form = CreditCardForm(instance=credit_card, data=request.POST) if shop.confirm_toc and ("confirm_toc" not in request.POST): toc = False if checkout_form.errors is None: checkout_form._errors = {} checkout_form.errors["confirm_toc"] = _(u"Please confirm our terms and conditions") else: toc = True if checkout_form.is_valid() and bank_account_form.is_valid() and iam.is_valid() and sam.is_valid() and toc: if CHECKOUT_NOT_REQUIRED_ADDRESS == 'shipping': iam.save() if request.POST.get("no_shipping", "") == "": # If the shipping address is given then save it. sam.save() else: # If the shipping address is not given, the invoice address is copied. if customer.selected_invoice_address: if customer.selected_shipping_address: # it might be possible that shipping and invoice addresses are same object if customer.selected_shipping_address.pk != customer.selected_invoice_address.pk: customer.selected_shipping_address.delete() shipping_address = deepcopy(customer.selected_invoice_address) shipping_address.id = None shipping_address.pk = None shipping_address.save() customer.selected_shipping_address = shipping_address else: sam.save() if request.POST.get("no_invoice", "") == "": iam.save() else: if customer.selected_shipping_address: if customer.selected_invoice_address: # it might be possible that shipping and invoice addresses are same object if customer.selected_invoice_address.pk != customer.selected_shipping_address.pk: customer.selected_invoice_address.delete() invoice_address = deepcopy(customer.selected_shipping_address) invoice_address.id = None invoice_address.pk = None invoice_address.save() customer.selected_invoice_address = invoice_address customer.sync_selected_to_default_addresses() # Save payment method customer.selected_payment_method_id = request.POST.get("payment_method") # Save bank account if customer.selected_payment_method_id and \ int(customer.selected_payment_method_id) == lfs.payment.settings.PM_BANK: customer.selected_bank_account = bank_account_form.save() # Save credit card if customer.selected_payment_method_id and \ int(customer.selected_payment_method_id) == lfs.payment.settings.PM_CREDIT_CARD: customer.selected_credit_card = credit_card_form.save() customer.save() # process the payment method result = lfs.payment.utils.process_payment(request) if result["accepted"]: return HttpResponseRedirect(result.get("next_url", reverse("lfs_thank_you"))) else: if "message" in result: checkout_form._errors[result.get("message_location")] = result.get("message") else: checkout_form = OnePageCheckoutForm() iam = AddressManagement(customer, invoice_address, "invoice", initial=initial_address) sam = AddressManagement(customer, shipping_address, "shipping", initial=initial_address) bank_account_form = BankAccountForm(instance=bank_account) credit_card_form = CreditCardForm(instance=credit_card) # Payment try: selected_payment_method_id = request.POST.get("payment_method") selected_payment_method = PaymentMethod.objects.get(pk=selected_payment_method_id) except PaymentMethod.DoesNotExist: selected_payment_method = lfs.payment.utils.get_selected_payment_method(request) valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request) display_bank_account = any([pm.type == lfs.payment.settings.PM_BANK for pm in valid_payment_methods]) display_credit_card = any([pm.type == lfs.payment.settings.PM_CREDIT_CARD for pm in valid_payment_methods]) return render_to_response(template_name, RequestContext(request, { "checkout_form": checkout_form, "bank_account_form": bank_account_form, "credit_card_form": credit_card_form, "invoice_address_inline": iam.render(request), "shipping_address_inline": sam.render(request), "shipping_inline": shipping_inline(request), "payment_inline": payment_inline(request, bank_account_form), "selected_payment_method": selected_payment_method, "display_bank_account": display_bank_account, "display_credit_card": display_credit_card, "voucher_number": lfs.voucher.utils.get_current_voucher_number(request), "cart_inline": cart_inline(request), "settings": settings, })) def empty_page_checkout(request, template_name="lfs/checkout/empty_page_checkout.html"): """ """ return render_to_response(template_name, RequestContext(request, { "shopping_url": reverse("lfs_shop_view"), })) def thank_you(request, template_name="lfs/checkout/thank_you_page.html"): """Displays a thank you page ot the customer """ order = request.session.get("order") pay_link = order.get_pay_link(request) if order else None return render_to_response(template_name, RequestContext(request, { "order": order, "pay_link": pay_link, })) def payment_inline(request, form, template_name="lfs/checkout/payment_inline.html"): """Displays the selectable payment methods of the checkout page. Factored out to be reusable for the starting request (which renders the whole checkout page and subsequent ajax requests which refresh the selectable payment methods. Passing the form to be able to display payment forms within the several payment methods, e.g. credit card form. """ selected_payment_method = lfs.payment.utils.get_selected_payment_method(request) valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request) return render_to_string(template_name, RequestContext(request, { "payment_methods": valid_payment_methods, "selected_payment_method": selected_payment_method, "form": form, })) def shipping_inline(request, template_name="lfs/checkout/shipping_inline.html"): """Displays the selectable shipping methods of the checkout page. Factored out to be reusable for the starting request (which renders the whole checkout page and subsequent ajax requests which refresh the selectable shipping methods. """ selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(request) shipping_methods = lfs.shipping.utils.get_valid_shipping_methods(request) return render_to_string(template_name, RequestContext(request, { "shipping_methods": shipping_methods, "selected_shipping_method": selected_shipping_method, })) def check_voucher(request): """ """ voucher_number = lfs.voucher.utils.get_current_voucher_number(request) lfs.voucher.utils.set_current_voucher_number(request, voucher_number) result = json.dumps({ "html": (("#cart-inline", cart_inline(request)),) }) return HttpResponse(result, content_type='application/json') def changed_checkout(request): """ """ OnePageCheckoutForm = lfs.core.utils.import_symbol(ONE_PAGE_CHECKOUT_FORM) form = OnePageCheckoutForm() customer = customer_utils.get_or_create_customer(request) _save_customer(request, customer) _save_country(request, customer) result = json.dumps({ "shipping": shipping_inline(request), "payment": payment_inline(request, form), "cart": cart_inline(request), }) return HttpResponse(result, content_type='application/json') def changed_invoice_country(request): """ Refreshes the invoice address form, after the invoice country has been changed. """ customer = lfs.customer.utils.get_or_create_customer(request) address = customer.selected_invoice_address country_iso = request.POST.get("invoice-country") if address and country_iso: address.country = Country.objects.get(code=country_iso.lower()) address.save() customer.sync_selected_to_default_invoice_address() am = AddressManagement(customer, address, "invoice") result = json.dumps({ "invoice_address": am.render(request, country_iso), }) return HttpResponse(result, content_type='application/json') def changed_shipping_country(request): """ Refreshes the shipping address form, after the shipping country has been changed. """ customer = lfs.customer.utils.get_or_create_customer(request) address = customer.selected_shipping_address country_iso = request.POST.get("shipping-country") if address: address.country = Country.objects.get(code=country_iso.lower()) address.save() customer.sync_selected_to_default_shipping_address() am = AddressManagement(customer, address, "shipping") result = json.dumps({ "shipping_address": am.render(request, country_iso), }) return HttpResponse(result, content_type='application/json') def _save_country(request, customer): """ """ # Update country for address that is marked as 'same as invoice' or 'same as shipping' if CHECKOUT_NOT_REQUIRED_ADDRESS == 'shipping': country_iso = request.POST.get("shipping-country", None) if request.POST.get("no_shipping") == "on": country_iso = request.POST.get("invoice-country", None) if country_iso is not None: country = Country.objects.get(code=country_iso.lower()) if customer.selected_shipping_address: customer.selected_shipping_address.country = country customer.selected_shipping_address.save() customer.selected_country = country customer.save() customer.sync_selected_to_default_shipping_address() lfs.shipping.utils.update_to_valid_shipping_method(request, customer) lfs.payment.utils.update_to_valid_payment_method(request, customer) customer.save() else: # update invoice address if 'same as shipping' address option is set and shipping address was changed if request.POST.get("no_invoice") == "on": country_iso = request.POST.get("shipping-country", None) if country_iso is not None: country = Country.objects.get(code=country_iso.lower()) if customer.selected_invoice_address: customer.selected_invoice_address.country = country customer.selected_invoice_address.save() customer.sync_selected_to_default_invoice_address() def _save_customer(request, customer): """ """ shipping_method = request.POST.get("shipping-method") customer.selected_shipping_method_id = shipping_method payment_method = request.POST.get("payment_method") customer.selected_payment_method_id = payment_method customer.save() lfs.shipping.utils.update_to_valid_shipping_method(request, customer) lfs.payment.utils.update_to_valid_payment_method(request, customer) customer.save()
#http://documen.tician.de/pyopencl/ import pyopencl as cl import numpy as np import struct import timing timings = timing.Timing() #ctx = cl.create_some_context() mf = cl.mem_flags class Bitonic: def __init__(self, max_elements, cta_size, dtype): plat = cl.get_platforms()[0] device = plat.get_devices()[0] self.ctx = cl.Context(devices=[device]) self.queue = cl.CommandQueue(self.ctx, device) self.loadProgram() self.uintsz = dtype.itemsize self.d_tempKeys = cl.Buffer(self.ctx, mf.READ_WRITE, size=self.uintsz * max_elements) self.d_tempValues = cl.Buffer(self.ctx, mf.READ_WRITE, size=self.uintsz * max_elements) def loadProgram(self): self.local_size_limit = 512 options = "-D LOCAL_SIZE_LIMIT=%d" % (self.local_size_limit,) print "build bitonic" f = open("bitonic.cl", 'r') fstr = "".join(f.readlines()) self.bitonic_prg = cl.Program(self.ctx, fstr).build(options=options) def factorRadix2(self, L): if(not L): log2L = 0 return log2L, 0 else: #for(log2L = 0; (L & 1) == 0; L >>= 1, log2L++); log2L = 0 while ((L & 1) == 0): L >>=1 log2L += 1 return log2L, L; @timings("Bitonic Sort") def sort(self, num, keys, values, batch=1, direction=1): print "bitonic sort" #num must be a power of 2 and <= max_num log2l, remainder = self.factorRadix2(num) if remainder != 1: return #self.keys = keys #self.values = values self.keys = cl.Buffer(self.ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=keys) self.values = cl.Buffer(self.ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=values) self.queue.finish() direction = (direction != 0) array_length = keys.size print "array_length", array_length if array_length < self.local_size_limit: self.local(array_length, direction) else: self.local1(batch, array_length, direction) size = 2 * self.local_size_limit while size <= array_length: stride = size / 2 while stride > 0: print "size, stride", size, stride if stride >= self.local_size_limit: self.merge_global(batch, array_length, stride, size, direction) else: self.merge_local(batch, array_length, size, stride, direction) break stride >>= 1 size <<= 1 self.queue.finish() #need to copy back cl.enqueue_copy_buffer(self.queue, self.d_tempKeys, self.keys).wait() cl.enqueue_copy_buffer(self.queue, self.d_tempValues, self.values).wait() self.queue.finish() #copy to cpu to view results cl.enqueue_read_buffer(self.queue, self.keys, keys) cl.enqueue_read_buffer(self.queue, self.values, values) self.queue.finish() #cl.enqueue_read_buffer(self.queue, self.d_tempKeys, keys).wait() #cl.enqueue_read_buffer(self.queue, self.d_tempValues, values).wait() return keys, values @timings("Bitonic: merge global") def merge_global(self, batch, array_length, stride, size, direction): local_size = None global_size = (batch * array_length / 2,) merge_global_args = ( self.d_tempKeys, self.d_tempValues, self.d_tempKeys, self.d_tempValues, np.int32(array_length), np.int32(size), np.int32(stride), np.int32(direction) ) self.bitonic_prg.bitonicMergeGlobal(self.queue, global_size, local_size, *(merge_global_args)).wait() #self.queue.finish() @timings("Bitonic: merge local") def merge_local(self, batch, array_length, size, stride, direction): local_size = (self.local_size_limit / 2,) global_size = (batch * array_length / 2,) merge_local_args = ( self.d_tempKeys, self.d_tempValues, self.d_tempKeys, self.d_tempValues, np.int32(array_length), np.int32(stride), np.int32(size), np.int32(direction) ) self.bitonic_prg.bitonicMergeLocal(self.queue, global_size, local_size, *(merge_local_args)).wait() self.queue.finish() @timings("Bitonic: local1 ") def local1(self, batch, array_length, direction): local_size = (self.local_size_limit / 2,) global_size = (batch * array_length / 2,) #print global_size, local_size local1_args = ( self.d_tempKeys, self.d_tempValues, self.keys, self.values ) #self.bitonic_prg.bitonicSortLocal1(self.queue, global_size, local_size, *(local1_args)).wait() self.bitonic_prg.bitonicSortLocal1(self.queue, global_size, local_size, self.d_tempKeys, self.d_tempValues, self.keys, self.values).wait() self.queue.finish() @timings("Bitonic: local ") def local(self, array_length, direction): local_size = (self.local_size_limit / 2,) global_size = (batch * array_length / 2,) local_args = ( self.d_tempKeys, self.d_tempValues, self.keys, self.values, np.int32(array_length), np.int32(direction) ) self.bitonic_prg.bitonicSortLocal(self.queue, global_size, local_size, *(local_args)).wait() self.queue.finish() if __name__ == "__main__": #These tests wont work as is since class was restructured to fit in with sph n = 1048576*2 #n = 32768*2 #n = 16384 #n = 8192 hashes = np.ndarray((n,), dtype=np.uint32) indices = np.ndarray((n,), dtype=np.uint32) print "hashes size", hashes.size import sys for i in xrange(0,n): hashes[i] = 1 * sys.maxint#n - i indices[i] = i fh = [597, 598, 598, 599, 599, 597, 598, 598, 599, 599, 613, 614, 614, 615, 615, 613, 614, 614, 615, 615] for i,f in enumerate(fh): hashes[i] = f npsorted = np.sort(hashes,0) print "hashes before:", hashes[0:25].T print "indices before: ", indices[0:25].T bitonic = Bitonic(n, 128, hashes.dtype) #num_to_sort = 32768 num_to_sort = n shashes, sindices = bitonic.sort(num_to_sort, hashes, indices) #read from buffer """ hashes = numpy.ndarray((num_to_sort,), dtype=numpy.int32) cl.enqueue_read_buffer(clsystem.queue, .sort_hashes, hashes) print "hashes" print hashes.T indices = numpy.ndarray((self.num,), dtype=numpy.int32) cl.enqueue_read_buffer(self.queue, self.sort_indices, indices) print "indices" print indices.T """ print "hashes after:", shashes[0:25].T #print "sorted hashes:", npsorted[0:20].T print "indices after: ", sindices[0:25].T print np.linalg.norm(shashes - npsorted) print timings
from abc import ABCMeta, abstractmethod import codecs import collections import struct import sys import numpy as np class Postings(object): __metaclass__ = ABCMeta def __init__(self, content): self.content = content @abstractmethod def getAll(self): """"Devuelve todas las postings""" pass @abstractmethod def getPosting(self, term): """"Devuelve la posting del termino""" pass @abstractmethod def addPosting(self, term, docId, value): """"Agrega posting""" pass @abstractmethod def addDocToPosting(self, term, docId, value): """"Agrega documento a la posting""" pass @abstractmethod def isPosting(self, term): """"Devuelve verdadero si existe la posting para el termino dado""" pass @abstractmethod def getValue(self, term, docId): """"Devuelve valor de la posting en el documento dado""" pass def isDocInPosting(self, term, docId): return self.isPosting(term) and docId in self.getPosting(term) class DictionaryPostings(Postings): def getAll(self): return self.content def getPosting(self, term): return self.content[term] def addPosting(self, termId, docId, value): if termId not in self.content: self.content[termId] = { docId: value } else: self.addDocToPosting(termId, docId, value) def addDocToPosting(self, term, docId, value): if term in self.content: self.content[term][docId] = value def isPosting(self, term): return term in self.content def getValue(self, term, docId): return self.getPosting(term)[docId] def sortByKey(self): ordered = collections.OrderedDict() for t, tValues in sorted(self.content.items()): tValuesOrdered = collections.OrderedDict() for d, dValues in sorted(tValues.items()): tValuesOrdered[d] = dValues ordered[t] = tValuesOrdered self.content = ordered def termToId(self, term, termId): try: allPostings = self.getAll() aux = allPostings[term] del allPostings[term] allPostings[termId] = aux return True except KeyError: return False def getStats(self): allPostings = self.getAll() stats = {} if allPostings: # Inicializo valores stats["min_len_posting"] = sys.maxint stats["max_len_posting"] = 0 stats["sum_len_posting"] = 0.0 for p in allPostings: lenP = len(allPostings[p]) if lenP > stats["max_len_posting"]: stats["max_len_posting"] = lenP if lenP < stats["min_len_posting"]: stats["min_len_posting"] = lenP stats["sum_len_posting"] += lenP stats["mean_len_posting"] = stats["sum_len_posting"] / len(allPostings) return stats class SequentialPostings(Postings): SEPARATOR_TERM = ":" SEPARATOR_DOC = ";" SEPARATOR_VALUE = "," def __init__(self, path): self.path = path @classmethod def create(self, postings, path=None, title=None): if path is None: path = "index_data/" if title is None: title = "seq_postings.txt" with open(path + title, "w") as f: allStr = [] for t in postings: postingStr = ["%d%s" % (t, self.SEPARATOR_TERM)] for d in postings[t]: value = postings[t][d] docStr = "%d" % d if isinstance(value, list): for item in value: docStr += "%s%d" % (self.SEPARATOR_VALUE, item) else: docStr += "%s%d" % (self.SEPARATOR_VALUE, value) docStr += "%s" % (self.SEPARATOR_DOC) postingStr.append(docStr) postingStr.append('\n') allStr.extend(postingStr) f.write(''.join(allStr)) return SequentialPostings(path+title) def getAll(self): """"Devuelve todas las postings""" postings = collections.OrderedDict() with codecs.open(self.path, mode='rt', encoding='utf-8') as f: for line in f: line = line.rstrip().split(self.SEPARATOR_TERM) postings[int(line[0])] = self.makePostingFromString(line[1]) return postings def getPosting(self, term): """"Devuelve la posting del termino""" with codecs.open(self.path, mode='rt', encoding='utf-8') as f: for line in f: splitted = line.split(self.SEPARATOR_TERM) if int(splitted[0]) == term: return self.makePostingFromString(splitted[1]) return False def addPosting(self, term, docId, value): """"Agrega posting""" pass def addDocToPosting(self, term, docId, value): """"Agrega documento a la posting""" pass def isPosting(self, term): with codecs.open(self.path, mode='rt', encoding='utf-8') as f: for line in f: splitted = line.split(self.SEPARATOR_TERM) if int(splitted[0]) == term: return True return False def getValue(self, term, docId): """"Devuelve valor de la posting en el documento dado""" posting = self.getPosting(term) if posting and docId in posting: return posting[docId] else: return False def makePostingFromString(self, strPosting): posting = collections.OrderedDict() for doc in strPosting.split(self.SEPARATOR_DOC): values = doc.split(self.SEPARATOR_VALUE) if len(values) == 2: posting[int(values[0])] = float(values[1]) elif len(values) > 2: posting[int(values[0])] = [int(i) for i in values[1:]] return posting def getDocsIdFromTerm(self, term): return self.getPosting(term).keys() class BinaryPostings(object): def __init__(self, path, termToPointer, dgaps=False): self.path = path self.termToPointer = termToPointer self.skipLists = {} self.dgaps = False @classmethod # CUIDADO: DGAPS AUN NO COMPLETO, NO IMPLEMENTAR def create(self, postings, path="index_data/", title="binary_postings.bin", dgaps=False): path = path + title termToPointer = {} pointer = 0 with open(path, "wb") as f: for pId in postings: termToPointer[pId] = { "pointer": pointer, "lenDocs": len(postings[pId]) } docIds = postings[pId].keys() freqs = postings[pId].values() if dgaps: docsToWrite = self.deltaEncode(self, docIds) else: docsToWrite = docIds f.write(struct.pack('<%sI' % len(docsToWrite), *docsToWrite)) f.write(struct.pack('<%sI' % len(freqs), *freqs)) pointer += len(docIds) * 4 * 2 return BinaryPostings(path, termToPointer, dgaps) def storeTermToPointer(self, path="index_data/", title="term_to_pointer.bin"): file_path = path + title with open(file_path, "wb") as f: dfs = [self.termToPointer[t]["lenDocs"] for t in range(0,len(self.termToPointer))] f.write(struct.pack('<%sI' % len(dfs), *dfs)) return file_path def readTermToPointerBinaryFile(self, terms, path="index_data/", title="term_to_pointer.bin"): file_path = path + title tp = {} with open(file_path, "rb") as f: for t in range(terms): tp[t] = {} bDf = f.read(4) bPointer = f.read(4) tp[t]["lenDocs"] = struct.unpack('<I', bDf)[0] tp[t]["pointer"] = struct.unpack('<I', bPointer)[0] return tp @staticmethod # NO IMPLEMENTAR def deltaEncode(self, docsId): out = [docsId[0]] for i in range(1, len(docsId)): out.append(docsId[i] - docsId[i-1]) return out def getAll(self): postings = collections.OrderedDict() for term in self.termToPointer: postings[term] = self.getPosting(term) return postings def getPosting(self, term): posting = collections.OrderedDict() with open(self.path, "rb") as f: # Me posiciono en el termino f.seek(self.termToPointer[term]["pointer"]) # Leo longitud de documents Id lenDocs = self.termToPointer[term]["lenDocs"] # Leo documents ids bDocs = f.read(lenDocs * 4) docIds = struct.unpack('<%iI' % lenDocs, bDocs) # Leo frecuencias bFreqs = f.read(lenDocs * 4) freqs = struct.unpack('<%iI' % lenDocs, bFreqs) # Armo posting for i in range(len(docIds)): posting[docIds[i]] = freqs[i] return posting def addPosting(self, term, docId, value): """"Agrega posting""" pass def addDocToPosting(self, term, docId, value): """"Agrega documento a la posting""" pass def isPosting(self, term): """"Devuelve verdadero si existe la posting para el termino dado""" pass def getValue(self, term, docId): """"Devuelve valor de la posting en el documento dado""" pass def getDocsIdFromTerm(self, term): out = {} with open(self.path, "rb") as f: # Me posiciono en el termino f.seek(self.termToPointer[term]["pointer"]) # Leo longitud de documents Id lenDocs = self.termToPointer[term]["lenDocs"] # Leo documents ids bDocs = f.read(lenDocs * 4) out = list(struct.unpack('<%iI' % lenDocs, bDocs)) return out def createSkipLists(self): skipLists = {} with open(self.path, "rb") as f: for term in self.termToPointer: # Leo longitud de documents Id lenDocs = self.termToPointer[term]["lenDocs"] if lenDocs < 2: totalSkipPointers = lenDocs else: totalSkipPointers = int(np.sqrt(lenDocs)) + 1 step = lenDocs / totalSkipPointers sl = collections.OrderedDict() pointer = self.termToPointer[term]["pointer"] for i in range(totalSkipPointers): pointer += (step - 1) * 4 f.seek(pointer) bDoc = f.read(4) docId = struct.unpack('<I', bDoc)[0] sl[docId] = pointer pointer += 4 skipLists[term] = sl return skipLists def setSkipLists(self, sl): self.skipLists = sl def intersect(self, t1, t2): out = set() p1 = self.termToPointer[t1]["pointer"] endP1 = p1 + (self.termToPointer[t1]["lenDocs"] * 4) p2 = self.termToPointer[t2]["pointer"] endP2 = p2 + (self.termToPointer[t2]["lenDocs"] * 4) with open(self.path, "rb") as f: while p1 < endP1: f.seek(p1) docT1 = struct.unpack("<I", f.read(4))[0] while p2 < endP2: f.seek(p2) docT2 = struct.unpack("<I", f.read(4))[0] if docT2 == docT1: out.add(docT1) p2 += 4 p1 += 4 return out def intersectWithSkip(self, t1, t2): out = set() p1 = self.termToPointer[t1]["pointer"] p1End = p1 + (self.termToPointer[t1]["lenDocs"] * 4) p2 = self.termToPointer[t2]["pointer"] p2End = p2 + (self.termToPointer[t2]["lenDocs"] * 4) with open(self.path, "rb") as f: while p1 < p1End and p2 < p2End: f.seek(p1) docT1 = struct.unpack("<I", f.read(4))[0] f.seek(p2) docT2 = struct.unpack("<I", f.read(4))[0] if docT1 == docT2: out.add(docT1) p1 += 4; p2 += 4 elif docT1 < docT2: p1HasChanged = False for skipDoc in self.skipLists[t1]: if skipDoc <= docT2: if skipDoc > docT1: p1 = self.skipLists[t1][skipDoc] p1HasChanged = True else: break if not p1HasChanged: p1 += 4 else: p2HasChanged = False for skipDoc in self.skipLists[t2]: if skipDoc <= docT1: if skipDoc > docT2: p2 = self.skipLists[t2][skipDoc] p2HasChanged = True else: break if not p2HasChanged: p2 += 4 return out
# Copyright (c) 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet from yaql.language import expressions from yaql.language import specs from yaql.language import utils from yaql.language import yaqltypes from murano.dsl import constants from murano.dsl import dsl from murano.dsl import dsl_types from murano.dsl import helpers from murano.dsl import reflection from murano.dsl import serializer @specs.parameter('object_', dsl.MuranoObjectParameter()) def id_(object_): return object_.id @specs.parameter('object_', dsl.MuranoObjectParameter()) @specs.parameter('type__', dsl.MuranoTypeParameter()) @specs.parameter('version_spec', yaqltypes.String(True)) def cast(context, object_, type__, version_spec=None): return helpers.cast( object_, type__.type.name, version_spec or helpers.get_type(context)) @specs.parameter('__type_name', dsl.MuranoTypeParameter()) @specs.parameter('__extra', utils.MappingType) @specs.parameter('__owner', dsl.MuranoObjectParameter( nullable=True, decorate=False)) @specs.parameter('__object_name', yaqltypes.String(True)) def new(__context, __type_name, __owner=None, __object_name=None, __extra=None, **parameters): data = { __type_name: parameters, 'name': __object_name } for key, value in (__extra or {}).items(): if key.startswith('_'): data[key] = value object_store = helpers.get_object_store() return object_store.load(data, __owner, context=__context, scope_type=helpers.get_names_scope(__context)) @specs.parameter('type_name', dsl.MuranoTypeParameter()) @specs.parameter('parameters', utils.MappingType) @specs.parameter('extra', utils.MappingType) @specs.parameter('owner', dsl.MuranoObjectParameter( nullable=True, decorate=False)) @specs.parameter('object_name', yaqltypes.String(True)) @specs.name('new') def new_from_dict(type_name, context, parameters, owner=None, object_name=None, extra=None): return new(context, type_name, owner, object_name, extra, **utils.filter_parameters_dict(parameters)) @specs.name('new') @specs.parameter('owner', dsl.MuranoObjectParameter( nullable=True, decorate=False)) @specs.parameter('model', utils.MappingType) def new_from_model(context, model, owner=None): object_store = helpers.get_object_store() return object_store.load(model, owner, context=context, scope_type=helpers.get_names_scope(context)) @specs.parameter('object_', dsl.MuranoObjectParameter(decorate=False)) @specs.parameter('func', yaqltypes.Lambda()) def super_(context, object_, func=None): cast_type = helpers.get_type(context) if func is None: return [object_.cast(type) for type in cast_type.parents] return map(func, super_(context, object_)) @specs.parameter('object_', dsl.MuranoObjectParameter(decorate=False)) @specs.parameter('func', yaqltypes.Lambda()) def psuper(context, object_, func=None): if func is None: return super_(context, object_) return helpers.parallel_select(super_(context, object_), func) @specs.extension_method def require(value): if value is None: raise ValueError('Required value is missing') return value @specs.parameter('obj', dsl.MuranoObjectParameter()) @specs.parameter('murano_class_ref', dsl.MuranoTypeParameter()) @specs.extension_method def find(obj, murano_class_ref): return obj.find_owner(murano_class_ref, optional=True) @specs.parameter('seconds', yaqltypes.Number()) def sleep_(seconds): eventlet.sleep(seconds) @specs.parameter('object_', dsl.MuranoObjectParameter(nullable=True)) def type_(object_): return None if object_ is None else object_.type.get_reference() @specs.name('type') @specs.parameter('object_', dsl.MuranoObjectParameter(nullable=True)) def type_legacy(object_): return None if object_ is None else object_.type.name @specs.name('type') @specs.parameter('cls', dsl.MuranoTypeParameter()) def type_from_name(cls): return cls @specs.parameter('object_', dsl.MuranoObjectParameter(nullable=True)) def typeinfo(object_): return None if object_ is None else object_.type @specs.parameter('cls', dsl.MuranoTypeParameter()) @specs.name('typeinfo') def typeinfo_for_class(cls): return cls.type @specs.parameter('object_', dsl.MuranoObjectParameter(nullable=True)) def name(object_): return None if object_ is None else object_.name @specs.parameter('object_', dsl.MuranoObjectParameter()) def metadata(object_): return object_.object.metadata @specs.parameter('obj', dsl.MuranoObjectParameter(decorate=False)) @specs.parameter('property_name', yaqltypes.Keyword()) @specs.name('#operator_.') def obj_attribution(context, obj, property_name): return obj.get_property(property_name, context) @specs.parameter('cls', dsl_types.MuranoTypeReference) @specs.parameter('property_name', yaqltypes.Keyword()) @specs.name('#operator_.') def obj_attribution_static(context, cls, property_name): return helpers.get_executor().get_static_property( cls.type, property_name, context) @specs.parameter('receiver', dsl.MuranoObjectParameter(decorate=False)) @specs.parameter('expr', yaqltypes.Lambda(method=True)) @specs.inject('operator', yaqltypes.Super(with_context=True)) @specs.name('#operator_.') def op_dot(context, receiver, expr, operator): executor = helpers.get_executor() type_context = executor.context_manager.create_type_context(receiver.type) obj_context = executor.context_manager.create_object_context(receiver) ctx2 = helpers.link_contexts( helpers.link_contexts(context, type_context), obj_context) return operator(ctx2, receiver, expr) @specs.parameter('receiver', dsl_types.MuranoTypeReference) @specs.parameter('expr', yaqltypes.Lambda(method=True)) @specs.inject('operator', yaqltypes.Super(with_context=True)) @specs.name('#operator_.') def op_dot_static(context, receiver, expr, operator): executor = helpers.get_executor() type_context = executor.context_manager.create_type_context( receiver.type) ctx2 = helpers.link_contexts(context, type_context) return operator(ctx2, receiver, expr) @specs.parameter('prefix', yaqltypes.Keyword()) @specs.parameter('name', yaqltypes.Keyword()) @specs.name('#operator_:') def ns_resolve(context, prefix, name): return helpers.get_class(prefix + ':' + name, context).get_reference() @specs.parameter('name', yaqltypes.Keyword()) @specs.name('#unary_operator_:') def ns_resolve_unary(context, name): return ns_resolve(context, '', name) @specs.parameter('obj', dsl.MuranoObjectParameter(nullable=True)) @specs.parameter('type_', dsl.MuranoTypeParameter()) @specs.name('#operator_is') def is_instance_of(obj, type_): if obj is None: return False return type_.type.is_compatible(obj) def is_object(value): return isinstance(value, (dsl_types.MuranoObject, dsl_types.MuranoTypeReference)) @specs.name('call') @specs.parameter('name', yaqltypes.String()) @specs.parameter('args', yaqltypes.Sequence()) @specs.parameter('kwargs', utils.MappingType) @specs.inject('op_dot', yaqltypes.Delegate('#operator_.', with_context=True)) @specs.inject('base', yaqltypes.Super(with_context=True)) def call_func(context, op_dot, base, name, args, kwargs, receiver=utils.NO_VALUE): if isinstance(receiver, (dsl_types.MuranoObject, dsl_types.MuranoTypeReference)): kwargs = utils.filter_parameters_dict(kwargs) args += tuple( expressions.MappingRuleExpression(expressions.KeywordConstant(key), value) for key, value in kwargs.items()) function = expressions.Function(name, *args) return op_dot(context, receiver, function) else: return base(context, name, args, kwargs, receiver) @specs.parameter('obj', dsl.MuranoObjectParameter(decorate=False)) @specs.parameter('serialization_type', yaqltypes.String()) @specs.parameter('ignore_upcasts', bool) def dump(obj, serialization_type=dsl_types.DumpTypes.Serializable, ignore_upcasts=True): if serialization_type not in dsl_types.DumpTypes.All: raise ValueError('Invalid Serialization Type') executor = helpers.get_executor() if ignore_upcasts: obj = obj.real_this return serializer.serialize(obj, executor, serialization_type) def register(context, runtime_version): context.register_function(cast) context.register_function(new) context.register_function(new_from_dict) context.register_function(new_from_model) context.register_function(id_) context.register_function(super_) context.register_function(psuper) context.register_function(require) context.register_function(find) context.register_function(sleep_) context.register_function(typeinfo) context.register_function(typeinfo_for_class) context.register_function(name) context.register_function(metadata) context.register_function(obj_attribution) context.register_function(obj_attribution_static) context.register_function(op_dot) context.register_function(op_dot_static) context.register_function(ns_resolve) context.register_function(ns_resolve_unary) reflection.register(context) context.register_function(is_instance_of) if runtime_version <= constants.RUNTIME_VERSION_1_3: context.register_function(type_legacy) else: context.register_function(type_) context.register_function(call_func) if runtime_version <= constants.RUNTIME_VERSION_1_1: context = context.create_child_context() for t in ('id', 'cast', 'super', 'psuper', 'type'): for spec in utils.to_extension_method(t, context): context.register_function(spec) context.register_function(type_from_name) context.register_function(is_object) context.register_function(dump) return context
# Copyright 2014 NEC Corporation. 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 heatclient import exc from oslo_service import loopingcall from magnum.common import exception from magnum.conductor.handlers import bay_conductor from magnum import objects from magnum.objects.fields import BayStatus as bay_status from magnum.tests import base from magnum.tests.unit.db import base as db_base from magnum.tests.unit.db import utils import mock from mock import patch from oslo_config import cfg class TestBayConductorWithK8s(base.TestCase): def setUp(self): super(TestBayConductorWithK8s, self).setUp() self.baymodel_dict = { 'image_id': 'image_id', 'flavor_id': 'flavor_id', 'master_flavor_id': 'master_flavor_id', 'keypair_id': 'keypair_id', 'dns_nameserver': 'dns_nameserver', 'external_network_id': 'external_network_id', 'fixed_network': '10.20.30.0/24', 'docker_volume_size': 20, 'cluster_distro': 'fedora-atomic', 'ssh_authorized_key': 'ssh_authorized_key', 'coe': 'kubernetes', 'token': None, 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy', } self.bay_dict = { 'baymodel_id': 'xx-xx-xx-xx', 'name': 'bay1', 'stack_id': 'xx-xx-xx-xx', 'api_address': '172.17.2.3', 'node_addresses': ['172.17.2.4'], 'node_count': 1, 'master_count': 1, 'discovery_url': 'https://discovery.etcd.io/test', 'master_addresses': ['172.17.2.18'], 'ca_cert_ref': 'http://barbican/v1/containers/xx-xx-xx-xx', 'magnum_cert_ref': 'http://barbican/v1/containers/xx-xx-xx-xx', } @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid) def _test_extract_template_definition( self, mock_objects_baymodel_get_by_uuid, missing_attr=None): if missing_attr in self.baymodel_dict: self.baymodel_dict[missing_attr] = None elif missing_attr in self.bay_dict: self.bay_dict[missing_attr] = None baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) mapping = { 'dns_nameserver': 'dns_nameserver', 'image_id': 'server_image', 'flavor_id': 'minion_flavor', 'docker_volume_size': 'docker_volume_size', 'fixed_network': 'fixed_network_cidr', 'master_flavor_id': 'master_flavor', 'apiserver_port': '', 'node_count': 'number_of_minions', 'master_count': 'number_of_masters', 'discovery_url': 'discovery_url', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy', } expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'minion_flavor': 'flavor_id', 'master_flavor': 'master_flavor_id', 'number_of_minions': '1', 'number_of_masters': '1', 'fixed_network_cidr': '10.20.30.0/24', 'docker_volume_size': 20, 'discovery_url': 'https://discovery.etcd.io/test', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy', } if missing_attr is not None: expected.pop(mapping[missing_attr], None) self.assertEqual(expected, definition) @patch('requests.get') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_coreos_with_disovery( self, mock_objects_baymodel_get_by_uuid, reqget): baymodel_dict = self.baymodel_dict baymodel_dict['cluster_distro'] = 'coreos' cfg.CONF.set_override('coreos_discovery_token_url', 'http://tokentest', group='bay') mock_req = mock.MagicMock(text='/h1/h2/h3') reqget.return_value = mock_req baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'minion_flavor': 'flavor_id', 'master_flavor': 'master_flavor_id', 'number_of_minions': '1', 'number_of_masters': '1', 'fixed_network_cidr': '10.20.30.0/24', 'docker_volume_size': 20, 'ssh_authorized_key': 'ssh_authorized_key', 'token': 'h3', 'discovery_url': 'https://discovery.etcd.io/test', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy', } self.assertEqual(expected, definition) @patch('uuid.uuid4') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_coreos_no_discoveryurl( self, mock_objects_baymodel_get_by_uuid, mock_uuid): baymodel_dict = self.baymodel_dict baymodel_dict['cluster_distro'] = 'coreos' cfg.CONF.set_override('coreos_discovery_token_url', None, group='bay') mock_uuid.return_value = mock.MagicMock( hex='ba3d1866282848ddbedc76112110c208') baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'minion_flavor': 'flavor_id', 'master_flavor': 'master_flavor_id', 'number_of_minions': '1', 'number_of_masters': '1', 'fixed_network_cidr': '10.20.30.0/24', 'docker_volume_size': 20, 'ssh_authorized_key': 'ssh_authorized_key', 'token': 'ba3d1866282848ddbedc76112110c208', 'discovery_url': 'https://discovery.etcd.io/test', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy', } self.assertEqual(expected, definition) @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_dns( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='dns_nameserver') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_server_image( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='image_id') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_minion_flavor( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='flavor_id') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_docker_volume_size( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='docker_volume_size') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_fixed_network( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='fixed_network') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_master_flavor( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='master_flavor_id') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_ssh_authorized_key( self, mock_objects_baymodel_get_by_uuid): baymodel_dict = self.baymodel_dict baymodel_dict['cluster_distro'] = 'coreos' baymodel_dict['ssh_authorized_key'] = None baymodel = objects.BayModel(self.context, **baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'master_flavor': 'master_flavor_id', 'minion_flavor': 'flavor_id', 'number_of_minions': '1', 'number_of_masters': '1', 'fixed_network_cidr': '10.20.30.0/24', 'docker_volume_size': 20, 'discovery_url': 'https://discovery.etcd.io/test', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.assertIn('token', definition) del definition['token'] self.assertEqual(expected, definition) @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_apiserver_port( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='apiserver_port') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_node_count( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='node_count') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_master_count( self, mock_objects_baymodel_get_by_uuid): self._test_extract_template_definition( mock_objects_baymodel_get_by_uuid, missing_attr='master_count') @patch('requests.get') @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_without_discovery_url( self, mock_objects_baymodel_get_by_uuid, reqget): baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay_dict = self.bay_dict bay_dict['discovery_url'] = None bay = objects.Bay(self.context, **bay_dict) cfg.CONF.set_override('etcd_discovery_service_endpoint_format', 'http://etcd/test?size=%(size)d', group='bay') mock_req = mock.MagicMock(text='https://address/token') reqget.return_value = mock_req (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'master_flavor': 'master_flavor_id', 'minion_flavor': 'flavor_id', 'number_of_minions': '1', 'number_of_masters': '1', 'fixed_network_cidr': '10.20.30.0/24', 'docker_volume_size': 20, 'discovery_url': 'https://address/token', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.assertEqual(expected, definition) reqget.assert_called_once_with('http://etcd/test?size=1') @patch('magnum.common.short_id.generate_id') @patch('heatclient.common.template_utils.get_template_contents') @patch('magnum.conductor.handlers.bay_conductor' '._extract_template_definition') def test_create_stack(self, mock_extract_template_definition, mock_get_template_contents, mock_generate_id): mock_generate_id.return_value = 'xx-xx-xx-xx' expected_stack_name = 'expected_stack_name-xx-xx-xx-xx' expected_template_contents = 'template_contents' exptected_files = [] dummy_bay_name = 'expected_stack_name' expected_timeout = 15 mock_tpl_files = mock.MagicMock() mock_tpl_files.items.return_value = exptected_files mock_get_template_contents.return_value = [ mock_tpl_files, expected_template_contents] mock_extract_template_definition.return_value = ('template/path', {}) mock_heat_client = mock.MagicMock() mock_osc = mock.MagicMock() mock_osc.heat.return_value = mock_heat_client mock_bay = mock.MagicMock() mock_bay.name = dummy_bay_name bay_conductor._create_stack(self.context, mock_osc, mock_bay, expected_timeout) expected_args = { 'stack_name': expected_stack_name, 'parameters': {}, 'template': expected_template_contents, 'files': dict(exptected_files), 'timeout_mins': expected_timeout } mock_heat_client.stacks.create.assert_called_once_with(**expected_args) @patch('magnum.common.short_id.generate_id') @patch('heatclient.common.template_utils.get_template_contents') @patch('magnum.conductor.handlers.bay_conductor' '._extract_template_definition') def test_create_stack_no_timeout_specified( self, mock_extract_template_definition, mock_get_template_contents, mock_generate_id): mock_generate_id.return_value = 'xx-xx-xx-xx' expected_stack_name = 'expected_stack_name-xx-xx-xx-xx' expected_template_contents = 'template_contents' exptected_files = [] dummy_bay_name = 'expected_stack_name' expected_timeout = cfg.CONF.bay_heat.bay_create_timeout mock_tpl_files = mock.MagicMock() mock_tpl_files.items.return_value = exptected_files mock_get_template_contents.return_value = [ mock_tpl_files, expected_template_contents] mock_extract_template_definition.return_value = ('template/path', {}) mock_heat_client = mock.MagicMock() mock_osc = mock.MagicMock() mock_osc.heat.return_value = mock_heat_client mock_bay = mock.MagicMock() mock_bay.name = dummy_bay_name bay_conductor._create_stack(self.context, mock_osc, mock_bay, None) expected_args = { 'stack_name': expected_stack_name, 'parameters': {}, 'template': expected_template_contents, 'files': dict(exptected_files), 'timeout_mins': expected_timeout } mock_heat_client.stacks.create.assert_called_once_with(**expected_args) @patch('magnum.common.short_id.generate_id') @patch('heatclient.common.template_utils.get_template_contents') @patch('magnum.conductor.handlers.bay_conductor' '._extract_template_definition') def test_create_stack_timeout_is_zero( self, mock_extract_template_definition, mock_get_template_contents, mock_generate_id): mock_generate_id.return_value = 'xx-xx-xx-xx' expected_stack_name = 'expected_stack_name-xx-xx-xx-xx' expected_template_contents = 'template_contents' exptected_files = [] dummy_bay_name = 'expected_stack_name' bay_timeout = 0 expected_timeout = None mock_tpl_files = mock.MagicMock() mock_tpl_files.items.return_value = exptected_files mock_get_template_contents.return_value = [ mock_tpl_files, expected_template_contents] mock_extract_template_definition.return_value = ('template/path', {}) mock_heat_client = mock.MagicMock() mock_osc = mock.MagicMock() mock_osc.heat.return_value = mock_heat_client mock_bay = mock.MagicMock() mock_bay.name = dummy_bay_name bay_conductor._create_stack(self.context, mock_osc, mock_bay, bay_timeout) expected_args = { 'stack_name': expected_stack_name, 'parameters': {}, 'template': expected_template_contents, 'files': dict(exptected_files), 'timeout_mins': expected_timeout } mock_heat_client.stacks.create.assert_called_once_with(**expected_args) @patch('heatclient.common.template_utils.get_template_contents') @patch('magnum.conductor.handlers.bay_conductor' '._extract_template_definition') def test_update_stack(self, mock_extract_template_definition, mock_get_template_contents): mock_stack_id = 'xx-xx-xx-xx' expected_template_contents = 'template_contents' exptected_files = [] mock_tpl_files = mock.MagicMock() mock_tpl_files.items.return_value = exptected_files mock_get_template_contents.return_value = [ mock_tpl_files, expected_template_contents] mock_extract_template_definition.return_value = ('template/path', {}) mock_heat_client = mock.MagicMock() mock_osc = mock.MagicMock() mock_osc.heat.return_value = mock_heat_client mock_bay = mock.MagicMock() mock_bay.stack_id = mock_stack_id bay_conductor._update_stack({}, mock_osc, mock_bay) expected_args = { 'parameters': {}, 'template': expected_template_contents, 'files': dict(exptected_files) } mock_heat_client.stacks.update.assert_called_once_with(mock_stack_id, **expected_args) @patch('magnum.conductor.utils.retrieve_baymodel') @patch('oslo_config.cfg') @patch('magnum.common.clients.OpenStackClients') def setup_poll_test(self, mock_openstack_client, cfg, mock_retrieve_baymodel): cfg.CONF.bay_heat.max_attempts = 10 bay = mock.MagicMock() mock_heat_stack = mock.MagicMock() mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client.heat.return_value = mock_heat_client baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_retrieve_baymodel.return_value = baymodel poller = bay_conductor.HeatPoller(mock_openstack_client, bay) return (mock_heat_stack, bay, poller) def test_poll_no_save(self): mock_heat_stack, bay, poller = self.setup_poll_test() bay.status = bay_status.CREATE_IN_PROGRESS mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.poll_and_check() self.assertEqual(bay.save.call_count, 0) self.assertEqual(poller.attempts, 1) def test_poll_save(self): mock_heat_stack, bay, poller = self.setup_poll_test() bay.status = bay_status.CREATE_IN_PROGRESS mock_heat_stack.stack_status = bay_status.CREATE_FAILED mock_heat_stack.stack_status_reason = 'Create failed' self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.save.call_count, 1) self.assertEqual(bay.status, bay_status.CREATE_FAILED) self.assertEqual(bay.status_reason, 'Create failed') self.assertEqual(poller.attempts, 1) def test_poll_done(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.DELETE_COMPLETE self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) mock_heat_stack.stack_status = bay_status.CREATE_FAILED self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(poller.attempts, 2) def test_poll_done_by_update(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.UPDATE_COMPLETE mock_heat_stack.parameters = {'number_of_minions': 2} self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.save.call_count, 1) self.assertEqual(bay.status, bay_status.UPDATE_COMPLETE) self.assertEqual(bay.node_count, 2) self.assertEqual(poller.attempts, 1) def test_poll_done_by_update_failed(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.UPDATE_FAILED mock_heat_stack.parameters = {'number_of_minions': 2} self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.save.call_count, 1) self.assertEqual(bay.status, bay_status.UPDATE_FAILED) self.assertEqual(bay.node_count, 2) self.assertEqual(poller.attempts, 1) def test_poll_destroy(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.DELETE_FAILED self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) # Destroy method is not called when stack delete failed self.assertEqual(bay.destroy.call_count, 0) mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS poller.poll_and_check() self.assertEqual(bay.destroy.call_count, 0) self.assertEqual(bay.status, bay_status.DELETE_IN_PROGRESS) mock_heat_stack.stack_status = bay_status.DELETE_COMPLETE self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) # The bay status should still be DELETE_IN_PROGRESS, because # the destroy() method may be failed. If success, this bay record # will delete directly, change status is meaningless. self.assertEqual(bay.status, bay_status.DELETE_IN_PROGRESS) self.assertEqual(bay.destroy.call_count, 1) def test_poll_delete_in_progress_timeout_set(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS mock_heat_stack.timeout_mins = 60 # timeout only affects stack creation so expecting this # to process normally poller.poll_and_check() def test_poll_delete_in_progress_max_attempts_reached(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS poller.attempts = cfg.CONF.bay_heat.max_attempts self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) def test_poll_create_in_prog_max_att_reached_no_timeout(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.attempts = cfg.CONF.bay_heat.max_attempts mock_heat_stack.timeout_mins = None self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) def test_poll_create_in_prog_max_att_reached_timeout_set(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.attempts = cfg.CONF.bay_heat.max_attempts mock_heat_stack.timeout_mins = 60 # since the timeout is set the max attempts gets ignored since # the timeout will eventually stop the poller either when # the stack gets created or the timeout gets reached poller.poll_and_check() def test_poll_create_in_prog_max_att_reached_timed_out(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_FAILED poller.attempts = cfg.CONF.bay_heat.max_attempts mock_heat_stack.timeout_mins = 60 self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) def test_poll_create_in_prog_max_att_not_reached_no_timeout(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS mock_heat_stack.timeout.mins = None poller.poll_and_check() def test_poll_create_in_prog_max_att_not_reached_timeout_set(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS mock_heat_stack.timeout_mins = 60 poller.poll_and_check() def test_poll_create_in_prog_max_att_not_reached_timed_out(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.stack_status = bay_status.CREATE_FAILED mock_heat_stack.timeout_mins = 60 self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) def test_poll_node_count(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_minions': 1} mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.poll_and_check() self.assertEqual(bay.node_count, 1) def test_poll_node_count_by_update(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_minions': 2} mock_heat_stack.stack_status = bay_status.UPDATE_COMPLETE self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.node_count, 2) class TestHandler(db_base.DbTestCase): def setUp(self): super(TestHandler, self).setUp() self.handler = bay_conductor.Handler() baymodel_dict = utils.get_test_baymodel() self.baymodel = objects.BayModel(self.context, **baymodel_dict) self.baymodel.create() bay_dict = utils.get_test_bay(node_count=1) self.bay = objects.Bay(self.context, **bay_dict) self.bay.create() @patch('magnum.conductor.scale_manager.ScaleManager') @patch('magnum.conductor.handlers.bay_conductor.Handler._poll_and_check') @patch('magnum.conductor.handlers.bay_conductor._update_stack') @patch('magnum.common.clients.OpenStackClients') def test_update_node_count_success( self, mock_openstack_client_class, mock_update_stack, mock_poll_and_check, mock_scale_manager): def side_effect(*args, **kwargs): self.bay.node_count = 2 self.bay.save() mock_poll_and_check.side_effect = side_effect mock_heat_stack = mock.MagicMock() mock_heat_stack.stack_status = bay_status.CREATE_COMPLETE mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client = mock_openstack_client_class.return_value mock_openstack_client.heat.return_value = mock_heat_client self.bay.node_count = 2 self.handler.bay_update(self.context, self.bay) mock_update_stack.assert_called_once_with( self.context, mock_openstack_client, self.bay, mock_scale_manager.return_value) bay = objects.Bay.get(self.context, self.bay.uuid) self.assertEqual(bay.node_count, 2) @patch('magnum.conductor.handlers.bay_conductor.Handler._poll_and_check') @patch('magnum.conductor.handlers.bay_conductor._update_stack') @patch('magnum.common.clients.OpenStackClients') def test_update_node_count_failure( self, mock_openstack_client_class, mock_update_stack, mock_poll_and_check): def side_effect(*args, **kwargs): self.bay.node_count = 2 self.bay.save() mock_poll_and_check.side_effect = side_effect mock_heat_stack = mock.MagicMock() mock_heat_stack.stack_status = bay_status.CREATE_FAILED mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client = mock_openstack_client_class.return_value mock_openstack_client.heat.return_value = mock_heat_client self.bay.node_count = 2 self.assertRaises(exception.NotSupported, self.handler.bay_update, self.context, self.bay) bay = objects.Bay.get(self.context, self.bay.uuid) self.assertEqual(bay.node_count, 1) @patch('magnum.common.clients.OpenStackClients') def test_update_bay_with_invalid_params( self, mock_openstack_client_class): mock_heat_stack = mock.MagicMock() mock_heat_stack.stack_status = bay_status.CREATE_COMPLETE mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client = mock_openstack_client_class.return_value mock_openstack_client.heat.return_value = mock_heat_client self.bay.node_count = 2 self.bay.api_address = '7.7.7.7' self.assertRaises(exception.InvalidParameterValue, self.handler.bay_update, self.context, self.bay) bay = objects.Bay.get(self.context, self.bay.uuid) self.assertEqual(bay.node_count, 1) @patch('magnum.conductor.handlers.common.cert_manager.' 'generate_certificates_to_bay') @patch('magnum.conductor.handlers.bay_conductor._create_stack') @patch('magnum.common.clients.OpenStackClients') def test_create(self, mock_openstack_client_class, mock_create_stack, mock_generate_certificates): mock_create_stack.side_effect = exc.HTTPBadRequest timeout = 15 self.assertRaises(exception.InvalidParameterValue, self.handler.bay_create, self.context, self.bay, timeout) mock_generate_certificates.assert_called_once_with(self.bay) @patch('magnum.common.clients.OpenStackClients') def test_bay_delete(self, mock_openstack_client_class): osc = mock.MagicMock() mock_openstack_client_class.return_value = osc osc.heat.side_effect = exc.HTTPNotFound self.handler.bay_delete(self.context, self.bay.uuid) # The bay has been destroyed self.assertRaises(exception.BayNotFound, objects.Bay.get, self.context, self.bay.uuid) class TestBayConductorWithSwarm(base.TestCase): def setUp(self): super(TestBayConductorWithSwarm, self).setUp() self.baymodel_dict = { 'image_id': 'image_id', 'flavor_id': 'flavor_id', 'keypair_id': 'keypair_id', 'dns_nameserver': 'dns_nameserver', 'external_network_id': 'external_network_id', 'fixed_network': '10.2.0.0/22', 'cluster_distro': 'fedora-atomic', 'coe': 'swarm', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.bay_dict = { 'id': 1, 'uuid': 'some_uuid', 'baymodel_id': 'xx-xx-xx-xx', 'name': 'bay1', 'stack_id': 'xx-xx-xx-xx', 'api_address': '172.17.2.3', 'node_addresses': ['172.17.2.4'], 'node_count': 1, 'discovery_url': 'token://39987da72f8386e0d0225ae8929e7cb4', } @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_all_values( self, mock_objects_baymodel_get_by_uuid): baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'server_flavor': 'flavor_id', 'number_of_nodes': '1', 'fixed_network_cidr': '10.2.0.0/22', 'discovery_url': 'token://39987da72f8386e0d0225ae8929e7cb4', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.assertEqual(expected, definition) @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_only_required( self, mock_objects_baymodel_get_by_uuid): cfg.CONF.set_override('public_swarm_discovery', False, group='bay') cfg.CONF.set_override('swarm_discovery_url_format', 'test_discovery', group='bay') not_required = ['image_id', 'flavor_id', 'dns_nameserver', 'fixed_network', 'http_proxy', 'https_proxy', 'no_proxy'] for key in not_required: self.baymodel_dict[key] = None self.bay_dict['discovery_url'] = None baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'number_of_nodes': '1', 'discovery_url': 'test_discovery' } self.assertEqual(expected, definition) @patch('magnum.conductor.utils.retrieve_baymodel') @patch('oslo_config.cfg') @patch('magnum.common.clients.OpenStackClients') def setup_poll_test(self, mock_openstack_client, cfg, mock_retrieve_baymodel): cfg.CONF.bay_heat.max_attempts = 10 bay = mock.MagicMock() mock_heat_stack = mock.MagicMock() mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client.heat.return_value = mock_heat_client baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_retrieve_baymodel.return_value = baymodel poller = bay_conductor.HeatPoller(mock_openstack_client, bay) return (mock_heat_stack, bay, poller) def test_poll_node_count(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_nodes': 1} mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.poll_and_check() self.assertEqual(bay.node_count, 1) def test_poll_node_count_by_update(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_nodes': 2} mock_heat_stack.stack_status = bay_status.UPDATE_COMPLETE self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.node_count, 2) class TestBayConductorWithMesos(base.TestCase): def setUp(self): super(TestBayConductorWithMesos, self).setUp() self.baymodel_dict = { 'image_id': 'image_id', 'flavor_id': 'flavor_id', 'master_flavor_id': 'master_flavor_id', 'keypair_id': 'keypair_id', 'dns_nameserver': 'dns_nameserver', 'external_network_id': 'external_network_id', 'fixed_network': '10.2.0.0/22', 'cluster_distro': 'ubuntu', 'coe': 'mesos', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.bay_dict = { 'id': 1, 'uuid': 'some_uuid', 'baymodel_id': 'xx-xx-xx-xx', 'name': 'bay1', 'stack_id': 'xx-xx-xx-xx', 'api_address': '172.17.2.3', 'node_addresses': ['172.17.2.4'], 'node_count': 1, } @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_all_values( self, mock_objects_baymodel_get_by_uuid): baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'dns_nameserver': 'dns_nameserver', 'server_image': 'image_id', 'master_flavor': 'master_flavor_id', 'slave_flavor': 'flavor_id', 'number_of_slaves': '1', 'fixed_network_cidr': '10.2.0.0/22', 'http_proxy': 'http_proxy', 'https_proxy': 'https_proxy', 'no_proxy': 'no_proxy' } self.assertEqual(expected, definition) @patch('magnum.objects.BayModel.get_by_uuid') def test_extract_template_definition_only_required( self, mock_objects_baymodel_get_by_uuid): not_required = ['image_id', 'master_flavor_id', 'flavor_id', 'dns_nameserver', 'fixed_network', 'http_proxy', 'https_proxy', 'no_proxy'] for key in not_required: self.baymodel_dict[key] = None baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_objects_baymodel_get_by_uuid.return_value = baymodel bay = objects.Bay(self.context, **self.bay_dict) (template_path, definition) = bay_conductor._extract_template_definition(self.context, bay) expected = { 'ssh_key_name': 'keypair_id', 'external_network': 'external_network_id', 'number_of_slaves': '1', } self.assertEqual(expected, definition) @patch('magnum.conductor.utils.retrieve_baymodel') @patch('oslo_config.cfg') @patch('magnum.common.clients.OpenStackClients') def setup_poll_test(self, mock_openstack_client, cfg, mock_retrieve_baymodel): cfg.CONF.bay_heat.max_attempts = 10 bay = mock.MagicMock() mock_heat_stack = mock.MagicMock() mock_heat_client = mock.MagicMock() mock_heat_client.stacks.get.return_value = mock_heat_stack mock_openstack_client.heat.return_value = mock_heat_client baymodel = objects.BayModel(self.context, **self.baymodel_dict) mock_retrieve_baymodel.return_value = baymodel poller = bay_conductor.HeatPoller(mock_openstack_client, bay) return (mock_heat_stack, bay, poller) def test_poll_node_count(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_slaves': 1} mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS poller.poll_and_check() self.assertEqual(bay.node_count, 1) def test_poll_node_count_by_update(self): mock_heat_stack, bay, poller = self.setup_poll_test() mock_heat_stack.parameters = {'number_of_slaves': 2} mock_heat_stack.stack_status = bay_status.UPDATE_COMPLETE self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check) self.assertEqual(bay.node_count, 2)
# vim: sw=4:expandtab:foldmethod=marker # # Copyright (c) 2007-2009, Mathieu Fenniak # 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. # * The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. __author__ = "Mathieu Fenniak" import datetime import decimal import struct from errors import (NotSupportedError, ArrayDataParseError, InternalError, ArrayContentEmptyError, ArrayContentNotHomogenousError, ArrayContentNotSupportedError, ArrayDimensionsNotConsistentError) try: from pytz import utc except ImportError: ZERO = datetime.timedelta(0) class UTC(datetime.tzinfo): def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO utc = UTC() class Bytea(str): pass class Interval(object): def __init__(self, microseconds=0, days=0, months=0): self.microseconds = microseconds self.days = days self.months = months def _setMicroseconds(self, value): if not isinstance(value, int) and not isinstance(value, long): raise TypeError("microseconds must be an int or long") elif not (min_int8 < value < max_int8): raise OverflowError("microseconds must be representable as a 64-bit integer") else: self._microseconds = value def _setDays(self, value): if not isinstance(value, int) and not isinstance(value, long): raise TypeError("days must be an int or long") elif not (min_int4 < value < max_int4): raise OverflowError("days must be representable as a 32-bit integer") else: self._days = value def _setMonths(self, value): if not isinstance(value, int) and not isinstance(value, long): raise TypeError("months must be an int or long") elif not (min_int4 < value < max_int4): raise OverflowError("months must be representable as a 32-bit integer") else: self._months = value microseconds = property(lambda self: self._microseconds, _setMicroseconds) days = property(lambda self: self._days, _setDays) months = property(lambda self: self._months, _setMonths) def __repr__(self): return "<Interval %s months %s days %s microseconds>" % (self.months, self.days, self.microseconds) def __cmp__(self, other): if other == None: return -1 c = cmp(self.months, other.months) if c != 0: return c c = cmp(self.days, other.days) if c != 0: return c return cmp(self.microseconds, other.microseconds) def pg_type_info(typ): value = None if isinstance(typ, dict): value = typ["value"] typ = typ["type"] data = py_types.get(typ) if data == None: raise NotSupportedError("type %r not mapped to pg type" % typ) # permit the type data to be determined by the value, if provided inspect_func = data.get("inspect") if value != None and inspect_func != None: data = inspect_func(value) type_oid = data.get("typeoid") if type_oid == None: raise InternalError("type %r has no type_oid" % typ) elif type_oid == -1: # special case: NULL values return type_oid, 0 # prefer bin, but go with whatever exists if data.get("bin_out"): format = 1 elif data.get("txt_out"): format = 0 else: raise InternalError("no conversion fuction for type %r" % typ) return type_oid, format def pg_value(value, fc, **kwargs): typ = type(value) data = py_types.get(typ) if data == None: raise NotSupportedError("type %r not mapped to pg type" % typ) # permit the type conversion to be determined by the value, if provided inspect_func = data.get("inspect") if value != None and inspect_func != None: data = inspect_func(value) # special case: NULL values if data.get("typeoid") == -1: return None if fc == 0: func = data.get("txt_out") elif fc == 1: func = data.get("bin_out") else: raise InternalError("unrecognized format code %r" % fc) if func == None: raise NotSupportedError("type %r, format code %r not supported" % (typ, fc)) return func(value, **kwargs) def py_type_info(description): type_oid = description['type_oid'] data = pg_types.get(type_oid) if data == None: raise NotSupportedError("type oid %r not mapped to py type" % type_oid) # prefer bin, but go with whatever exists if data.get("bin_in"): format = 1 elif data.get("txt_in"): format = 0 else: raise InternalError("no conversion fuction for type oid %r" % type_oid) return format def py_value(v, description, **kwargs): if v == None: # special case - NULL value return None type_oid = description['type_oid'] format = description['format'] data = pg_types.get(type_oid) if data == None: raise NotSupportedError("type oid %r not supported" % type_oid) if format == 0: func = data.get("txt_in") elif format == 1: func = data.get("bin_in") else: raise NotSupportedError("format code %r not supported" % format) if func == None: raise NotSupportedError("data response format %r, type %r not supported" % (format, type_oid)) return func(v, **kwargs) def boolrecv(data, **kwargs): return data == "\x01" def boolsend(v, **kwargs): if v: return "\x01" else: return "\x00" min_int2, max_int2 = -2 ** 15, 2 ** 15 min_int4, max_int4 = -2 ** 31, 2 ** 31 min_int8, max_int8 = -2 ** 63, 2 ** 63 def int_inspect(value): if min_int2 < value < max_int2: return {"typeoid": 21, "bin_out": int2send} elif min_int4 < value < max_int4: return {"typeoid": 23, "bin_out": int4send} elif min_int8 < value < max_int8: return {"typeoid": 20, "bin_out": int8send} else: return {"typeoid": 1700, "bin_out": numeric_send} def int2recv(data, **kwargs): return struct.unpack("!h", data)[0] def int2send(v, **kwargs): return struct.pack("!h", v) def int4recv(data, **kwargs): return struct.unpack("!i", data)[0] def int4send(v, **kwargs): return struct.pack("!i", v) def int8recv(data, **kwargs): return struct.unpack("!q", data)[0] def int8send(v, **kwargs): return struct.pack("!q", v) def float4recv(data, **kwargs): return struct.unpack("!f", data)[0] def float8recv(data, **kwargs): return struct.unpack("!d", data)[0] def float8send(v, **kwargs): return struct.pack("!d", v) def datetime_inspect(value): if value.tzinfo != None: # send as timestamptz if timezone is provided return {"typeoid": 1184, "bin_out": timestamptz_send} else: # otherwise send as timestamp return {"typeoid": 1114, "bin_out": timestamp_send} def timestamp_recv(data, integer_datetimes, **kwargs): if integer_datetimes: # data is 64-bit integer representing milliseconds since 2000-01-01 val = struct.unpack("!q", data)[0] return datetime.datetime(2000, 1, 1) + datetime.timedelta(microseconds=val) else: # data is double-precision float representing seconds since 2000-01-01 val = struct.unpack("!d", data)[0] return datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds=val) # return a timezone-aware datetime instance if we're reading from a # "timestamp with timezone" type. The timezone returned will always be UTC, # but providing that additional information can permit conversion to local. def timestamptz_recv(data, **kwargs): return timestamp_recv(data, **kwargs).replace(tzinfo=utc) def timestamp_send(v, integer_datetimes, **kwargs): delta = v - datetime.datetime(2000, 1, 1) val = delta.microseconds + (delta.seconds * 1000000) + (delta.days * 86400000000) if integer_datetimes: # data is 64-bit integer representing milliseconds since 2000-01-01 return struct.pack("!q", val) else: # data is double-precision float representing seconds since 2000-01-01 return struct.pack("!d", val / 1000.0 / 1000.0) def timestamptz_send(v, **kwargs): # timestamps should be sent as UTC. If they have zone info, # convert them. return timestamp_send(v.astimezone(utc).replace(tzinfo=None), **kwargs) def date_in(data, **kwargs): year = int(data[0:4]) month = int(data[5:7]) day = int(data[8:10]) return datetime.date(year, month, day) def date_out(v, **kwargs): return v.isoformat() def time_in(data, **kwargs): hour = int(data[0:2]) minute = int(data[3:5]) sec = decimal.Decimal(data[6:]) return datetime.time(hour, minute, int(sec), int((sec - int(sec)) * 1000000)) def time_out(v, **kwargs): return v.isoformat() def numeric_in(data, **kwargs): if data.find(".") == -1: return int(data) else: return decimal.Decimal(data) def numeric_recv(data, **kwargs): num_digits, weight, sign, scale = struct.unpack("!hhhh", data[:8]) data = data[8:] digits = struct.unpack("!" + ("h" * num_digits), data) weight = decimal.Decimal(weight) retval = 0 for d in digits: d = decimal.Decimal(d) retval += d * (10000 ** weight) weight -= 1 if sign: retval *= -1 return retval DEC_DIGITS = 4 def numeric_send(d, **kwargs): # This is a very straight port of src/backend/utils/adt/numeric.c set_var_from_str() s = str(d) pos = 0 sign = 0 if s[0] == '-': sign = 0x4000 # NEG pos = 1 elif s[0] == '+': sign = 0 # POS pos = 1 have_dp = False decdigits = [0, 0, 0, 0] dweight = -1 dscale = 0 for char in s[pos:]: if char.isdigit(): decdigits.append(int(char)) if not have_dp: dweight += 1 else: dscale += 1 pos += 1 elif char == '.': have_dp = True pos += 1 else: break if len(s) > pos: char = s[pos] if char == 'e' or char == 'E': pos += 1 exponent = int(s[pos:]) dweight += exponent dscale -= exponent if dscale < 0: dscale = 0 if dweight >= 0: weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1 else: weight = -((-dweight - 1) / DEC_DIGITS + 1) offset = (weight + 1) * DEC_DIGITS - (dweight + 1) ndigits = (len(decdigits) - DEC_DIGITS + offset + DEC_DIGITS - 1) / DEC_DIGITS i = DEC_DIGITS - offset decdigits.extend([0, 0, 0]) ndigits_ = ndigits digits = '' while ndigits_ > 0: # ifdef DEC_DIGITS == 4 digits += struct.pack("!h", ((decdigits[i] * 10 + decdigits[i + 1]) * 10 + decdigits[i + 2]) * 10 + decdigits[i + 3]) ndigits_ -= 1 i += DEC_DIGITS # strip_var() if ndigits == 0: sign = 0x4000 # pos weight = 0 # ---------- retval = struct.pack("!hhhh", ndigits, weight, sign, dscale) + digits return retval def numeric_out(v, **kwargs): return str(v) # PostgreSQL encodings: # http://www.postgresql.org/docs/8.3/interactive/multibyte.html # Python encodings: # http://www.python.org/doc/2.4/lib/standard-encodings.html # # Commented out encodings don't require a name change between PostgreSQL and # Python. If the py side is None, then the encoding isn't supported. pg_to_py_encodings = { # Not supported: "mule_internal": None, "euc_tw": None, # Name fine as-is: # "euc_jp", # "euc_jis_2004", # "euc_kr", # "gb18030", # "gbk", # "johab", # "sjis", # "shift_jis_2004", # "uhc", # "utf8", # Different name: "euc_cn": "gb2312", "iso_8859_5": "is8859_5", "iso_8859_6": "is8859_6", "iso_8859_7": "is8859_7", "iso_8859_8": "is8859_8", "koi8": "koi8_r", "latin1": "iso8859-1", "latin2": "iso8859_2", "latin3": "iso8859_3", "latin4": "iso8859_4", "latin5": "iso8859_9", "latin6": "iso8859_10", "latin7": "iso8859_13", "latin8": "iso8859_14", "latin9": "iso8859_15", "sql_ascii": "ascii", "win866": "cp886", "win874": "cp874", "win1250": "cp1250", "win1251": "cp1251", "win1252": "cp1252", "win1253": "cp1253", "win1254": "cp1254", "win1255": "cp1255", "win1256": "cp1256", "win1257": "cp1257", "win1258": "cp1258", } def encoding_convert(encoding): return pg_to_py_encodings.get(encoding.lower(), encoding) def varcharin(data, client_encoding, **kwargs): return unicode(data, encoding_convert(client_encoding)) def textout(v, client_encoding, **kwargs): if isinstance(v, unicode): return v.encode(encoding_convert(client_encoding)) else: return v def byteasend(v, **kwargs): return str(v) def bytearecv(data, **kwargs): return Bytea(data) # interval support does not provide a Python-usable interval object yet def interval_recv(data, integer_datetimes, **kwargs): if integer_datetimes: microseconds, days, months = struct.unpack("!qii", data) else: seconds, days, months = struct.unpack("!dii", data) microseconds = int(seconds * 1000 * 1000) return Interval(microseconds, days, months) def interval_send(data, integer_datetimes, **kwargs): if integer_datetimes: return struct.pack("!qii", data.microseconds, data.days, data.months) else: return struct.pack("!dii", data.microseconds / 1000.0 / 1000.0, data.days, data.months) def array_recv(data, **kwargs): dim, hasnull, typeoid = struct.unpack("!iii", data[:12]) data = data[12:] # get type conversion method for typeoid conversion = pg_types[typeoid]["bin_in"] # Read dimension info dim_lengths = [] element_count = 1 for idim in range(dim): dim_len, dim_lbound = struct.unpack("!ii", data[:8]) data = data[8:] dim_lengths.append(dim_len) element_count *= dim_len # Read all array values array_values = [] for i in range(element_count): if len(data): element_len, = struct.unpack("!i", data[:4]) data = data[4:] if element_len == -1: array_values.append(None) else: array_values.append(conversion(data[:element_len], **kwargs)) data = data[element_len:] if data != "": raise ArrayDataParseError("unexpected data left over after array read") # at this point, {{1,2,3},{4,5,6}}::int[][] looks like [1,2,3,4,5,6]. # go through the dimensions and fix up the array contents to match # expected dimensions for dim_length in reversed(dim_lengths[1:]): val = [] while array_values: val.append(array_values[:dim_length]) array_values = array_values[dim_length:] array_values = val return array_values def array_inspect(value): # Check if array has any values. If not, we can't determine the proper # array typeoid. first_element = array_find_first_element(value) if first_element == None: raise ArrayContentEmptyError("array has no values") # supported array output typ = type(first_element) if issubclass(typ, int) or issubclass(typ, long): # special int array support -- send as smallest possible array type special_int_support = True int2_ok, int4_ok, int8_ok = True, True, True for v in array_flatten(value): if v == None: continue if min_int2 < v < max_int2: continue int2_ok = False if min_int4 < v < max_int4: continue int4_ok = False if min_int8 < v < max_int8: continue int8_ok = False if int2_ok: array_typeoid = 1005 # INT2[] elif int4_ok: array_typeoid = 1007 # INT4[] elif int8_ok: array_typeoid = 1016 # INT8[] else: raise ArrayContentNotSupportedError("numeric not supported as array contents") else: special_int_support = False array_typeoid = py_array_types.get(typ) if array_typeoid == None: raise ArrayContentNotSupportedError("type %r not supported as array contents" % typ) # check for homogenous array for v in array_flatten(value): if v != None and not ( isinstance(v, typ) or (typ == long and isinstance(v, int)) or (typ == int and isinstance(v, long))): raise ArrayContentNotHomogenousError("not all array elements are of type %r" % typ) # check that all array dimensions are consistent array_check_dimensions(value) type_data = py_types[typ] if special_int_support: if array_typeoid == 1005: type_data = {"typeoid": 21, "bin_out": int2send} elif array_typeoid == 1007: type_data = {"typeoid": 23, "bin_out": int4send} elif array_typeoid == 1016: type_data = {"typeoid": 20, "bin_out": int8send} else: type_data = py_types[typ] return { "typeoid": array_typeoid, "bin_out": array_send(type_data["typeoid"], type_data["bin_out"]) } def array_find_first_element(arr): for v in array_flatten(arr): if v != None: return v return None def array_flatten(arr): for v in arr: if isinstance(v, list): for v2 in array_flatten(v): yield v2 else: yield v def array_check_dimensions(arr): v0 = arr[0] if isinstance(v0, list): req_len = len(v0) req_inner_lengths = array_check_dimensions(v0) for v in arr: inner_lengths = array_check_dimensions(v) if len(v) != req_len or inner_lengths != req_inner_lengths: raise ArrayDimensionsNotConsistentError("array dimensions not consistent") retval = [req_len] retval.extend(req_inner_lengths) return retval else: # make sure nothing else at this level is a list for v in arr: if isinstance(v, list): raise ArrayDimensionsNotConsistentError("array dimensions not consistent") return [] def array_has_null(arr): for v in array_flatten(arr): if v == None: return True return False def array_dim_lengths(arr): v0 = arr[0] if isinstance(v0, list): retval = [len(v0)] retval.extend(array_dim_lengths(v0)) else: return [len(arr)] return retval class array_send(object): def __init__(self, typeoid, bin_out_func): self.typeoid = typeoid self.bin_out_func = bin_out_func def __call__(self, arr, **kwargs): has_null = array_has_null(arr) dim_lengths = array_dim_lengths(arr) data = struct.pack("!iii", len(dim_lengths), has_null, self.typeoid) for i in dim_lengths: data += struct.pack("!ii", i, 1) for v in array_flatten(arr): if v == None: data += struct.pack("!i", -1) else: inner_data = self.bin_out_func(v, **kwargs) data += struct.pack("!i", len(inner_data)) data += inner_data return data py_types = { bool: {"typeoid": 16, "bin_out": boolsend}, int: {"inspect": int_inspect}, long: {"inspect": int_inspect}, str: {"typeoid": 25, "bin_out": textout}, unicode: {"typeoid": 25, "bin_out": textout}, float: {"typeoid": 701, "bin_out": float8send}, decimal.Decimal: {"typeoid": 1700, "bin_out": numeric_send}, Bytea: {"typeoid": 17, "bin_out": byteasend}, datetime.datetime: {"typeoid": 1114, "bin_out": timestamp_send, "inspect": datetime_inspect}, datetime.date: {"typeoid": 1082, "txt_out": date_out}, datetime.time: {"typeoid": 1083, "txt_out": time_out}, Interval: {"typeoid": 1186, "bin_out": interval_send}, type(None): {"typeoid": -1}, list: {"inspect": array_inspect}, } # py type -> pg array typeoid py_array_types = { float: 1022, bool: 1000, str: 1009, # TEXT[] unicode: 1009, # TEXT[] decimal.Decimal: 1231, # NUMERIC[] } pg_types = { 16: {"bin_in": boolrecv}, 17: {"bin_in": bytearecv}, 19: {"bin_in": varcharin}, # name type 20: {"bin_in": int8recv}, 21: {"bin_in": int2recv}, 23: {"bin_in": int4recv}, 25: {"bin_in": varcharin}, # TEXT type 26: {"txt_in": numeric_in}, # oid type 142: {"bin_in": varcharin}, # XML 194: {"bin_in": varcharin}, # "string representing an internal node tree" 700: {"bin_in": float4recv}, 701: {"bin_in": float8recv}, 705: {"bin_in": varcharin}, 829: {"txt_in": varcharin}, # MACADDR type 1000: {"bin_in": array_recv}, # BOOL[] 1003: {"bin_in": array_recv}, # NAME[] 1005: {"bin_in": array_recv}, # INT2[] 1007: {"bin_in": array_recv}, # INT4[] 1009: {"bin_in": array_recv}, # TEXT[] 1014: {"bin_in": array_recv}, # CHAR[] 1015: {"bin_in": array_recv}, # VARCHAR[] 1016: {"bin_in": array_recv}, # INT8[] 1021: {"bin_in": array_recv}, # FLOAT4[] 1022: {"bin_in": array_recv}, # FLOAT8[] 1042: {"bin_in": varcharin}, # CHAR type 1043: {"bin_in": varcharin}, # VARCHAR type 1082: {"txt_in": date_in}, 1083: {"txt_in": time_in}, 1114: {"bin_in": timestamp_recv}, 1184: {"bin_in": timestamptz_recv}, # timestamp w/ tz 1186: {"bin_in": interval_recv}, 1231: {"bin_in": array_recv}, # NUMERIC[] 1263: {"bin_in": array_recv}, # cstring[] 1700: {"bin_in": numeric_recv}, 2275: {"bin_in": varcharin}, # cstring }
__author__ = 'Vale Tolpegin' # Importing relevant classes import sys, os, re import argparse from tkCommonDialog import Dialog class frame_generator: # Initialization method def init( self, *args, **kwargs ): pass # Function that delegates frame file generation for every language that was requested def generate_frame_files( self, base_directory, language ): if language == "propc": self.generate_c_frame( base_directory ) elif language == "spin": self.generate_spin_frame( base_directory ) return True # Function that actually generates the frame file for the C language def generate_c_frame( self, base_directory ): bad_c_blocks = "" bad_c_blocks += "set_ramp_step_toward," blocks = self.get_blocks( base_directory, 'propc', bad_c_blocks ) names = self.get_file_names( base_directory, 'propc' ) keepers = "" scripts = "" for block in blocks: if block != "": keepers += '\n\t\t\t"' + block + '",' keepers = keepers[ 0 : len(keepers) - 1 ] keepers += '\n' for name in names: if name != "": scripts += '\n\t\t<script type="text/javascript" src="generators/propc/' + name + '"></script>' scripts += '\n' assembled = "" assembled += open( os.getcwd() + '/templates/header_template_c.html', 'r' ).read() assembled += scripts assembled += open( os.getcwd() + '/templates/body_template.html', 'r' ).read() assembled += keepers assembled += open( os.getcwd() + '/templates/footer_template.html', 'r' ).read() file = open( base_directory + '/framec.html', 'w' ) file.write( assembled ) file.close() # Function that actually generates the frame file for the Spin language def generate_spin_frame( self, base_directory ): bad_spin_blocks = "" blocks = self.get_blocks( base_directory, 'Spin', bad_spin_blocks ) names = self.get_file_names( base_directory, 'spin' ) keepers = "" scripts = "" for block in blocks: if block != "": keepers += '\n\t\t\t"' + block + '",' keepers = keepers[ 0 : len(keepers) - 1 ] keepers += '\n' for name in names: scripts += '\n\t' + '<script type="text/javascript" src="generators/spin/' + name + '"></script>' assembled = "" assembled += open( os.getcwd() + '/templates/header_template_spin.html', 'r' ).read() assembled += scripts assembled += open( os.getcwd() + '/templates/body_template.html', 'r' ).read() assembled += keepers assembled += open( os.getcwd() + '/templates/footer_template.html', 'r' ).read() file = open( base_directory + '/frame.html', 'w' ) file.write( assembled ) file.close() # Function that returns the block name and other useful information about the blocks def get_blocks( self, path, language, bad_blocks ): blocks = "" if bad_blocks == "": bad_blocks = "----------" # Walking the directory to get all of the names of the blocks for root, dir, file in os.walk( path + "/generators/" + language + "/" ): for file_name in file: if '.js' in str( file_name ): file_blocks = open( path + "/generators/" + language + "/" + str( file_name ), 'r' ).read() file_blocks = file_blocks.split( '\n' ) for line in file_blocks: line = line.split( ' ' ) name = "" if 'Blockly.Language' in line[0]: name = re.sub( 'Blockly.Language.', '', line[0] ) elif 'Blockly.' + language + '.' in line[0]: name = re.sub( 'Blockly.' + language + '.', '', line[0] ) block_accept = True if 'propc' in language: for bad_block in bad_blocks.split( ',' ): if bad_block in name: block_accept = False break elif 'spin' in language: for bad_block in bad_blocks.split( ',' ): if bad_block in name: block_accept = False break if block_accept: if '.' not in name and name not in blocks: blocks += "," + name elif '.' in name: name = re.sub( '.*', '', name ) if name not in blocks: blocks += "," + name if '.' not in name and name not in blocks: blocks += "," + name elif '.' in name: name = re.sub( '.*', '', name ) if name not in blocks: blocks += "," + name return blocks.split( ',' ) # Function that returns the file names of all of the block files def get_file_names( self, path, language ): names = "" for root, dir, file in os.walk( path + "/generators/" + language + "/" ): for file_name in file: if '.js' in str( file_name ): names += "," + str( file_name ) return names.split( ',' ) # Opens a directory chooser dialog window and returns the path of the directory the user chose def askdirectory(self, **options): return apply(self.Chooser, (), options).show() class Chooser(Dialog): command = "tk_chooseDirectory" def _fixresult(self, widget, result): if result: # keep directory until next time self.options["initialdir"] = result self.directory = result # compatibility return result if __name__ == '__main__': # Get language & other command line arguements parser = argparse.ArgumentParser( description="frame generator for BlocklyProp" ) parser.add_argument( '-c', help='Generate the propc frame file' ) parser.add_argument( '-s', help='Generate the spin frame file' ) args = parser.parse_args() # Instantiate a frame_generator object frame_creator = frame_generator() # Get base directory base_directory = frame_creator.askdirectory() # Setting up variables languages = "" generated_truefalse = False # If C or Spin is supposed to be parsed, parse them & generate the frame files if 'c' in args: generated_truefalse = frame_creator.generate_frame_files( base_directory, 'propc' ) if 's' in args: generated_truefalse = frame_creator.generate_frame_files( base_directory, 'spin' ) # If the files were successfully generated if generated_truefalse: # Let the user know the files were generated successfully print "" print "[ Info ] Frame files generated" print "" # Otherwise if the files were not successfully generated else: # Let the user know the files were not successfully generated print "" print "[ Error ] Frame files could not be generated due to some unknown error. Please try again" print ""
#!/usr/bin/env python """ refguide_check.py [OPTIONS] [-- ARGS] Check for a PyWavelets submodule whether the objects in its __all__ dict correspond to the objects included in the reference guide. Example of usage:: $ python refguide_check.py optimize Note that this is a helper script to be able to check if things are missing; the output of this script does need to be checked manually. In some cases objects are left out of the refguide for a good reason (it's an alias of another function, or deprecated, or ...) Another use of this helper script is to check validity of code samples in docstrings. This is different from doctesting [we do not aim to have scipy docstrings doctestable!], this is just to make sure that code in docstrings is valid python:: $ python refguide_check.py --check_docs optimize """ from __future__ import print_function import sys import os import re import copy import inspect import warnings import doctest import tempfile import io import docutils.core from docutils.parsers.rst import directives import shutil import glob from doctest import NORMALIZE_WHITESPACE, ELLIPSIS, IGNORE_EXCEPTION_DETAIL from argparse import ArgumentParser import numpy as np # FIXME: doctests need the str/repr formatting used in Numpy < 1.14. try: np.set_printoptions(legacy='1.13') except TypeError: pass # sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'doc', # 'sphinxext')) from numpydoc.docscrape_sphinx import get_doc_object # Remove sphinx directives that don't run without Sphinx environment directives._directives.pop('versionadded', None) directives._directives.pop('versionchanged', None) directives._directives.pop('moduleauthor', None) directives._directives.pop('sectionauthor', None) directives._directives.pop('codeauthor', None) directives._directives.pop('toctree', None) BASE_MODULE = "pywt" PUBLIC_SUBMODULES = [] # Docs for these modules are included in the parent module OTHER_MODULE_DOCS = {} # these names are known to fail doctesting and we like to keep it that way # e.g. sometimes pseudocode is acceptable etc DOCTEST_SKIPLIST = set([]) # these names are not required to be present in ALL despite being in # autosummary:: listing REFGUIDE_ALL_SKIPLIST = [] HAVE_MATPLOTLIB = False def short_path(path, cwd=None): """ Return relative or absolute path name, whichever is shortest. """ if not isinstance(path, str): return path if cwd is None: cwd = os.getcwd() abspath = os.path.abspath(path) relpath = os.path.relpath(path, cwd) if len(abspath) <= len(relpath): return abspath return relpath def find_names(module, names_dict): # Refguide entries: # # - 3 spaces followed by function name, and maybe some spaces, some # dashes, and an explanation; only function names listed in # refguide are formatted like this (mostly, there may be some false # positives) # # - special directives, such as data and function # # - (scipy.constants only): quoted list # patterns = [ r"^\s\s\s([a-z_0-9A-Z]+)(\s+-+.*)?$", r"^\.\. (?:data|function)::\s*([a-z_0-9A-Z]+)\s*$" ] if module.__name__ == 'scipy.constants': patterns += ["^``([a-z_0-9A-Z]+)``"] patterns = [re.compile(pattern) for pattern in patterns] module_name = module.__name__ for line in module.__doc__.splitlines(): res = re.search(r"^\s*\.\. (?:currentmodule|module):: ([a-z0-9A-Z_.]+)\s*$", line) if res: module_name = res.group(1) continue for pattern in patterns: res = re.match(pattern, line) if res is not None: name = res.group(1) entry = '.'.join([module_name, name]) names_dict.setdefault(module_name, set()).add(name) break def get_all_dict(module): """Return a copy of the __all__ dict with irrelevant items removed.""" if hasattr(module, "__all__"): all_dict = copy.deepcopy(module.__all__) else: all_dict = copy.deepcopy(dir(module)) all_dict = [name for name in all_dict if not name.startswith("_")] for name in ['absolute_import', 'division', 'print_function']: try: all_dict.remove(name) except ValueError: pass # Modules are almost always private; real submodules need a separate # run of refguide_check. all_dict = [name for name in all_dict if not inspect.ismodule(getattr(module, name, None))] deprecated = [] not_deprecated = [] for name in all_dict: f = getattr(module, name, None) if callable(f) and is_deprecated(f): deprecated.append(name) else: not_deprecated.append(name) others = set(dir(module)).difference(set(deprecated)).difference(set(not_deprecated)) return not_deprecated, deprecated, others def compare(all_dict, others, names, module_name): """Return sets of objects only in __all__, refguide, or completely missing.""" only_all = set() for name in all_dict: if name not in names: only_all.add(name) only_ref = set() missing = set() for name in names: if name not in all_dict: for pat in REFGUIDE_ALL_SKIPLIST: if re.match(pat, module_name + '.' + name): if name not in others: missing.add(name) break else: only_ref.add(name) return only_all, only_ref, missing def is_deprecated(f): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("error") try: f(**{"not a kwarg": None}) except DeprecationWarning: return True except: pass return False def check_items(all_dict, names, deprecated, others, module_name, dots=True): num_all = len(all_dict) num_ref = len(names) output = "" output += "Non-deprecated objects in __all__: %i\n" % num_all output += "Objects in refguide: %i\n\n" % num_ref only_all, only_ref, missing = compare(all_dict, others, names, module_name) dep_in_ref = set(only_ref).intersection(deprecated) only_ref = set(only_ref).difference(deprecated) if len(dep_in_ref) > 0: output += "Deprecated objects in refguide::\n\n" for name in sorted(deprecated): output += " " + name + "\n" if len(only_all) == len(only_ref) == len(missing) == 0: if dots: output_dot('.') return [(None, True, output)] else: if len(only_all) > 0: output += "ERROR: objects in %s.__all__ but not in refguide::\n\n" % module_name for name in sorted(only_all): output += " " + name + "\n" if len(only_ref) > 0: output += "ERROR: objects in refguide but not in %s.__all__::\n\n" % module_name for name in sorted(only_ref): output += " " + name + "\n" if len(missing) > 0: output += "ERROR: missing objects::\n\n" for name in sorted(missing): output += " " + name + "\n" if dots: output_dot('F') return [(None, False, output)] def validate_rst_syntax(text, name, dots=True): if text is None: if dots: output_dot('E') return False, "ERROR: %s: no documentation" % (name,) ok_unknown_items = set([ 'mod', 'currentmodule', 'autosummary', 'data', 'obj', 'versionadded', 'versionchanged', 'module', 'class', 'ref', 'func', 'toctree', 'moduleauthor', 'sectionauthor', 'codeauthor', 'eq', ]) # Run through docutils error_stream = io.StringIO() def resolve(name, is_label=False): return ("http://foo", name) token = '<RST-VALIDATE-SYNTAX-CHECK>' docutils.core.publish_doctree( text, token, settings_overrides = dict(halt_level=5, traceback=True, default_reference_context='title-reference', default_role='emphasis', link_base='', resolve_name=resolve, stylesheet_path='', raw_enabled=0, file_insertion_enabled=0, warning_stream=error_stream)) # Print errors, disregarding unimportant ones error_msg = error_stream.getvalue() errors = error_msg.split(token) success = True output = "" for error in errors: lines = error.splitlines() if not lines: continue m = re.match(r'.*Unknown (?:interpreted text role|directive type) "(.*)".*$', lines[0]) if m: if m.group(1) in ok_unknown_items: continue m = re.match(r'.*Error in "math" directive:.*unknown option: "label"', " ".join(lines), re.S) if m: continue output += name + lines[0] + "::\n " + "\n ".join(lines[1:]).rstrip() + "\n" success = False if not success: output += " " + "-"*72 + "\n" for lineno, line in enumerate(text.splitlines()): output += " %-4d %s\n" % (lineno+1, line) output += " " + "-"*72 + "\n\n" if dots: output_dot('.' if success else 'F') return success, output def output_dot(msg='.', stream=sys.stderr): stream.write(msg) stream.flush() def check_rest(module, names, dots=True): """ Check reStructuredText formatting of docstrings Returns: [(name, success_flag, output), ...] """ try: skip_types = (dict, str, unicode, float, int) except NameError: # python 3 skip_types = (dict, str, float, int) results = [] if module.__name__[6:] not in OTHER_MODULE_DOCS: results += [(module.__name__,) + validate_rst_syntax(inspect.getdoc(module), module.__name__, dots=dots)] for name in names: full_name = module.__name__ + '.' + name obj = getattr(module, name, None) if obj is None: results.append((full_name, False, "%s has no docstring" % (full_name,))) continue elif isinstance(obj, skip_types): continue if inspect.ismodule(obj): text = inspect.getdoc(obj) else: try: text = str(get_doc_object(obj)) except: import traceback results.append((full_name, False, "Error in docstring format!\n" + traceback.format_exc())) continue m = re.search("([\x00-\x09\x0b-\x1f])", text) if m: msg = ("Docstring contains a non-printable character %r! " "Maybe forgot r\"\"\"?" % (m.group(1),)) results.append((full_name, False, msg)) continue try: src_file = short_path(inspect.getsourcefile(obj)) except TypeError: src_file = None if src_file: file_full_name = src_file + ':' + full_name else: file_full_name = full_name results.append((full_name,) + validate_rst_syntax(text, file_full_name, dots=dots)) return results ### Doctest helpers #### # the namespace to run examples in DEFAULT_NAMESPACE = {'np': np} # the namespace to do checks in CHECK_NAMESPACE = { 'np': np, 'assert_allclose': np.testing.assert_allclose, 'assert_equal': np.testing.assert_equal, # recognize numpy repr's 'array': np.array, 'matrix': np.matrix, 'int64': np.int64, 'uint64': np.uint64, 'int8': np.int8, 'int32': np.int32, 'float64': np.float64, 'dtype': np.dtype, 'nan': np.nan, 'NaN': np.nan, 'inf': np.inf, 'Inf': np.inf, } class DTRunner(doctest.DocTestRunner): DIVIDER = "\n" def __init__(self, item_name, checker=None, verbose=None, optionflags=0): self._item_name = item_name doctest.DocTestRunner.__init__(self, checker=checker, verbose=verbose, optionflags=optionflags) def _report_item_name(self, out, new_line=False): if self._item_name is not None: if new_line: out("\n") self._item_name = None def report_start(self, out, test, example): self._checker._source = example.source return doctest.DocTestRunner.report_start(self, out, test, example) def report_success(self, out, test, example, got): if self._verbose: self._report_item_name(out, new_line=True) return doctest.DocTestRunner.report_success( self, out, test, example, got) def report_unexpected_exception(self, out, test, example, exc_info): self._report_item_name(out) return doctest.DocTestRunner.report_unexpected_exception( self, out, test, example, exc_info) def report_failure(self, out, test, example, got): self._report_item_name(out) return doctest.DocTestRunner.report_failure(self, out, test, example, got) class Checker(doctest.OutputChecker): obj_pattern = re.compile('at 0x[0-9a-fA-F]+>') vanilla = doctest.OutputChecker() rndm_markers = {'# random', '# Random', '#random', '#Random', "# may vary"} stopwords = {'plt.', '.hist', '.show', '.ylim', '.subplot(', 'set_title', 'imshow', 'plt.show', 'ax.axis', 'plt.plot(', '.bar(', '.title', '.ylabel', '.xlabel', 'set_ylim', 'set_xlim', '# reformatted'} def __init__(self, parse_namedtuples=True, ns=None, atol=1e-8, rtol=1e-2): self.parse_namedtuples = parse_namedtuples self.atol, self.rtol = atol, rtol if ns is None: self.ns = dict(CHECK_NAMESPACE) else: self.ns = ns def check_output(self, want, got, optionflags): # cut it short if they are equal if want == got: return True # skip stopwords in source if any(word in self._source for word in self.stopwords): return True # skip random stuff if any(word in want for word in self.rndm_markers): return True # skip function/object addresses if self.obj_pattern.search(got): return True # ignore comments (e.g. signal.freqresp) if want.lstrip().startswith("#"): return True # try the standard doctest try: if self.vanilla.check_output(want, got, optionflags): return True except Exception: pass # OK then, convert strings to objects try: a_want = eval(want, dict(self.ns)) a_got = eval(got, dict(self.ns)) except: if not self.parse_namedtuples: return False # suppose that "want" is a tuple, and "got" is smth like # MoodResult(statistic=10, pvalue=0.1). # Then convert the latter to the tuple (10, 0.1), # and then compare the tuples. try: num = len(a_want) regex = ('[\w\d_]+\(' + ', '.join(['[\w\d_]+=(.+)']*num) + '\)') grp = re.findall(regex, got.replace('\n', ' ')) if len(grp) > 1: # no more than one for now return False # fold it back to a tuple got_again = '(' + ', '.join(grp[0]) + ')' return self.check_output(want, got_again, optionflags) except Exception: return False # ... and defer to numpy try: return self._do_check(a_want, a_got) except Exception: # heterog tuple, eg (1, np.array([1., 2.])) try: return all(self._do_check(w, g) for w, g in zip(a_want, a_got)) except (TypeError, ValueError): return False def _do_check(self, want, got): # This should be done exactly as written to correctly handle all of # numpy-comparable objects, strings, and heterogenous tuples try: if want == got: return True except Exception: pass return np.allclose(want, got, atol=self.atol, rtol=self.rtol) def _run_doctests(tests, full_name, verbose, doctest_warnings): """Run modified doctests for the set of `tests`. Returns: list of [(success_flag, output), ...] """ flags = NORMALIZE_WHITESPACE | ELLIPSIS | IGNORE_EXCEPTION_DETAIL runner = DTRunner(full_name, checker=Checker(), optionflags=flags, verbose=verbose) output = [] success = True def out(msg): output.append(msg) class MyStderr(object): """Redirect stderr to the current stdout""" def write(self, msg): if doctest_warnings: sys.stdout.write(msg) else: out(msg) # Run tests, trying to restore global state afterward old_printoptions = np.get_printoptions() old_errstate = np.seterr() old_stderr = sys.stderr cwd = os.getcwd() tmpdir = tempfile.mkdtemp() sys.stderr = MyStderr() try: os.chdir(tmpdir) # try to ensure random seed is NOT reproducible np.random.seed(None) for t in tests: t.filename = short_path(t.filename, cwd) fails, successes = runner.run(t, out=out) if fails > 0: success = False finally: sys.stderr = old_stderr os.chdir(cwd) shutil.rmtree(tmpdir) np.set_printoptions(**old_printoptions) np.seterr(**old_errstate) return success, output def check_doctests(module, verbose, ns=None, dots=True, doctest_warnings=False): """Check code in docstrings of the module's public symbols. Returns: list of [(item_name, success_flag, output), ...] """ if ns is None: ns = dict(DEFAULT_NAMESPACE) # Loop over non-deprecated items results = [] for name in get_all_dict(module)[0]: full_name = module.__name__ + '.' + name if full_name in DOCTEST_SKIPLIST: continue try: obj = getattr(module, name) except AttributeError: import traceback results.append((full_name, False, "Missing item!\n" + traceback.format_exc())) continue finder = doctest.DocTestFinder() try: tests = finder.find(obj, name, globs=dict(ns)) except: import traceback results.append((full_name, False, "Failed to get doctests!\n" + traceback.format_exc())) continue success, output = _run_doctests(tests, full_name, verbose, doctest_warnings) if dots: output_dot('.' if success else 'F') results.append((full_name, success, "".join(output))) if HAVE_MATPLOTLIB: import matplotlib.pyplot as plt plt.close('all') return results def check_doctests_testfile(fname, verbose, ns=None, dots=True, doctest_warnings=False): """Check code in a text file. Mimic `check_doctests` above, differing mostly in test discovery. (which is borrowed from stdlib's doctest.testfile here, https://github.com/python-git/python/blob/master/Lib/doctest.py) Returns: list of [(item_name, success_flag, output), ...] Notes ----- We also try to weed out pseudocode: * We maintain a list of exceptions which signal pseudocode, * We split the text file into "blocks" of code separated by empty lines and/or intervening text. * If a block contains a marker, the whole block is then assumed to be pseudocode. It is then not being doctested. The rationale is that typically, the text looks like this: blah <BLANKLINE> >>> from numpy import some_module # pseudocode! >>> func = some_module.some_function >>> func(42) # still pseudocode 146 <BLANKLINE> blah <BLANKLINE> >>> 2 + 3 # real code, doctest it 5 """ results = [] if ns is None: ns = dict(DEFAULT_NAMESPACE) _, short_name = os.path.split(fname) if short_name in DOCTEST_SKIPLIST: return results full_name = fname text = open(fname).read() PSEUDOCODE = set(['some_function', 'some_module', 'import example', 'ctypes.CDLL', # likely need compiling, skip it 'integrate.nquad(func,' # ctypes integrate tutotial ]) # split the text into "blocks" and try to detect and omit pseudocode blocks. parser = doctest.DocTestParser() good_parts = [] for part in text.split('\n\n'): tests = parser.get_doctest(part, ns, fname, fname, 0) if any(word in ex.source for word in PSEUDOCODE for ex in tests.examples): # omit it pass else: # `part` looks like a good code, let's doctest it good_parts += [part] # Reassemble the good bits and doctest them: good_text = '\n\n'.join(good_parts) tests = parser.get_doctest(good_text, ns, fname, fname, 0) success, output = _run_doctests([tests], full_name, verbose, doctest_warnings) if dots: output_dot('.' if success else 'F') results.append((full_name, success, "".join(output))) if HAVE_MATPLOTLIB: import matplotlib.pyplot as plt plt.close('all') return results def init_matplotlib(): global HAVE_MATPLOTLIB try: import matplotlib matplotlib.use('Agg') HAVE_MATPLOTLIB = True except ImportError: HAVE_MATPLOTLIB = False def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("module_names", metavar="SUBMODULES", default=[], nargs='*', help="Submodules to check (default: all public)") parser.add_argument("--doctests", action="store_true", help="Run also doctests") parser.add_argument("-v", "--verbose", action="count", default=0) parser.add_argument("--doctest-warnings", action="store_true", help="Enforce warning checking for doctests") parser.add_argument("--skip-examples", action="store_true", help="Skip running doctests in the examples.") args = parser.parse_args(argv) modules = [] names_dict = {} if args.module_names: args.skip_examples = True else: args.module_names = list(PUBLIC_SUBMODULES) os.environ['SCIPY_PIL_IMAGE_VIEWER'] = 'true' module_names = list(args.module_names) for name in list(module_names): if name in OTHER_MODULE_DOCS: name = OTHER_MODULE_DOCS[name] if name not in module_names: module_names.append(name) for submodule_name in module_names: module_name = BASE_MODULE + '.' + submodule_name __import__(module_name) module = sys.modules[module_name] if submodule_name not in OTHER_MODULE_DOCS: find_names(module, names_dict) if submodule_name in args.module_names: modules.append(module) dots = True success = True results = [] print("Running checks for %d modules:" % (len(modules),)) if args.doctests or not args.skip_examples: init_matplotlib() for module in modules: if dots: if module is not modules[0]: sys.stderr.write(' ') sys.stderr.write(module.__name__ + ' ') sys.stderr.flush() all_dict, deprecated, others = get_all_dict(module) names = names_dict.get(module.__name__, set()) mod_results = [] mod_results += check_items(all_dict, names, deprecated, others, module.__name__) mod_results += check_rest(module, set(names).difference(deprecated), dots=dots) if args.doctests: mod_results += check_doctests(module, (args.verbose >= 2), dots=dots, doctest_warnings=args.doctest_warnings) for v in mod_results: assert isinstance(v, tuple), v results.append((module, mod_results)) if dots: sys.stderr.write("\n") sys.stderr.flush() if not args.skip_examples: examples_path = os.path.join( os.getcwd(), 'doc', 'source', 'regression', '*.rst') print('\nChecking examples files at %s:' % examples_path) for filename in sorted(glob.glob(examples_path)): if dots: sys.stderr.write('\n') sys.stderr.write(os.path.split(filename)[1] + ' ') sys.stderr.flush() examples_results = check_doctests_testfile( filename, (args.verbose >= 2), dots=dots, doctest_warnings=args.doctest_warnings) def scratch(): pass # stub out a "module", see below scratch.__name__ = filename results.append((scratch, examples_results)) if dots: sys.stderr.write("\n") sys.stderr.flush() # Report results all_success = True for module, mod_results in results: success = all(x[1] for x in mod_results) all_success = all_success and success if success and args.verbose == 0: continue print("") print("=" * len(module.__name__)) print(module.__name__) print("=" * len(module.__name__)) print("") for name, success, output in mod_results: if name is None: if not success or args.verbose >= 1: print(output.strip()) print("") elif not success or (args.verbose >= 2 and output.strip()): print(name) print("-"*len(name)) print("") print(output.strip()) print("") if all_success: print("\nOK: refguide and doctests checks passed!") sys.exit(0) else: print("\nERROR: refguide or doctests have errors") sys.exit(1) if __name__ == '__main__': main(argv=sys.argv[1:])
# Copyright 2016 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. import datetime import json import logging import os import time import webapp2 import filters import gcs_async import github.models as ghm import pull_request import view_base PR_PREFIX = view_base.PR_PREFIX @view_base.memcache_memoize('pr-details://', expires=60 * 3) def pr_builds(path): """Return {job: [(build, {started.json}, {finished.json})]} for each job under gcs path.""" jobs_dirs_fut = gcs_async.listdirs(path) def base(path): return os.path.basename(os.path.dirname(path)) jobs_futures = [(job, gcs_async.listdirs(job)) for job in jobs_dirs_fut.get_result()] futures = [] for job, builds_fut in jobs_futures: for build in builds_fut.get_result(): futures.append([ base(job), base(build), gcs_async.read('/%sstarted.json' % build), gcs_async.read('/%sfinished.json' % build)]) futures.sort(key=lambda (job, build, s, f): (job, view_base.pad_numbers(build)), reverse=True) jobs = {} for job, build, started_fut, finished_fut in futures: started = started_fut.get_result() finished = finished_fut.get_result() if started is not None: started = json.loads(started) if finished is not None: finished = json.loads(finished) jobs.setdefault(job, []).append((build, started, finished)) return jobs def pr_path(org, repo, pr): """Builds the correct gs://prefix/maybe_kubernetes/maybe_repo_org/pr.""" # TODO(fejta): make this less specific to kubernetes. if org == repo == 'kubernetes': return '%s/%s' % (PR_PREFIX['kubernetes'], pr) if org == 'kubernetes': return '%s/%s/%s' % (PR_PREFIX['kubernetes'], repo, pr) return '%s/%s_%s/%s' % (PR_PREFIX[org], org, repo, pr) def org_repo(path): """Converts /maybe_org/maybe_repo into (org, repo).""" # TODO(fejta): make this less specific to kubernetes. parts = path.split('/')[1:] if len(parts) == 2: org, repo = parts elif len(parts) == 1: org = 'kubernetes' repo = parts[0] else: org = repo = 'kubernetes' return org, repo class PRHandler(view_base.BaseHandler): """Show a list of test runs for a PR.""" def get(self, path, pr): # pylint: disable=too-many-locals org, repo = org_repo(path) path = pr_path(org, repo, pr) builds = pr_builds(path) # TODO(fejta): assume all builds are monotonically increasing. for bs in builds.itervalues(): if any(len(b) > 8 for b, _, _ in bs): bs.sort(key=lambda (b, s, f): -(s or {}).get('timestamp', 0)) if pr == 'batch': # truncate batch results to last day cutoff = time.time() - 60 * 60 * 24 builds = {} for job, job_builds in builds.iteritems(): builds[job] = [ (b, s, f) for b, s, f in job_builds if not s or s.get('timestamp') > cutoff ] max_builds, headings, rows = pull_request.builds_to_table(builds) digest = ghm.GHIssueDigest.get('%s/%s' % (org, repo), pr) self.render( 'pr.html', dict( pr=pr, digest=digest, max_builds=max_builds, header=headings, org=org, repo=repo, rows=rows, path=path, ) ) def get_acks(login, prs): acks = {} result = ghm.GHUserState.make_key(login).get() if result: acks = result.acks if prs: # clear acks for PRs that user is no longer involved in. stale = set(acks) - set(pr.key.id() for pr in prs) if stale: for key in stale: result.acks.pop(key) result.put() return acks class PRDashboard(view_base.BaseHandler): def get(self, user=None): # pylint: disable=singleton-comparison login = self.session.get('user') if not user: user = login if not user: self.redirect('/github_auth/pr') return logging.debug('user=%s', user) elif user == 'all': user = None qs = [ghm.GHIssueDigest.is_pr == True] if not self.request.get('all', False): qs.append(ghm.GHIssueDigest.is_open == True) if user: qs.append(ghm.GHIssueDigest.involved == user) prs = list(ghm.GHIssueDigest.query(*qs)) prs.sort(key=lambda x: x.updated_at, reverse=True) acks = None if login and user == login: # user getting their own page acks = get_acks(login, prs) fmt = self.request.get('format', 'html') if fmt == 'json': self.response.headers['Content-Type'] = 'application/json' def serial(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() elif isinstance(obj, ghm.GHIssueDigest): # pylint: disable=protected-access keys = ['repo', 'number'] + list(obj._values) return {k: getattr(obj, k) for k in keys} raise TypeError self.response.write(json.dumps(prs, sort_keys=True, default=serial)) elif fmt == 'html': if user: def acked(p): if 'lgtm' in p.payload.get('labels', {}): return True # LGTM is an implicit Ack if acks is None: return False return filters.do_get_latest(p.payload, user) <= acks.get(p.key.id(), 0) cats = [ ('Needs Attention', lambda p: user in p.payload['attn'] and not acked(p), ''), ('Approvable', lambda p: user in p.payload.get('approvers', []), 'is:open is:pr ("additional approvers: {0}" ' + 'OR "additional approver: {0}")'.format(user)), ('Incoming', lambda p: user != p.payload['author'] and user in p.payload['assignees'], 'is:open is:pr user:kubernetes assignee:%s' % user), ('Outgoing', lambda p: user == p.payload['author'], 'is:open is:pr user:kubernetes author:%s' % user), ] else: cats = [('Open Kubernetes PRs', lambda x: True, 'is:open is:pr user:kubernetes')] self.render('pr_dashboard.html', dict( prs=prs, cats=cats, user=user, login=login, acks=acks)) else: self.abort(406) def post(self): login = self.session.get('user') if not login: self.abort(403) state = ghm.GHUserState.make_key(login).get() if state is None: state = ghm.GHUserState.make(login) body = json.loads(self.request.body) if body['command'] == 'ack': delta = {'%s %s' % (body['repo'], body['number']): body['latest']} state.acks.update(delta) state.put() elif body['command'] == 'ack-clear': state.acks = {} state.put() else: self.abort(400) class PRBuildLogHandler(webapp2.RequestHandler): def get(self, path): self.redirect('https://storage.googleapis.com/%s/%s' % (PR_PREFIX, path))
from __future__ import absolute_import from __future__ import print_function import sys,os import pandas as pd #import get_compounds_from_wikidata as wd sys.path.append('/global/project/projectdirs/openmsi/jupyterhub_libs/anaconda/lib/python2.7/site-packages') from rdkit import Chem import numpy as np from rdkit.Chem import PandasTools # MolToSmiles( (Mol)mol [, (bool)isomericSmiles=False # http://www.rdkit.org/Python_Docs/rdkit.Chem.rdmolfiles-module.html#MolToSmiles # - isomericSmiles: (optional) include information about stereochemistry in # the SMILES. Defaults to false. # https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchikey/RZJQGNCSTQAWON-UHFFFAOYSA-N/synonyms/json def desalt(mol): #input is an rdkit mol #returns an rdkit mol keeping the biggest component #returns original mol if only one component #returns a boolean indicated if cleaning was necessary d = Chem.rdmolops.GetMolFrags(mol) #these are atom indices if len(d) == 1: #If there are fragments or multiple molecules this will be greater than 1 return mol,False my_smiles=Chem.MolToSmiles(mol,True) parent_atom_count=0; disconnected=my_smiles.split('.') #With GetMolFrags, we've already established that there is more than one disconnected structure status = False for s in disconnected: little_mol=Chem.MolFromInchi(Chem.MolToInchi(Chem.MolFromSmiles(s))) if little_mol is not None: count = little_mol.GetNumAtoms() if count > parent_atom_count: parent_atom_count = count parent_mol = little_mol status = True return parent_mol,status def get_wikidata(terms_to_keep): prop_file = '/project/projectdirs/openmsi/projects/compound_data/wikidata/wikidata_compound_properties.xlsx' result = wd.get_wikidata(prop_file) df = pd.DataFrame(result) df.rename(columns={'canonicalSMILES': 'smiles'}, inplace=True) df.rename(columns={'InChI': 'inchi'}, inplace=True) df.rename(columns={'compoundLabel': 'common_name'}, inplace=True) df['source_database'] = 'wikidata' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_img(terms_to_keep): df = pd.read_csv('/project/projectdirs/openmsi/projects/compound_data/img_abc/NPlist32763_30-mar-2016.xls',delimiter='\t') df.rename(columns={'SMILES': 'smiles'}, inplace=True) df.rename(columns={'InChl': 'inchi'}, inplace=True) df.rename(columns={'SM ID': 'img_abc_id'}, inplace=True) df.rename(columns={'Secondary Metabolite (SM) Name': 'common_name'}, inplace=True) df['source_database'] = 'img' df['ROMol'] = '' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_enzo(terms_to_keep): df = pd.read_csv('/project/projectdirs/openmsi/projects/compound_data/enzo/BML-2865.txt',delimiter='\t') df.rename(columns={'SMILES': 'smiles'}, inplace=True) df.rename(columns={'Name': 'common_name'}, inplace=True) df['inchi'] = np.nan df['source_database'] = 'enzo' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_msmls(terms_to_keep): df = pd.read_excel('/project/projectdirs/openmsi/projects/compound_data/msmls/MSMLS map - mz overlap edit sk.xlsx') df.rename(columns={'SMILES': 'smiles'}, inplace=True) df.rename(columns={'CNAME': 'common_name'}, inplace=True) df.rename(columns={'PC_CID': 'pubchem_compound_id'}, inplace=True) df['source_database'] = 'msmls' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def dequote(s): """ If a string has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the string unchanged. """ if (s[0] == s[-1]) and s.startswith(("'", '"')): return s[1:-1] return s def get_metacyc(terms_to_keep): df = pd.read_excel('/project/projectdirs/openmsi/projects/compound_data/metacyc/MetAtlas_Export_MetaCyc_Compounds.xlsx', encoding='utf-8') df.rename(columns={'InChI': 'inchi'}, inplace=True) df.rename(columns={'KEGG': 'kegg_id'}, inplace=True) df.rename(columns={'PubChem': 'pubchem_compound_id'}, inplace=True) df.rename(columns={'Common-Name': 'common_name'}, inplace=True) df.rename(columns={'Names': 'synonyms'}, inplace=True) # reduced DCPIP // "2,6-dichloro-4-[(4-hydroxyphenyl)amino]phenol" // "reduced dichloroindophenol" // "reduced 2,6-dichlorophenolindophenol" // "reduced DCIP" df.rename(columns={'Object ID': 'metacyc_id'}, inplace=True) #df.synonyms.astype(str,inplace=True) #df['synonyms'].astype(basestring) df.loc[:,'synonyms'] = [[ s.strip() for s in mystr.split('//')] for mystr in df['synonyms'].astype(str).tolist() ] df.loc[:,'synonyms'] = [[ dequote(s) for s in mystr] for mystr in df['synonyms'].tolist() ] df['source_database'] = 'metacyc' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df # terms_to_keep = ['smiles','inchi','source_database','ROMol','common_name','synonyms','pubchem_compound_id','lipidmaps_id','metacyc_id','hmdb_id','img_abc_id','chebi_id','kegg_id'] def get_gnps(terms_to_keep): from pyteomics import mgf gnps = [s['params'] for s in mgf.read('/project/projectdirs/openmsi/projects/compound_data/gnps/ALL_GNPS (1).mgf')] df = pd.DataFrame(gnps) df['source_database'] = 'gnps' # df.rename(columns={'name': 'name'}, inplace=True) #name has adduct "Hoiamide B M+H" k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_dr_dukes(): df = pd.read_csv('/project/projectdirs/openmsi/projects/compound_data/dr_dukes_phytochemicals/CHEMICALS.csv',delimiter=',') df['source_database'] = 'dr_dukes' print(list(df.keys())) return df def get_lipid_maps(terms_to_keep): df = PandasTools.LoadSDF('/project/projectdirs/openmsi/projects/compound_data/lipidmaps/LMSDFDownload28Jun15FinalAll.sdf') df['source_database'] = 'lipidmaps' df.rename(columns={'KEGG_ID': 'kegg_id'}, inplace=True) df.rename(columns={'PUBCHEM_CID': 'pubchem_compound_id'}, inplace=True) df.rename(columns={'COMMON_NAME': 'common_name'}, inplace=True) df.rename(columns={'SYNONYMS': 'synonyms'}, inplace=True) # Decanohydroxamic acid; caprinohydroxamic acid; n-Decanohydroxamic acid df.loc[:,'synonyms'] = [[ s.strip() for s in mystr.split(';')] for mystr in df['synonyms'].astype(str).tolist() ] df.rename(columns={'ID': 'lipidmaps_id'}, inplace=True) k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_hmdb(terms_to_keep): df = PandasTools.LoadSDF('/project/projectdirs/openmsi/projects/compound_data/hmdb/structures.sdf') df['source_database'] = 'hmdb' df.rename(columns={'GENERIC_NAME': 'common_name'}, inplace=True) df.rename(columns={'SYNONYMS': 'synonyms'}, inplace=True) df.loc[:,'synonyms'] = [[ s.strip() for s in mystr.split(';')] for mystr in df['synonyms'].astype(str).tolist() ] # 2-(8S,9S,13S,14S)-3-Hydroxy-2-methoxy-13-methyl-7,8,9,11,12,14,15,16-octahydro-6H-cyclopenta[a]phenanthren-17-one; 2-Hydroxyestrone 2-methyl ether; 2-Methoxy-17-oxoestra-1,3,5(10)-trien-3-ol; 2-Methoxy-3-hydroxyestra-1,3,5(10)-trien-17-one; 3-Hydroxy-2-methoxy-Estra-1,3,5(10)-trien-17-one; 3-Hydroxy-2-methoxyestra-1,3,5(10)-trien-17-one; Methoxy-Estrone df.rename(columns={'HMDB_ID': 'hmdb_id'}, inplace=True) k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_chembl(terms_to_keep): sdf_file = '/project/projectdirs/openmsi/projects/compound_data/chembl/chembl_21.sdf.gz' df = PandasTools.LoadSDF(sdf_file) df['source_database'] = 'chembl' k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df def get_chebi(terms_to_keep): df = PandasTools.LoadSDF('/project/projectdirs/openmsi/projects/compound_data/chebi/ChEBI_complete.sdf.gz') # df = PandasTools.LoadSDF('/project/projectdirs/openmsi/projects/compound_data/chebi/ChEBI_complete_3star.sdf.gz') for index, row in df.iterrows(): mol = row['ROMol'] try: df.loc[index,'inchi'] = Chem.MolToInchi(mol) except: pass df['source_database'] = 'chebi' df.rename(columns={'KEGG COMPOUND Database Links': 'kegg_id'}, inplace=True) df.rename(columns={'ChEBI Name': 'common_name'}, inplace=True) df.rename(columns={'Synonyms': 'synonyms'}, inplace=True) df.loc[:,'synonyms'] = [[ s.strip() for s in mystr.split('\n')] for mystr in df['synonyms'].astype(str).tolist() ] # (-)-Epicatechin\n(-)-Epicatechol\n(2R,3R)-(-)-Epicatechin\n(2R,3R)-2-(3,4-dihydroxyphenyl)-3,4-dihydro-2H-1-benzopyran-3,5,7-triol\n3,3',4',5,7-Pentahydroxyflavane\nEpicatechol\nEpigallocatechin\nL(-)-Epicatechin\nL-Acacatechin\nL-Epicatechin\nL-Epicatechol\nalpha-Catechin df.rename(columns={'ChEBI ID': 'chebi_id'}, inplace=True) k = list(df.keys()) for t in terms_to_keep: if not t in k: df[t] = '' return df """ contribution from Hans de Winter """ def _InitialiseNeutralisationReactions(): patts= ( # Imidazoles ('[n+;H]','n'), # Amines ('[N+;!H0]','N'), # Carboxylic acids and alcohols ('[$([O-]);!$([O-][#7])]','O'), # Thiols ('[S-;X1]','S'), # Sulfonamides ('[$([N-;X2]S(=O)=O)]','N'), # Enamines ('[$([N-;X2][C,N]=C)]','N'), # Tetrazoles ('[n-]','[nH]'), # Sulfoxides ('[$([S-]=O)]','S'), # Amides ('[$([N-]C=O)]','N'), ) return [(Chem.MolFromSmarts(x),Chem.MolFromSmiles(y)) for x,y in patts] _reactions=None def NeutraliseCharges(mol, reactions=None): global _reactions if reactions is None: if _reactions is None: _reactions=_InitialiseNeutralisationReactions() reactions=_reactions # mol = Chem.MolFromSmiles(smiles) replaced = False for i,(reactant, product) in enumerate(reactions): while mol.HasSubstructMatch(reactant): replaced = True # print Chem.MolToSmiles(mol,True) # print Chem.MolToSmiles(mol), Chem.MolToSmarts(reactant),Chem.MolToSmiles(product) rms = Chem.AllChem.ReplaceSubstructs(mol, reactant, product, replaceAll=True) # rms_smiles = Chem.MolToSmiles(rms[0],True) # mol = Chem.MolFromSmiles(rms_smiles) mol = rms[0] # print Chem.MolToSmiles(mol,True) if replaced: return (mol, True) #Chem.MolToSmiles(mol,True) else: return (mol, False) # _reactions=None # def NeutraliseCharges(smiles, reactions=None): # global _reactions # if reactions is None: # if _reactions is None: # _reactions=_InitialiseNeutralisationReactions() # reactions=_reactions # mol = Chem.MolFromSmiles(smiles) # replaced = False # for i,(reactant, product) in enumerate(reactions): # while mol.HasSubstructMatch(reactant): # replaced = True # rms = AllChem.ReplaceSubstructs(mol, reactant, product) # mol = rms[0] # if replaced: # return (Chem.MolToSmiles(mol,True), True) # else: # return (smiles, False)
#!/usr/bin/python2.4 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''The 'grit resize' tool. ''' import getopt import os import types from grit.tool import interface from grit.tool import build from grit import grd_reader from grit import pseudo from grit import util from grit.node import include from grit.node import structure from grit.node import message from grit.format import rc_header # Template for the .vcproj file, with a couple of [[REPLACEABLE]] parts. PROJECT_TEMPLATE = '''\ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.10" Name="[[DIALOG_NAME]]" ProjectGUID="[[PROJECT_GUID]]" Keyword="Win32Proj"> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="1" CharacterSet="2"> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="Resource Files" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"> <File RelativePath=".\[[DIALOG_NAME]].rc"> </File> </Filter> </Files> <Globals> </Globals> </VisualStudioProject>''' # Template for the .rc file with a couple of [[REPLACEABLE]] parts. # TODO(joi) Improve this (and the resource.h template) to allow saving and then # reopening of the RC file in Visual Studio. Currently you can only open it # once and change it, then after you close it you won't be able to reopen it. RC_TEMPLATE = '''\ // Copyright (c) Google Inc. 2005 // All rights reserved. // This file is automatically generated by GRIT and intended for editing // the layout of the dialogs contained in it. Do not edit anything but the // dialogs. Any changes made to translateable portions of the dialogs will // be ignored by GRIT. #include "resource.h" #include <winresrc.h> #ifdef IDC_STATIC #undef IDC_STATIC #endif #define IDC_STATIC (-1) LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page([[CODEPAGE_NUM]]) [[INCLUDES]] [[DIALOGS]] ''' # Template for the resource.h file with a couple of [[REPLACEABLE]] parts. HEADER_TEMPLATE = '''\ // Copyright (c) Google Inc. 2005 // All rights reserved. // This file is automatically generated by GRIT. Do not edit. #pragma once // Edit commands #define ID_EDIT_CLEAR 0xE120 #define ID_EDIT_CLEAR_ALL 0xE121 #define ID_EDIT_COPY 0xE122 #define ID_EDIT_CUT 0xE123 #define ID_EDIT_FIND 0xE124 #define ID_EDIT_PASTE 0xE125 #define ID_EDIT_PASTE_LINK 0xE126 #define ID_EDIT_PASTE_SPECIAL 0xE127 #define ID_EDIT_REPEAT 0xE128 #define ID_EDIT_REPLACE 0xE129 #define ID_EDIT_SELECT_ALL 0xE12A #define ID_EDIT_UNDO 0xE12B #define ID_EDIT_REDO 0xE12C [[DEFINES]] ''' class ResizeDialog(interface.Tool): '''Generates an RC file, header and Visual Studio project that you can use with Visual Studio's GUI resource editor to modify the layout of dialogs for the language of your choice. You then use the RC file, after you resize the dialog, for the language or languages of your choice, using the <skeleton> child of the <structure> node for the dialog. The translateable bits of the dialog will be ignored when you use the <skeleton> node (GRIT will instead use the translateable bits from the original dialog) but the layout changes you make will be used. Note that your layout changes must preserve the order of the translateable elements in the RC file. Usage: grit resize [-f BASEFOLDER] [-l LANG] [-e RCENCODING] DIALOGID* Arguments: DIALOGID The 'name' attribute of a dialog to output for resizing. Zero or more of these parameters can be used. If none are specified, all dialogs from the input .grd file are output. Options: -f BASEFOLDER The project will be created in a subfolder of BASEFOLDER. The name of the subfolder will be the first DIALOGID you specify. Defaults to '.' -l LANG Specifies that the RC file should contain a dialog translated into the language LANG. The default is a cp1252-representable pseudotranslation, because Visual Studio's GUI RC editor only supports single-byte encodings. -c CODEPAGE Code page number to indicate to the RC compiler the encoding of the RC file, default is something reasonable for the language you selected (but this does not work for every single language). See details on codepages below. NOTE that you do not need to specify the codepage unless the tool complains that it's not sure which codepage to use. See the following page for codepage numbers supported by Windows: http://www.microsoft.com/globaldev/reference/wincp.mspx -D NAME[=VAL] Specify a C-preprocessor-like define NAME with optional value VAL (defaults to 1) which will be used to control conditional inclusion of resources. IMPORTANT NOTE: For now, the tool outputs a UTF-8 encoded file for any language that can not be represented in cp1252 (i.e. anything other than Western European languages). You will need to open this file in a text editor and save it using the codepage indicated in the #pragma code_page(XXXX) command near the top of the file, before you open it in Visual Studio. ''' # TODO(joi) It would be cool to have this tool note the Perforce revision # of the original RC file somewhere, such that the <skeleton> node could warn # if the original RC file gets updated without the skeleton file being updated. # TODO(joi) Would be cool to have option to add the files to Perforce def __init__(self): self.lang = pseudo.PSEUDO_LANG self.defines = {} self.base_folder = '.' self.codepage_number = 1252 self.codepage_number_specified_explicitly = False def SetLanguage(self, lang): '''Sets the language code to output things in. ''' self.lang = lang if not self.codepage_number_specified_explicitly: self.codepage_number = util.LanguageToCodepage(lang) def GetEncoding(self): if self.codepage_number == 1200: return 'utf_16' if self.codepage_number == 65001: return 'utf_8' return 'cp%d' % self.codepage_number def ShortDescription(self): return 'Generate a file where you can resize a given dialog.' def Run(self, opts, args): self.SetOptions(opts) own_opts, args = getopt.getopt(args, 'l:f:c:D:') for key, val in own_opts: if key == '-l': self.SetLanguage(val) if key == '-f': self.base_folder = val if key == '-c': self.codepage_number = int(val) self.codepage_number_specified_explicitly = True if key == '-D': name, val = build.ParseDefine(val) self.defines[name] = val res_tree = grd_reader.Parse(opts.input, debug=opts.extra_verbose) res_tree.OnlyTheseTranslations([self.lang]) res_tree.RunGatherers(True) # Dialog IDs are either explicitly listed, or we output all dialogs from the # .grd file dialog_ids = args if not len(dialog_ids): for node in res_tree: if node.name == 'structure' and node.attrs['type'] == 'dialog': dialog_ids.append(node.attrs['name']) self.Process(res_tree, dialog_ids) def Process(self, grd, dialog_ids): '''Outputs an RC file and header file for the dialog 'dialog_id' stored in resource tree 'grd', to self.base_folder, as discussed in this class's documentation. Arguments: grd: grd = grd_reader.Parse(...); grd.RunGatherers() dialog_ids: ['IDD_MYDIALOG', 'IDD_OTHERDIALOG'] ''' grd.SetOutputContext(self.lang, self.defines) project_name = dialog_ids[0] dir_path = os.path.join(self.base_folder, project_name) if not os.path.isdir(dir_path): os.mkdir(dir_path) # If this fails then we're not on Windows (or you don't have the required # win32all Python libraries installed), so what are you doing mucking # about with RC files anyway? :) import pythoncom # Create the .vcproj file project_text = PROJECT_TEMPLATE.replace( '[[PROJECT_GUID]]', str(pythoncom.CreateGuid()) ).replace('[[DIALOG_NAME]]', project_name) fname = os.path.join(dir_path, '%s.vcproj' % project_name) self.WriteFile(fname, project_text) print "Wrote %s" % fname # Create the .rc file # Output all <include> nodes since the dialogs might depend on them (e.g. # for icons and bitmaps). include_items = [] for node in grd: if isinstance(node, include.IncludeNode): formatter = node.ItemFormatter('rc_all') if formatter: include_items.append(formatter.Format(node, self.lang)) rc_text = RC_TEMPLATE.replace('[[CODEPAGE_NUM]]', str(self.codepage_number)) rc_text = rc_text.replace('[[INCLUDES]]', ''.join(include_items)) # Then output the dialogs we have been asked to output. dialogs = [] for dialog_id in dialog_ids: node = grd.GetNodeById(dialog_id) # TODO(joi) Add exception handling for better error reporting formatter = node.ItemFormatter('rc_all') dialogs.append(formatter.Format(node, self.lang)) rc_text = rc_text.replace('[[DIALOGS]]', ''.join(dialogs)) fname = os.path.join(dir_path, '%s.rc' % project_name) self.WriteFile(fname, rc_text, self.GetEncoding()) print "Wrote %s" % fname # Create the resource.h file header_defines = [] for node in grd: formatter = node.ItemFormatter('rc_header') if formatter and not isinstance(formatter, rc_header.TopLevel): header_defines.append(formatter.Format(node, self.lang)) header_text = HEADER_TEMPLATE.replace('[[DEFINES]]', ''.join(header_defines)) fname = os.path.join(dir_path, 'resource.h') self.WriteFile(fname, header_text) print "Wrote %s" % fname def WriteFile(self, filename, contents, encoding='cp1252'): f = util.WrapOutputStream(file(filename, 'wb'), encoding) f.write(contents) f.close()
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2014 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import functools import operator import sys import types __author__ = "Benjamin Peterson <benjamin@python.org>" __version__ = "1.7.3" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. # This is a bit ugly, but it avoids running this again. delattr(obj.__class__, self.name) return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) else: def iterkeys(d, **kw): return iter(d.iterkeys(**kw)) def itervalues(d, **kw): return iter(d.itervalues(**kw)) def iteritems(d, **kw): return iter(d.iteritems(**kw)) def iterlists(d, **kw): return iter(d.iterlists(**kw)) _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr if sys.version_info[1] <= 1: def int2byte(i): return bytes((i,)) else: # This is about 2x faster than the implementation above on 3.2+ int2byte = operator.methodcaller("to_bytes", 1, "big") byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) def iterbytes(buf): return (ord(byte) for byte in buf) import StringIO StringIO = BytesIO = StringIO.StringIO _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
# -*- coding: utf-8 -*- """ requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import os.path import socket from urllib3.poolmanager import PoolManager, proxy_from_url from urllib3.response import HTTPResponse from urllib3.util import parse_url from urllib3.util import Timeout as TimeoutSauce from urllib3.util.retry import Retry from urllib3.exceptions import ClosedPoolError from urllib3.exceptions import ConnectTimeoutError from urllib3.exceptions import HTTPError as _HTTPError from urllib3.exceptions import InvalidHeader as _InvalidHeader from urllib3.exceptions import MaxRetryError from urllib3.exceptions import NewConnectionError from urllib3.exceptions import ProxyError as _ProxyError from urllib3.exceptions import ProtocolError from urllib3.exceptions import ReadTimeoutError from urllib3.exceptions import SSLError as _SSLError from urllib3.exceptions import ResponseError from urllib3.exceptions import LocationValueError from .models import Response from .compat import urlparse, basestring from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths, get_encoding_from_headers, prepend_scheme_if_needed, get_auth_from_url, urldefragauth, select_proxy) from .structures import CaseInsensitiveDict from .cookies import extract_cookies_to_jar from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError, ProxyError, RetryError, InvalidSchema, InvalidProxyURL, InvalidURL, InvalidHeader) from .auth import _basic_auth_str try: from urllib3.contrib.socks import SOCKSProxyManager except ImportError: def SOCKSProxyManager(*args, **kwargs): raise InvalidSchema("Missing dependencies for SOCKS support.") DEFAULT_POOLBLOCK = False DEFAULT_POOLSIZE = 10 DEFAULT_RETRIES = 0 DEFAULT_POOL_TIMEOUT = None class BaseAdapter(object): """The Base Transport Adapter""" def __init__(self): super(BaseAdapter, self).__init__() def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError def close(self): """Cleans up adapter specific items.""" raise NotImplementedError class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the :class:`Session <Session>` class under the covers. :param pool_connections: The number of urllib3 connection pools to cache. :param pool_maxsize: The maximum number of connections to save in the pool. :param max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3's ``Retry`` class and pass that instead. :param pool_block: Whether the connection pool should block for connections. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize', '_pool_block'] def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super(HTTPAdapter, self).__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager(self._pool_connections, self._pool_maxsize, block=self._pool_block) def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs) def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith('https') and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise IOError("Could not find a suitable TLS CA certificate bundle, " "invalid path: {}".format(cert_loc)) conn.cert_reqs = 'CERT_REQUIRED' if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise IOError("Could not find the TLS certificate file, " "invalid path: {}".format(conn.cert_file)) if conn.key_file and not os.path.exists(conn.key_file): raise IOError("Could not find the TLS key file, " "invalid path: {}".format(conn.key_file)) def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear() def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) chunked = not (request.body is None or 'Content-Length' in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError as e: # this may raise a string formatting error. err = ("Invalid timeout {}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: skip_host = 'Host' in request.headers low_conn.putrequest(request.method, url, skip_accept_encoding=True, skip_host=skip_host) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode('utf-8')) low_conn.send(b'\r\n') low_conn.send(i) low_conn.send(b'\r\n') low_conn.send(b'0\r\n\r\n') # Receive the response from the server try: # For Python 2.7, use buffering of HTTP responses r = low_conn.getresponse(buffering=True) except TypeError: # For compatibility with Python 3.3+ r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False ) except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)
#!/usr/bin/env python # # Copyright 2013, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import unittest from vtdb import vtgate_client import environment import tablet import utils from protocols_flavor import protocols_flavor SHARDED_KEYSPACE = 'TEST_KEYSPACE_SHARDED' UNSHARDED_KEYSPACE = 'TEST_KEYSPACE_UNSHARDED' # shards for SHARDED_KEYSPACE # range '' - 80 shard_0_master = tablet.Tablet() shard_0_replica = tablet.Tablet() # range 80 - '' shard_1_master = tablet.Tablet() shard_1_replica = tablet.Tablet() # shard for UNSHARDED_KEYSPACE unsharded_master = tablet.Tablet() unsharded_replica = tablet.Tablet() shard_names = ['-80', '80-'] shard_kid_map = { '-80': [527875958493693904, 626750931627689502, 345387386794260318, 332484755310826578, 1842642426274125671, 1326307661227634652, 1761124146422844620, 1661669973250483744, 3361397649937244239, 2444880764308344533], '80-': [9767889778372766922, 9742070682920810358, 10296850775085416642, 9537430901666854108, 10440455099304929791, 11454183276974683945, 11185910247776122031, 10460396697869122981, 13379616110062597001, 12826553979133932576], } create_vt_insert_test = '''create table vt_insert_test ( id bigint auto_increment, msg varchar(64), keyspace_id bigint(20) unsigned NOT NULL, primary key (id) ) Engine=InnoDB''' def setUpModule(): try: environment.topo_server().setup() setup_procs = [ shard_0_master.init_mysql(), shard_0_replica.init_mysql(), shard_1_master.init_mysql(), shard_1_replica.init_mysql(), unsharded_master.init_mysql(), unsharded_replica.init_mysql(), ] utils.wait_procs(setup_procs) setup_tablets() except: tearDownModule() raise def tearDownModule(): if utils.options.skip_teardown: return tablet.kill_tablets([shard_0_master, shard_0_replica, shard_1_master, shard_1_replica]) teardown_procs = [ shard_0_master.teardown_mysql(), shard_0_replica.teardown_mysql(), shard_1_master.teardown_mysql(), shard_1_replica.teardown_mysql(), unsharded_master.teardown_mysql(), unsharded_replica.teardown_mysql(), ] utils.wait_procs(teardown_procs, raise_on_error=False) environment.topo_server().teardown() utils.kill_sub_processes() utils.remove_tmp_files() shard_0_master.remove_tree() shard_0_replica.remove_tree() shard_1_master.remove_tree() shard_1_replica.remove_tree() unsharded_master.remove_tree() unsharded_replica.remove_tree() def setup_tablets(): setup_sharded_keyspace() setup_unsharded_keyspace() utils.VtGate().start() def setup_sharded_keyspace(): utils.run_vtctl(['CreateKeyspace', SHARDED_KEYSPACE]) utils.run_vtctl(['SetKeyspaceShardingInfo', '-force', SHARDED_KEYSPACE, 'keyspace_id', 'uint64']) shard_0_master.init_tablet('master', keyspace=SHARDED_KEYSPACE, shard='-80') shard_0_replica.init_tablet( 'replica', keyspace=SHARDED_KEYSPACE, shard='-80') shard_1_master.init_tablet('master', keyspace=SHARDED_KEYSPACE, shard='80-') shard_1_replica.init_tablet( 'replica', keyspace=SHARDED_KEYSPACE, shard='80-') utils.run_vtctl(['RebuildKeyspaceGraph', SHARDED_KEYSPACE,], auto_log=True) for t in [shard_0_master, shard_0_replica, shard_1_master, shard_1_replica]: t.create_db('vt_test_keyspace_sharded') t.mquery(shard_0_master.dbname, create_vt_insert_test) t.start_vttablet(wait_for_state=None) for t in [shard_0_master, shard_0_replica, shard_1_master, shard_1_replica]: t.wait_for_vttablet_state('SERVING') utils.run_vtctl(['InitShardMaster', '%s/-80' % SHARDED_KEYSPACE, shard_0_master.tablet_alias], auto_log=True) utils.run_vtctl(['InitShardMaster', '%s/80-' % SHARDED_KEYSPACE, shard_1_master.tablet_alias], auto_log=True) utils.run_vtctl(['RebuildKeyspaceGraph', SHARDED_KEYSPACE], auto_log=True) utils.check_srv_keyspace('test_nj', SHARDED_KEYSPACE, 'Partitions(master): -80 80-\n' 'Partitions(rdonly): -80 80-\n' 'Partitions(replica): -80 80-\n') def setup_unsharded_keyspace(): utils.run_vtctl(['CreateKeyspace', UNSHARDED_KEYSPACE]) utils.run_vtctl(['SetKeyspaceShardingInfo', '-force', UNSHARDED_KEYSPACE, 'keyspace_id', 'uint64']) unsharded_master.init_tablet( 'master', keyspace=UNSHARDED_KEYSPACE, shard='0') unsharded_replica.init_tablet( 'replica', keyspace=UNSHARDED_KEYSPACE, shard='0') utils.run_vtctl(['RebuildKeyspaceGraph', UNSHARDED_KEYSPACE,], auto_log=True) for t in [unsharded_master, unsharded_replica]: t.create_db('vt_test_keyspace_unsharded') t.mquery(unsharded_master.dbname, create_vt_insert_test) t.start_vttablet(wait_for_state=None) for t in [unsharded_master, unsharded_replica]: t.wait_for_vttablet_state('SERVING') utils.run_vtctl(['InitShardMaster', '%s/0' % UNSHARDED_KEYSPACE, unsharded_master.tablet_alias], auto_log=True) utils.run_vtctl(['RebuildKeyspaceGraph', UNSHARDED_KEYSPACE], auto_log=True) utils.check_srv_keyspace('test_nj', UNSHARDED_KEYSPACE, 'Partitions(master): -\n' 'Partitions(rdonly): -\n' 'Partitions(replica): -\n') ALL_DB_TYPES = ['master', 'rdonly', 'replica'] class TestKeyspace(unittest.TestCase): def _read_srv_keyspace(self, keyspace_name): addr = utils.vtgate.rpc_endpoint() protocol = protocols_flavor().vtgate_python_protocol() conn = vtgate_client.connect(protocol, addr, 30.0) result = conn.get_srv_keyspace(keyspace_name) conn.close() return result def test_get_keyspace(self): ki = utils.run_vtctl_json(['GetKeyspace', UNSHARDED_KEYSPACE]) self.assertEqual('keyspace_id', ki['sharding_column_name']) self.assertEqual(1, ki['sharding_column_type']) def test_delete_keyspace(self): utils.run_vtctl(['CreateKeyspace', 'test_delete_keyspace']) utils.run_vtctl(['CreateShard', 'test_delete_keyspace/0']) utils.run_vtctl( ['InitTablet', '-keyspace=test_delete_keyspace', '-shard=0', 'test_nj-0000000100', 'master']) # Can't delete keyspace if there are shards present. utils.run_vtctl( ['DeleteKeyspace', 'test_delete_keyspace'], expect_fail=True) # Can't delete shard if there are tablets present. utils.run_vtctl(['DeleteShard', 'test_delete_keyspace/0'], expect_fail=True) # Use recursive DeleteShard to remove tablets. utils.run_vtctl(['DeleteShard', '-recursive', 'test_delete_keyspace/0']) # Now non-recursive DeleteKeyspace should work. utils.run_vtctl(['DeleteKeyspace', 'test_delete_keyspace']) # Start over and this time use recursive DeleteKeyspace to do everything. utils.run_vtctl(['CreateKeyspace', 'test_delete_keyspace']) utils.run_vtctl(['CreateShard', 'test_delete_keyspace/0']) utils.run_vtctl( ['InitTablet', '-port=1234', '-keyspace=test_delete_keyspace', '-shard=0', 'test_nj-0000000100', 'master']) # Create the serving/replication entries and check that they exist, # so we can later check they're deleted. utils.run_vtctl(['RebuildKeyspaceGraph', 'test_delete_keyspace']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0']) utils.run_vtctl(['GetSrvKeyspace', 'test_nj', 'test_delete_keyspace']) utils.run_vtctl(['GetSrvShard', 'test_nj', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/0', 'master']) # Recursive DeleteKeyspace utils.run_vtctl(['DeleteKeyspace', '-recursive', 'test_delete_keyspace']) # Check that everything is gone. utils.run_vtctl(['GetKeyspace', 'test_delete_keyspace'], expect_fail=True) utils.run_vtctl(['GetShard', 'test_delete_keyspace/0'], expect_fail=True) utils.run_vtctl(['GetTablet', 'test_nj-0000000100'], expect_fail=True) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0'], expect_fail=True) utils.run_vtctl( ['GetSrvKeyspace', 'test_nj', 'test_delete_keyspace'], expect_fail=True) utils.run_vtctl( ['GetSrvShard', 'test_nj', 'test_delete_keyspace/0'], expect_fail=True) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/0', 'master'], expect_fail=True) def test_remove_keyspace_cell(self): utils.run_vtctl(['CreateKeyspace', 'test_delete_keyspace']) utils.run_vtctl(['CreateShard', 'test_delete_keyspace/0']) utils.run_vtctl(['CreateShard', 'test_delete_keyspace/1']) utils.run_vtctl( ['InitTablet', '-port=1234', '-keyspace=test_delete_keyspace', '-shard=0', 'test_ca-0000000100', 'master']) utils.run_vtctl( ['InitTablet', '-port=1234', '-keyspace=test_delete_keyspace', '-shard=0', 'test_nj-0000000100', 'replica']) utils.run_vtctl( ['InitTablet', '-port=1234', '-keyspace=test_delete_keyspace', '-shard=1', 'test_nj-0000000101', 'replica']) # Create the serving/replication entries and check that they exist, # so we can later check they're deleted. utils.run_vtctl(['RebuildKeyspaceGraph', 'test_delete_keyspace']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/0']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/1']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/1']) utils.run_vtctl(['GetSrvKeyspace', 'test_nj', 'test_delete_keyspace']) utils.run_vtctl(['GetSrvShard', 'test_nj', 'test_delete_keyspace/0']) utils.run_vtctl(['GetSrvShard', 'test_nj', 'test_delete_keyspace/1']) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/0', 'replica']) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/1', 'replica']) # Just remove the shard from one cell (including tablets), # but leaving the global records and other cells/shards alone. utils.run_vtctl( ['RemoveShardCell', '-recursive', 'test_delete_keyspace/0', 'test_nj']) utils.run_vtctl(['RebuildKeyspaceGraph', 'test_delete_keyspace']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/0']) utils.run_vtctl(['GetKeyspace', 'test_delete_keyspace']) utils.run_vtctl(['GetShard', 'test_delete_keyspace/0']) utils.run_vtctl(['GetTablet', 'test_ca-0000000100']) utils.run_vtctl(['GetTablet', 'test_nj-0000000100'], expect_fail=True) utils.run_vtctl(['GetTablet', 'test_nj-0000000101']) utils.run_vtctl( ['GetShardReplication', 'test_ca', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0'], expect_fail=True) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/1']) utils.run_vtctl(['GetSrvKeyspace', 'test_nj', 'test_delete_keyspace']) utils.run_vtctl(['GetSrvShard', 'test_nj', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/1', 'replica']) utils.run_vtctl( ['GetEndPoints', 'test_nj', 'test_delete_keyspace/0', 'replica'], expect_fail=True) # Add it back to do another test. utils.run_vtctl( ['InitTablet', '-port=1234', '-keyspace=test_delete_keyspace', '-shard=0', 'test_nj-0000000100', 'replica']) utils.run_vtctl(['RebuildKeyspaceGraph', 'test_delete_keyspace']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0']) # Now use RemoveKeyspaceCell to remove all shards. utils.run_vtctl( ['RemoveKeyspaceCell', '-recursive', 'test_delete_keyspace', 'test_nj']) utils.run_vtctl(['RebuildKeyspaceGraph', 'test_delete_keyspace']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/0']) utils.run_vtctl(['RebuildShardGraph', 'test_delete_keyspace/1']) utils.run_vtctl( ['GetShardReplication', 'test_ca', 'test_delete_keyspace/0']) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/0'], expect_fail=True) utils.run_vtctl( ['GetShardReplication', 'test_nj', 'test_delete_keyspace/1'], expect_fail=True) # Clean up. utils.run_vtctl(['DeleteKeyspace', '-recursive', 'test_delete_keyspace']) def test_shard_count(self): sharded_ks = self._read_srv_keyspace(SHARDED_KEYSPACE) for db_type in ALL_DB_TYPES: self.assertEqual(sharded_ks.get_shard_count(db_type), 2) unsharded_ks = self._read_srv_keyspace(UNSHARDED_KEYSPACE) for db_type in ALL_DB_TYPES: self.assertEqual(unsharded_ks.get_shard_count(db_type), 1) def test_shard_names(self): sharded_ks = self._read_srv_keyspace(SHARDED_KEYSPACE) for db_type in ALL_DB_TYPES: self.assertEqual(sharded_ks.get_shard_names(db_type), ['-80', '80-']) unsharded_ks = self._read_srv_keyspace(UNSHARDED_KEYSPACE) for db_type in ALL_DB_TYPES: self.assertEqual(unsharded_ks.get_shard_names(db_type), ['0']) def test_keyspace_id_to_shard_name(self): sharded_ks = self._read_srv_keyspace(SHARDED_KEYSPACE) for _, sn in enumerate(shard_names): for keyspace_id in shard_kid_map[sn]: self.assertEqual( sharded_ks.keyspace_id_to_shard_name_for_db_type(keyspace_id, 'master'), sn) unsharded_ks = self._read_srv_keyspace(UNSHARDED_KEYSPACE) for keyspace_id in shard_kid_map[sn]: self.assertEqual( unsharded_ks.keyspace_id_to_shard_name_for_db_type( keyspace_id, 'master'), '0') def test_get_srv_keyspace_names(self): stdout, _ = utils.run_vtctl(['GetSrvKeyspaceNames', 'test_nj'], trap_output=True) self.assertEqual( set(stdout.splitlines()), {SHARDED_KEYSPACE, UNSHARDED_KEYSPACE}) if __name__ == '__main__': utils.main()
from collections import defaultdict from email.Utils import formatdate import re from string import Template import sys from time import time from urlparse import parse_qsl from django.core.management import setup_environ import commonware.log import jinja2 from utils import log_configure import settings_local as settings setup_environ(settings) # This has to be imported after the settings so statsd knows where to log to. from django_statsd.clients import statsd # Go configure the log. log_configure() error_log = commonware.log.getLogger('z.pfs') xml_template = """\ <?xml version="1.0"?> <RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:pfs="http://www.mozilla.org/2004/pfs-rdf#"> <RDF:Description about="urn:mozilla:plugin-results:$mimetype"> <pfs:plugins><RDF:Seq> <RDF:li resource="urn:mozilla:plugin:$guid"/> </RDF:Seq></pfs:plugins> </RDF:Description> <RDF:Description about="urn:mozilla:plugin:$guid"> <pfs:updates><RDF:Seq> <RDF:li resource="urn:mozilla:plugin:$guid:$version"/> </RDF:Seq></pfs:updates> </RDF:Description> <RDF:Description about="urn:mozilla:plugin:$guid:$version"> <pfs:name>$name</pfs:name> <pfs:requestedMimetype>$mimetype</pfs:requestedMimetype> <pfs:guid>$guid</pfs:guid> <pfs:version>$version</pfs:version> <pfs:IconUrl>$iconUrl</pfs:IconUrl> <pfs:InstallerLocation>$InstallerLocation</pfs:InstallerLocation> <pfs:InstallerHash>$InstallerHash</pfs:InstallerHash> <pfs:XPILocation>$XPILocation</pfs:XPILocation> <pfs:InstallerShowsUI>$InstallerShowsUI</pfs:InstallerShowsUI> <pfs:manualInstallationURL>$manualInstallationURL</pfs:manualInstallationURL> <pfs:licenseURL>$licenseURL</pfs:licenseURL> <pfs:needsRestart>$needsRestart</pfs:needsRestart> </RDF:Description> </RDF:RDF> """ flash_re = re.compile(r'^(Win|(PPC|Intel) Mac OS X|Linux.+(x86_64|i\d86))|SunOs', re.IGNORECASE) quicktime_re = re.compile(r'^(application/(sdp|x-(mpeg|rtsp|sdp))|audio/(3gpp(2)?|AMR|aiff|basic|mid(i)?|mp4|mpeg|vnd\.qcelp|wav|x-(aiff|m4(a|b|p)|midi|mpeg|wav))|image/(pict|png|tiff|x-(macpaint|pict|png|quicktime|sgi|targa|tiff))|video/(3gpp(2)?|flc|mp4|mpeg|quicktime|sd-video|x-mpeg))$') java_re = re.compile(r'^application/x-java-((applet|bean)(;jpi-version=1\.5|;version=(1\.(1(\.[1-3])?|(2|4)(\.[1-2])?|3(\.1)?|5)))?|vm)$') wmp_re = re.compile(r'^(application/(asx|x-(mplayer2|ms-wmp))|video/x-ms-(asf(-plugin)?|wm(p|v|x)?|wvx)|audio/x-ms-w(ax|ma))$') def get_output(data): g = defaultdict(str, [(k, jinja2.escape(v)) for k, v in data.iteritems()]) required = ['mimetype', 'appID', 'appVersion', 'clientOS', 'chromeLocale'] # Some defaults we override depending on what we find below. plugin = dict(mimetype='-1', name='-1', guid='-1', version='', iconUrl='', XPILocation='', InstallerLocation='', InstallerHash='', InstallerShowsUI='', manualInstallationURL='', licenseURL='', needsRestart='true') # Special case for mimetype if they are provided. plugin['mimetype'] = g['mimetype'] or '-1' output = Template(xml_template) for s in required: if s not in data: # A sort of 404, matching what was returned in the original PHP. return output.substitute(plugin) # Figure out what plugins we've got, and what plugins we know where # to get. # Begin our huge and embarrassing if-else statement. if (g['mimetype'] in ['application/x-shockwave-flash', 'application/futuresplash'] and re.match(flash_re, g['clientOS'])): # Tell the user where they can go to get the installer. plugin.update( name='Adobe Flash Player', manualInstallationURL='http://www.adobe.com/go/getflashplayer') # Offer Windows users a specific flash plugin installer instead. # Don't use a https URL for the license here, per request from # Macromedia. if g['clientOS'].startswith('Win'): plugin.update( guid='{4cfaef8a-a6c9-41a0-8e6f-967eb8f49143}', XPILocation='', iconUrl='http://fpdownload2.macromedia.com/pub/flashplayer/current/fp_win_installer.ico', needsRestart='false', InstallerShowsUI='true', version='11.9.900.152', InstallerHash='sha256:68ef5992a658e1304fcb4d556c770fb9f381928c5de1e133f3a741b51d9671cf', InstallerLocation='http://download.macromedia.com/pub/flashplayer/pdc/fp_pl_pfs_installer.exe') elif (g['mimetype'] == 'application/x-director' and g['clientOS'].startswith('Win')): plugin.update( name='Adobe Shockwave Player', manualInstallationURL='http://get.adobe.com/shockwave/') # Even though the shockwave installer is not a silent installer, we # need to show its EULA here since we've got a slimmed down # installer that doesn't do that itself. if g['chromeLocale'] != 'ja-JP': plugin.update( licenseURL='http://www.adobe.com/go/eula_shockwaveplayer') else: plugin.update( licenseURL='http://www.adobe.com/go/eula_shockwaveplayer_jp') plugin.update( guid='{45f2a22c-4029-4209-8b3d-1421b989633f}', XPILocation='', version='12.0.5.146', InstallerHash='sha256:eb6e5fb375c7e2f75c14d8678c595569bfc3da5fb5b1a7a0b293197867e42545', InstallerLocation='http://fpdownload.macromedia.com/pub/shockwave/default/english/win95nt/latest/Shockwave_Installer_FF.exe', needsRestart='false', InstallerShowsUI='false') elif (g['mimetype'] in ['audio/x-pn-realaudio-plugin', 'audio/x-pn-realaudio'] and re.match(r'^(Win|Linux|PPC Mac OS X)', g['clientOS'])): plugin.update( name='Real Player', version='10.5', manualInstallationURL='http://www.real.com') if g['clientOS'].startswith('Win'): plugin.update( XPILocation='http://forms.real.com/real/player/download.html?type=firefox', guid='{d586351c-cb55-41a7-8e7b-4aaac5172d39}') else: plugin.update( guid='{269eb771-59de-4702-9209-ca97ce522f6d}') elif (re.match(quicktime_re, g['mimetype']) and re.match(r'^(Win|PPC Mac OS X)', g['clientOS'])): # Well, we don't have a plugin that can handle any of those # mimetypes, but the Apple Quicktime plugin can. Point the user to # the Quicktime download page. plugin.update( name='Apple Quicktime', guid='{a42bb825-7eee-420f-8ee7-834062b6fefd}', InstallerShowsUI='true', manualInstallationURL='http://www.apple.com/quicktime/download/') elif (re.match(java_re, g['mimetype']) and re.match(r'^(Win|Linux|PPC Mac OS X)', g['clientOS'])): # We serve up the Java plugin for the following mimetypes: # # application/x-java-vm # application/x-java-applet;jpi-version=1.5 # application/x-java-bean;jpi-version=1.5 # application/x-java-applet;version=1.3 # application/x-java-bean;version=1.3 # application/x-java-applet;version=1.2.2 # application/x-java-bean;version=1.2.2 # application/x-java-applet;version=1.2.1 # application/x-java-bean;version=1.2.1 # application/x-java-applet;version=1.4.2 # application/x-java-bean;version=1.4.2 # application/x-java-applet;version=1.5 # application/x-java-bean;version=1.5 # application/x-java-applet;version=1.3.1 # application/x-java-bean;version=1.3.1 # application/x-java-applet;version=1.4 # application/x-java-bean;version=1.4 # application/x-java-applet;version=1.4.1 # application/x-java-bean;version=1.4.1 # application/x-java-applet;version=1.2 # application/x-java-bean;version=1.2 # application/x-java-applet;version=1.1.3 # application/x-java-bean;version=1.1.3 # application/x-java-applet;version=1.1.2 # application/x-java-bean;version=1.1.2 # application/x-java-applet;version=1.1.1 # application/x-java-bean;version=1.1.1 # application/x-java-applet;version=1.1 # application/x-java-bean;version=1.1 # application/x-java-applet # application/x-java-bean # # # We don't want to link users directly to the Java plugin because # we want to warn them about ongoing security problems first. Link # to SUMO. plugin.update( name='Java Runtime Environment', manualInstallationURL='https://support.mozilla.org/kb/use-java-plugin-to-view-interactive-content', needsRestart='false', guid='{fbe640ef-4375-4f45-8d79-767d60bf75b8}') elif (g['mimetype'] in ['application/pdf', 'application/vnd.fdf', 'application/vnd.adobe.xfdf', 'application/vnd.adobe.xdp+xml', 'application/vnd.adobe.xfd+xml'] and re.match(r'^(Win|PPC Mac OS X|Linux(?! x86_64))', g['clientOS'])): plugin.update( name='Adobe Acrobat Plug-In', guid='{d87cd824-67cb-4547-8587-616c70318095}', manualInstallationURL='http://www.adobe.com/products/acrobat/readstep.html') elif (g['mimetype'] == 'application/x-mtx' and re.match(r'^(Win|PPC Mac OS X)', g['clientOS'])): plugin.update( name='Viewpoint Media Player', guid='{03f998b2-0e00-11d3-a498-00104b6eb52e}', manualInstallationURL='http://www.viewpoint.com/pub/products/vmp.html') elif re.match(wmp_re, g['mimetype']): # We serve up the Windows Media Player plugin for the following # mimetypes: # # application/asx # application/x-mplayer2 # audio/x-ms-wax # audio/x-ms-wma # video/x-ms-asf # video/x-ms-asf-plugin # video/x-ms-wm # video/x-ms-wmp # video/x-ms-wmv # video/x-ms-wmx # video/x-ms-wvx # # For all windows users who don't have the WMP 11 plugin, give them # a link for it. if g['clientOS'].startswith('Win'): plugin.update( name='Windows Media Player', version='11', guid='{cff1240a-fd24-4b9f-8183-ccd96e5300d0}', manualInstallationURL='http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx') # For OSX users -- added Intel to this since flip4mac is a UB. # Contact at MS was okay w/ this, plus MS points to this anyway. elif re.match(r'^(PPC|Intel) Mac OS X', g['clientOS']): plugin.update( name='Flip4Mac', version='2.1', guid='{cff0240a-fd24-4b9f-8183-ccd96e5300d0}', manualInstallationURL='http://www.flip4mac.com/wmv_download.htm') elif (g['mimetype'] == 'application/x-xstandard' and re.match(r'^(Win|PPC Mac OS X)', g['clientOS'])): plugin.update( name='XStandard XHTML WYSIWYG Editor', guid='{3563d917-2f44-4e05-8769-47e655e92361}', iconUrl='http://xstandard.com/images/xicon32x32.gif', XPILocation='http://xstandard.com/download/xstandard.xpi', InstallerShowsUI='false', manualInstallationURL='http://xstandard.com/download/', licenseURL='http://xstandard.com/license/') elif (g['mimetype'] == 'application/x-dnl' and g['clientOS'].startswith('Win')): plugin.update( name='DNL Reader', guid='{ce9317a3-e2f8-49b9-9b3b-a7fb5ec55161}', version='5.5', iconUrl='http://digitalwebbooks.com/reader/dwb16.gif', XPILocation='http://digitalwebbooks.com/reader/xpinst.xpi', InstallerShowsUI='false', manualInstallationURL='http://digitalwebbooks.com/reader/') elif (g['mimetype'] == 'application/x-videoegg-loader' and g['clientOS'].startswith('Win')): plugin.update( name='VideoEgg Publisher', guid='{b8b881f0-2e07-11db-a98b-0800200c9a66}', iconUrl='http://videoegg.com/favicon.ico', XPILocation='http://update.videoegg.com/Install/Windows/Initial/VideoEggPublisher.xpi', InstallerShowsUI='true', manualInstallationURL='http://www.videoegg.com/') elif (g['mimetype'] == 'video/vnd.divx' and g['clientOS'].startswith('Win')): plugin.update( name='DivX Web Player', guid='{a8b771f0-2e07-11db-a98b-0800200c9a66}', iconUrl='http://images.divx.com/divx/player/webplayer.png', XPILocation='http://download.divx.com/player/DivXWebPlayer.xpi', InstallerShowsUI='false', licenseURL='http://go.divx.com/plugin/license/', manualInstallationURL='http://go.divx.com/plugin/download/') elif (g['mimetype'] == 'video/vnd.divx' and re.match(r'^(PPC|Intel) Mac OS X', g['clientOS'])): plugin.update( name='DivX Web Player', guid='{a8b771f0-2e07-11db-a98b-0800200c9a66}', iconUrl='http://images.divx.com/divx/player/webplayer.png', XPILocation='http://download.divx.com/player/DivXWebPlayerMac.xpi', InstallerShowsUI='false', licenseURL='http://go.divx.com/plugin/license/', manualInstallationURL='http://go.divx.com/plugin/download/') # End ridiculously huge and embarrassing if-else block. return output.substitute(plugin) def format_date(secs): return '%s GMT' % formatdate(time() + secs)[:25] def get_headers(length): return [('Content-Type', 'text/xml; charset=utf-8'), ('Cache-Control', 'public, max-age=3600'), ('Last-Modified', format_date(0)), ('Expires', format_date(3600)), ('Content-Length', str(length))] def log_exception(data): (typ, value, traceback) = sys.exc_info() error_log.error(u'Type: %s, %s. Query: %s' % (typ, value, data)) def application(environ, start_response): status = '200 OK' with statsd.timer('services.pfs'): data = dict(parse_qsl(environ['QUERY_STRING'])) try: output = get_output(data).encode('utf-8') start_response(status, get_headers(len(output))) except: log_exception(data) raise return [output]
#!/usr/bin/env python # coding: utf-8 import dask from dask import delayed from dask.distributed import Client import dask.dataframe as dd import json import numpy as np import pandas as pd import geopandas from shapely.geometry import Point import os import sys import joblib dtype_list = { # 'dropoff_datetime': object, # set by parse_dates in pandas read_csv 'dropoff_latitude': np.float64, 'dropoff_taxizone_id': np.float64, 'dropoff_longitude': np.float64, 'ehail_fee': np.float64, 'extra': np.float64, 'fare_amount': np.float64, 'improvement_surcharge': np.float64, 'junk1': object, 'junk2': object, 'mta_tax': np.float64, 'passenger_count': object, 'payment_type': object, # 'pickup_datetime': object, # set by parse_dates in pandas read_csv 'pickup_latitude': np.float64, 'pickup_taxizone_id': np.float64, 'pickup_longitude': np.float64, 'rate_code_id': object, 'store_and_fwd_flag': object, 'tip_amount': np.float64, 'tolls_amount': np.float64, 'total_amount': np.float64, 'trip_distance': np.float64, 'trip_type': object, 'vendor_id': object } with open('config.json', 'r') as fh: config = json.load(fh) def glob(x): from glob import glob return sorted(glob(x)) def trymakedirs(path): try: os.makedirs(path) except: pass def assign_taxi_zones(df, lon_var, lat_var, locid_var): """Joins DataFrame with Taxi Zones shapefile. This function takes longitude values provided by `lon_var`, and latitude values provided by `lat_var` in DataFrame `df`, and performs a spatial join with the NYC taxi_zones shapefile. The shapefile is hard coded in, as this function makes a hard assumption of latitude and longitude coordinates. It also assumes latitude=0 and longitude=0 is not a datapoint that can exist in your dataset. Which is reasonable for a dataset of New York, but bad for a global dataset. Only rows where `df.lon_var`, `df.lat_var` are reasonably near New York, and `df.locid_var` is set to np.nan are updated. Parameters ---------- df : pandas.DataFrame or dask.DataFrame DataFrame containing latitudes, longitudes, and location_id columns. lon_var : string Name of column in `df` containing longitude values. Invalid values should be np.nan. lat_var : string Name of column in `df` containing latitude values. Invalid values should be np.nan locid_var : string Name of column in `df` containing taxi_zone location ids. Rows with valid, nonzero values are not overwritten. """ import geopandas from shapely.geometry import Point localdf = df[[lon_var, lat_var, locid_var]].copy() # localdf = localdf.reset_index() localdf[lon_var] = localdf[lon_var].fillna(value=0.) localdf[lat_var] = localdf[lat_var].fillna(value=0.) localdf['replace_locid'] = (localdf[locid_var].isnull() & (localdf[lon_var] != 0.) & (localdf[lat_var] != 0.)) if (np.any(localdf['replace_locid'])): shape_df = geopandas.read_file('../shapefiles/taxi_zones.shp') shape_df.drop(['OBJECTID', "Shape_Area", "Shape_Leng", "borough", "zone"], axis=1, inplace=True) shape_df = shape_df.to_crs({'init': 'epsg:4326'}) try: local_gdf = geopandas.GeoDataFrame( localdf, crs={'init': 'epsg:4326'}, geometry=[Point(xy) for xy in zip(localdf[lon_var], localdf[lat_var])]) local_gdf = geopandas.sjoin( local_gdf, shape_df, how='left', op='within') # one point can intersect more than one zone -- for example if on # the boundary between two zones. Deduplicate by taking first valid. local_gdf = local_gdf[~local_gdf.index.duplicated(keep='first')] local_gdf.LocationID.values[~local_gdf.replace_locid] = ( (local_gdf[locid_var])[~local_gdf.replace_locid]).values return local_gdf.LocationID.rename(locid_var) except ValueError as ve: print(ve) print(ve.stacktrace()) return df[locid_var].astype(np.float64) else: return df[locid_var] def get_green(): green_schema_pre_2015 = "vendor_id,pickup_datetime,dropoff_datetime,store_and_fwd_flag,rate_code_id,pickup_longitude,pickup_latitude,dropoff_longitude,dropoff_latitude,passenger_count,trip_distance,fare_amount,extra,mta_tax,tip_amount,tolls_amount,ehail_fee,total_amount,payment_type,trip_type,junk1,junk2" green_glob_pre_2015 = glob( os.path.join(config['taxi_raw_data_path'], 'green_tripdata_201[34]*.csv')) green_schema_2015_h1 = "vendor_id,pickup_datetime,dropoff_datetime,store_and_fwd_flag,rate_code_id,pickup_longitude,pickup_latitude,dropoff_longitude,dropoff_latitude,passenger_count,trip_distance,fare_amount,extra,mta_tax,tip_amount,tolls_amount,ehail_fee,improvement_surcharge,total_amount,payment_type,trip_type,junk1,junk2" green_glob_2015_h1 = glob( os.path.join(config['taxi_raw_data_path'], 'green_tripdata_2015-0[1-6].csv')) green_schema_2015_h2_2016_h1 = "vendor_id,pickup_datetime,dropoff_datetime,store_and_fwd_flag,rate_code_id,pickup_longitude,pickup_latitude,dropoff_longitude,dropoff_latitude,passenger_count,trip_distance,fare_amount,extra,mta_tax,tip_amount,tolls_amount,ehail_fee,improvement_surcharge,total_amount,payment_type,trip_type" green_glob_2015_h2_2016_h1 = glob(os.path.join(config['taxi_raw_data_path'], 'green_tripdata_2015-0[7-9].csv')) + glob(os.path.join( config['taxi_raw_data_path'], 'green_tripdata_2015-1[0-2].csv')) + glob(os.path.join(config['taxi_raw_data_path'], 'green_tripdata_2016-0[1-6].csv')) green_schema_2016_h2 = "vendor_id,pickup_datetime,dropoff_datetime,store_and_fwd_flag,rate_code_id,pickup_taxizone_id,dropoff_taxizone_id,passenger_count,trip_distance,fare_amount,extra,mta_tax,tip_amount,tolls_amount,ehail_fee,improvement_surcharge,total_amount,payment_type,trip_type,junk1,junk2" green_glob_2016_h2 = glob(os.path.join(config['taxi_raw_data_path'], 'green_tripdata_2016-0[7-9].csv')) + glob( os.path.join(config['taxi_raw_data_path'], 'green_tripdata_2016-1[0-2].csv')) # Green green1 = dd.read_csv(green_glob_pre_2015, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=green_schema_pre_2015.split(',')) green1['dropoff_taxizone_id'] = green1['total_amount'].copy() green1['dropoff_taxizone_id'] = np.nan green1['pickup_taxizone_id'] = green1['total_amount'].copy() green1['pickup_taxizone_id'] = np.nan green1['improvement_surcharge'] = green1['total_amount'].copy() green1['improvement_surcharge'] = np.nan green1 = green1.drop(['junk1', 'junk2'], axis=1) green2 = dd.read_csv(green_glob_2015_h1, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=green_schema_2015_h1.split(',')) green2['dropoff_taxizone_id'] = green2['total_amount'].copy() green2['dropoff_taxizone_id'] = np.nan green2['pickup_taxizone_id'] = green2['total_amount'].copy() green2['pickup_taxizone_id'] = np.nan green2 = green2.drop(['junk1', 'junk2'], axis=1) green3 = dd.read_csv(green_glob_2015_h2_2016_h1, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=green_schema_2015_h2_2016_h1.split(',')) green3['dropoff_taxizone_id'] = green3['total_amount'].copy() green3['dropoff_taxizone_id'] = np.nan green3['pickup_taxizone_id'] = green3['total_amount'].copy() green3['pickup_taxizone_id'] = np.nan green4 = dd.read_csv(green_glob_2016_h2, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=green_schema_2016_h2.split(',')) green4['dropoff_latitude'] = green4['total_amount'].copy() green4['dropoff_latitude'] = np.nan green4['dropoff_longitude'] = green4['total_amount'].copy() green4['dropoff_longitude'] = np.nan green4['pickup_latitude'] = green4['total_amount'].copy() green4['pickup_latitude'] = np.nan green4['pickup_longitude'] = green4['total_amount'].copy() green4['pickup_longitude'] = np.nan green4 = green4.drop(['junk1', 'junk2'], axis=1) green = green1[sorted(green1.columns)].append( green2[sorted(green1.columns)]) green = green.append(green3[sorted(green1.columns)]) green = green.append(green4[sorted(green1.columns)]) for field in list(green.columns): if field in dtype_list: green[field] = green[field].astype(dtype_list[field]) green['trip_type'] = 'green' return green def get_yellow(): yellow_schema_pre_2015 = "vendor_id,pickup_datetime,dropoff_datetime,passenger_count,trip_distance,pickup_longitude,pickup_latitude,rate_code_id,store_and_fwd_flag,dropoff_longitude,dropoff_latitude,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,total_amount" yellow_glob_pre_2015 = glob( os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_201[0-4]*.csv')) + glob( os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_2009*.csv')) yellow_schema_2015_2016_h1 = "vendor_id,pickup_datetime,dropoff_datetime,passenger_count,trip_distance,pickup_longitude,pickup_latitude,rate_code_id,store_and_fwd_flag,dropoff_longitude,dropoff_latitude,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount" yellow_glob_2015_2016_h1 = glob(os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_2015*.csv')) + glob( os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_2016-0[1-6].csv')) yellow_schema_2016_h2 = "vendor_id,pickup_datetime,dropoff_datetime,passenger_count,trip_distance,rate_code_id,store_and_fwd_flag,pickup_taxizone_id,dropoff_taxizone_id,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount,junk1,junk2" yellow_glob_2016_h2 = glob(os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_2016-0[7-9].csv')) + glob( os.path.join(config['taxi_raw_data_path'], 'yellow_tripdata_2016-1[0-2].csv')) yellow1 = dd.read_csv(yellow_glob_pre_2015, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=yellow_schema_pre_2015.split(',')) yellow1['dropoff_taxizone_id'] = yellow1['total_amount'].copy() yellow1['dropoff_taxizone_id'] = np.nan yellow1['pickup_taxizone_id'] = yellow1['total_amount'].copy() yellow1['pickup_taxizone_id'] = np.nan yellow1['ehail_fee'] = yellow1['total_amount'].copy() yellow1['ehail_fee'] = np.nan yellow1['improvement_surcharge'] = yellow1['total_amount'].copy() yellow1['improvement_surcharge'] = np.nan yellow1['trip_type'] = yellow1['rate_code_id'].copy() yellow1['trip_type'] = -999 yellow2 = dd.read_csv(yellow_glob_2015_2016_h1, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=yellow_schema_2015_2016_h1.split(',')) yellow2['dropoff_taxizone_id'] = yellow2['rate_code_id'].copy() yellow2['dropoff_taxizone_id'] = np.nan yellow2['pickup_taxizone_id'] = yellow2['rate_code_id'].copy() yellow2['pickup_taxizone_id'] = np.nan yellow2['ehail_fee'] = yellow2['total_amount'].copy() yellow2['ehail_fee'] = np.nan yellow2['trip_type'] = yellow2['rate_code_id'].copy() yellow2['trip_type'] = -999 yellow3 = dd.read_csv(yellow_glob_2016_h2, header=0, na_values=["NA"], parse_dates=[1, 2], infer_datetime_format=True, dtype=dtype_list, names=yellow_schema_2016_h2.split(',')) yellow3['dropoff_latitude'] = yellow3['total_amount'].copy() yellow3['dropoff_latitude'] = np.nan yellow3['dropoff_longitude'] = yellow3['total_amount'].copy() yellow3['dropoff_longitude'] = np.nan yellow3['pickup_latitude'] = yellow3['total_amount'].copy() yellow3['pickup_latitude'] = np.nan yellow3['pickup_longitude'] = yellow3['total_amount'].copy() yellow3['pickup_longitude'] = np.nan yellow3['ehail_fee'] = yellow3['total_amount'].copy() yellow3['ehail_fee'] = np.nan yellow3['trip_type'] = yellow3['rate_code_id'].copy() yellow3['trip_type'] = -999 yellow3 = yellow3.drop(['junk1', 'junk2'], axis=1) yellow = yellow1[sorted(yellow1.columns)].append( yellow2[sorted(yellow1.columns)]) yellow = yellow.append(yellow3[sorted(yellow1.columns)]) for field in list(yellow.columns): if field in dtype_list: yellow[field] = yellow[field].astype(dtype_list[field]) yellow['trip_type'] = 'yellow' return yellow def get_uber(): uber_schema_2014="pickup_datetime,pickup_latitude,pickup_longitude,junk1" uber_glob_2014 = glob(os.path.join(config['uber_raw_data_path'],'uber*-???14.csv')) uber_schema_2015="junk1,pickup_datetime,junk2,pickup_taxizone_id" uber_glob_2015 = glob(os.path.join(config['uber_raw_data_path'],'uber*15.csv')) uber1 = dd.read_csv(uber_glob_2014, header=0, na_values=["NA"], parse_dates=[0,], infer_datetime_format = True, dtype=dtype_list, names=uber_schema_2014.split(',')) uber1 = uber1.drop(['junk1',], axis=1) uber1 = uber1.assign(pickup_taxizone_id=np.nan) uber2 = dd.read_csv(uber_glob_2015, header=0, na_values=["NA"], parse_dates=[1,], infer_datetime_format = True, dtype=dtype_list, names=uber_schema_2015.split(',')) uber2 = uber2.drop(['junk1', 'junk2'], axis=1) uber2 = uber2.assign(pickup_latitude=np.nan, pickup_longitude=np.nan) uber1 = uber1[sorted(uber1.columns)] uber2 = uber2[sorted(uber2.columns)] uberdf = uber1.append(uber2) default_values = {np.float64: np.nan, np.int64: -999, object: ""} for field in dtype_list: if (field in uberdf.columns): uberdf[field] = uberdf[field].astype(dtype_list[field]) elif field == 'pickup_datetime': pass else: uberdf = uberdf.assign(**{field: default_values[dtype_list[field]]}) uberdf = uberdf.drop(['junk1', 'junk2'], axis=1) uberdf['dropoff_datetime'] = np.datetime64("1970-01-01 00:00:00") #uberdf = uberdf.repartition(npartitions=20) uberdf['trip_type'] = 'uber' uberdf = uberdf[sorted(uberdf.columns)] return uberdf def main(client): uber = get_uber() green = get_green() yellow = get_yellow() all_trips = uber.append(green).append(yellow) all_trips['dropoff_taxizone_id'] = all_trips.map_partitions( assign_taxi_zones, "dropoff_longitude", "dropoff_latitude", "dropoff_taxizone_id", meta=('dropoff_taxizone_id', np.float64)) all_trips['pickup_taxizone_id'] = all_trips.map_partitions( assign_taxi_zones, "pickup_longitude", "pickup_latitude", "pickup_taxizone_id", meta=('pickup_taxizone_id', np.float64)) all_trips = all_trips[sorted(all_trips.columns)] # all_trips = all_trips.repartition(npartitions=1200) all_trips = all_trips.map_partitions(lambda x: x.sort_values('pickup_datetime'), meta=all_trips) for fieldName in all_trips.columns: if fieldName in dtype_list: all_trips[fieldName] = all_trips[fieldName].astype(dtype_list[fieldName]) all_trips.to_parquet( os.path.join(config['parquet_output_path'], 'all_trips_unprocessed.parquet'), compression='GZIP', has_nulls=True, object_encoding='json') if __name__ == '__main__': client = Client() # client=None # dask.set_options(get=dask.async.get_sync) main(client)
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CNN haiku models.""" from typing import Tuple import haiku as hk import jax import jax.numpy as jnp import functools Batch = Tuple[jnp.ndarray, jnp.ndarray] _DEFAULT_BN_CONFIG = { "decay_rate": 0.9, "eps": 1e-5, "create_scale": True, "create_offset": True } def make_lenet5_fn(data_info): num_classes = data_info["num_classes"] def lenet_fn(batch, is_training): """Network inspired by LeNet-5.""" x, _ = batch cnn = hk.Sequential([ hk.Conv2D(output_channels=6, kernel_shape=5, padding="SAME"), jax.nn.relu, hk.MaxPool(window_shape=3, strides=2, padding="VALID"), hk.Conv2D(output_channels=16, kernel_shape=5, padding="SAME"), jax.nn.relu, hk.MaxPool(window_shape=3, strides=2, padding="VALID"), hk.Conv2D(output_channels=120, kernel_shape=5, padding="SAME"), jax.nn.relu, hk.MaxPool(window_shape=3, strides=2, padding="VALID"), hk.Flatten(), hk.Linear(84), jax.nn.relu, hk.Linear(num_classes), ]) return cnn(x) return lenet_fn he_normal = hk.initializers.VarianceScaling(2.0, "fan_in", "truncated_normal") class FeatureResponseNorm(hk.Module): def __init__(self, eps=1e-6, name="frn"): super().__init__(name=name) self.eps = eps def __call__(self, x, **unused_kwargs): del unused_kwargs par_shape = (1, 1, 1, x.shape[-1]) # [1,1,1,C] tau = hk.get_parameter("tau", par_shape, x.dtype, init=jnp.zeros) beta = hk.get_parameter("beta", par_shape, x.dtype, init=jnp.zeros) gamma = hk.get_parameter("gamma", par_shape, x.dtype, init=jnp.ones) nu2 = jnp.mean(jnp.square(x), axis=[1, 2], keepdims=True) x = x * jax.lax.rsqrt(nu2 + self.eps) y = gamma * x + beta z = jnp.maximum(y, tau) return z def _resnet_layer(inputs, num_filters, normalization_layer, kernel_size=3, strides=1, activation=lambda x: x, use_bias=True, is_training=True): x = inputs x = hk.Conv2D( num_filters, kernel_size, stride=strides, padding="same", w_init=he_normal, with_bias=use_bias)( x) x = normalization_layer()(x, is_training=is_training) x = activation(x) return x def make_resnet_fn( num_classes, depth, normalization_layer, width = 16, use_bias = True, activation=jax.nn.relu, ): num_res_blocks = (depth - 2) // 6 if (depth - 2) % 6 != 0: raise ValueError("depth must be 6n+2 (e.g. 20, 32, 44).") def forward(batch, is_training): num_filters = width x, _ = batch x = _resnet_layer( x, num_filters=num_filters, activation=activation, use_bias=use_bias, normalization_layer=normalization_layer) for stack in range(3): for res_block in range(num_res_blocks): strides = 1 if stack > 0 and res_block == 0: # first layer but not first stack strides = 2 # downsample y = _resnet_layer( x, num_filters=num_filters, strides=strides, activation=activation, use_bias=use_bias, is_training=is_training, normalization_layer=normalization_layer) y = _resnet_layer( y, num_filters=num_filters, use_bias=use_bias, is_training=is_training, normalization_layer=normalization_layer) if stack > 0 and res_block == 0: # first layer but not first stack # linear projection residual shortcut connection to match changed dims x = _resnet_layer( x, num_filters=num_filters, kernel_size=1, strides=strides, use_bias=use_bias, is_training=is_training, normalization_layer=normalization_layer) x = activation(x + y) num_filters *= 2 x = hk.AvgPool((8, 8, 1), 8, "VALID")(x) x = hk.Flatten()(x) logits = hk.Linear(num_classes, w_init=he_normal)(x) return logits return forward def make_resnet20_fn(data_info, activation=jax.nn.relu): num_classes = data_info["num_classes"] def normalization_layer(): hk.BatchNorm(**_DEFAULT_BN_CONFIG) return make_resnet_fn( num_classes, depth=20, normalization_layer=normalization_layer, activation=activation) def make_resnet20_frn_fn(data_info, activation=jax.nn.relu): num_classes = data_info["num_classes"] return make_resnet_fn( num_classes, depth=20, normalization_layer=FeatureResponseNorm, activation=activation) def make_cnn_lstm(data_info, max_features=20000, embedding_size=128, cell_size=128, num_filters=64, kernel_size=5, pool_size=4, use_swish=False, use_maxpool=True): """CNN LSTM architecture for the IMDB dataset.""" num_classes = data_info["num_classes"] def forward(batch, is_training): x, _ = batch batch_size = x.shape[0] x = hk.Embed(vocab_size=max_features, embed_dim=embedding_size)(x) x = hk.Conv1D( output_channels=num_filters, kernel_shape=kernel_size, padding="VALID")( x) if use_swish: x = jax.nn.swish(x) else: x = jax.nn.relu(x) if use_maxpool: x = hk.MaxPool( window_shape=pool_size, strides=pool_size, padding="VALID", channel_axis=2)( x) x = jnp.moveaxis(x, 1, 0)[:, :] #[T, B, F] lstm_layer = hk.LSTM(hidden_size=cell_size) init_state = lstm_layer.initial_state(batch_size) x, state = hk.static_unroll(lstm_layer, x, init_state) x = x[-1] logits = hk.Linear(num_classes)(x) return logits return forward def make_smooth_cnn_lstm(data_info, max_features=20000, embedding_size=128, cell_size=128, num_filters=64, kernel_size=5, pool_size=4): num_classes = data_info["num_classes"] return make_cnn_lstm( num_classes, max_features, embedding_size, cell_size, num_filters, kernel_size, pool_size, use_swish=True, use_maxpool=False) def make_mlp(layer_dims, output_dim): def forward(batch, is_training): x, _ = batch x = hk.Flatten()(x) for layer_dim in layer_dims: x = hk.Linear(layer_dim)(x) x = jax.nn.relu(x) x = hk.Linear(output_dim)(x) return x return forward def make_mlp_regression(data_info, output_dim=2, layer_dims=[100, 100]): return make_mlp(layer_dims, output_dim) def make_mlp_regression_small(data_info): return make_mlp([50], 2) def make_mlp_classification(data_info, layer_dims=[256, 256]): num_classes = data_info["num_classes"] return make_mlp(layer_dims, num_classes) def make_logistic_regression(data_info): num_classes = data_info["num_classes"] return make_mlp([], num_classes) def get_model(model_name, data_info, **kwargs): _MODEL_FNS = { "lenet": make_lenet5_fn, "resnet20": make_resnet20_fn, "resnet20_frn": make_resnet20_frn_fn, "resnet20_frn_swish": functools.partial(make_resnet20_frn_fn, activation=jax.nn.swish), "cnn_lstm": make_cnn_lstm, "smooth_cnn_lstm": make_smooth_cnn_lstm, "mlp_regression": make_mlp_regression, "mlp_regression_small": make_mlp_regression_small, "mlp_classification": make_mlp_classification, "logistic_regression": make_logistic_regression, } net_fn = _MODEL_FNS[model_name](data_info, **kwargs) net = hk.transform_with_state(net_fn) return net.apply, net.init
# Copyright 2011 Hakan Kjellerstrand hakank@bonetmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Magic square (integer programming) in Google or-tools. Translated from GLPK:s example magic.mod ''' MAGIC, Magic Square Written in GNU MathProg by Andrew Makhorin <mao@mai2.rcnet.ru> In recreational mathematics, a magic square of order n is an arrangement of n^2 numbers, usually distinct integers, in a square, such that n numbers in all rows, all columns, and both diagonals sum to the same constant. A normal magic square contains the integers from 1 to n^2. (From Wikipedia, the free encyclopedia.) ''' Compare to the CP version: http://www.hakank.org/google_or_tools/magic_square.py Here we also experiment with how long it takes when using an output_matrix (much longer). This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ """ from __future__ import print_function import sys from ortools.linear_solver import pywraplp # # main(n, use_output_matrix) # n: size of matrix # use_output_matrix: use the output_matrix # def main(n=3, sol='CBC', use_output_matrix=0): # Create the solver. print('Solver: ', sol) # using GLPK if sol == 'GLPK': solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: # Using CLP solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data # print('n = ', n) # range_n = range(1, n+1) range_n = list(range(0, n)) N = n * n range_N = list(range(1, N + 1)) # # variables # # x[i,j,k] = 1 means that cell (i,j) contains integer k x = {} for i in range_n: for j in range_n: for k in range_N: x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k)) # For output. Much slower.... if use_output_matrix == 1: print('Using an output matrix') square = {} for i in range_n: for j in range_n: square[i, j] = solver.IntVar(1, n * n, 'square[%i,%i]' % (i, j)) # the magic sum s = solver.IntVar(1, n * n * n, 's') # # constraints # # each cell must be assigned exactly one integer for i in range_n: for j in range_n: solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1) # each integer must be assigned exactly to one cell for k in range_N: solver.Add(solver.Sum([x[i, j, k] for i in range_n for j in range_n]) == 1) # # the sum in each row must be the magic sum for i in range_n: solver.Add(solver.Sum([k * x[i, j, k] for j in range_n for k in range_N]) == s) # # the sum in each column must be the magic sum for j in range_n: solver.Add(solver.Sum([k * x[i, j, k] for i in range_n for k in range_N]) == s) # # the sum in the diagonal must be the magic sum solver.Add(solver.Sum([k * x[i, i, k] for i in range_n for k in range_N]) == s) # # the sum in the co-diagonal must be the magic sum if range_n[0] == 1: # for range_n = 1..n solver.Add(solver.Sum([k * x[i, n - i + 1, k] for i in range_n for k in range_N]) == s) else: # for range_n = 0..n-1 solver.Add(solver.Sum([k * x[i, n - i - 1, k] for i in range_n for k in range_N]) == s) # for output if use_output_matrix == 1: for i in range_n: for j in range_n: solver.Add(square[i, j] == solver.Sum([k * x[i, j, k] for k in range_N])) # # solution and search # solver.Solve() print() print('s: ', int(s.SolutionValue())) if use_output_matrix == 1: for i in range_n: for j in range_n: print(int(square[i, j].SolutionValue()), end=' ') print() print() else: for i in range_n: for j in range_n: print(sum([int(k * x[i, j, k].SolutionValue()) for k in range_N]), ' ', end=' ') print() print('\nx:') for i in range_n: for j in range_n: for k in range_N: print(int(x[i, j, k].SolutionValue()), end=' ') print() print() print('walltime :', solver.WallTime(), 'ms') if sol == 'CBC': print('iterations:', solver.Iterations()) if __name__ == '__main__': n = 3 sol = 'GLPK' use_output_matrix = 0 if len(sys.argv) > 1: n = int(sys.argv[1]) if len(sys.argv) > 2: sol = sys.argv[2] if sol != 'GLPK' and sol != 'CBC': print('Solver must be either GLPK or CBC') sys.exit(1) if len(sys.argv) > 3: use_output_matrix = int(sys.argv[3]) main(n, sol, use_output_matrix)
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import copy from testrunner import testhelp import tempfile import random import string import subprocess import os import sys import StringIO from testutils import mock from mint_rephelp import MINT_HOST, MINT_DOMAIN, MINT_PROJECT_DOMAIN from mint_rephelp import resetCache from mint_test import resources import mint.db.database from mint import shimclient from mint import config from mint import buildtypes from mint.flavors import stockFlavors from mint import server from mint import userlevels from mint.lib.data import RDT_STRING from conary import dbstore from conary.deps import deps from conary.lib import util from testutils import sqlharness from rpath_proddef import api1 as proddef from proddef_test import resources as proddef_resources def stockBuildFlavor(db, buildId, arch = "x86_64"): cu = db.cursor() flavor = deps.parseFlavor(stockFlavors['1#' + arch]).freeze() cu.execute("UPDATE Builds set troveFlavor=? WHERE buildId=?", flavor, buildId) db.commit() class FixtureCache(object): _fixtures = {} def list(self): fixtureNames = [x for x in self.__class__.__base__.__dict__ \ if x.startswith('fixture')] return dict([(x.replace('fixture', ''), self.__getattribute__(x).__doc__) for x in fixtureNames]) def loadFixture(self, key, loadFn=None): if not loadFn: name = 'fixture' + key loadFn = self.__getattribute__(name) if key not in self._fixtures: self._fixtures[key] = loadFn(self.newMintCfg(key)) return self._fixtures[key] def load(self, name, loadFn=None): raise NotImplementedError def newMintCfg(self, name): # IDEA: If fixtures did things differently # and instead of creating a new config for you # to use just used the existing config # and froze at the end, we could stack # fixtures, making them less expensive to create. cfg = config.MintConfig() cfg.authUser = 'mintauth' cfg.authPass = 'mintpass' cfg.debugMode = True cfg.namespace = 'yournamespace' cfg.hostName = MINT_HOST cfg.projectDomainName = MINT_PROJECT_DOMAIN cfg.siteDomainName = MINT_DOMAIN cfg.secureHostName = "%s.%s" % (MINT_HOST, MINT_PROJECT_DOMAIN) cfg.dataPath = tempfile.mkdtemp(prefix = "fixture%s" % name) cfg.logPath = os.path.join(cfg.dataPath, 'logs') cfg.reposPath = os.path.join(cfg.dataPath, 'repos') cfg.reposContentsDir = "%s %s" % (os.path.join(cfg.dataPath, 'contents1', '%s'), os.path.join(cfg.dataPath, 'contents2', '%s')) cfg.imagesPath = os.path.join(cfg.dataPath, 'images') util.mkdirChain(cfg.imagesPath) cfg.storagePath = os.path.join(cfg.dataPath, 'jobs') util.mkdirChain(cfg.storagePath) cfg.sendNotificationEmails = False util.mkdirChain(os.path.join(cfg.dataPath, 'run')) util.mkdirChain(os.path.join(cfg.dataPath, 'tmp')) cfg.ec2AccountId = '012345678901' cfg.ec2PublicKey = 'publicKey' cfg.ec2PrivateKey = 'secretKey' cfg.platformSources = ['plat1source', 'plat2source0', 'plat2source1'] cfg.platformSourceTypes = ['satellite', 'RHN', 'RHN'] cfg.platformSourceUrls = ['http://plat1source.example.com', 'https://plat2source0.example.com', 'https://plat2source1.example.com'] cfg.platformSourceNames = ['Platform 1 Source', 'Platform 2 Source 0', 'Platform 2 Source 1'] cfg.platformSourceLabels = ['localhost@rpath:plat-1', 'localhost@rpath:plat-2', 'localhost@rpath:plat-2'] cfg.reposLog = False cfg.postCfg() util.mkdirChain(cfg.logPath) return cfg def delRepos(self): raise NotImplementedError def createUser(self, cfg, db, username, isAdmin = False): """ Creates a user named "username" filled with the following data: password -> "<username>pass" fullname -> "A User Named <username>" email -> "<username>@example.com" contactInfo -> "<username> at example.com" If isAdmin is True, then the user will be given admin privileges. Returns the user id of the user. """ client = shimclient.ShimMintClient(cfg, (cfg.authUser, cfg.authPass)) assert(username) password = "%spass" % username fullname = "A User Named %s" % username email = "%s@example.com" % username contactInfo = "%s at example.com" % username cu = db.cursor() userId = client.registerNewUser(username, password, fullname, email, contactInfo, "", active=True) cu.execute("UPDATE Users SET is_admin = ? WHERE userId = ?", isAdmin, userId) return userId def fixtureEmpty(self, cfg): """ Empty fixture. Should be used when you want a (mostly) blank setup for testing. Creates the following setup: - Two users: - test (a basic user with no special privileges) - admin (a user wih admin privileges) @param cfg: The current effective Mint configuration. @return: A 2-tuple consisting of the current Mint configuration and a a dictionary containing the following: - C{test} - the id of the user "test" - C{admin} - the id of the user "admin" """ db = dbstore.connect(cfg.dbPath, cfg.dbDriver) testId = self.createUser(cfg, db, "test") adminId = self.createUser(cfg, db, "admin", isAdmin=True) return cfg, { 'test': testId, 'admin': adminId } def fixtureFull(self, cfg): """ Full (featured) fixture. This fixture should be good enough for 90% of the tests written and should be used UNLESS the absence of data provided by this fixture is needed. Creates the following setup: - One project called "foo" - Six users - admin (a user with admin privileges) - owner (who owns the "foo" project) - developer (who is a developer in the "foo" project) - user (a user or watcher of the "foo" project - nobody (a user with no allegiance to any project) - Two Versions - 'FooV1', 'FooV1Description' - 'FooV2', 'FooV2Description' - Two published release objects - One publishd, or published, containing one build - One not publishd, containing another build - Three builds inside the "foo" project: - one published (i.e. belongs to the published release) - one unpublished (belongs to a release not yet published) - one available (not belonging to any release) @param cfg: The current effective Mint configuration. @return: A 2-tuple consisting of the current Mint configuration and a a dictionary containing the following: - C{test} - the id of the user "test" - C{user} - the id of the user "user" - C{admin} - the id of the user "admin" - C{owner} - the id of the user "owner" - C{developer} - the id of the user "developer" - C{nobody} - the id of the user "nobody" - C{projectId} - the id of the "Foo" project - C{buildId} - the id of the build in the "Foo" project """ # connect to the database and open a MintServer instance db = dbstore.connect(cfg.dbPath, cfg.dbDriver) # create the users adminId = self.createUser(cfg, db, username = "admin", isAdmin = True) ownerId = self.createUser(cfg, db, username = "owner") developerId = self.createUser(cfg, db, username = "developer") userId = self.createUser(cfg, db, username = "user") nobodyId = self.createUser(cfg, db, username = "nobody") # set up EC2 site credentials amiData = { 'ec2PublicKey' : '123456789ABCDEFGHIJK', 'ec2PrivateKey' : '123456789ABCDEFGHIJK123456789ABCDEFGHIJK', 'ec2AccountId' : '000000000000', 'ec2S3Bucket' : 'extracrispychicken', 'ec2LaunchUsers' : ["000000001111", "000000002222"], 'ec2LaunchGroups' : ["group1", "group2"], 'ec2Certificate': open(resources.get_archive('ec2.pem')).read(), 'ec2CertificateKey': open(resources.get_archive('ec2.key')).read(), } adminClient = shimclient.ShimMintClient(cfg, ("admin", "adminpass")) adminClient.addTarget('ec2', 'aws', amiData) # create the project client = shimclient.ShimMintClient(cfg, ("owner", "ownerpass")) hostname = shortname = "foo" projectId = client.newProject("Foo", hostname, MINT_PROJECT_DOMAIN, shortname=shortname, version="1.0", prodtype="Component") project = client.getProject(projectId) # add the developer project.addMemberById(developerId, userlevels.DEVELOPER) # add the watcher # (note: you have to use a separate client with the watcher's # credentials to add the watcher) userClient = shimclient.ShimMintClient(cfg, ("user", "userpass")) userProject = userClient.getProject(projectId) userProject.addMemberById(userId, userlevels.USER) # create a build for the "foo" project called "Test Build" # and add it to an unpublished (not final) release build = client.newBuild(projectId, "Test Build") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.1-1-1", "1#x86") build.setBuildType(buildtypes.STUB_IMAGE) build.setFiles([["file", "file title 1"]]) stockBuildFlavor(db, build.id) pubRelease = client.newPublishedRelease(projectId) pubRelease.name = "(Not final) Release" pubRelease.version = "1.1" pubRelease.addBuild(build.id) pubRelease.save() # create another build for the "foo" project and publish it # i.e. make it a part of a published release pubBuild = client.newBuild(projectId, "Test Published Build") pubBuild.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.0-1-1", "1#x86") pubBuild.setBuildType(buildtypes.STUB_IMAGE) pubBuild.setFiles([["file", "file title 1"]]) stockBuildFlavor(db, pubBuild.id) pubReleaseFinal = client.newPublishedRelease(projectId) pubReleaseFinal.name = "Published Release" pubReleaseFinal.version = "1.0" pubReleaseFinal.addBuild(pubBuild.id) pubReleaseFinal.save() pubReleaseFinal.publish() # Create another build that just lies around somewhere # unattached to any published releases anotherBuild = client.newBuild(projectId, "Test Extra Build") anotherBuild.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.0-1-2", "1#x86") anotherBuild.setBuildType(buildtypes.STUB_IMAGE) anotherBuild.setFiles([["file", "file title 1"]]) stockBuildFlavor(db, anotherBuild.id, "x86") # create an imageless group trove build and release imagelessBuild = client.newBuild(projectId, "Test Imageless Build") imagelessBuild.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.0-1-2", "1#x86") imagelessBuild.setBuildType(buildtypes.IMAGELESS) imagelessBuild.setFiles([["file", "file title 1"]]) imagelessRelease = client.newPublishedRelease(projectId) imagelessRelease.name = "Published Imageless Release" imagelessRelease.version = "1.0" imagelessRelease.addBuild(imagelessBuild.id) imagelessRelease.save() # create 2 product versions in the project versionId = client.addProductVersion(projectId, 'ns', 'FooV1', 'FooV1Description') versionId2 = client.addProductVersion(projectId, 'ns2', 'FooV2', 'FooV2Description') return cfg, { 'projectId': projectId, 'admin': adminId, 'owner': ownerId, 'developer': developerId, 'user': userId, 'nobody': nobodyId, 'buildId': build.id, 'pubBuildId': pubBuild.id, 'pubReleaseId': pubRelease.id, 'pubReleaseFinalId': pubReleaseFinal.id, 'anotherBuildId': anotherBuild.id, 'imagelessBuildId': imagelessBuild.id, 'imagelessReleaseId': imagelessRelease.id, 'versionId' : versionId, 'versionId2' : versionId2 } def fixtureImageJob(self, cfg): """ ImageJob fixture. Creates the following setup: - One user: - test (a basic user with no special privileges) - A project called "foo" - "test" is a member of "foo" - A build called "Test Build" - A single image job, in the "started" state @param cfg: The current effective Mint configuration. @return: A 2-tuple consisting of the current Mint configuration and a a dictionary containing the following: - C{test} - the id of the user "test" """ db = dbstore.connect(cfg.dbPath, cfg.dbDriver) testId = self.createUser(cfg, db, 'test') client = shimclient.ShimMintClient(cfg, ('test', 'testpass')) projectId = client.newProject("Foo", "foo", "rpath.org") build = client.newBuild(projectId, "Test Build") build.setBuildType(buildtypes.STUB_IMAGE) stockBuildFlavor(db, build.getId()) prodJob = client.startImageJob(build.getId()) return cfg, { 'test': testId } def fixtureEC2(self, cfg): db = dbstore.connect(cfg.dbPath, cfg.dbDriver) adminId = self.createUser(cfg, db, username = 'admin', isAdmin = True) developerId = self.createUser(cfg, db, username = 'developer', isAdmin = False) someOtherDeveloperId = self.createUser(cfg, db, username = 'someotherdeveloper', isAdmin = False) normalUserId = self.createUser(cfg, db, username = 'normaluser', isAdmin = False) client = shimclient.ShimMintClient(cfg, ('admin', 'adminpass')) someOtherClient = shimclient.ShimMintClient(cfg, ('someotherdeveloper', 'someotherdeveloperpass')) normalUserClient = shimclient.ShimMintClient(cfg, ('normaluser', 'normaluserpass')) # Create a user to be used for joining products in the tests. loneUserId = self.createUser(cfg, db, username = 'loneuser', isAdmin = False) amiData = { 'ec2PublicKey' : '123456789ABCDEFGHIJK', 'ec2PrivateKey' : '123456789ABCDEFGHIJK123456789ABCDEFGHIJK', 'ec2AccountId' : '000000000000', 'ec2S3Bucket' : 'extracrispychicken', 'ec2LaunchUsers' : ["000000001111", "000000002222"], 'ec2LaunchGroups' : ["group1", "group2"], 'ec2CertificateFile': open(resources.get_archive('ec2.pem')).read(), 'ec2CertificateKeyFile': open(resources.get_archive('ec2.key')).read(), } client.addTarget('ec2', 'aws', amiData) hostname = shortname = "testproject" projectId = someOtherClient.newProject("Test Project", hostname, MINT_PROJECT_DOMAIN, shortname=shortname, version="1.0", prodtype="Component") hostname = shortname = "otherproject" otherProjectId = someOtherClient.newProject("Other Project", hostname, MINT_PROJECT_DOMAIN, shortname=shortname, version="1.0", prodtype="Component") hostname = shortname = "hiddenproject" hiddenProjectId = someOtherClient.newProject("Hidden Test Project", hostname, MINT_PROJECT_DOMAIN, shortname=shortname, version="1.0", prodtype="Component") hiddenproject = client.getProject(hiddenProjectId) # add the developer to the testproject project = client.getProject(projectId) project.addMemberById(developerId, userlevels.DEVELOPER) # add the normal user to the testproject normalProject = normalUserClient.getProject(projectId) normalProject.addMemberById(normalUserId, userlevels.USER) # add the developer to the hiddenproject hiddenproject.addMemberById(developerId, userlevels.DEVELOPER) # add the normal user to the hiddenproject normalHiddenProject = normalUserClient.getProject(hiddenProjectId) normalHiddenProject.addMemberById(normalUserId, userlevels.USER) ret = client.hideProject(hiddenProjectId) # create an AMI build that isn't a part of a release build = client.newBuild(projectId, "Test AMI Build (Unpublished, not in release)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.1-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000001', RDT_STRING, validate=False) # create an AMI build and add it to an unpublished # (not final) release build = client.newBuild(projectId, "Test AMI Build (Unpublished)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.2-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000002', RDT_STRING, validate=False) pubRelease = client.newPublishedRelease(projectId) pubRelease.name = "(Not final) Release" pubRelease.version = "1.1" pubRelease.addBuild(build.id) pubRelease.save() buildId1 = build.id # create an AMI build and add it to a published release build = client.newBuild(projectId, "Test AMI Build (Published)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.3-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000003', RDT_STRING, validate=False) pubRelease = client.newPublishedRelease(projectId) pubRelease.name = "Release" pubRelease.version = "1.0" pubRelease.addBuild(build.id) pubRelease.save() pubRelease.publish() buildId2 = build.id # create a published AMI build on the other project build = client.newBuild(otherProjectId, "Test AMI Build (Published)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.4-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000004', RDT_STRING, validate=False) pubRelease = client.newPublishedRelease(otherProjectId) pubRelease.name = "Release" pubRelease.version = "1.0" pubRelease.addBuild(build.id) pubRelease.save() pubRelease.publish() buildId3 = build.id # create a plain ol' AMI build on the other project build = client.newBuild(otherProjectId, "Test AMI Build (Published)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.5-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000005', RDT_STRING, validate=False) buildId4 = build.id # create an AMI build and add it to an unpublished # (not final) release on the hiddenproject build = client.newBuild(hiddenProjectId, "Test AMI Build (Unpublished)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.2-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000006', RDT_STRING, validate=False) pubRelease = client.newPublishedRelease(hiddenProjectId) pubRelease.name = "(Not final) Release" pubRelease.version = "1.1" pubRelease.addBuild(build.id) pubRelease.save() hiddenProjUnpubPubReleaseId = pubRelease.id buildId5 = build.id # create an AMI build and add it to a published release on the hidden # project. build = client.newBuild(hiddenProjectId, "Test AMI Build (Published)") build.setTrove("group-dist", "/testproject." + \ MINT_PROJECT_DOMAIN + "@rpl:devel/0.0:1.3-1-1", "1#x86") build.setBuildType(buildtypes.AMI) build.setDataValue('amiId', 'ami-00000007', RDT_STRING, validate=False) pubRelease = client.newPublishedRelease(hiddenProjectId) pubRelease.name = "Release" pubRelease.version = "1.0" pubRelease.addBuild(build.id) pubRelease.save() pubRelease.publish() hiddenProjPubPubReleaseId = pubRelease.id buildId6 = build.id return cfg, { 'adminId': adminId, 'developerId': developerId, 'normalUserId': normalUserId, 'someOtherDeveloperId': someOtherDeveloperId, 'projectId': projectId, 'otherProjectId': otherProjectId, 'hiddenProjectId': hiddenProjectId, 'loneUserId': loneUserId, 'hiddenProjUnpubPubReleaseId': hiddenProjUnpubPubReleaseId, 'hiddenProjPubPubReleaseId': hiddenProjPubPubReleaseId, 'buildId1' : buildId1, 'buildId2' : buildId2, 'buildId3' : buildId3, 'buildId4' : buildId4, 'buildId5' : buildId5, 'buildId6' : buildId6, } def __del__(self): for f in self._fixtures.values(): util.rmtree(f[0].dataPath) class SqliteFixtureCache(FixtureCache): def newMintCfg(self, name): cfg = FixtureCache.newMintCfg(self, name) cfg.dbDriver = 'sqlite' cfg.dbPath = os.path.join(cfg.dataPath, 'mintdb') reposDBPath = os.path.join(cfg.dataPath, 'repos', '%s', 'sqldb') cfg.configLine('database default sqlite ' + reposDBPath) from mint.db import schema db = dbstore.connect(cfg.dbPath, cfg.dbDriver) schema.loadSchema(db, cfg) return cfg def load(self, name, loadFn=None): cfg, data = self.loadFixture(name, loadFn=loadFn) # make a copy of the data directory and update the cfg testDataPath = tempfile.mkdtemp(prefix = "fixture%s" % name, suffix = '.copy') self.testDataPath = testDataPath util.copytree(os.path.join(cfg.dataPath,'*'), testDataPath) testCfg = copy.deepcopy(cfg) testCfg.dataPath = testDataPath testCfg.dbPath = os.path.join(testCfg.dataPath, 'mintdb') testCfg.imagesPath = os.path.join(testCfg.dataPath, 'images') testCfg.reposContentsDir = "%s %s" % ( os.path.join(testCfg.dataPath, 'contents1', '%s'), os.path.join(testCfg.dataPath, 'contents2', '%s')) reposDBPath = os.path.join(testCfg.dataPath, 'repos', '%s', 'sqldb') testCfg.configLine('database default sqlite ' + reposDBPath) testCfg.reposPath = os.path.join(testCfg.dataPath, 'repos') f = open(os.path.join(testCfg.dataPath, "rbuilder.conf"), 'w') testCfg.display(out=f) f.close() return testCfg, data def delRepos(self): try: util.rmtree(self.testDataPath) except AttributeError: pass class SQLServerFixtureCache(FixtureCache): harness = None def __init__(self): self.harness = sqlharness.getHarness(self.driver) def _randomName(self): return "".join(random.sample(string.lowercase, 5)) def _getConnectStringForDb(self, dbName = "%s"): return os.path.join(self.harness.conn, dbName) def newMintCfg(self, name): dbName = ("mf%s" % name).lower().replace('.', '__') self.keepDbs.append(dbName) db = self.harness.getDB(dbName) cfg = FixtureCache.newMintCfg(self, name) cfg.dbDriver = self.driver cfg.dbPath = self._getConnectStringForDb(dbName) reposDBPath = self._getConnectStringForDb() cfg.configLine('database default %s %s' % (self.driver, reposDBPath)) from mint.db import schema schema.loadSchema(db.connect(), cfg) db.stop() return cfg class MySqlFixtureCache(SQLServerFixtureCache): keepDbs = ['mysql', 'test', 'information_schema', 'testdb'] driver = "mysql" def _dupDb(self, srcDb, destDb): self.harness.getDB(destDb) output = ["mysqldump", "-u", "root", "-S", "%s/socket" % self.harness.path, srcDb] input = ["mysql", "-u", "root", "-S", "%s/socket" % self.harness.path, destDb] dump = subprocess.Popen(output, stdout = subprocess.PIPE) load = subprocess.Popen(input, stdin = dump.stdout) load.communicate() def loadFixture(self, name, loadFn=None): ret = super(self.__class__, self).loadFixture(name, loadFn=loadFn) # save repos tables off for later db = self.harness.getRootDB() cu = db.cursor() cu.execute("SHOW DATABASES") for dbname in [x[0] for x in cu.fetchall() if x[0] not in self.keepDbs]: if '_' in dbname and not dbname.startswith('cr'): newName = ("cr%s%s" % (name, dbname)).lower() self._dupDb(dbname, newName) self.harness.dropDB(dbname) self.keepDbs.append(newName) return ret def load(self, name, loadFn=None): cfg, data = self.loadFixture(name, loadFn=loadFn) # get a random name for this particular instance of the fixture # in order to create unique copies randomDbName = self._randomName() # make a copy of the data directory and update the cfg testDataPath = tempfile.mkdtemp(prefix = "fixture%s" % name, suffix = '.copy') util.copytree(os.path.join(cfg.dataPath,'*'), testDataPath) testCfg = copy.deepcopy(cfg) testCfg.dataPath = testDataPath testCfg.imagesPath = os.path.join(testCfg.dataPath, 'images') testCfg.reposContentsDir = "%s %s" % (os.path.join(testCfg.dataPath, 'contents1', '%s'), os.path.join(testCfg.dataPath, 'contents2', '%s')) testCfg.reposPath = os.path.join(testCfg.dataPath, 'repos') # restore the mint db into a unique copy fixtureMintDbName = ("mf%s" % name).lower() fixtureCopyMintDbName = ("cmf_%s%s" % (name, randomDbName)).lower() self._dupDb(fixtureMintDbName, fixtureCopyMintDbName) testCfg.dbPath = self._getConnectStringForDb(fixtureCopyMintDbName) # restore the repos dbs db = self.harness.getRootDB() cu = db.cursor() cu.execute("SHOW DATABASES LIKE 'cr%s%%'" % name.lower()) for dbname in [x[0] for x in cu.fetchall()]: fixtureCopyReposDbName = dbname[2+len(name):] self._dupDb(dbname, fixtureCopyReposDbName) f = open(os.path.join(testCfg.dataPath, "rbuilder.conf"), 'w') testCfg.display(out=f) f.close() return testCfg, data def delRepos(self): db = self.harness.getRootDB() cu = db.cursor() cu.execute("SHOW DATABASES") for dbname in [x[0] for x in cu.fetchall() if x[0] not in self.keepDbs]: if '_' in dbname and not dbname.startswith('cr'): self.harness.dropDB(dbname) def __del__(self): self.harness.stop() for f in self._fixtures.values(): util.rmtree(f[0].dataPath) class PostgreSqlFixtureCache(SQLServerFixtureCache): keepDbs = ['postgres', 'testdb', 'template1', 'template0'] driver = "postgresql" def _dupDb(self, srcDb, destDb): self.harness.getDB(destDb) output = ["pg_dump", "-U", self.harness.user, '-c', '-O', '-p', str(self.harness.port), '-d', srcDb] input = ["psql", '-p', str(self.harness.port), "-U", self.harness.user, destDb.lower()] dump = subprocess.Popen(output, stdout = subprocess.PIPE) fd = open('/dev/null', 'w') load = subprocess.Popen(input, stdin = dump.stdout, stdout=fd, stderr=fd) load.communicate() fd.close() def loadFixture(self, name, loadFn=None): ret = super(self.__class__, self).loadFixture(name, loadFn=loadFn) # save repos tables off for later db = self.harness.getRootDB() cu = db.cursor() cu.execute("SELECT datname FROM pg_database") for dbname in [x[0] for x in cu.fetchall() if x[0] not in self.keepDbs]: if '_' in dbname and not dbname.startswith('cr'): newName = "cr%s%s" % (name, dbname) self._dupDb(dbname, newName) self.harness.dropDB(dbname) self.keepDbs.append(newName.lower()) return ret def load(self, name, loadFn=None): cfg, data = self.loadFixture(name, loadFn=loadFn) # get a random name for this particular instance of the fixture # in order to create unique copies randomDbName = self._randomName() # make a copy of the data directory and update the cfg testDataPath = tempfile.mkdtemp(prefix = "fixture%s" % name, suffix = '.copy') util.copytree(os.path.join(cfg.dataPath,'*'), testDataPath) testCfg = copy.deepcopy(cfg) testCfg.dataPath = testDataPath testCfg.dbPath = os.path.join(testCfg.dataPath, 'mintdb') testCfg.imagesPath = os.path.join(testCfg.dataPath, 'images') testCfg.reposContentsDir = "%s %s" % (os.path.join(testCfg.dataPath, 'contents1', '%s'), os.path.join(testCfg.dataPath, 'contents2', '%s')) testCfg.reposPath = os.path.join(testCfg.dataPath, 'repos') f = open(os.path.join(testCfg.dataPath, "rbuilder.conf"), 'w') testCfg.display(out=f) f.close() # restore the repos dbs db = self.harness.getRootDB() cu = db.cursor() cu.execute("""SELECT datname FROM pg_database WHERE datname LIKE 'cr%s%%'""" % name.lower()) for dbname in [x[0] for x in cu.fetchall()]: fixtureCopyReposDbName = dbname[2+len(name):] self._dupDb(dbname, fixtureCopyReposDbName) return testCfg, data def delRepos(self): db = self.harness.getRootDB() cu = db.cursor() cu.execute("SELECT datname FROM pg_database") for dbname in [x[0] for x in cu.fetchall() if x[0] not in self.keepDbs]: if '_' in dbname and not dbname.startswith('cr'): self.harness.dropDB(dbname) def __del__(self): self.harness.stop() for f in self._fixtures.values(): util.rmtree(f[0].dataPath) class FixturedUnitTest(testhelp.TestCase): adminClient = None cfg = None # apply default context of "fixtured" to all children of this class contexts = ("fixtured",) def setUpProductDefinition(self): from rpath_proddef import api1 as proddef schemaDir = proddef_resources.get_xsd() schemaFile = "rpd-%s.xsd" % proddef.ProductDefinition.version if not os.path.exists(os.path.join(schemaDir, schemaFile)): # Not running from a checkout schemaDir = os.path.join("/usr/share/rpath_proddef") assert(os.path.exists(os.path.join(schemaDir, schemaFile))) self.mock(proddef.ProductDefinition, 'schemaDir', schemaDir) self.mock(proddef.PlatformDefinition, 'schemaDir', schemaDir) self.mock(proddef.Platform, 'schemaDir', schemaDir) def listFixtures(self): return fixtureCache.list() def loadFixture(self, name, loadFn=None): """ Loads the fixture for the unit test. @param name: the name of the fixture (e.g. "Full") @returns: A 3-typle consisting of a database connection, a Mint client with admin credentials, and a dictionary of fixture data (may be empty). """ # reset the cached db connection mint.db.database.dbConnection = None self.cfg, fixtureData = fixtureCache.load(name, loadFn=loadFn) db = dbstore.connect(self.cfg.dbPath, self.cfg.dbDriver) # this is so fugly it makes me wanna cry --gafton mint.db.database.dbConnection = db mint.db.database.tables = None return db, fixtureData def getAdminClient(self): return shimclient.ShimMintClient(self.cfg, ('mintauth', 'mintpass')) def getClient(self, username, password=None): if password is None: if username == 'anonymous': password = 'anonymous' else: password = '%spass' % username return shimclient.ShimMintClient(self.cfg, (username, password)) def getAnonymousClient(self): return self.getClient('anonymous') def quickMintUser(self, username, password, email = "test@example.com"): client = self.getAdminClient() userId = client.registerNewUser(username, password, "Test User", email, "test at example.com", "", active=True) client = shimclient.ShimMintClient(self.cfg, (username, password)) return client, userId def getMirrorAcl(self, project, username): """ Given a project and a username, will determine whether or not the user has the ability to mirror. @param project: the project to check against @param username: the user whose credentials should be checked @returns: C{True} if C{username} can mirror C{project}; C{False} otherwise. """ dbCon = project.server._server.projects.reposDB.getRepositoryDB( \ project.getFQDN()) db = dbstore.connect(dbCon[1], dbCon[0]) cu = db.cursor() cu.execute("""SELECT canMirror FROM Users LEFT JOIN UserGroupMembers ON Users.userId = UserGroupMembers.userId LEFT JOIN UserGroups ON UserGroups.userGroupId = UserGroupMembers.userGroupId WHERE Users.username=?""", username) try: # nonexistent results trigger value error canMirror = max([x[0] for x in cu.fetchall()]) except ValueError: canMirror = None db.close() return canMirror def getWriteAcl(self, project, username): dbCon = project.server._server.projects.reposDB.getRepositoryDB( \ project.getFQDN()) db = dbstore.connect(dbCon[1], dbCon[0]) cu = db.cursor() cu.execute("""SELECT MAX(canWrite) FROM Users LEFT JOIN UserGroupMembers ON Users.userId = UserGroupMembers.userId LEFT JOIN Permissions ON Permissions.userGroupId = UserGroupMembers.userGroupId WHERE Users.username=?""", username) return cu.fetchone()[0] def getAdminAcl(self, project, username): dbCon = project.server._server.projects.reposDB.getRepositoryDB( \ project.getFQDN()) db = dbstore.connect(dbCon[1], dbCon[0]) cu = db.cursor() cu.execute("""SELECT MAX(admin) FROM Users JOIN UserGroupMembers ON Users.userId = UserGroupMembers.userId JOIN UserGroups ON UserGroups.userGroupId = UserGroupMembers.userGroupId WHERE Users.username=?""", username) return cu.fetchone()[0] def captureAllOutput(self, func, *args, **kwargs): oldErr = os.dup(sys.stderr.fileno()) oldOut = os.dup(sys.stdout.fileno()) fd = os.open(os.devnull, os.W_OK) os.dup2(fd, sys.stderr.fileno()) os.dup2(fd, sys.stdout.fileno()) try: return func(*args, **kwargs) finally: os.dup2(oldErr, sys.stderr.fileno()) os.dup2(oldOut, sys.stdout.fileno()) def setUp(self): testhelp.TestCase.setUp(self) resetCache() # Prevent the mcp from talking to anyone interesting. server.MintServer._getMcpClient = mock.MockObject() server.MintServer._getMcpClient( ).new_job._mock.setDefaultReturn('0' * 32) def tearDown(self): mock.unmockAll() if getattr(server, 'dbConnection', None): server.dbConnection.close() server.dbConnection = None testhelp.TestCase.tearDown(self) try: fixtureCache.delRepos() self.cfg and util.rmtree(self.cfg.dataPath) except OSError: pass class FixturedProductVersionTest(FixturedUnitTest): oldProductDefinition = proddef.ProductDefinition class _MockProductDefinition(oldProductDefinition): _testxmldata = [] def saveToRepository(self, *args, **kwargs): sio = StringIO.StringIO() self.serialize(sio) _testxmldata = sio.getvalue() self._testxmldata.append(_testxmldata) def loadFromRepository(self, *args, **kwargs): if not self._testxmldata: raise proddef.ProductDefinitionTroveNotFound sio = StringIO.StringIO(self._testxmldata[-1]) sio.seek(0) self.parseStream(sio) def setUp(self): proddef.ProductDefinition = self._MockProductDefinition FixturedUnitTest.setUp(self) del self._MockProductDefinition._testxmldata[:] def tearDown(self): FixturedUnitTest.tearDown(self) proddef.ProductDefinition = self.oldProductDefinition del self._MockProductDefinition._testxmldata[:] driver = os.environ.get("CONARY_REPOS_DB", "sqlite") if driver == "sqlite": fixtureCache = SqliteFixtureCache() elif driver == "mysql": fixtureCache = MySqlFixtureCache() elif driver == "postgresql": fixtureCache = PostgreSqlFixtureCache() else: raise RuntimeError, "Invalid database driver specified" # test case decorator def fixture(arg): def deco(func): def wrapper(self): db, data = self.loadFixture(arg) return func(self, db, data) wrapper.__name__ = func.__name__ wrapper.__dict__.update(func.__dict__) return wrapper return deco
"""Build factory instances.""" import collections from . import declarations, enums, errors, utils DeclarationWithContext = collections.namedtuple( 'DeclarationWithContext', ['name', 'declaration', 'context'], ) class DeclarationSet: """A set of declarations, including the recursive parameters. Attributes: declarations (dict(name => declaration)): the top-level declarations contexts (dict(name => dict(subfield => value))): the nested parameters related to a given top-level declaration This object behaves similarly to a dict mapping a top-level declaration name to a DeclarationWithContext, containing field name, declaration object and extra context. """ def __init__(self, initial=None): self.declarations = {} self.contexts = collections.defaultdict(dict) self.update(initial or {}) @classmethod def split(cls, entry): """Split a declaration name into a (declaration, subpath) tuple. Examples: >>> DeclarationSet.split('foo__bar') ('foo', 'bar') >>> DeclarationSet.split('foo') ('foo', None) >>> DeclarationSet.split('foo__bar__baz') ('foo', 'bar__baz') """ if enums.SPLITTER in entry: return entry.split(enums.SPLITTER, 1) else: return (entry, None) @classmethod def join(cls, root, subkey): """Rebuild a full declaration name from its components. for every string x, we have `join(split(x)) == x`. """ if subkey is None: return root return enums.SPLITTER.join((root, subkey)) def copy(self): return self.__class__(self.as_dict()) def update(self, values): """Add new declarations to this set/ Args: values (dict(name, declaration)): the declarations to ingest. """ for k, v in values.items(): root, sub = self.split(k) if sub is None: self.declarations[root] = v else: self.contexts[root][sub] = v extra_context_keys = set(self.contexts) - set(self.declarations) if extra_context_keys: raise errors.InvalidDeclarationError( "Received deep context for unknown fields: %r (known=%r)" % ( { self.join(root, sub): v for root in extra_context_keys for sub, v in self.contexts[root].items() }, sorted(self.declarations), ) ) def filter(self, entries): """Filter a set of declarations: keep only those related to this object. This will keep: - Declarations that 'override' the current ones - Declarations that are parameters to current ones """ return [ entry for entry in entries if self.split(entry)[0] in self.declarations ] def sorted(self): return utils.sort_ordered_objects( self.declarations, getter=lambda entry: self.declarations[entry], ) def __contains__(self, key): return key in self.declarations def __getitem__(self, key): return DeclarationWithContext( name=key, declaration=self.declarations[key], context=self.contexts[key], ) def __iter__(self): return iter(self.declarations) def values(self): """Retrieve the list of declarations, with their context.""" for name in self: yield self[name] def _items(self): """Extract a list of (key, value) pairs, suitable for our __init__.""" for name in self.declarations: yield name, self.declarations[name] for subkey, value in self.contexts[name].items(): yield self.join(name, subkey), value def as_dict(self): """Return a dict() suitable for our __init__.""" return dict(self._items()) def __repr__(self): return '<DeclarationSet: %r>' % self.as_dict() def parse_declarations(decls, base_pre=None, base_post=None): pre_declarations = base_pre.copy() if base_pre else DeclarationSet() post_declarations = base_post.copy() if base_post else DeclarationSet() # Inject extra declarations, splitting between known-to-be-post and undetermined extra_post = {} extra_maybenonpost = {} for k, v in decls.items(): if enums.get_builder_phase(v) == enums.BuilderPhase.POST_INSTANTIATION: if k in pre_declarations: # Conflict: PostGenerationDeclaration with the same # name as a BaseDeclaration raise errors.InvalidDeclarationError( "PostGenerationDeclaration %s=%r shadows declaration %r" % (k, v, pre_declarations[k]) ) extra_post[k] = v elif k in post_declarations: # Passing in a scalar value to a PostGenerationDeclaration # Set it as `key__` magic_key = post_declarations.join(k, '') extra_post[magic_key] = v elif k in pre_declarations and isinstance( pre_declarations[k].declaration, declarations.Transformer ): extra_maybenonpost[k] = pre_declarations[k].declaration.function(v) else: extra_maybenonpost[k] = v # Start with adding new post-declarations post_declarations.update(extra_post) # Fill in extra post-declaration context extra_pre_declarations = {} extra_post_declarations = {} post_overrides = post_declarations.filter(extra_maybenonpost) for k, v in extra_maybenonpost.items(): if k in post_overrides: extra_post_declarations[k] = v else: # Anything else is pre_declarations extra_pre_declarations[k] = v pre_declarations.update(extra_pre_declarations) post_declarations.update(extra_post_declarations) return pre_declarations, post_declarations class BuildStep: def __init__(self, builder, sequence, parent_step=None): self.builder = builder self.sequence = sequence self.attributes = {} self.parent_step = parent_step self.stub = None def resolve(self, declarations): self.stub = Resolver( declarations=declarations, step=self, sequence=self.sequence, ) for field_name in declarations: self.attributes[field_name] = getattr(self.stub, field_name) @property def chain(self): if self.parent_step: parent_chain = self.parent_step.chain else: parent_chain = () return (self.stub,) + parent_chain def recurse(self, factory, declarations, force_sequence=None): from . import base if not issubclass(factory, base.BaseFactory): raise errors.AssociatedClassError( "%r: Attempting to recursing into a non-factory object %r" % (self, factory)) builder = self.builder.recurse(factory._meta, declarations) return builder.build(parent_step=self, force_sequence=force_sequence) def __repr__(self): return f"<BuildStep for {self.builder!r}>" class StepBuilder: """A factory instantiation step. Attributes: - parent: the parent StepBuilder, or None for the root step - extras: the passed-in kwargs for this branch - factory: the factory class being built - strategy: the strategy to use """ def __init__(self, factory_meta, extras, strategy): self.factory_meta = factory_meta self.strategy = strategy self.extras = extras self.force_init_sequence = extras.pop('__sequence', None) def build(self, parent_step=None, force_sequence=None): """Build a factory instance.""" # TODO: Handle "batch build" natively pre, post = parse_declarations( self.extras, base_pre=self.factory_meta.pre_declarations, base_post=self.factory_meta.post_declarations, ) if force_sequence is not None: sequence = force_sequence elif self.force_init_sequence is not None: sequence = self.force_init_sequence else: sequence = self.factory_meta.next_sequence() step = BuildStep( builder=self, sequence=sequence, parent_step=parent_step, ) step.resolve(pre) args, kwargs = self.factory_meta.prepare_arguments(step.attributes) instance = self.factory_meta.instantiate( step=step, args=args, kwargs=kwargs, ) postgen_results = {} for declaration_name in post.sorted(): declaration = post[declaration_name] postgen_results[declaration_name] = declaration.declaration.evaluate_post( instance=instance, step=step, overrides=declaration.context, ) self.factory_meta.use_postgeneration_results( instance=instance, step=step, results=postgen_results, ) return instance def recurse(self, factory_meta, extras): """Recurse into a sub-factory call.""" return self.__class__(factory_meta, extras, strategy=self.strategy) def __repr__(self): return f"<StepBuilder({self.factory_meta!r}, strategy={self.strategy!r})>" class Resolver: """Resolve a set of declarations. Attributes are set at instantiation time, values are computed lazily. Attributes: __initialized (bool): whether this object's __init__ as run. If set, setting any attribute will be prevented. __declarations (dict): maps attribute name to their declaration __values (dict): maps attribute name to computed value __pending (str list): names of the attributes whose value is being computed. This allows to detect cyclic lazy attribute definition. __step (BuildStep): the BuildStep related to this resolver. This allows to have the value of a field depend on the value of another field """ __initialized = False def __init__(self, declarations, step, sequence): self.__declarations = declarations self.__step = step self.__values = {} self.__pending = [] self.__initialized = True @property def factory_parent(self): return self.__step.parent_step.stub if self.__step.parent_step else None def __repr__(self): return '<Resolver for %r>' % self.__step def __getattr__(self, name): """Retrieve an attribute's value. This will compute it if needed, unless it is already on the list of attributes being computed. """ if name in self.__pending: raise errors.CyclicDefinitionError( "Cyclic lazy attribute definition for %r; cycle found in %r." % (name, self.__pending)) elif name in self.__values: return self.__values[name] elif name in self.__declarations: declaration = self.__declarations[name] value = declaration.declaration if enums.get_builder_phase(value) == enums.BuilderPhase.ATTRIBUTE_RESOLUTION: self.__pending.append(name) try: value = value.evaluate_pre( instance=self, step=self.__step, overrides=declaration.context, ) finally: last = self.__pending.pop() assert name == last self.__values[name] = value return value else: raise AttributeError( "The parameter %r is unknown. Evaluated attributes are %r, " "definitions are %r." % (name, self.__values, self.__declarations)) def __setattr__(self, name, value): """Prevent setting attributes once __init__ is done.""" if not self.__initialized: return super().__setattr__(name, value) else: raise AttributeError('Setting of object attributes is not allowed')
# coding: utf-8 """ Pagination serializers determine the structure of the output that should be used for paginated responses. """ from __future__ import unicode_literals import warnings from base64 import b64decode, b64encode from collections import namedtuple from django.core.paginator import Paginator as DjangoPaginator from django.core.paginator import InvalidPage from django.template import Context, loader from django.utils import six from django.utils.six.moves.urllib import parse as urlparse from django.utils.translation import ugettext_lazy as _ from rest_framework.compat import OrderedDict from rest_framework.exceptions import NotFound from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.utils.urls import remove_query_param, replace_query_param def _positive_int(integer_string, strict=False, cutoff=None): """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: ret = min(ret, cutoff) return ret def _divide_with_ceil(a, b): """ Returns 'a' divded by 'b', with any remainder rounded up. """ if a % b: return (a // b) + 1 return a // b def _get_count(queryset): """ Determine an object count, supporting either querysets or regular lists. """ try: return queryset.count() except (AttributeError, TypeError): return len(queryset) def _get_displayed_page_numbers(current, final): """ This utility function determines a list of page numbers to display. This gives us a nice contextually relevant set of page numbers. For example: current=14, final=16 -> [1, None, 13, 14, 15, 16] This implementation gives one page to each side of the cursor, or two pages to the side when the cursor is at the edge, then ensures that any breaks between non-continous page numbers never remove only a single page. For an alernativative implementation which gives two pages to each side of the cursor, eg. as in GitHub issue list pagination, see: https://gist.github.com/tomchristie/321140cebb1c4a558b15 """ assert current >= 1 assert final >= current if final <= 5: return list(range(1, final + 1)) # We always include the first two pages, last two pages, and # two pages either side of the current page. included = set(( 1, current - 1, current, current + 1, final )) # If the break would only exclude a single page number then we # may as well include the page number instead of the break. if current <= 4: included.add(2) included.add(3) if current >= final - 3: included.add(final - 1) included.add(final - 2) # Now sort the page numbers and drop anything outside the limits. included = [ idx for idx in sorted(list(included)) if idx > 0 and idx <= final ] # Finally insert any `...` breaks if current > 4: included.insert(1, None) if current < final - 3: included.insert(len(included) - 1, None) return included def _get_page_links(page_numbers, current, url_func): """ Given a list of page numbers and `None` page breaks, return a list of `PageLink` objects. """ page_links = [] for page_number in page_numbers: if page_number is None: page_link = PAGE_BREAK else: page_link = PageLink( url=url_func(page_number), number=page_number, is_active=(page_number == current), is_break=False ) page_links.append(page_link) return page_links def _reverse_ordering(ordering_tuple): """ Given an order_by tuple such as `('-created', 'uuid')` reverse the ordering and return a new tuple, eg. `('created', '-uuid')`. """ def invert(x): return x[1:] if (x.startswith('-')) else '-' + x return tuple([invert(item) for item in ordering_tuple]) Cursor = namedtuple('Cursor', ['offset', 'reverse', 'position']) PageLink = namedtuple('PageLink', ['url', 'number', 'is_active', 'is_break']) PAGE_BREAK = PageLink(url=None, number=None, is_active=False, is_break=True) class BasePagination(object): display_page_controls = False def paginate_queryset(self, queryset, request, view=None): # pragma: no cover raise NotImplementedError('paginate_queryset() must be implemented.') def get_paginated_response(self, data): # pragma: no cover raise NotImplementedError('get_paginated_response() must be implemented.') def to_html(self): # pragma: no cover raise NotImplementedError('to_html() must be implemented to display page controls.') class PageNumberPagination(BasePagination): """ A simple page number based style that supports page numbers as query parameters. For example: http://api.example.org/accounts/?page=4 http://api.example.org/accounts/?page=4&page_size=100 """ # The default page size. # Defaults to `None`, meaning pagination is disabled. page_size = api_settings.PAGE_SIZE # Client can control the page using this query parameter. page_query_param = 'page' # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. page_size_query_param = None # Set to an integer to limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. max_page_size = None last_page_strings = ('last',) template = 'rest_framework/pagination/numbers.html' invalid_page_message = _('Invalid page "{page_number}": {message}.') def _handle_backwards_compat(self, view): """ Prior to version 3.1, pagination was handled in the view, and the attributes were set there. The attributes should now be set on the pagination class, but the old style is still pending deprecation. """ assert not ( getattr(view, 'pagination_serializer_class', None) or getattr(api_settings, 'DEFAULT_PAGINATION_SERIALIZER_CLASS', None) ), ( "The pagination_serializer_class attribute and " "DEFAULT_PAGINATION_SERIALIZER_CLASS setting have been removed as " "part of the 3.1 pagination API improvement. See the pagination " "documentation for details on the new API." ) for (settings_key, attr_name) in ( ('PAGINATE_BY', 'page_size'), ('PAGINATE_BY_PARAM', 'page_size_query_param'), ('MAX_PAGINATE_BY', 'max_page_size') ): value = getattr(api_settings, settings_key, None) if value is not None: setattr(self, attr_name, value) warnings.warn( "The `%s` settings key is pending deprecation. " "Use the `%s` attribute on the pagination class instead." % ( settings_key, attr_name ), PendingDeprecationWarning, ) for (view_attr, attr_name) in ( ('paginate_by', 'page_size'), ('page_query_param', 'page_query_param'), ('paginate_by_param', 'page_size_query_param'), ('max_paginate_by', 'max_page_size') ): value = getattr(view, view_attr, None) if value is not None: setattr(self, attr_name, value) warnings.warn( "The `%s` view attribute is pending deprecation. " "Use the `%s` attribute on the pagination class instead." % ( view_attr, attr_name ), PendingDeprecationWarning, ) def paginate_queryset(self, queryset, request, view=None): """ Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ self._handle_backwards_compat(view) page_size = self.get_page_size(request) if not page_size: return None paginator = DjangoPaginator(queryset, page_size) page_number = request.query_params.get(self.page_query_param, 1) if page_number in self.last_page_strings: page_number = paginator.num_pages try: self.page = paginator.page(page_number) except InvalidPage as exc: msg = self.invalid_page_message.format( page_number=page_number, message=six.text_type(exc) ) raise NotFound(msg) if paginator.count > 1 and self.template is not None: # The browsable API should display pagination controls. self.display_page_controls = True self.request = request return list(self.page) def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) def get_page_size(self, request): if self.page_size_query_param: try: return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) except (KeyError, ValueError): pass return self.page_size def get_next_link(self): if not self.page.has_next(): return None url = self.request.build_absolute_uri() page_number = self.page.next_page_number() return replace_query_param(url, self.page_query_param, page_number) def get_previous_link(self): if not self.page.has_previous(): return None url = self.request.build_absolute_uri() page_number = self.page.previous_page_number() if page_number == 1: return remove_query_param(url, self.page_query_param) return replace_query_param(url, self.page_query_param, page_number) def get_html_context(self): base_url = self.request.build_absolute_uri() def page_number_to_url(page_number): if page_number == 1: return remove_query_param(base_url, self.page_query_param) else: return replace_query_param(base_url, self.page_query_param, page_number) current = self.page.number final = self.page.paginator.num_pages page_numbers = _get_displayed_page_numbers(current, final) page_links = _get_page_links(page_numbers, current, page_number_to_url) return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link(), 'page_links': page_links } def to_html(self): template = loader.get_template(self.template) context = Context(self.get_html_context()) return template.render(context) class LimitOffsetPagination(BasePagination): """ A limit/offset based style. For example: http://api.example.org/accounts/?limit=100 http://api.example.org/accounts/?offset=400&limit=100 """ default_limit = api_settings.PAGE_SIZE limit_query_param = 'limit' offset_query_param = 'offset' max_limit = None template = 'rest_framework/pagination/numbers.html' def paginate_queryset(self, queryset, request, view=None): self.limit = self.get_limit(request) if self.limit is None: return None self.offset = self.get_offset(request) self.count = _get_count(queryset) self.request = request if self.count > self.limit and self.template is not None: self.display_page_controls = True return list(queryset[self.offset:self.offset + self.limit]) def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) def get_limit(self, request): if self.limit_query_param: try: return _positive_int( request.query_params[self.limit_query_param], cutoff=self.max_limit ) except (KeyError, ValueError): pass return self.default_limit def get_offset(self, request): try: return _positive_int( request.query_params[self.offset_query_param], ) except (KeyError, ValueError): return 0 def get_next_link(self): if self.offset + self.limit >= self.count: return None url = self.request.build_absolute_uri() url = replace_query_param(url, self.limit_query_param, self.limit) offset = self.offset + self.limit return replace_query_param(url, self.offset_query_param, offset) def get_previous_link(self): if self.offset <= 0: return None url = self.request.build_absolute_uri() url = replace_query_param(url, self.limit_query_param, self.limit) if self.offset - self.limit <= 0: return remove_query_param(url, self.offset_query_param) offset = self.offset - self.limit return replace_query_param(url, self.offset_query_param, offset) def get_html_context(self): base_url = self.request.build_absolute_uri() current = _divide_with_ceil(self.offset, self.limit) + 1 # The number of pages is a little bit fiddly. # We need to sum both the number of pages from current offset to end # plus the number of pages up to the current offset. # When offset is not strictly divisible by the limit then we may # end up introducing an extra page as an artifact. final = ( _divide_with_ceil(self.count - self.offset, self.limit) + _divide_with_ceil(self.offset, self.limit) ) def page_number_to_url(page_number): if page_number == 1: return remove_query_param(base_url, self.offset_query_param) else: offset = self.offset + ((page_number - current) * self.limit) return replace_query_param(base_url, self.offset_query_param, offset) page_numbers = _get_displayed_page_numbers(current, final) page_links = _get_page_links(page_numbers, current, page_number_to_url) return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link(), 'page_links': page_links } def to_html(self): template = loader.get_template(self.template) context = Context(self.get_html_context()) return template.render(context) class CursorPagination(BasePagination): """ The cursor pagination implementation is neccessarily complex. For an overview of the position/offset style we use, see this post: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ """ cursor_query_param = 'cursor' page_size = api_settings.PAGE_SIZE invalid_cursor_message = _('Invalid cursor') ordering = '-created' template = 'rest_framework/pagination/previous_and_next.html' def paginate_queryset(self, queryset, request, view=None): page_size = self.get_page_size(request) if not page_size: return None self.base_url = request.build_absolute_uri() self.ordering = self.get_ordering(request, queryset, view) self.cursor = self.decode_cursor(request) if self.cursor is None: (offset, reverse, current_position) = (0, False, None) else: (offset, reverse, current_position) = self.cursor # Cursor pagination always enforces an ordering. if reverse: queryset = queryset.order_by(*_reverse_ordering(self.ordering)) else: queryset = queryset.order_by(*self.ordering) # If we have a cursor with a fixed position then filter by that. if current_position is not None: order = self.ordering[0] is_reversed = order.startswith('-') order_attr = order.lstrip('-') # Test for: (cursor reversed) XOR (queryset reversed) if self.cursor.reverse != is_reversed: kwargs = {order_attr + '__lt': current_position} else: kwargs = {order_attr + '__gt': current_position} queryset = queryset.filter(**kwargs) # If we have an offset cursor then offset the entire page by that amount. # We also always fetch an extra item in order to determine if there is a # page following on from this one. results = list(queryset[offset:offset + page_size + 1]) self.page = list(results[:page_size]) # Determine the position of the final item following the page. if len(results) > len(self.page): has_following_postion = True following_position = self._get_position_from_instance(results[-1], self.ordering) else: has_following_postion = False following_position = None # If we have a reverse queryset, then the query ordering was in reverse # so we need to reverse the items again before returning them to the user. if reverse: self.page = list(reversed(self.page)) if reverse: # Determine next and previous positions for reverse cursors. self.has_next = (current_position is not None) or (offset > 0) self.has_previous = has_following_postion if self.has_next: self.next_position = current_position if self.has_previous: self.previous_position = following_position else: # Determine next and previous positions for forward cursors. self.has_next = has_following_postion self.has_previous = (current_position is not None) or (offset > 0) if self.has_next: self.next_position = following_position if self.has_previous: self.previous_position = current_position # Display page controls in the browsable API if there is more # than one page. if (self.has_previous or self.has_next) and self.template is not None: self.display_page_controls = True return self.page def get_page_size(self, request): return self.page_size def get_next_link(self): if not self.has_next: return None if self.cursor and self.cursor.reverse and self.cursor.offset != 0: # If we're reversing direction and we have an offset cursor # then we cannot use the first position we find as a marker. compare = self._get_position_from_instance(self.page[-1], self.ordering) else: compare = self.next_position offset = 0 for item in reversed(self.page): position = self._get_position_from_instance(item, self.ordering) if position != compare: # The item in this position and the item following it # have different positions. We can use this position as # our marker. break # The item in this postion has the same position as the item # following it, we can't use it as a marker position, so increment # the offset and keep seeking to the previous item. compare = position offset += 1 else: # There were no unique positions in the page. if not self.has_previous: # We are on the first page. # Our cursor will have an offset equal to the page size, # but no position to filter against yet. offset = self.page_size position = None elif self.cursor.reverse: # The change in direction will introduce a paging artifact, # where we end up skipping forward a few extra items. offset = 0 position = self.previous_position else: # Use the position from the existing cursor and increment # it's offset by the page size. offset = self.cursor.offset + self.page_size position = self.previous_position cursor = Cursor(offset=offset, reverse=False, position=position) return self.encode_cursor(cursor) def get_previous_link(self): if not self.has_previous: return None if self.cursor and not self.cursor.reverse and self.cursor.offset != 0: # If we're reversing direction and we have an offset cursor # then we cannot use the first position we find as a marker. compare = self._get_position_from_instance(self.page[0], self.ordering) else: compare = self.previous_position offset = 0 for item in self.page: position = self._get_position_from_instance(item, self.ordering) if position != compare: # The item in this position and the item following it # have different positions. We can use this position as # our marker. break # The item in this postion has the same position as the item # following it, we can't use it as a marker position, so increment # the offset and keep seeking to the previous item. compare = position offset += 1 else: # There were no unique positions in the page. if not self.has_next: # We are on the final page. # Our cursor will have an offset equal to the page size, # but no position to filter against yet. offset = self.page_size position = None elif self.cursor.reverse: # Use the position from the existing cursor and increment # it's offset by the page size. offset = self.cursor.offset + self.page_size position = self.next_position else: # The change in direction will introduce a paging artifact, # where we end up skipping back a few extra items. offset = 0 position = self.next_position cursor = Cursor(offset=offset, reverse=True, position=position) return self.encode_cursor(cursor) def get_ordering(self, request, queryset, view): """ Return a tuple of strings, that may be used in an `order_by` method. """ ordering_filters = [ filter_cls for filter_cls in getattr(view, 'filter_backends', []) if hasattr(filter_cls, 'get_ordering') ] if ordering_filters: # If a filter exists on the view that implements `get_ordering` # then we defer to that filter to determine the ordering. filter_cls = ordering_filters[0] filter_instance = filter_cls() ordering = filter_instance.get_ordering(request, queryset, view) assert ordering is not None, ( 'Using cursor pagination, but filter class {filter_cls} ' 'returned a `None` ordering.'.format( filter_cls=filter_cls.__name__ ) ) else: # The default case is to check for an `ordering` attribute # on this pagination instance. ordering = self.ordering assert ordering is not None, ( 'Using cursor pagination, but no ordering attribute was declared ' 'on the pagination class.' ) assert isinstance(ordering, (six.string_types, list, tuple)), ( 'Invalid ordering. Expected string or tuple, but got {type}'.format( type=type(ordering).__name__ ) ) if isinstance(ordering, six.string_types): return (ordering,) return tuple(ordering) def decode_cursor(self, request): """ Given a request with a cursor, return a `Cursor` instance. """ # Determine if we have a cursor, and if so then decode it. encoded = request.query_params.get(self.cursor_query_param) if encoded is None: return None # The offset in the cursor is used in situations where we have a # nearly-unique index. (Eg millisecond precision creation timestamps) # We guard against malicious users attempting to cause expensive database # queries, by having a hard cap on the maximum possible size of the offset. OFFSET_CUTOFF = 1000 try: querystring = b64decode(encoded.encode('ascii')).decode('ascii') tokens = urlparse.parse_qs(querystring, keep_blank_values=True) offset = tokens.get('o', ['0'])[0] offset = _positive_int(offset, cutoff=OFFSET_CUTOFF) reverse = tokens.get('r', ['0'])[0] reverse = bool(int(reverse)) position = tokens.get('p', [None])[0] except (TypeError, ValueError): raise NotFound(self.invalid_cursor_message) return Cursor(offset=offset, reverse=reverse, position=position) def encode_cursor(self, cursor): """ Given a Cursor instance, return an url with encoded cursor. """ tokens = {} if cursor.offset != 0: tokens['o'] = str(cursor.offset) if cursor.reverse: tokens['r'] = '1' if cursor.position is not None: tokens['p'] = cursor.position querystring = urlparse.urlencode(tokens, doseq=True) encoded = b64encode(querystring.encode('ascii')).decode('ascii') return replace_query_param(self.base_url, self.cursor_query_param, encoded) def _get_position_from_instance(self, instance, ordering): attr = getattr(instance, ordering[0].lstrip('-')) return six.text_type(attr) def get_paginated_response(self, data): return Response(OrderedDict([ ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) def get_html_context(self): return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link() } def to_html(self): template = loader.get_template(self.template) context = Context(self.get_html_context()) return template.render(context)
import re import sys import os import json import version import data_migration from Exceptions import * def addNewTodo(app, arguments): if len(arguments) < 1: raise ChaidoError("No todo item was provided") newTodoIndex = app.addTodo(arguments[0]) if len(arguments) >= 3 and arguments[1] == 'before': app.setTaskAsDependant(newTodoIndex, arguments[2:]) highest_priority = app.getTaskPriority(arguments[2]) for task in arguments[2:]: task_priority = app.getTaskPriority(task) if task_priority < highest_priority: highest_priority = task_priority app.setTaskPriority(newTodoIndex, highest_priority) return "OK" def addNewTodoToTop(app, arguments): if len(arguments) < 1: raise ChaidoError("No todo item was provided") newTodoIndex = app.addTodo(arguments[0]) if len(arguments) >= 3 and arguments[1] == 'before': app.setTaskAsDependant(newTodoIndex, arguments[2:]) app.setTaskPriority(newTodoIndex, app.getTaskPriority("1") - 1) return "OK" def removeTodoWithoutLogging(app, arguments): while len(arguments) > 0: app.removeTodo(arguments.pop(0), log=False) return "OK" def removeTodo(app, arguments): while len(arguments) > 0: app.removeTodo(arguments.pop(0)) return "OK" def displayHelp(app, arguments): pass def listToDos(app, arguments): if app.visibleDirty: app.recalculateVisible() result = [] for counter, todo in enumerate(app.getVisibleTodos()): if len(arguments) > 0 and arguments[0] == 'short': todo_name = str(app.todoItems[todo]['name']) todo_words = todo_name.split(' ') todo_number = str(counter + 1) result.append(todo_number + ": " + ' '.join(todo_words[0:7])) for word_bunch in range(7,len(todo_words), 7): result.append(' ' * (len(todo_number) + 2) + ' '.join(todo_words[word_bunch:word_bunch + 7])) else: result.append(str(counter + 1) + ': ' + str(app.todoItems[todo]['name'])) return "\n".join(result) def listAllToDos(app, arguments): result = [] for task_index in sorted(list(app.todoItems.keys())): result.append(str(app.todoItems[task_index]['name'])) return "\n".join(result) def setTaskAsDependant(app, arguments): if "then" in arguments: taskLists = [[]] for argument in arguments: if argument == 'then': taskLists.append([]) else: taskLists[-1].append(argument) if len(taskLists) < 2: raise ChaidoError("Syntax is {tasks to do first} then {tasks to do later} ... then ... etc") for taskListNumber, taskList in enumerate(taskLists[:-1]): for beforeTask in taskList: app.setTaskAsDependant(beforeTask, taskLists[taskListNumber + 1]) else: listingBeforeTasks = True beforeTasks = [] afterTasks = [] if "before" not in arguments: raise ChaidoError("Syntax is {tasks to do first} before {tasks to do later}") for argument in arguments: if argument == 'before': listingBeforeTasks = False elif listingBeforeTasks: beforeTasks.append(argument) else: afterTasks.append(argument) if len(afterTasks) == 0: raise ChaidoError("You must specify task(s) that depend on " + dependant) for beforeTask in beforeTasks: app.setTaskAsDependant(beforeTask, afterTasks) return "OK" def bumpTodo(app, arguments): if 'before' in arguments: listingBeforeTasks = True beforeTasks = [] afterTasks = [] for argument in arguments: if argument == 'before': listingBeforeTasks = False elif listingBeforeTasks: beforeTasks.append(argument) else: afterTasks.append(argument) max_priority = app.getTaskPriority(afterTasks[0]) for afterTask in afterTasks: if max_priority > app.getTaskPriority(afterTask): max_priority = app.getTaskPriority(afterTask) for beforeTask in beforeTasks: app.setTaskPriority(beforeTask, max_priority - 1) else: for argument in arguments: app.bumpTodo(argument) return "OK" def renameTodo(app, arguments): if len(arguments) < 2: raise ChaidoError("You must specify a task, and the new name for the task") taskIndex = app.getTaskIndexByIdentifier(arguments[0]) app.setTaskName(taskIndex, arguments[1]) return "OK" def pushTodoDown(app, arguments): if len(arguments) == 0: raise ChaidoError("You must specify a task to push down the list") if 'after' in arguments: beforeTasks = [] afterTasks = [] listingBeforeTasks = True for argument in arguments: if argument == 'after': listingBeforeTasks = False elif listingBeforeTasks: beforeTasks.append(argument) else: afterTasks.append(argument) if len(afterTasks) == 0: raise ChaidoError("You must specify task(s) that you want to push these after") for beforeTask in beforeTasks: app.pushTaskAfter(beforeTask, afterTasks) else: for argument in arguments: app.pushTaskToBottom(argument) return "OK" commands = { "new" : addNewTodoToTop, "later" : addNewTodo, "done" : removeTodo, "help" : displayHelp, "list" : listToDos, "all" : listAllToDos, "bump" : bumpTodo, "must" : setTaskAsDependant, "rename" : renameTodo, "remove" : removeTodoWithoutLogging, "push" : pushTodoDown, } def cleanUpArguments(argumentList): argumentsToJoin = [] result = [] for (index, arg) in enumerate(argumentList): if arg in ['before', 'then'] or isInt(arg): if len(argumentsToJoin) > 0: result.append(" ".join(argumentsToJoin)) argumentsToJoin = [] if isInt(arg): result.append(int(arg)) else: result.append(arg) elif re.match(r'^\d+-\d+$', arg): start_range = int(arg.split('-')[0]) end_range = int(arg.split('-')[1]) + 1 result += list(range(start_range, end_range)) else: argumentsToJoin.append(arg) if len(argumentsToJoin) > 0: result.append(" ".join(argumentsToJoin)) return result def isInt(s): try: int(s) return True except ValueError: return False class ChaidoApp: def __init__(self): self.todoItems = {} self.visibleTodoItems = [] self.visibleDirty = False self.nextTodoIndex = 0 self.next_max_priority = -1 self.logMessages = [] def getLogMessages(self): return self.logMessages def log(self, command, message): self.logMessages.append({ "command" : command, "message" : message }) @property def totalTodoCount(self): if self.visibleDirty: self.recalculateVisible() return len(self.todoItems) @property def visibleTodoCount(self): if self.visibleDirty: self.recalculateVisible() return len(self.visibleTodoItems) def setTaskName(self, taskIndex, newName): oldName = self.todoItems[taskIndex]['name'] self.todoItems[taskIndex]['name'] = newName self.log("rename", "\t".join([oldName, newName])) def getVisibleTodos(self): if self.visibleDirty: self.recalculateVisible() return self.visibleTodoItems def addTodo(self, todoName): self.todoItems[str(self.nextTodoIndex)] = {"name" : todoName, "children" : [], "priority" : self.nextTodoIndex} self.visibleTodoItems.append(str(self.nextTodoIndex)) self.nextTodoIndex += 1 self.log("new", todoName) return len(self.visibleTodoItems) def bumpTodo(self, todoName): self.visibleDirty = True taskIndex = self.getTaskIndexByIdentifier(todoName) self.todoItems[taskIndex]['priority'] -= 1 def getTaskPriority(self, todoName): taskIndex = self.getTaskIndexByIdentifier(todoName) return self.todoItems[taskIndex]['priority'] def setTaskPriority(self, todoName, newPriority): self.visibleDirty = True taskIndex = self.getTaskIndexByIdentifier(todoName) self.todoItems[taskIndex]['priority'] = newPriority def pushTaskAfter(self, beforeTask, afterTasks): lowest_priority = None for task in afterTasks: task_priority = self.getTaskPriority(task) if lowest_priority is None: lowest_priority = task_priority elif lowest_priority < task_priority: lowest_priority = task_priority self.setTaskPriority(beforeTask, lowest_priority + 1) def removeTodo(self, todoName, log=True): self.visibleDirty = True taskIndex = self.getTaskIndexByIdentifier(todoName) if taskIndex not in self.todoItems: raise ChaidoError("No such task: " + todoName) if log: self.log("done", self.todoItems[taskIndex]['name']) del self.todoItems[taskIndex] def setTaskAsDependant(self, beforeTask, afterTasks): self.visibleDirty = True beforeTaskIndex = self.getTaskIndexByIdentifier(beforeTask) for afterTask in afterTasks: afterTaskIndex = self.getTaskIndexByIdentifier(afterTask) if afterTaskIndex == beforeTaskIndex: continue self.log('set_dependant', self.todoItems[afterTaskIndex]['name'] + "\t" + self.todoItems[beforeTaskIndex]['name']) self.todoItems[afterTaskIndex]['children'].append(beforeTaskIndex) def getTaskIndexByIdentifier(self, todoIdentifier): if isInt(todoIdentifier): return self.visibleTodoItems[int(todoIdentifier) - 1] else: return self.getTaskIndexByName(todoIdentifier) def getTaskIndexByName(self, task): for index, todo in self.todoItems.items(): if todo.get("name") == task: return index raise ChaidoError("No visible task named " + task) def pushTaskToBottom(self, taskName): self.visibleDirty = True taskIndex = self.getTaskIndexByIdentifier(taskName) self.setTaskPriority(taskName, self.todoItems[self.visibleTodoItems[-1]]['priority'] + 1) def recalculateVisible(self): self.visibleTodoItems = sorted(self.todoItems.keys(), key=(lambda x : int(self.todoItems[x]['priority']))) for index, todoItem in self.todoItems.items(): newChildrenList = [] for child in todoItem['children']: if child in self.todoItems: newChildrenList.append(child) todoItem['children'] = newChildrenList if len(newChildrenList) > 0: self.visibleTodoItems.remove(index) self.visibleDirty = False def getTodo(self, index): if self.visibleDirty: self.recalculateVisible() if index > len(self.visibleTodoItems): raise ChaidoError("There are fewer than " + str(index) + " visible todos") return self.todoItems[self.visibleTodoItems[index]].get("name") def addDependantTasks(self, dependantTask, depended): newIndex = self.addTodo(dependantTask) self.todoItems[newIndex]['children'].append( [self.getTaskIndexByIdentifier(task) for task in depended] ) def load(self, filename): if os.path.exists(filename): with open(filename, "r") as f: data = json.loads(f.read()) if '__format_version__' not in data: data['__format_version__'] = 0 if data['__format_version__'] <= version.__format_version__: data = data_migration.migrate_old_data(data) self.todoItems = data.get('todo_items', {}) self.visibleTodoItems = data.get('visible_todo_items', []) self.nextTodoIndex = data.get('next_todo_index', 0) self.visibleDirty = data['visible_dirty'] self.next_max_priority = data['next_max_priority'] def save(self, filename): data = {} data['visible_dirty'] = self.visibleDirty data['todo_items'] = self.todoItems data['visible_todo_items'] = self.visibleTodoItems data['next_todo_index'] = self.nextTodoIndex data['next_max_priority'] = self.next_max_priority data['__format_version__'] = version.__format_version__ with open(filename, "w") as f: f.write(json.dumps(data))
# Copyright (c) 2013 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. """ Unit Tests for ml2 rpc """ import collections import contextlib import mock from oslo_context import context as oslo_context from sqlalchemy.orm import exc from neutron.agent import rpc as agent_rpc from neutron.common import constants from neutron.common import exceptions from neutron.common import topics from neutron.plugins.ml2.drivers import type_tunnel from neutron.plugins.ml2 import rpc as plugin_rpc from neutron.tests import base class RpcCallbacksTestCase(base.BaseTestCase): def setUp(self): super(RpcCallbacksTestCase, self).setUp() self.callbacks = plugin_rpc.RpcCallbacks(mock.Mock(), mock.Mock()) self.manager = mock.patch.object( plugin_rpc.manager, 'NeutronManager').start() self.l3plugin = mock.Mock() self.manager.get_service_plugins.return_value = { 'L3_ROUTER_NAT': self.l3plugin } self.plugin = self.manager.get_plugin() def _test_update_device_up(self, extensions, kwargs): with mock.patch('neutron.plugins.ml2.plugin.Ml2Plugin' '._device_to_port_id'): type(self.l3plugin).supported_extension_aliases = ( mock.PropertyMock(return_value=extensions)) self.callbacks.update_device_up(mock.ANY, **kwargs) def test_update_device_up_without_dvr(self): kwargs = { 'agent_id': 'foo_agent', 'device': 'foo_device' } self._test_update_device_up(['router'], kwargs) self.assertFalse(self.l3plugin.dvr_vmarp_table_update.call_count) def test_update_device_up_with_dvr(self): kwargs = { 'agent_id': 'foo_agent', 'device': 'foo_device' } self._test_update_device_up(['router', 'dvr'], kwargs) self.l3plugin.dvr_vmarp_table_update.assert_called_once_with( mock.ANY, mock.ANY, 'add') def test_update_device_up_with_dvr_when_port_not_found(self): kwargs = { 'agent_id': 'foo_agent', 'device': 'foo_device' } self.l3plugin.dvr_vmarp_table_update.side_effect = ( exceptions.PortNotFound(port_id='foo_port_id')) self._test_update_device_up(['router', 'dvr'], kwargs) self.assertTrue(self.l3plugin.dvr_vmarp_table_update.call_count) def test_get_device_details_without_port_context(self): self.plugin.get_bound_port_context.return_value = None self.assertEqual( {'device': 'fake_device'}, self.callbacks.get_device_details('fake_context', device='fake_device')) def test_get_device_details_port_context_without_bounded_segment(self): self.plugin.get_bound_port_context().bottom_bound_segment = None self.assertEqual( {'device': 'fake_device'}, self.callbacks.get_device_details('fake_context', device='fake_device')) def test_get_device_details_port_status_equal_new_status(self): port = collections.defaultdict(lambda: 'fake') self.plugin.get_bound_port_context().current = port for admin_state_up in (True, False): new_status = (constants.PORT_STATUS_BUILD if admin_state_up else constants.PORT_STATUS_DOWN) for status in (constants.PORT_STATUS_ACTIVE, constants.PORT_STATUS_BUILD, constants.PORT_STATUS_DOWN, constants.PORT_STATUS_ERROR): port['admin_state_up'] = admin_state_up port['status'] = status self.plugin.update_port_status.reset_mock() self.callbacks.get_device_details('fake_context', host='fake_host') self.assertEqual(status == new_status, not self.plugin.update_port_status.called) def test_get_devices_details_list(self): devices = [1, 2, 3, 4, 5] kwargs = {'host': 'fake_host', 'agent_id': 'fake_agent_id'} with mock.patch.object(self.callbacks, 'get_device_details', side_effect=devices) as f: res = self.callbacks.get_devices_details_list('fake_context', devices=devices, **kwargs) self.assertEqual(devices, res) self.assertEqual(len(devices), f.call_count) calls = [mock.call('fake_context', device=i, **kwargs) for i in devices] f.assert_has_calls(calls) def test_get_devices_details_list_with_empty_devices(self): with mock.patch.object(self.callbacks, 'get_device_details') as f: res = self.callbacks.get_devices_details_list('fake_context') self.assertFalse(f.called) self.assertEqual([], res) def _test_update_device_not_bound_to_host(self, func): self.plugin.port_bound_to_host.return_value = False self.plugin._device_to_port_id.return_value = 'fake_port_id' res = func('fake_context', device='fake_device', host='fake_host') self.plugin.port_bound_to_host.assert_called_once_with('fake_context', 'fake_port_id', 'fake_host') return res def test_update_device_up_with_device_not_bound_to_host(self): self.assertIsNone(self._test_update_device_not_bound_to_host( self.callbacks.update_device_up)) def test_update_device_down_with_device_not_bound_to_host(self): self.assertEqual( {'device': 'fake_device', 'exists': True}, self._test_update_device_not_bound_to_host( self.callbacks.update_device_down)) def test_update_device_down_call_update_port_status(self): self.plugin.update_port_status.return_value = False self.plugin._device_to_port_id.return_value = 'fake_port_id' self.assertEqual( {'device': 'fake_device', 'exists': False}, self.callbacks.update_device_down('fake_context', device='fake_device', host='fake_host')) self.plugin.update_port_status.assert_called_once_with( 'fake_context', 'fake_port_id', constants.PORT_STATUS_DOWN, 'fake_host') def test_update_device_down_call_update_port_status_failed(self): self.plugin.update_port_status.side_effect = exc.StaleDataError self.assertEqual({'device': 'fake_device', 'exists': False}, self.callbacks.update_device_down( 'fake_context', device='fake_device')) class RpcApiTestCase(base.BaseTestCase): def _test_rpc_api(self, rpcapi, topic, method, rpc_method, **kwargs): ctxt = oslo_context.RequestContext('fake_user', 'fake_project') expected_retval = 'foo' if rpc_method == 'call' else None expected_version = kwargs.pop('version', None) fanout = kwargs.pop('fanout', False) with contextlib.nested( mock.patch.object(rpcapi.client, rpc_method), mock.patch.object(rpcapi.client, 'prepare'), ) as ( rpc_mock, prepare_mock ): prepare_mock.return_value = rpcapi.client rpc_mock.return_value = expected_retval retval = getattr(rpcapi, method)(ctxt, **kwargs) prepare_args = {} if expected_version: prepare_args['version'] = expected_version if fanout: prepare_args['fanout'] = fanout if topic: prepare_args['topic'] = topic prepare_mock.assert_called_once_with(**prepare_args) self.assertEqual(retval, expected_retval) rpc_mock.assert_called_once_with(ctxt, method, **kwargs) def test_delete_network(self): rpcapi = plugin_rpc.AgentNotifierApi(topics.AGENT) self._test_rpc_api( rpcapi, topics.get_topic_name(topics.AGENT, topics.NETWORK, topics.DELETE), 'network_delete', rpc_method='cast', fanout=True, network_id='fake_request_spec') def test_port_update(self): rpcapi = plugin_rpc.AgentNotifierApi(topics.AGENT) self._test_rpc_api( rpcapi, topics.get_topic_name(topics.AGENT, topics.PORT, topics.UPDATE), 'port_update', rpc_method='cast', fanout=True, port='fake_port', network_type='fake_network_type', segmentation_id='fake_segmentation_id', physical_network='fake_physical_network') def test_tunnel_update(self): rpcapi = plugin_rpc.AgentNotifierApi(topics.AGENT) self._test_rpc_api( rpcapi, topics.get_topic_name(topics.AGENT, type_tunnel.TUNNEL, topics.UPDATE), 'tunnel_update', rpc_method='cast', fanout=True, tunnel_ip='fake_ip', tunnel_type='gre') def test_device_details(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_rpc_api(rpcapi, None, 'get_device_details', rpc_method='call', device='fake_device', agent_id='fake_agent_id', host='fake_host') def test_devices_details_list(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_rpc_api(rpcapi, None, 'get_devices_details_list', rpc_method='call', devices=['fake_device1', 'fake_device2'], agent_id='fake_agent_id', host='fake_host', version='1.3') def test_update_device_down(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_rpc_api(rpcapi, None, 'update_device_down', rpc_method='call', device='fake_device', agent_id='fake_agent_id', host='fake_host') def test_tunnel_sync(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_rpc_api(rpcapi, None, 'tunnel_sync', rpc_method='call', tunnel_ip='fake_tunnel_ip', tunnel_type=None) def test_update_device_up(self): rpcapi = agent_rpc.PluginApi(topics.PLUGIN) self._test_rpc_api(rpcapi, None, 'update_device_up', rpc_method='call', device='fake_device', agent_id='fake_agent_id', host='fake_host')
#!/usr/bin/python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import sys import getpass from urlparse import urljoin from allura.lib import rest_api SRC_CRED = dict( api_key='c03efc6cca1cf78be9e9', secret_key='575eda2f25f6490d8cfe5d02f2506c010112894d0ea10660e43157a87a7e620c61ac06397b028af1', http_username=raw_input('LDAP username: '), http_password=getpass.getpass('LDAP password: ')) SRC_SERVER = 'https://newforge.sf.geek.net/' SRC_TOOL = '/rest/p/forge/tickets/' # Credentials for sf-overlords # DST_CRED=dict( # api_key='a4a88c67179137053d70', # secret_key='fcc48a0c31459e99a88cc42cdd7f908fad78b283ca30a86caac1ab65036ff71fc195a18e56534dc5') # DST_SERVER='http://sourceforge.net/' # DST_TOOL='/rest/p/allura/tickets/' DST_CRED = dict( api_key='aa7244645424513d9636', secret_key='cd1d97be98497f7b615b297aa2061177ddf6d42b95a8484193f84690486694234dbf817efc3b2d6e') DST_SERVER = 'http://localhost:8080/' DST_TOOL = '/rest/p/test/bugs/' FAKE_TICKET = { u'created_date': u'2010-03-08 17:29:42.802000', u'assigned_to_id': u'', u'assigned_to': u'', u'custom_fields': {'_component': '', '_size': 0, '_priority': '', '_type': ''}, u'description': u'Ticket was not present in source', u'milestone': u'', u'reported_by': u'', u'reported_by_id': u'', u'status': u'closed', u'sub_ids': [], u'summary': u'Placeholder ticket', u'super_id': u'None'} def main(): src_cli = rest_api.RestClient( base_uri=SRC_SERVER, **SRC_CRED) dst_cli = rest_api.RestClient( base_uri=DST_SERVER, **DST_CRED) src = TicketAPI(src_cli, SRC_TOOL) dst = TicketAPI(dst_cli, DST_TOOL) for ticket in src.iter_tickets(min_ticket=3, check=True): print 'Migrating ticket %s:\n%s' % (ticket['ticket_num'], ticket) print 'Create ticket on %s' % DST_SERVER dst.create_ticket(ticket) print 'Create discussion on %s' % DST_SERVER src_thread = src.load_thread(ticket) if not src_thread or not src_thread['posts']: print '... no posts' continue dst_thread = dst.load_thread(ticket) slug_map = {} for post in src.iter_posts(src_thread): print '... migrate post %s:\n%r' % (post['slug'], post['text']) dst.create_post(dst_thread, post, slug_map) class TicketAPI(object): def __init__(self, client, path): self.client = client self.path = path def iter_tickets(self, min_ticket=1, max_ticket=None, check=False): if check: tickets = self.client.request('GET', self.path)['tickets'] valid_tickets = set(t['ticket_num'] for t in tickets) max_valid_ticket = max(valid_tickets) cur_ticket = min_ticket while True: if check and cur_ticket not in valid_tickets: if cur_ticket > max_valid_ticket: break yield dict(FAKE_TICKET, ticket_num=cur_ticket) cur_ticket += 1 continue ticket = self.client.request( 'GET', self.ticket_path(cur_ticket))['ticket'] if ticket is None: break yield ticket cur_ticket += 1 if max_ticket and cur_ticket > max_ticket: break def load_thread(self, ticket): discussion = self.client.request( 'GET', self.discussion_path())['discussion'] for thd in discussion['threads']: if thd['subject'].startswith('#%d ' % ticket['ticket_num']): break else: return None thread = self.client.request( 'GET', self.thread_path(thd['_id']))['thread'] return thread def iter_posts(self, thread): for p in sorted(thread['posts'], key=lambda p: p['slug']): post = self.client.request( 'GET', self.post_path(thread['_id'], p['slug']))['post'] yield post def create_ticket(self, ticket): ticket = dict(ticket, labels='') ticket['description'] = 'Created by: %s\nCreated date: %s\nAssigned to:%s\n\n%s' % ( ticket['reported_by'], ticket['created_date'], ticket['assigned_to'], ticket['description']) for bad_key in ('assigned_to_id', 'created_date', 'reported_by', 'reported_by_id', 'super_id', 'sub_ids', '_id'): if bad_key in ticket: del ticket[bad_key] ticket.setdefault('labels', '') ticket['custom_fields'].setdefault('_size', 0) ticket['custom_fields'].setdefault('_priority', 'low') ticket['custom_fields'].setdefault('_type', 'Bug') ticket['custom_fields'].setdefault('_type', 'Component') if ticket['custom_fields']['_size'] is None: ticket['custom_fields']['_size'] = 0 if ticket['milestone'] not in ('backlog', 'public2', 'GA', 'post-GA'): ticket['milestone'] = '' if ticket['status'] not in 'open in-progress code-review validation closed'.split(): ticket['status'] = 'open' r = self.client.request( 'POST', self.new_ticket_path(), ticket_form=ticket) self.client.request( 'POST', self.ticket_path(r['ticket']['ticket_num'], 'save'), ticket_form=ticket) def create_post(self, thread, post, slug_map): text = 'Post by %s:\n%s' % ( post['author'], post['text']) if '/' in post['slug']: parent_post = slug_map[post['slug'].rsplit('/', 1)[0]] new_post = self.client.request( 'POST', self.post_path(thread['_id'], parent_post, 'reply'), text=text)['post'] else: new_post = self.client.request( 'POST', self.thread_path(thread['_id'], 'new'), text=text)['post'] slug_map[post['slug']] = new_post['slug'] return new_post def new_ticket_path(self): return urljoin(self.path, 'new') def ticket_path(self, ticket_num, suffix=''): return urljoin(self.path, str(ticket_num)) + '/' + suffix def discussion_path(self): return '%s_discuss/' % (self.path) def thread_path(self, thread_id, suffix=''): return '%s_discuss/thread/%s/%s' % (self.path, thread_id, suffix) def post_path(self, thread_id, post_slug, suffix=''): return '%s_discuss/thread/%s/%s/%s' % (self.path, thread_id, post_slug, suffix) def pm(etype, value, tb): # pragma no cover import pdb import traceback try: from IPython.ipapi import make_session make_session() from IPython.Debugger import Pdb sys.stderr.write('Entering post-mortem IPDB shell\n') p = Pdb(color_scheme='Linux') p.reset() p.setup(None, tb) p.print_stack_trace() sys.stderr.write('%s: %s\n' % (etype, value)) p.cmdloop() p.forget() # p.interaction(None, tb) except ImportError: sys.stderr.write('Entering post-mortem PDB shell\n') traceback.print_exception(etype, value, tb) pdb.post_mortem(tb) sys.excepthook = pm if __name__ == '__main__': main()
from django.core.exceptions import ValidationError from cyder.base.tests import ModelTestMixin from cyder.core.ctnr.models import Ctnr from cyder.core.system.models import System from cyder.cydhcp.interface.static_intr.models import StaticInterface from cyder.cydhcp.range.models import Range from cyder.cydhcp.constants import STATIC from cyder.cydhcp.network.models import Network from cyder.cydhcp.vrf.models import Vrf from cyder.cydns.address_record.models import AddressRecord from cyder.cydns.cname.models import CNAME from cyder.cydns.domain.models import Domain from cyder.cydns.nameserver.models import Nameserver from cyder.cydns.mx.models import MX from cyder.cydns.ptr.models import PTR from cyder.cydns.soa.models import SOA from cyder.cydns.srv.models import SRV from cyder.cydns.tests.utils import create_zone, DNSTest from cyder.cydns.txt.models import TXT class CNAMETests(DNSTest, ModelTestMixin): def setUp(self): super(CNAMETests, self).setUp() self.vrf = Vrf.objects.create(name='test_vrf') create_zone('128.in-addr.arpa') self.ctnr2 = Ctnr.objects.create(name='test_ctnr2') self.g = create_zone('gz') self.c_g = create_zone('coo.gz') self.d = create_zone('dz') Domain.objects.create(name='cd') self.whatcd = create_zone('what.cd') for dom in (self.g, self.c_g, self.d, self.whatcd): self.ctnr.domains.add(dom) self.r1 = create_zone('10.in-addr.arpa') self.r1.save() self.s = System.objects.create(name='test_system') self.net1 = Network.objects.create(network_str='10.0.0.0/8') self.net2 = Network.objects.create(network_str='128.193.1.0/30') self.sr1 = Range.objects.create( network=self.net1, range_type=STATIC, start_str='10.0.0.1', end_str='10.0.0.3') self.sr2 = Range.objects.create( network=self.net1, range_type=STATIC, start_str='10.193.1.1', end_str='10.193.1.2') self.sr3 = Range.objects.create( network=self.net2, range_type=STATIC, start_str='128.193.1.1', end_str='128.193.1.2') for r in (self.sr1, self.sr2, self.sr3): self.ctnr.ranges.add(r) def create_cname(self, **kwargs): kwargs.setdefault('ctnr', self.ctnr) return CNAME.objects.create(**kwargs) @property def objs(self): """Create objects for test_create_delete.""" return ( self.create_cname( label='a', domain=self.g, target='foo.com'), self.create_cname( label='bbbbbbbbbbbbbbbbb', domain=self.c_g, target='foo.foo.com'), self.create_cname( label='c-c-c-c-c-c-c-c-c', domain=self.g, target='foo.com'), self.create_cname( label='d1d', domain=self.g, target='foo.com'), ) def test1_add_glob(self): self.create_cname(label='*foo', domain=self.g, target='foo.com') self.create_cname(label='*', domain=self.c_g, target='foo.foo.com') self.assertRaises( ValidationError, self.create_cname, label='*.fo1', domain=self.g, target='foo.com') self.create_cname( label='*sadfasfd-asdf', domain=self.g, target='foo.com') def test2_add_glob(self): self.create_cname(label='*coo', domain=self.g, target='foo.com') self.create_cname(label='*', domain=self.c_g, target='foo.com') def test_soa_condition(self): self.assertRaises( ValidationError, self.create_cname, label='', domain=self.c_g, target='foo.com') def test_add_bad(self): self.assertRaises( ValidationError, self.create_cname, label='', domain=self.g, target='..foo.com') def test_add_mx_with_cname(self): def create_mx(): return MX.objects.create( label='', domain=self.c_g, ctnr=self.ctnr, server=('cnamederp1.' + self.c_g.name), priority=2, ttl=2222) create_mx.name = 'MX' def create_cname(): return CNAME.objects.create( label='cnamederp1', domain=self.c_g, ctnr=self.ctnr, target='foo.com') create_cname.name = 'CNAME' self.assertObjectsConflict((create_mx, create_cname)) def test_address_record_exists(self): def create_a(): return AddressRecord.objects.create( label='testyfoo', ctnr=self.ctnr, domain=self.whatcd, ip_type='4', ip_str="128.193.1.1") create_a.name = 'AddressRecord' def create_cname(): return CNAME.objects.create( label='testyfoo', ctnr=self.ctnr, domain=self.whatcd, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_a, create_cname)) def test_address_record_exists_uppercase(self): def create_a(): return AddressRecord.objects.create( label='testyfoo', ctnr=self.ctnr, domain=self.whatcd, ip_type='4', ip_str="128.193.1.1") create_a.name = 'AddressRecord' def create_cname(): return CNAME.objects.create( label='Testyfoo', ctnr=self.ctnr, domain=self.whatcd, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_a, create_cname)) def test_srv_exists(self): def create_srv(): return SRV.objects.create( label='_testyfoo', ctnr=self.ctnr, domain=self.whatcd, target='asdf', port=2, priority=2, weight=4) create_srv.name = 'SRV' def create_cname(): return CNAME.objects.create( label='_testyfoo', ctnr=self.ctnr, domain=self.whatcd, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_srv, create_cname)) def test_txt_exists(self): def create_txt(): return TXT.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, txt_data='asdf') create_txt.name = 'TXT' def create_cname(): return CNAME.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_txt, create_cname)) def test_mx_exists(self): def create_mx(): return MX.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, server='asdf', priority=123, ttl=123) create_mx.name = 'MX' def create_cname(): return CNAME.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_mx, create_cname)) def test_ns_exists(self): bleh = Domain.objects.create(name='bleh.what.cd') self.ctnr.domains.add(bleh) def create_ns(): return Nameserver.objects.create(domain=bleh, server='asdf') create_ns.name = 'Nameserver' def create_cname(): return CNAME.objects.create( label='', ctnr=self.ctnr, domain=bleh, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_ns, create_cname)) def test_intr_exists(self): def create_static_intr(): return StaticInterface.objects.create( label='testyfoo', domain=self.whatcd, ip_str='10.0.0.1', ip_type='4', system=self.s, ctnr=self.ctnr, mac="11:22:33:44:55:66") create_static_intr.name = 'StaticInterface' def create_cname(): return CNAME.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_static_intr, create_cname)) def test_ptr_exists(self): def create_ptr(): return PTR.objects.create( ip_str="10.193.1.1", ip_type='4', fqdn='testyfoo.what.cd', ctnr=self.ctnr) create_ptr.name = 'PTR' def create_cname(): return CNAME.objects.create( label='testyfoo', domain=self.whatcd, ctnr=self.ctnr, target='wat') create_cname.name = 'CNAME' self.assertObjectsConflict((create_ptr, create_cname)) def test_cname_point_to_itself(self): self.assertRaises( ValidationError, CNAME.objects.create, label='foopy', domain=self.whatcd, ctnr=self.ctnr, target='foopy.what.cd') def test_domain_ctnr(self): """Test that a CNAME's domain must be in the CNAME's container""" gz = Domain.objects.get(name='gz') self.ctnr.domains.add(gz) CNAME.objects.create( label='bar1', domain=gz, target='foo1.gz', ctnr=self.ctnr) self.assertRaises( ValidationError, CNAME.objects.create, label='bar2', domain=gz, target='foo2.gz', ctnr=self.ctnr2) def test_name_uniqueness(self): """Test that CNAMEs must share a ctnr if they have the same name""" cn1 = CNAME.objects.create( label='bar', domain=self.g, target='foo1.gz', ctnr=self.ctnr) cn2 = CNAME.objects.create( label='bar', domain=self.g, target='foo2.gz', ctnr=self.ctnr) self.assertRaises( ValidationError, CNAME.objects.create, label='bar', domain=self.g, target='foo3.gz', ctnr=self.ctnr2) def bootstrap_zone_and_range(self): d = Domain.objects.create(name='example.gz') self.ctnr.domains.add(d) soa = SOA.objects.create( root_domain=d, primary='ns.example.gz', contact='root.mail.example.gz') n = Network.objects.create( vrf=self.vrf, ip_type='4', network_str='128.193.0.0/24') r = Range.objects.create( network=n, range_type=STATIC, start_str='128.193.0.2', end_str='128.193.0.100') # Cyder has a catch-22 relating to nameservers: If a nameserver's name # is in the same domain it serves as a nameserver for, a glue record # must exist before that nameserver can be created, but the nameserver # must exist before the glue record can be created. Thus, we have to # set the nameserver's name to something outside the domain it's a # nameserver for, add the glue record, then fix the nameserver's name. ns = Nameserver.objects.create(domain=d, server='cyderhack') glue = AddressRecord.objects.create( label='ns', domain=d, ip_str='128.193.0.2', ctnr=self.ctnr) ns.server = 'ns.example.gz' ns.save() def test_a_mx_conflict(self): """Test that a CNAME cannot have the same name as an AR or MX""" self.bootstrap_zone_and_range() e_g = Domain.objects.get(name='example.gz') def create_cname(): return CNAME.objects.create( label='foo', domain=e_g, target='bar.example.gz', ctnr=self.ctnr) create_cname.name = 'CNAME' def create_si(): s = System.objects.create(name='test_system') return StaticInterface.objects.create( mac='be:ef:fa:ce:11:11', label='foo', domain=e_g, ip_str='128.193.0.3', ip_type='4', system=s, ctnr=self.ctnr) create_si.name = 'StaticInterface' def create_mx(): return MX.objects.create( label='foo', domain=e_g, server='mail.example.gz', priority=1, ctnr=self.ctnr) create_mx.name = 'MX' self.assertObjectsConflict((create_cname, create_si)) self.assertObjectsConflict((create_cname, create_mx)) def test_soa_conflict(self): """Test that a CNAME cannot have the same name as an SOA""" self.bootstrap_zone_and_range() f_e_g = Domain.objects.create(name='foo.example.gz') self.ctnr.domains.add(f_e_g) def create_cname(): return CNAME.objects.create( label='', domain=f_e_g.reload(), target='bar.example.gz', ctnr=self.ctnr) create_cname.name = 'CNAME' def create_soa(): return SOA.objects.create( root_domain=f_e_g.reload(), primary='ns1.example.gz', contact='root.mail.example.gz') create_soa.name = 'SOA' self.assertObjectsConflict((create_cname, create_soa)) def test_target_validation(self): """Test that target must be a valid non-IP hostname but need not exist """ valid_targets = ( 'example.com', 'www.example.com', 'foo.bar.example.com', ) for target in valid_targets: cn = CNAME.objects.create( label='bar', domain=self.g, target=target, ctnr=self.ctnr) cn.delete() invalid_targets = ( '10.234.30.253', '128.193.0.2', ) for target in invalid_targets: self.assertRaises( ValidationError, CNAME.objects.create, label='bar', domain=self.g, target=target, ctnr=self.ctnr) def test_staticinterface_conflict(self): """Test that a CNAME can't have the same name as a StaticInterface""" self.bootstrap_zone_and_range() d = Domain.objects.get(name='example.gz') def create_cname(): return CNAME.objects.create( label='foo', domain=d, target='www.example.gz', ctnr=self.ctnr) create_cname.name = 'CNAME' def create_si(): s = System.objects.create(name='test_system') return StaticInterface.objects.create( mac='be:ef:fa:ce:11:11', label='foo', domain=d, ip_str='128.193.0.3', ip_type='4', system=s, ctnr=self.ctnr) create_si.name = 'StaticInterface' self.assertObjectsConflict((create_cname, create_si)) def test_duplicate_cname(self): def x(): self.create_cname(label='foo', domain=self.g, target='foo.com') x() self.assertRaises(ValidationError, x)
import re from collections import OrderedDict, deque from collections.abc import Hashable as CollectionsHashable from datetime import date, datetime, time, timedelta from decimal import Decimal, DecimalException from enum import Enum, IntEnum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from typing import ( TYPE_CHECKING, Any, Callable, Deque, Dict, FrozenSet, Generator, Hashable, List, NamedTuple, Pattern, Set, Tuple, Type, TypeVar, Union, ) from uuid import UUID from . import errors from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time from .typing import ( AnyCallable, ForwardRef, all_literal_values, display_as_type, get_class, is_callable_type, is_literal_type, is_namedtuple, is_none_type, is_typeddict, ) from .utils import almost_equal_floats, lenient_issubclass, sequence_like if TYPE_CHECKING: from typing_extensions import Literal, TypedDict from .config import BaseConfig from .fields import ModelField from .types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt ConstrainedNumber = Union[ConstrainedDecimal, ConstrainedFloat, ConstrainedInt] AnyOrderedDict = OrderedDict[Any, Any] Number = Union[int, float, Decimal] StrBytes = Union[str, bytes] def str_validator(v: Any) -> Union[str]: if isinstance(v, str): if isinstance(v, Enum): return v.value else: return v elif isinstance(v, (float, int, Decimal)): # is there anything else we want to add here? If you think so, create an issue. return str(v) elif isinstance(v, (bytes, bytearray)): return v.decode() else: raise errors.StrError() def strict_str_validator(v: Any) -> Union[str]: if isinstance(v, str) and not isinstance(v, Enum): return v raise errors.StrError() def bytes_validator(v: Any) -> bytes: if isinstance(v, bytes): return v elif isinstance(v, bytearray): return bytes(v) elif isinstance(v, str): return v.encode() elif isinstance(v, (float, int, Decimal)): return str(v).encode() else: raise errors.BytesError() def strict_bytes_validator(v: Any) -> Union[bytes]: if isinstance(v, bytes): return v elif isinstance(v, bytearray): return bytes(v) else: raise errors.BytesError() BOOL_FALSE = {0, '0', 'off', 'f', 'false', 'n', 'no'} BOOL_TRUE = {1, '1', 'on', 't', 'true', 'y', 'yes'} def bool_validator(v: Any) -> bool: if v is True or v is False: return v if isinstance(v, bytes): v = v.decode() if isinstance(v, str): v = v.lower() try: if v in BOOL_TRUE: return True if v in BOOL_FALSE: return False except TypeError: raise errors.BoolError() raise errors.BoolError() def int_validator(v: Any) -> int: if isinstance(v, int) and not (v is True or v is False): return v try: return int(v) except (TypeError, ValueError): raise errors.IntegerError() def strict_int_validator(v: Any) -> int: if isinstance(v, int) and not (v is True or v is False): return v raise errors.IntegerError() def float_validator(v: Any) -> float: if isinstance(v, float): return v try: return float(v) except (TypeError, ValueError): raise errors.FloatError() def strict_float_validator(v: Any) -> float: if isinstance(v, float): return v raise errors.FloatError() def number_multiple_validator(v: 'Number', field: 'ModelField') -> 'Number': field_type: ConstrainedNumber = field.type_ if field_type.multiple_of is not None: mod = float(v) / float(field_type.multiple_of) % 1 if not almost_equal_floats(mod, 0.0) and not almost_equal_floats(mod, 1.0): raise errors.NumberNotMultipleError(multiple_of=field_type.multiple_of) return v def number_size_validator(v: 'Number', field: 'ModelField') -> 'Number': field_type: ConstrainedNumber = field.type_ if field_type.gt is not None and not v > field_type.gt: raise errors.NumberNotGtError(limit_value=field_type.gt) elif field_type.ge is not None and not v >= field_type.ge: raise errors.NumberNotGeError(limit_value=field_type.ge) if field_type.lt is not None and not v < field_type.lt: raise errors.NumberNotLtError(limit_value=field_type.lt) if field_type.le is not None and not v <= field_type.le: raise errors.NumberNotLeError(limit_value=field_type.le) return v def constant_validator(v: 'Any', field: 'ModelField') -> 'Any': """Validate ``const`` fields. The value provided for a ``const`` field must be equal to the default value of the field. This is to support the keyword of the same name in JSON Schema. """ if v != field.default: raise errors.WrongConstantError(given=v, permitted=[field.default]) return v def anystr_length_validator(v: 'StrBytes', config: 'BaseConfig') -> 'StrBytes': v_len = len(v) min_length = config.min_anystr_length if v_len < min_length: raise errors.AnyStrMinLengthError(limit_value=min_length) max_length = config.max_anystr_length if max_length is not None and v_len > max_length: raise errors.AnyStrMaxLengthError(limit_value=max_length) return v def anystr_strip_whitespace(v: 'StrBytes') -> 'StrBytes': return v.strip() def anystr_lower(v: 'StrBytes') -> 'StrBytes': return v.lower() def ordered_dict_validator(v: Any) -> 'AnyOrderedDict': if isinstance(v, OrderedDict): return v try: return OrderedDict(v) except (TypeError, ValueError): raise errors.DictError() def dict_validator(v: Any) -> Dict[Any, Any]: if isinstance(v, dict): return v try: return dict(v) except (TypeError, ValueError): raise errors.DictError() def list_validator(v: Any) -> List[Any]: if isinstance(v, list): return v elif sequence_like(v): return list(v) else: raise errors.ListError() def tuple_validator(v: Any) -> Tuple[Any, ...]: if isinstance(v, tuple): return v elif sequence_like(v): return tuple(v) else: raise errors.TupleError() def set_validator(v: Any) -> Set[Any]: if isinstance(v, set): return v elif sequence_like(v): return set(v) else: raise errors.SetError() def frozenset_validator(v: Any) -> FrozenSet[Any]: if isinstance(v, frozenset): return v elif sequence_like(v): return frozenset(v) else: raise errors.FrozenSetError() def deque_validator(v: Any) -> Deque[Any]: if isinstance(v, deque): return v elif sequence_like(v): return deque(v) else: raise errors.DequeError() def enum_member_validator(v: Any, field: 'ModelField', config: 'BaseConfig') -> Enum: try: enum_v = field.type_(v) except ValueError: # field.type_ should be an enum, so will be iterable raise errors.EnumMemberError(enum_values=list(field.type_)) return enum_v.value if config.use_enum_values else enum_v def uuid_validator(v: Any, field: 'ModelField') -> UUID: try: if isinstance(v, str): v = UUID(v) elif isinstance(v, (bytes, bytearray)): try: v = UUID(v.decode()) except ValueError: # 16 bytes in big-endian order as the bytes argument fail # the above check v = UUID(bytes=v) except ValueError: raise errors.UUIDError() if not isinstance(v, UUID): raise errors.UUIDError() required_version = getattr(field.type_, '_required_version', None) if required_version and v.version != required_version: raise errors.UUIDVersionError(required_version=required_version) return v def decimal_validator(v: Any) -> Decimal: if isinstance(v, Decimal): return v elif isinstance(v, (bytes, bytearray)): v = v.decode() v = str(v).strip() try: v = Decimal(v) except DecimalException: raise errors.DecimalError() if not v.is_finite(): raise errors.DecimalIsNotFiniteError() return v def hashable_validator(v: Any) -> Hashable: if isinstance(v, Hashable): return v raise errors.HashableError() def ip_v4_address_validator(v: Any) -> IPv4Address: if isinstance(v, IPv4Address): return v try: return IPv4Address(v) except ValueError: raise errors.IPv4AddressError() def ip_v6_address_validator(v: Any) -> IPv6Address: if isinstance(v, IPv6Address): return v try: return IPv6Address(v) except ValueError: raise errors.IPv6AddressError() def ip_v4_network_validator(v: Any) -> IPv4Network: """ Assume IPv4Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network """ if isinstance(v, IPv4Network): return v try: return IPv4Network(v) except ValueError: raise errors.IPv4NetworkError() def ip_v6_network_validator(v: Any) -> IPv6Network: """ Assume IPv6Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network """ if isinstance(v, IPv6Network): return v try: return IPv6Network(v) except ValueError: raise errors.IPv6NetworkError() def ip_v4_interface_validator(v: Any) -> IPv4Interface: if isinstance(v, IPv4Interface): return v try: return IPv4Interface(v) except ValueError: raise errors.IPv4InterfaceError() def ip_v6_interface_validator(v: Any) -> IPv6Interface: if isinstance(v, IPv6Interface): return v try: return IPv6Interface(v) except ValueError: raise errors.IPv6InterfaceError() def path_validator(v: Any) -> Path: if isinstance(v, Path): return v try: return Path(v) except TypeError: raise errors.PathError() def path_exists_validator(v: Any) -> Path: if not v.exists(): raise errors.PathNotExistsError(path=v) return v def callable_validator(v: Any) -> AnyCallable: """ Perform a simple check if the value is callable. Note: complete matching of argument type hints and return types is not performed """ if callable(v): return v raise errors.CallableError(value=v) def enum_validator(v: Any) -> Enum: if isinstance(v, Enum): return v raise errors.EnumError(value=v) def int_enum_validator(v: Any) -> IntEnum: if isinstance(v, IntEnum): return v raise errors.IntEnumError(value=v) def make_literal_validator(type_: Any) -> Callable[[Any], Any]: permitted_choices = all_literal_values(type_) # To have a O(1) complexity and still return one of the values set inside the `Literal`, # we create a dict with the set values (a set causes some problems with the way intersection works). # In some cases the set value and checked value can indeed be different (see `test_literal_validator_str_enum`) allowed_choices = {v: v for v in permitted_choices} def literal_validator(v: Any) -> Any: try: return allowed_choices[v] except KeyError: raise errors.WrongConstantError(given=v, permitted=permitted_choices) return literal_validator def constr_length_validator(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': v_len = len(v) min_length = field.type_.min_length if field.type_.min_length is not None else config.min_anystr_length if v_len < min_length: raise errors.AnyStrMinLengthError(limit_value=min_length) max_length = field.type_.max_length if field.type_.max_length is not None else config.max_anystr_length if max_length is not None and v_len > max_length: raise errors.AnyStrMaxLengthError(limit_value=max_length) return v def constr_strip_whitespace(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': strip_whitespace = field.type_.strip_whitespace or config.anystr_strip_whitespace if strip_whitespace: v = v.strip() return v def constr_lower(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': lower = field.type_.to_lower or config.anystr_lower if lower: v = v.lower() return v def validate_json(v: Any, config: 'BaseConfig') -> Any: if v is None: # pass None through to other validators return v try: return config.json_loads(v) # type: ignore except ValueError: raise errors.JsonError() except TypeError: raise errors.JsonTypeError() T = TypeVar('T') def make_arbitrary_type_validator(type_: Type[T]) -> Callable[[T], T]: def arbitrary_type_validator(v: Any) -> T: if isinstance(v, type_): return v raise errors.ArbitraryTypeError(expected_arbitrary_type=type_) return arbitrary_type_validator def make_class_validator(type_: Type[T]) -> Callable[[Any], Type[T]]: def class_validator(v: Any) -> Type[T]: if lenient_issubclass(v, type_): return v raise errors.SubclassError(expected_class=type_) return class_validator def any_class_validator(v: Any) -> Type[T]: if isinstance(v, type): return v raise errors.ClassError() def none_validator(v: Any) -> 'Literal[None]': if v is None: return v raise errors.NotNoneError() def pattern_validator(v: Any) -> Pattern[str]: if isinstance(v, Pattern): return v str_value = str_validator(v) try: return re.compile(str_value) except re.error: raise errors.PatternError() NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple) def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tuple[Any, ...]], NamedTupleT]: from .annotated_types import create_model_from_namedtuple NamedTupleModel = create_model_from_namedtuple( namedtuple_cls, __module__=namedtuple_cls.__module__, ) namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined] def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT: annotations = NamedTupleModel.__annotations__ if len(values) > len(annotations): raise errors.ListMaxLengthError(limit_value=len(annotations)) dict_values: Dict[str, Any] = dict(zip(annotations, values)) validated_dict_values: Dict[str, Any] = dict(NamedTupleModel(**dict_values)) return namedtuple_cls(**validated_dict_values) return namedtuple_validator def make_typeddict_validator( typeddict_cls: Type['TypedDict'], config: Type['BaseConfig'] # type: ignore[valid-type] ) -> Callable[[Any], Dict[str, Any]]: from .annotated_types import create_model_from_typeddict TypedDictModel = create_model_from_typeddict( typeddict_cls, __config__=config, __module__=typeddict_cls.__module__, ) typeddict_cls.__pydantic_model__ = TypedDictModel # type: ignore[attr-defined] def typeddict_validator(values: 'TypedDict') -> Dict[str, Any]: # type: ignore[valid-type] return TypedDictModel.parse_obj(values).dict(exclude_unset=True) return typeddict_validator class IfConfig: def __init__(self, validator: AnyCallable, *config_attr_names: str) -> None: self.validator = validator self.config_attr_names = config_attr_names def check(self, config: Type['BaseConfig']) -> bool: return any(getattr(config, name) not in {None, False} for name in self.config_attr_names) # order is important here, for example: bool is a subclass of int so has to come first, datetime before date same, # IPv4Interface before IPv4Address, etc _VALIDATORS: List[Tuple[Type[Any], List[Any]]] = [ (IntEnum, [int_validator, enum_member_validator]), (Enum, [enum_member_validator]), ( str, [ str_validator, IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), IfConfig(anystr_lower, 'anystr_lower'), IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), ], ), ( bytes, [ bytes_validator, IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), IfConfig(anystr_lower, 'anystr_lower'), IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), ], ), (bool, [bool_validator]), (int, [int_validator]), (float, [float_validator]), (Path, [path_validator]), (datetime, [parse_datetime]), (date, [parse_date]), (time, [parse_time]), (timedelta, [parse_duration]), (OrderedDict, [ordered_dict_validator]), (dict, [dict_validator]), (list, [list_validator]), (tuple, [tuple_validator]), (set, [set_validator]), (frozenset, [frozenset_validator]), (deque, [deque_validator]), (UUID, [uuid_validator]), (Decimal, [decimal_validator]), (IPv4Interface, [ip_v4_interface_validator]), (IPv6Interface, [ip_v6_interface_validator]), (IPv4Address, [ip_v4_address_validator]), (IPv6Address, [ip_v6_address_validator]), (IPv4Network, [ip_v4_network_validator]), (IPv6Network, [ip_v6_network_validator]), ] def find_validators( # noqa: C901 (ignore complexity) type_: Type[Any], config: Type['BaseConfig'] ) -> Generator[AnyCallable, None, None]: from .dataclasses import is_builtin_dataclass, make_dataclass_validator if type_ is Any or type_ is object: return type_type = type_.__class__ if type_type == ForwardRef or type_type == TypeVar: return if is_none_type(type_): yield none_validator return if type_ is Pattern: yield pattern_validator return if type_ is Hashable or type_ is CollectionsHashable: yield hashable_validator return if is_callable_type(type_): yield callable_validator return if is_literal_type(type_): yield make_literal_validator(type_) return if is_builtin_dataclass(type_): yield from make_dataclass_validator(type_, config) return if type_ is Enum: yield enum_validator return if type_ is IntEnum: yield int_enum_validator return if is_namedtuple(type_): yield tuple_validator yield make_namedtuple_validator(type_) return if is_typeddict(type_): yield make_typeddict_validator(type_, config) return class_ = get_class(type_) if class_ is not None: if isinstance(class_, type): yield make_class_validator(class_) else: yield any_class_validator return for val_type, validators in _VALIDATORS: try: if issubclass(type_, val_type): for v in validators: if isinstance(v, IfConfig): if v.check(config): yield v.validator else: yield v return except TypeError: raise RuntimeError(f'error checking inheritance of {type_!r} (type: {display_as_type(type_)})') if config.arbitrary_types_allowed: yield make_arbitrary_type_validator(type_) else: raise RuntimeError(f'no validator found for {type_}, see `arbitrary_types_allowed` in Config')
from .helpers import * import os import disnake import cogs.utils.botdatatypes as types from collections import OrderedDict import logging logger = logging.getLogger("mangologger") class ListVar: def __init__(self, t): self.type = t class BotDataItem: def __init__(self, botdata, list_key, primary_keys, defaults): self.__dict__.update({ "_botdata": botdata, "_list_key": list_key, "_primary_keys": primary_keys, "defaults": defaults }) @property def json_data(self): for item in self._botdata.json_data[self._list_key]: if all(item.get(key) == self._primary_keys[key] for key in self._primary_keys): return item return None def __getattr__(self, key): if key in self._primary_keys: return self._primary_keys[key] if key not in self.defaults: raise ValueError(f"Tried to get invalid '{key}' in {self._list_key}") if self.json_data: return self.json_data.get(key, self.defaults.get(key)) return self.defaults.get(key) def __setattr__(self, key, val): if key in self._primary_keys: raise ValueError("You can't set a primary key") if key not in self.defaults: raise ValueError(f"Tried to set invalid '{key}' in {self._list_key}") # recreate to order correctly newdict = OrderedDict(self._primary_keys) for k in self.defaults: if k == key: if val != self.defaults[key]: newdict[k] = val elif self.json_data and k in self.json_data: newdict[k] = self.json_data[k] # now save to json if self.json_data: index = self._botdata.json_data[self._list_key].index(self.json_data) self._botdata.json_data[self._list_key][index] = newdict else: self._botdata.json_data[self._list_key].append(newdict) self._botdata.save_data() __getitem__ = __getattr__ __setitem__ = __setattr__ # adds an item to a list variable, like banned_users def add_list_item(self, key, item): if item not in self[key]: new_list = list(self[key]) new_list.append(item) self[key] = new_list # removes an item from a list variable, like banned_users def remove_list_item(self, key, item): if item in self[key]: new_list = list(self[key]) new_list.remove(item) self[key] = new_list class UserInfo(BotDataItem): def __init__(self, botdata, discord): defaults = OrderedDict([]) for var in self.variables: defaults[var["key"]] = var["default"] BotDataItem.__init__(self, botdata, "userinfo", { "discord": discord }, defaults) variables = [ { "key": "steam", "default": None, "type": types.SteamId, "description": "This links your steam account to your discord account for mangobyte. You have to give this either your steam32 or steam64 id. An easy way to find this is to open dota and find your 'Friend ID', or look at the end of your dotabuff/opendota profile url.\n\nIf you open up dota and go to your profile, your 'Friend ID' will be just under your name, and will look like this:\n<:steam:414724031380586496> **FRIEND ID:** `<number>`\n\nIn which case you should do `?userconfig steam <number>`\n\nTo un-register, try setting this to `clear` or `reset`", "example": "70388657" }, { "key": "intro", "default": "local:helloits", "type": types.ShortClip, "description": "This sets the clip that will play whenever you join a voice channel that mangobyte is in. Note that this clip cannot be longer than 4.5 seconds\n\nTo make it so no clip plays when you join the channel, try setting this to `none`, `silent`, `off`, or `disable`", "example": "local:math" }, { "key": "outro", "default": "local:farewell", "type": types.ShortClip, "description": "This sets the clip that will play whenever you leave a voice channel that mangobyte is in. Note that this clip cannot be longer than 4.5 seconds\n\nTo make it so no clip plays when you join the channel, try setting this to `none`, `silent`, `off`, or `disable`", "example": "dota:troll_warlord_troll_lose_03" }, { "key": "introtts", "default": "it's", "type": types.ShortText, "description": "This is what is said before saying your name when announcing that you have joined the channel. To set your tts to be nothing, try setting this to `nothing` or `none`\n\nNote that this clip can be no longer than 32 characters.", "example": "it's the magnificent" }, { "key": "outrotts", "default": "has left!", "type": types.ShortText, "description": "This is what is said after saying your name when announcing that you have left the channel. To set your tts to be nothing, try setting this to `nothing` or `none`\n\nNote that this clip can be no longer than 32 characters.", "example": "dun gone left" }, { "key": "dmdotapatch", "default": None, "type": types.Boolean, "description": "If enabled, mango will private message you when a new dota patch gets released", "example": "enable" }, { "key": "dmdotablog", "default": None, "type": types.Boolean, "description": "Enabling this will let mangobyte dm you about Dota blog updates", "example": "enable" } ] def set_default(self, ctx, key): var = next((v for v in self.variables if v["key"] == key), None) if var: self[key] = var["default"] class GuildInfo(BotDataItem): def __init__(self, botdata, guildid): defaults = OrderedDict([ ("voicechannel", None), ("invalidcommands", False), ("banned_users", []), ("disabled_commands", []) ]) for var in self.variables: defaults[var["key"]] = var["default"] BotDataItem.__init__(self, botdata, "guildinfo", { "id": guildid }, defaults) variables = [ { "key": "prefix", "default": "?", "type": types.CommandPrefix, "description": "Configures the character to use to prefix your commands for this server", "example": "!" }, { "key": "reactions", "default": False, "type": types.Boolean, "description": "Allows mangobyte to react to users messages depending on what they are saying", "example": "enable" }, { "key": "ttschannel", "default": None, "type": types.TextChannel, "description": "If someone types in the given channel, mangobyte will automatically interpret it as a `?smarttts` command, and say it in the voicechannel that they are in. To say something in this channel without doing a tts, try adding a `//` or `#` to the front of your message", "example": "#tts" }, { "key": "botadmin", "default": None, "type": types.Role, "description": "Users who have the specified role will be able to use commands from the admin section. To set this role, do `?config botadmin <role>` where <role> is an @mention of a role in the server. You can also use @everyone to give everyone permissions to use admin commands.", "example": "@BotAdmin" }, { "key": "intros", "default": True, "type": types.Boolean, "description": "Allows mangobyte to announce users when they enter the voice channel that mangobyte is currently in", "example": "disable" }, { "key": "outros", "default": True, "type": types.Boolean, "description": "Allows mangobyte to announce when users leave the voice channel that mangobyte is currently in", "example": "disable" }, { "key": "ttslang", "default": "en", "type": types.GttsLang, "description": "Sets the language/voice that mangobyte will use to speak using the `?tts` command. To see a list of all of the possible languages, check out [this file](https://github.com/mdiller/MangoByte/blob/master/resource/json/gtts_languages.json) in the github repo", "example": "Russian" }, { "key": "usenickname", "default": False, "type": types.Boolean, "description": "Sets whether mangobyte will use the user's name or nickname when announcing that they have joined or left a channel", "example": "enable" }, { "key": "simpletts", "default": False, "type": types.Boolean, "description": "If enabled, the configured ttschannel will use the `?tts` command, instead of the `?smarttts` command.", "example": "enable" }, { "key": "announcetts", "default": False, "type": types.Boolean, "description": "Sets whether mangobyte announce the user's name before playing the clip when they the user plays a clip by typing something in the tts channel", "example": "enable" }, { "key": "dotapatchchannel", "default": None, "type": types.TextChannel, "description": "The channel in which mangobyte will post to notify about new dota patches when it detects them", "example": "#dota" }, { "key": "dotablogchannel", "default": None, "type": types.TextChannel, "description": "The channel to which mangobyte will post blog notifications", "example": "#dota" }, { "key": "ttschannelwarn", "default": True, "type": types.Boolean, "description": "Disable this to prevent mangobyte from saying \"I'm not in a voice channel on this server/guild\" when you type in a tts channel and mangobyte isn't summoned", "example": "disable" }, { "key": "allowedbots", "default": [], "list": True, "type": types.UserBot, "description": "A list of bots that mangobyte will not ignore when processing commands or tts", "example": "add @Bot123" }, { "key": "allowwebhooks", "default": False, "type": types.Boolean, "description": "Whether or not the bot should pay attention to webhooks when processing commands or tts", "example": "enable" } ] def is_banned(self, user): return user.id in self.banned_users def botban(self, user): self.add_list_item("banned_users", user.id) def botunban(self, user): self.remove_list_item("banned_users", user.id) def is_disabled(self, cmd): if isinstance(cmd, disnake.ext.commands.Command): return self.is_disabled(cmd.name) or self.is_disabled(cmd.cog_name) if isinstance(cmd, disnake.ext.commands.Cog): return self.is_disabled(cmd.name) return cmd in self.disabled_commands def disable_command(self, cmd): self.add_list_item("disabled_commands", cmd) def enable_command(self, cmd): self.remove_list_item("disabled_commands", cmd) class BotData: def __init__(self): self.path = "botdata.json" self.defaults = OrderedDict([ ("userinfo" , []), ("guildinfo" , []), ("dotapatch", None), ("dotablog",None) ]) if not os.path.exists(self.path): self.json_data = self.defaults self.save_data() else: current = read_json(self.path) if current.keys() != self.defaults.keys(): for key in self.defaults.keys(): if key not in current.keys(): current[key] = self.defaults[key] logger.info("Adding " + str(key) + " field to botdata.json") write_json(self.path, current) self.json_data = read_json(self.path) def __getitem__(self, key): if key not in self.defaults: return self.__dict__[key] return self.json_data.get(key, self.defaults.get(key)) def __setitem__(self, key, val): if key not in self.defaults: self.__dict__[key] = val self.json_data[key] = val self.save_data() def save_data(self): write_json(self.path, self.json_data) def userinfo(self, userid): if isinstance(userid, disnake.User) or isinstance(userid, disnake.Member): userid = userid.id return UserInfo(self, userid) def guildinfo(self, guildid): if isinstance(guildid, disnake.ext.commands.Context): guildid = guildid.message.guild if isinstance(guildid, disnake.abc.GuildChannel): guildid = guildid.guild if isinstance(guildid, disnake.Guild): guildid = guildid.id if guildid is None: return None return GuildInfo(self, guildid) def guildinfo_list(self): guildinfos = [] for data in self.json_data['guildinfo']: guildinfos.append(GuildInfo(self, data['id'])) return guildinfos def userinfo_list(self): userinfos = [] for data in self.json_data['userinfo']: userinfos.append(UserInfo(self, data['discord'])) return userinfos def count_users_with_key(self, key): count = 0 for data in self.json_data['userinfo']: if key in data and data[key]: count += 1 return count # gets the command prefix def command_prefix(self, ctx): return self.command_prefix_guild(ctx) # will act the same for self.guildinfo def command_prefix_botmessage(self, bot, message): return self.command_prefix_guild(message.guild) def command_prefix_guild(self, guild): guildinfo = self.guildinfo(guild) if guildinfo is not None: return guildinfo.prefix else: return "?"
import numpy as np import sys import copy from scipy.spatial import Delaunay import scipy.interpolate import cv2 class AbstractModel(object): def __init__(self): pass def score(self, X, y, epsilon=100.0, min_inlier_ratio=0.01, min_num_inlier=7): """ Computes how good is the transformation. This is done by applying the transformation to the collection of points in X, and then computing the corresponding distance to the matched point in y. If the distance is less than epsilon, the match is considered good. """ X2 = self.apply_special(X) # dists_sqr = np.sum((y - X2) ** 2, axis=1) dists = np.sqrt(np.sum((y - X2) ** 2, axis=1)) # print "dists", dists good_dists_mask = dists < epsilon good_dists_num = np.sum(good_dists_mask) # good_dists = dists[dists < epsilon] # accepted_ratio = float(good_dists.shape[0]) / X2.shape[0] accepted_ratio = float(good_dists_num) / X2.shape[0] # The transformation does not adhere to the wanted values, give it a very low score if good_dists_num < min_num_inlier or accepted_ratio < min_inlier_ratio: return -1, None, -1 return accepted_ratio, good_dists_mask, 0 def apply(self, p): raise RuntimeError, "Not implemented, but probably should be" def apply_special(self, p): raise RuntimeError, "Not implemented, but probably should be" def fit(self, X, y): raise RuntimeError, "Not implemented, but probably should be" def set_from_modelspec(self, s): raise RuntimeError, "Not implemented, but probably should be" def is_affine(self): return False class AbstractAffineModel(AbstractModel): def __init__(self): pass def get_matrix(self): raise RuntimeError, "Not implemented, but probably should be" def apply(self, p): """ Returns a new 2D point(s) after applying the transformation on the given point(s) p """ # Check if p is a single 2D point or a list/array of 2D points m = self.get_matrix() if len(p.shape) == 1: # a single 2D point return np.dot(m, np.append(p, [1]))[:2] elif len(p.shape) == 2: # A list of 2D points return np.vstack([np.dot(m, np.append(p_i, [1]))[:2] for p_i in p]) raise RuntimeError, "Invalid points input" def is_affine(self): return True class TranslationModel(AbstractAffineModel): MIN_MATCHES_NUM = 2 class_name = "mpicbg.trakem2.transform.TranslationModel2D" def __init__(self, delta=np.array([0, 0])): self.delta = delta def set(self, delta): self.delta = np.array(delta) def apply(self, p): # Check if p is a single 2D point or a list/array of 2D points if len(p.shape) == 1: # a single 2D point return p + self.delta elif len(p.shape) == 2: # A list of 2D points return np.vstack([p_i + self.delta for p_i in p]) raise RuntimeError, "Invalid points input" def apply_special(self, p): return np.atleast_2d(p) + np.asarray(self.delta).reshape((-1, 2)) def to_str(self): return "T={}".format(self.delta) def to_modelspec(self): return { "className" : self.class_name, "dataString" : "{}".format(' '.join([str(float(x)) for x in self.delta])) } def set_from_modelspec(self, s): self.delta = np.array([float(d) for d in s.split()]) def get_matrix(self): return np.array([ [1.0, 0.0, self.delta[0]], [0.0, 1.0, self.delta[1]], [0.0, 0.0, 1.0] ]) def fit(self, X, y): """ A non-weighted fitting of a collection of 2D points in X to a collection of 2D points in y. X and y are assumed to be arrays of 2D points of the same shape. """ assert(X.shape[0] >= 2) # the minimal number of of matches for a 2d rigid transformation pc = np.mean(X, axis=0) qc = np.mean(y, axis=0) self.delta = qc - pc return True class RigidModel(AbstractAffineModel): MIN_MATCHES_NUM = 2 class_name = "mpicbg.trakem2.transform.RigidModel2D" def __init__(self, r=0.0, delta=np.array([0, 0])): self.set(r, delta) def set(self, r, delta): self.cos_val = np.cos(r) self.sin_val = np.sin(r) self.delta = np.array(delta) def apply(self, p): """ Returns a new 2D point(s) after applying the transformation on the given point(s) p """ if len(p.shape) == 1: # a single 2D point return np.array([ self.cos_val * p[0] - self.sin_val * p[1], self.sin_val * p[0] + self.cos_val * p[1]]) + self.delta elif len(p.shape) == 2: # A list of 2D points return np.vstack([ np.array([self.cos_val * p_i[0] - self.sin_val * p_i[1], self.sin_val * p_i[0] + self.cos_val * p_i[1]]) + self.delta for p_i in p]) raise RuntimeError, "Invalid points input" def apply_special(self, p): pts = np.atleast_2d(p) return np.dot([[self.cos_val, -self.sin_val], [self.sin_val, self.cos_val]], pts.T).T + np.asarray(self.delta).reshape((1, 2)) def to_str(self): return "R={}, T={}".format(np.arccos(self.cos_val), self.delta) def to_modelspec(self): return { "className" : self.class_name, "dataString" : "{} {}".format(np.arccos(self.cos_val), ' '.join([str(float(x)) for x in self.delta])) } def set_from_modelspec(self, s): splitted = s.split() r = float(splitted[0]) self.cos_val = np.cos(r) self.sin_val = np.sin(r) self.delta = np.array([float(d) for d in splitted[1:]]) def get_matrix(self): return np.vstack([ [self.cos_val, -self.sin_val, self.delta[0]], [self.sin_val, self.cos_val, self.delta[1]], [0, 0, 1] ]) def fit(self, X, y): """ A non-weighted fitting of a collection of 2D points in X to a collection of 2D points in y. X and y are assumed to be arrays of 2D points of the same shape. """ assert(X.shape[0] >= 2) # the minimal number of of matches for a 2d rigid transformation pc = np.mean(X, axis=0) qc = np.mean(y, axis=0) delta_c = pc - qc # dx = pc[0] - qc[0] # dy = pc[1] - qc[1] cosd = 0.0 sind = 0.0 delta1 = X - pc # delta2 = y - qc + np.array([dx, dy]) delta2 = y - qc + delta_c # for xy1, xy2 in zip(delta1, delta2): # sind += xy1[0] * xy2[1] - xy1[1] * xy2[0] # cosd += xy1[0] * xy2[0] + xy1[1] * xy2[1] sind = np.sum(delta1[:,0] * delta2[:,1] - delta1[:,1] * delta2[:,0]) cosd = np.sum(delta1[:,0] * delta2[:,0] + delta1[:,1] * delta2[:,1]) norm = np.sqrt(cosd * cosd + sind * sind) if norm < 0.0001: # print "normalization may be invalid, skipping fitting" return False cosd /= norm sind /= norm self.cos_val = cosd self.sin_val = sind self.delta[0] = qc[0] - cosd * pc[0] + sind * pc[1] self.delta[1] = qc[1] - sind * pc[0] - cosd * pc[1] return True class SimilarityModel(AbstractAffineModel): MIN_MATCHES_NUM = 2 class_name = "mpicbg.trakem2.transform.SimilarityModel2D" def __init__(self, s=0.0, delta=np.array([0, 0])): self.set(s, delta) def set(self, s, delta): self.scos_val = np.cos(s) self.ssin_val = np.sin(s) self.delta = np.array(delta) def apply(self, p): """ Returns a new 2D point(s) after applying the transformation on the given point(s) p """ if len(p.shape) == 1: # a single 2D point return np.array([ self.scos_val * p[0] - self.ssin_val * p[1], self.ssin_val * p[0] + self.scos_val * p[1]]) + self.delta elif len(p.shape) == 2: # A list of 2D points return np.vstack([ np.array([self.scos_val * p_i[0] - self.ssin_val * p_i[1], self.ssin_val * p_i[0] + self.scos_val * p_i[1]]) + self.delta for p_i in p]) raise RuntimeError, "Invalid points input" def to_str(self): return "S={}, T={}".format(np.arccos(self.scos_val), self.delta) def to_modelspec(self): return { "className" : self.class_name, "dataString" : "{} {} {}".format(self.scos_val, self.ssin_val, ' '.join([str(float(x)) for x in self.delta])) } def set_from_modelspec(self, s): splitted = s.split() r = float(splitted[0]) self.scos_val = np.cos(r) self.ssin_val = np.sin(r) self.delta = np.array([float(d) for d in splitted[1:]]) def get_matrix(self): return np.vstack( np.array([self.scos_val, -self.ssin_val, self.delta[0]]), np.array([self.ssin_val, self.scos_val, self.delta[1]]), np.array([0, 0, 1]) ) def fit(self, X, y): """ A non-weighted fitting of a collection of 2D points in X to a collection of 2D points in y. X and y are assumed to be arrays of 2D points of the same shape. """ assert(X.shape[0] >= 2) # the minimal number of of matches for a 2d rigid transformation pc = np.mean(X, axis=0) qc = np.mean(y, axis=0) delta_c = pc - qc # dx = pc[0] - qc[0] # dy = pc[1] - qc[1] scosd = 0.0 ssind = 0.0 delta1 = X - pc # delta2 = y - qc + np.array([dx, dy]) delta2 = y - qc + delta_c norm = 0.0 for xy1, xy2 in zip(delta1, delta2): ssind += xy1[0] * xy2[1] - xy1[1] * xy2[0] scosd += xy1[0] * xy2[0] + xy1[1] * xy2[1] norm += xy1[0] ** 2 + xy1[1] ** 2 if norm < 0.0001: # print "normalization may be invalid, skipping fitting" return False scosd /= norm ssind /= norm self.scos_val = scosd self.ssin_val = ssind self.delta[0] = qc[0] - scosd * pc[0] + ssind * pc[1] self.delta[1] = qc[1] - ssind * pc[0] - scosd * pc[1] return True class AffineModel(AbstractAffineModel): MIN_MATCHES_NUM = 3 class_name = "mpicbg.trakem2.transform.AffineModel2D" def __init__(self, m=np.eye(3)): """m is a 3x3 matrix""" self.set(m) def set(self, m): """m is a 3x3 matrix""" # make sure that this a 3x3 matrix m = np.array(m) if m.shape != (3, 3): raise RuntimeError, "Error when parsing the given affine matrix, should be of size 3x3" self.m = m def apply(self, p): """ Returns a new 2D point(s) after applying the transformation on the given point(s) p """ if len(p.shape) == 1: # a single 2D point return np.dot(self.m, np.append(p, [1]))[:2] elif len(p.shape) == 2: # A list of 2D points return np.vstack([ np.dot(self.m, np.append(p_i, [1]))[:2] for p_i in p]) raise RuntimeError, "Invalid points input" # def apply(self, p): # # Check if p is a single 2D point or a list/array of 2D points # if len(p.shape) == 1: # a single 2D point # return np.dot(self.m, p) # elif len(p.shape) == 2: # A list of 2D points # return np.vstack([np.dot(self.m, p_i) for p_i in p]) # raise RuntimeError, "Invalid points input" def apply_special(self, p): pts = np.atleast_2d(p) return np.dot(self.m[:2,:2], pts.T).T + np.asarray(self.m.T[2][:2]).reshape((1, 2)) def to_str(self): return "M={}".format(self.m) def to_modelspec(self): return { "className" : self.class_name, # keeping it in the Fiji model format "dataString" : "{}".format(' '.join([str(float(x)) for x in self.m[:2].T.flatten()])) } def set_from_modelspec(self, s): splitted = s.split() # The input is 6 numbers that correspond to m00 m10 m01 m11 m02 m12 self.m = np.vstack( np.array([float(d) for d in splitted[0::2]]), np.array([float(d) for d in splitted[1::2]]), np.array([0.0, 0.0, 1.0]) ) def get_matrix(self): return self.m def fit(self, X, y): """ A non-weighted fitting of a collection of 2D points in X to a collection of 2D points in y. X and y are assumed to be arrays of 2D points of the same shape. """ assert(X.shape[0] >= 2) # the minimal number of of matches for a 2d rigid transformation pc = np.mean(X, axis=0) qc = np.mean(y, axis=0) delta1 = X - pc delta2 = y - qc a00 = np.sum(delta1[:,0] * delta1[:,0]) a01 = np.sum(delta1[:,0] * delta1[:,1]) a11 = np.sum(delta1[:,1] * delta1[:,1]) b00 = np.sum(delta1[:,0] * delta2[:,0]) b01 = np.sum(delta1[:,0] * delta2[:,1]) b10 = np.sum(delta1[:,1] * delta2[:,0]) b11 = np.sum(delta1[:,1] * delta2[:,1]) det = a00 * a11 - a01 * a01 if det == 0: # print "determinant is 0, skipping fitting" return False m00 = (a11 * b00 - a01 * b10) / det m01 = (a00 * b10 - a01 * b00) / det m10 = (a11 * b01 - a01 * b11) / det m11 = (a00 * b11 - a01 * b01) / det self.m = np.array([ [m00, m01, qc[0] - m00 * pc[0] - m01 * pc[1]], [m10, m11, qc[1] - m10 * pc[0] - m11 * pc[1]], [0.0, 0.0, 1.0] ]) return True # def fit(self, X, y): # """ # A non-weighted fitting of a collection of 2D points in X to a collection of 2D points in y. # X and y are assumed to be arrays of 2D points of the same shape. # """ # fp = X # tp = y # assert(fp.shape[0] >= 3) # """ taken from: http://www.janeriksolem.net/2009/06/affine-transformations-and-warping.html # find H, affine transformation, such that # tp is affine transf of fp""" # if fp.shape != tp.shape: # raise RuntimeError, 'number of points do not match' # #condition points # #-from points- # m = np.mean(fp[:2], axis=1) # maxstd = max(np.std(fp[:2], axis=1)) # C1 = np.diag([1 / maxstd, 1 / maxstd, 1]) # C1[0][2] = -m[0] / maxstd # C1[1][2] = -m[1] / maxstd # fp_cond = np.dot(C1, fp) # #-to points- # m = np.mean(tp[:2], axis=1) # C2 = C1.copy() #must use same scaling for both point sets # C2[0][2] = -m[0] / maxstd # C2[1][2] = -m[1] / maxstd # tp_cond = np.dot(C2, tp) # #conditioned points have mean zero, so translation is zero # A = np.concatenate((fp_cond[:2], tp_cond[:2]), axis=0) # U,S,V = np.linalg.svd(A.T) # #create B and C matrices as Hartley-Zisserman (2:nd ed) p 130. # tmp = V[:2].T # B = tmp[:2] # C = tmp[2:4] # tmp2 = np.concatenate((np.dot(C, np.linalg.pinv(B)), np.zeros((2, 1))), axis=1) # H = np.vstack((tmp2, [0, 0, 1])) # #decondition # H = np.dot(np.linalg.inv(C2), np.dot(H, C1)) # self.m = H / H[2][2] # return True class RestrictedMovingLeastSquaresTransform2(AbstractModel): class_name = "mpicbg.trakem2.transform.RestrictedMovingLeastSquaresTransform2" def __init__(self, radius=None, point_map=None): assert((radius is None and point_map is None) or (radius is not None and point_map is not None)) self.radius = radius self.point_map = point_map self.interpolator = None def apply(self, p): return None # self.compute_interpolator() # # self.compute_affine_transforms() # # # Find an index of a simplex that contains p # simplex_index = self.triang.find_simplex(p)[0] # assert(simplex_index != -1) # # # compute the barycentric weights for point p in the simplex # b = self.triang.transform[simplex_index, :2].dot(p - self.triang.transform[simplex_index, 2]) # bary = np.c_[b, 1 - b.sum(axis=1)] # # # Compute the weighted average of the affine transformations of the simplex vertices # simplex = self.triang.simplices[simplex_index] # final_affine = np.average(self.point_avg_affine[simplex], axis=0, weights=bary) # # return np.dot(final_affine[:2,:2], p.T).T + np.asarray(final_affine.T[2][:2]).reshape((1, 2)) def apply_special(self, pts): return None # # Computes the affine transformation for many points # self.compute_affine_transforms() # # # Find the indices of all simplices, for each of the points in pts # simplex_indices = self.triang.find_simplex(p) # assert not np.any(simplex_indices == -1) # # # http://codereview.stackexchange.com/questions/41024/faster-computation-of-barycentric-coordinates-for-many-points # X = self.triang.transform[simplex_indices, :2] # Y = pts - self.triang.transform[simplex_indices, 2] # b = np.einsum('ijk,ik->ij', X, Y) # barys = np.c_[b, 1 - b.sum(axis=1)] # shape: (pts#, 3) --> for each point its 3 barycentric values # # # apply for each point in pts the 3 affine transformations around it # pt_indices = self.triangulation.simplices[simplex_indices].astype(np.uint32) # all_affine_transfroms = self.point_avg_affine[pt_indices] # shape: (pts#, 3, 2, 3) --> three 2x3 affine transform matrices for each point in pts # # # TODO - need to improve speed # res = np.array((pts.shape[0], 3, 2), dtype=np.float) # will store for each point the three coordinates after affine transform # for p_i, p in enumerate(pts): # pt_affine_transforms = all_affine_transforms[p_i] # three affine transfrom matrices (2x3) # for a_i, pt_affine_transform in enumerate(pt_affine_transforms): # res[p_i][a_i] = np.dot(pt_affine_transform[:2,:2], p.T).T + np.asarray(pt_affine_transform.T[2][:2]).reshape((1, 2)) # # global_res = np.array((pts.shape[0], 2), dtype=np.float) # for res_i, pt_affines in enumerate(res): # global_res[res_i] = np.average(res_i, axis=0, weights=barys[res_i]) # # return global_res def set_from_modelspec(self, s): data = s.split() assert(data[0] == 'affine') assert(data[1] == '2') assert(data[2] == '2.0') self.radius = float(data[3]) points_data = data[4:] # format is: p1_src_x p1_src_y p1_dest_x p1_dest_y 1.0 ... (1.0 is the weight of the match) src = np.array( [np.array(points_data[0::5], dtype=np.float32), np.array(points_data[1::5], dtype=np.float32)] ).T dest = np.array( [np.array(points_data[2::5], dtype=np.float32), np.array(points_data[3::5], dtype=np.float32)] ).T self.point_map = (src, dest) self.interpolator = None def get_point_map(self): return self.point_map # def compute_interpolator(self): # """Uses griddata to interpolate all the pixels in the output window""" # if self.interpolator is not None: # return # # # Compute the interpolator using scipy.interpolate.LinearNDInterpolator # self.interpolator = LinearNDInterpolator(#TODO) # def compute_affine_transforms(self): # """Computes an average affine transformation for each point from the source points, # using the affine trasnformations of all neighboring triangles""" # if self.point_avg_affine is not None: # return # # # Create the triangulation of the source points # src = self.point_map[0] # dest = self.point_map[1] # self.triang = Delaunay(src) # # Compute a per simplex affine transformation # simplex_transforms = np.array((len(self.triang.simplices), 2, 3), dtype=np.float) # # Also, set a per-point list of all simplices around it # point_neighboring_simplices = [] * src.shape[0] # for simplex_i, simplex in enumerate(self.triang.simplices): # simplex_src_points = src[simplex] # simplex_dest_points = dest[simplex] # affine_transform = cv2.getAffineTransform(simplex_src_points, simplex_dest_points) # simplex_transforms[simplex_i] = affine_transform # # add the simplex as a neighbor to all of its points # point_neighboring_simplices.append(simplex_i) # # # Compute a per-point average affine transform # self.point_avg_affine = np.array((src.shape[0], 2, 3), dtype=np.float) # for p_i, _ in enumerate(src): # self.point_avg_affine[p_i] = np.mean(simplex_transforms[np.array(point_neighboring_simplices[p_i])], axis=0) class Transforms(object): transformations = [ TranslationModel(), RigidModel(), SimilarityModel(), AffineModel() ] transforms_classnames = { TranslationModel.class_name : TranslationModel(), RigidModel.class_name : RigidModel(), SimilarityModel.class_name : SimilarityModel(), AffineModel.class_name : AffineModel(), RestrictedMovingLeastSquaresTransform2.class_name : RestrictedMovingLeastSquaresTransform2(), } @classmethod def create(cls, model_type_idx): return copy.deepcopy(cls.transformations[model_type_idx]) @classmethod def from_tilespec(cls, ts_transform): transform = copy.deepcopy(cls.transforms_classnames[ts_transform["className"]]) transform.set_from_modelspec(ts_transform["dataString"]) return transform
"""Platform-specific support for compiling/executing C sources.""" import py, os, sys from rpython.tool.runsubprocess import run_subprocess as _run_subprocess from rpython.tool.udir import udir from rpython.tool.version import rpythonroot log = py.log.Producer("platform") class CompilationError(Exception): def __init__(self, out, err): self.out = out.replace('\r\n', '\n') self.err = err.replace('\r\n', '\n') def __repr__(self): if self.err: attr = 'err' else: attr = 'out' text = getattr(self, attr).replace('\n', '\n\t') return 'CompilationError(%s="""\n\t%s""")' % (attr, text) __str__ = __repr__ class ExecutionResult(object): def __init__(self, returncode, out, err): self.returncode = returncode self.out = out.replace('\r\n', '\n') self.err = err.replace('\r\n', '\n') def __repr__(self): return "<ExecutionResult retcode=%d>" % (self.returncode,) class Platform(object): name = "abstract platform" c_environ = None relevant_environ = () log_errors = True so_prefixes = ('',) extra_libs = () def __init__(self, cc): if self.__class__ is Platform: raise TypeError("You should not instantiate Platform class directly") self.cc = cc def compile(self, cfiles, eci, outputfilename=None, standalone=True): ofiles = self._compile_o_files(cfiles, eci, standalone) return self._finish_linking(ofiles, eci, outputfilename, standalone) def _all_cfiles(self, cfiles, eci): seen = set() result = [] for cfile in list(cfiles) + list(eci.separate_module_files): cfile = py.path.local(cfile) if cfile not in seen: seen.add(cfile) result.append(cfile) return result def _compile_o_files(self, cfiles, eci, standalone=True): cfiles = self._all_cfiles(cfiles, eci) compile_args = self._compile_args_from_eci(eci, standalone) ofiles = [] for cfile in cfiles: # Windows hack: use masm for files ending in .asm if str(cfile).lower().endswith('.asm'): ofiles.append(self._compile_c_file(self.masm, cfile, [])) else: ofiles.append(self._compile_c_file(self.cc, cfile, compile_args)) return ofiles def execute(self, executable, args=None, env=None, compilation_info=None): if env is None: env = os.environ.copy() else: env = env.copy() # On Windows, %SystemRoot% must be present for most programs to start if (os.name == 'nt' and "SystemRoot" not in env and "SystemRoot" in os.environ): env["SystemRoot"] = os.environ["SystemRoot"] # Set LD_LIBRARY_PATH on posix platforms if os.name == 'posix' and compilation_info is not None: library_path = ':'.join([str(i) for i in compilation_info.library_dirs]) if sys.platform == 'darwin': env['DYLD_LIBRARY_PATH'] = library_path else: env['LD_LIBRARY_PATH'] = library_path returncode, stdout, stderr = _run_subprocess(str(executable), args, env) return ExecutionResult(returncode, stdout, stderr) def gen_makefile(self, cfiles, eci, exe_name=None, path=None, shared=False, headers_to_precompile=[], no_precompile_cfiles = [], icon=None): raise NotImplementedError("Pure abstract baseclass") def __repr__(self): return '<%s cc=%s>' % (self.__class__.__name__, self.cc) def __hash__(self): return hash(self.__class__.__name__) def __ne__(self, other): return not self == other def __eq__(self, other): return (self.__class__ is other.__class__ and self.__dict__ == other.__dict__) def key(self): bits = [self.__class__.__name__, 'cc=%r' % self.cc] for varname in self.relevant_environ: bits.append('%s=%r' % (varname, os.environ.get(varname))) # adding sys.maxint to disambiguate windows bits.append('%s=%r' % ('sys.maxint', sys.maxint)) return ' '.join(bits) # some helpers which seem to be cross-platform enough def _execute_c_compiler(self, cc, args, outname, cwd=None): log.execute(cc + ' ' + ' '.join(args)) # 'cc' can also contain some options for the C compiler; # e.g. it can be "gcc -m32". We handle it by splitting on ' '. cclist = cc.split() cc = cclist[0] args = cclist[1:] + args returncode, stdout, stderr = _run_subprocess(cc, args, self.c_environ, cwd) self._handle_error(returncode, stdout, stderr, outname) def _handle_error(self, returncode, stdout, stderr, outname): if returncode != 0: errorfile = outname.new(ext='errors') errorfile.write(stderr, 'wb') if self.log_errors: stderrlines = stderr.splitlines() for line in stderrlines: log.Error(line) # ^^^ don't use ERROR, because it might actually be fine. # Also, ERROR confuses lib-python/conftest.py. raise CompilationError(stdout, stderr) else: for line in stderr.splitlines(): log.WARNING(line) def _make_o_file(self, cfile, ext): """Create an object file name under the udir for a .c file""" ofile = cfile.new(ext=ext) if ofile.relto(udir): return ofile assert ofile.relto(rpythonroot), ( "%r should be relative to either %r or %r" % ( ofile, rpythonroot, udir)) ofile = udir.join(ofile.relto(rpythonroot)) ofile.dirpath().ensure(dir=True) return ofile def preprocess_include_dirs(self, include_dirs): if 'PYPY_LOCALBASE' in os.environ: dirs = list(self._preprocess_include_dirs(include_dirs)) return [os.environ['PYPY_LOCALBASE'] + '/include'] + dirs return self._preprocess_include_dirs(include_dirs) def _preprocess_include_dirs(self, include_dirs): return include_dirs def _compile_args_from_eci(self, eci, standalone): include_dirs = self.preprocess_include_dirs(eci.include_dirs) args = self._includedirs(include_dirs) if standalone: extra = self.standalone_only else: extra = self.get_shared_only_compile_flags() cflags = list(self.cflags) + list(extra) return (cflags + list(eci.compile_extra) + args) def get_shared_only_compile_flags(self): return tuple(self.shared_only) def preprocess_library_dirs(self, library_dirs): if 'PYPY_LOCALBASE' in os.environ: dirs = list(self._preprocess_library_dirs(library_dirs)) return [os.environ['PYPY_LOCALBASE'] + '/lib'] + dirs return self._preprocess_library_dirs(library_dirs) def _preprocess_library_dirs(self, library_dirs): return library_dirs def _link_args_from_eci(self, eci, standalone): library_dirs = self.preprocess_library_dirs(eci.library_dirs) library_dirs = self._libdirs(library_dirs) libraries = self._libs(eci.libraries) link_files = self._linkfiles(eci.link_files) export_flags = self._exportsymbols_link_flags() return (library_dirs + list(self.link_flags) + export_flags + link_files + list(eci.link_extra) + libraries + list(self.extra_libs)) def _exportsymbols_link_flags(self): return [] def _finish_linking(self, ofiles, eci, outputfilename, standalone): if outputfilename is None: outputfilename = ofiles[0].purebasename if ofiles: dirname = ofiles[0].dirpath() else: dirname = udir.join('module_cache') exe_name = dirname.join(outputfilename, abs=True) if standalone: if self.exe_ext: exe_name += '.' + self.exe_ext else: exe_name += '.' + self.so_ext if eci.use_cpp_linker: cc_link = 'g++' # XXX hard-coded so far else: cc_link = self.cc largs = self._link_args_from_eci(eci, standalone) return self._link(cc_link, ofiles, largs, standalone, exe_name) # below are some detailed information for platforms def include_dirs_for_libffi(self): dirs = self._include_dirs_for_libffi() if 'PYPY_LOCALBASE' in os.environ: return [os.environ['PYPY_LOCALBASE'] + '/include'] + dirs return dirs def library_dirs_for_libffi(self): dirs = self._library_dirs_for_libffi() if 'PYPY_LOCALBASE' in os.environ: return [os.environ['PYPY_LOCALBASE'] + '/lib'] + dirs return dirs def _include_dirs_for_libffi(self): raise NotImplementedError("Needs to be overwritten") def _library_dirs_for_libffi(self): raise NotImplementedError("Needs to be overwritten") def check___thread(self): return True if sys.platform.startswith('linux'): from rpython.translator.platform.linux import Linux, LinuxPIC import platform # Only required on armhf and mips{,el}, not armel. But there's no way to # detect armhf without shelling out if (platform.architecture()[0] == '64bit' or platform.machine().startswith(('arm', 'mips', 'ppc'))): host_factory = LinuxPIC else: host_factory = Linux elif sys.platform == 'darwin': from rpython.translator.platform.darwin import Darwin_i386, Darwin_x86_64, Darwin_PowerPC import platform assert platform.machine() in ('Power Macintosh', 'i386', 'x86_64') if platform.machine() == 'Power Macintosh': host_factory = Darwin_PowerPC elif sys.maxint <= 2147483647: host_factory = Darwin_i386 else: host_factory = Darwin_x86_64 elif "gnukfreebsd" in sys.platform: from rpython.translator.platform.freebsd import GNUkFreebsd, GNUkFreebsd_64 import platform if platform.architecture()[0] == '32bit': host_factory = GNUkFreebsd else: host_factory = GNUkFreebsd_64 elif "freebsd" in sys.platform: from rpython.translator.platform.freebsd import Freebsd, Freebsd_64 import platform if platform.architecture()[0] == '32bit': host_factory = Freebsd else: host_factory = Freebsd_64 elif sys.platform.startswith('netbsd'): from rpython.translator.platform.netbsd import Netbsd, Netbsd_64 import platform if platform.architecture()[0] == '32bit': host_factory = Netbsd else: host_factory = Netbsd_64 elif "openbsd" in sys.platform: from rpython.translator.platform.openbsd import OpenBSD, OpenBSD_64 import platform if platform.architecture()[0] == '32bit': host_factory = OpenBSD else: host_factory = OpenBSD_64 elif os.name == 'nt': from rpython.translator.platform.windows import Windows, Windows_x64 import platform if platform.architecture()[0] == '32bit': host_factory = Windows else: host_factory = Windows_x64 elif sys.platform == 'cygwin': from rpython.translator.platform.cygwin import Cygwin, Cygwin64 import platform if platform.architecture()[0] == '32bit': host_factory = Cygwin else: host_factory = Cygwin64 else: # pray from rpython.translator.platform.distutils_platform import DistutilsPlatform host_factory = DistutilsPlatform platform = host = host_factory() def pick_platform(new_platform, cc): if new_platform == 'host': return host_factory(cc) elif new_platform == 'maemo': from rpython.translator.platform.maemo import Maemo return Maemo(cc) elif new_platform == 'arm': from rpython.translator.platform.arm import ARM return ARM(cc) elif new_platform == 'distutils': from rpython.translator.platform.distutils_platform import DistutilsPlatform return DistutilsPlatform() else: raise ValueError("platform = %s" % (new_platform,)) def set_platform(new_platform, cc): global platform platform = pick_platform(new_platform, cc) if not platform: raise ValueError("pick_platform(%r, %s) failed"%(new_platform, cc)) log.msg("Set platform with %r cc=%s, using cc=%r, version=%r" % (new_platform, cc, getattr(platform, 'cc','Unknown'), getattr(platform, 'version','Unknown'), )) if new_platform == 'host': global host host = platform def is_host_build(): return host == platform
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Scanner for Google Groups.""" from Queue import Queue import anytree import yaml from google.cloud.security.common.util import log_util from google.cloud.security.common.data_access import group_dao from google.cloud.security.scanner.scanners import base_scanner LOGGER = log_util.get_logger(__name__) MY_CUSTOMER = 'my_customer' class GroupsScanner(base_scanner.BaseScanner): """Pipeline to IAM data from DAO""" def __init__(self, snapshot_timestamp): """Constructor for the base pipeline. Args: snapshot_timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: None """ super(GroupsScanner, self).__init__( snapshot_timestamp) self.dao = group_dao.GroupDao() def get_recursive_members(self, starting_node, timestamp): """Get all the recursive members of a group. Args: starting_node: Member node from which to start getting the recursive members. timestamp: String of snapshot timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: starting_node: Member node with all its recursive members. """ queue = Queue() queue.put(starting_node) while not queue.empty(): queued_node = queue.get() members = self.dao.get_group_members('group_members', queued_node.member_id, timestamp) for member in members: member_node = MemberNode(member.get('member_id'), member.get('member_email'), member.get('member_type'), member.get('member_status'), queued_node) if member_node.member_type == 'GROUP': queue.put(member_node) return starting_node def _build_group_tree(self, timestamp): """Build a tree of all the groups in the organization. Args: timestamp: String of snapshot timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: The root node that holds the tree structure of all the groups in the organization. """ root = MemberNode(MY_CUSTOMER, MY_CUSTOMER) all_groups = self.dao.get_all_groups('groups', timestamp) for group in all_groups: group_node = MemberNode(group.get('group_id'), group.get('group_email'), 'group', 'ACTIVE', root) group_node = self.get_recursive_members(group_node, timestamp) LOGGER.debug(anytree.RenderTree( root, style=anytree.AsciiStyle()).by_attr('member_email')) return root @staticmethod def _apply_one_rule(starting_node, rule): """Append the rule to all the applicable nodes. Args: starting_node: Member node from which to start appending the rule. rule: A dictionary representation of a rule. Returns: starting_node: Member node with all its recursive members, with the rule appended. """ for node in anytree.iterators.PreOrderIter(starting_node): node.rules.append(rule) return starting_node def _apply_all_rules(self, starting_node, rules): """Apply all rules to all the applicable nodes. Args: starting_node: Member node from which to start appending the rule. rules: A list of rules, in dictionary form. Returns: starting_node: Member node with all the rules applied to all the nodes. """ for rule in rules: if rule.get('group_email') == MY_CUSTOMER: # Apply rule to every node. # Because this is simply the root node, there is no need # to find this node, i.e. just start at the root. # Traversal order should not matter. starting_node = self._apply_one_rule(starting_node, rule) else: # Apply rule to only specific node. # Need to find this node. # Traversal should not matter since we need to find all # instances of the group (because a group can be added # to multiple groups). # # Start at the tree root, find all instances of the specified # group, then add the rule to all the members of the specified # group. for node in anytree.iterators.PreOrderIter(starting_node): if node.member_email == rule.get('group_email'): node = self._apply_one_rule(node, rule) return starting_node # pylint: disable=arguments-differ def run(self, rules_path): """Runs the groups scanner. Args: rules: String of the path to rules file (yaml/json). Returns: List of all the nodes in violations. """ root = self._build_group_tree(self.snapshot_timestamp) with open(rules_path, 'r') as f: rules = yaml.load(f) root = self._apply_all_rules(root, rules) return self.find_violations(root) # pylint: disable=arguments-differ # pylint: disable=too-many-branches def find_violations(self, root): """Find violations, starting from the given root. At this point, we can start to find violations at each node! We have a tree, with data populated at each node. ...and rules are also applied at each node. Traversal order should not matter, since we need to evaluate all nodes. Each node can have multiple rules. Each rule can have multiple conditions. If a rule is violated, then the node is in violation. i.e. if all rules pass, then the node is not in violation. Args: root: The nodes (tree structure) to find violations in. Returns: A list of nodes that are in violation. """ all_violations = [] for node in anytree.iterators.PreOrderIter(root): # No need to evaluate these nodes. # This represents the org, i.e. is not a group. if node.member_email == MY_CUSTOMER: continue # This represents the auto-generated group, containing all the users # in the org. if node.member_email == '': continue node.violations = [] whitelist_rule_statuses = [] for rule in node.rules: condition_statuses = [] if rule.get('mode') == 'whitelist': for condition in rule.get('conditions'): if condition.get('member_email') in node.member_email: condition_statuses.append(True) else: condition_statuses.append(False) # All the conditions of this rule have evaluated. # The rule is fulfilled, if any condition matches. if any(condition_statuses): whitelist_rule_statuses.append(True) else: whitelist_rule_statuses.append(False) elif rule.get('mode') == 'blacklist': pass # TODO elif rule.get('mode') == 'required': pass # TODO else: pass # TODO # Determine if the node is in violations or not. # All rules must be fulfilled, for a node to not be in violation. # If any rule is not fulfilled, then node is in violation. # # truth table # http://stackoverflow.com/a/19389957/2830207 if not any(whitelist_rule_statuses): all_violations.append(node) return all_violations class MemberNode(anytree.node.NodeMixin): """A custom anytree node with Group Member attributes.""" def __init__(self, member_id, member_email, member_type=None, member_status=None, parent=None): self.member_id = member_id self.member_email = member_email self.member_type = member_type self.member_status = member_status self.parent = parent self.rules = []
from __future__ import division, print_function, absolute_import import warnings import sys import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_allclose, assert_equal, assert_, suppress_warnings) import pytest from pytest import raises as assert_raises from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten, ClusterError, _krandinit) from scipy.cluster import _vq from scipy.sparse.sputils import matrix TESTDATA_2D = np.array([ -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68, -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45, 2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28, -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07, -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29, -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25, 2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21, -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67, -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94, -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33, 2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8, -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29, 2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75, -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17, 0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44, -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83, 0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28, 3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62, -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35, 3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84, -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75, -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86, -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83, 0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75, -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03, 3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0, 3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99, -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21, 1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75, 4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37, -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0, -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84, 2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69, -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51, -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71, -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61, 2.11]).reshape((200, 2)) # Global data X = np.array([[3.0, 3], [4, 3], [4, 2], [9, 2], [5, 1], [6, 2], [9, 4], [5, 2], [5, 4], [7, 4], [6, 5]]) CODET1 = np.array([[3.0000, 3.0000], [6.2000, 4.0000], [5.8000, 1.8000]]) CODET2 = np.array([[11.0/3, 8.0/3], [6.7500, 4.2500], [6.2500, 1.7500]]) LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1]) class TestWhiten(object): def test_whiten(self): desired = np.array([[5.08738849, 2.97091878], [3.19909255, 0.69660580], [4.51041982, 0.02640918], [4.38567074, 0.95120889], [2.32191480, 1.63195503]]) for tp in np.array, matrix: obs = tp([[0.98744510, 0.82766775], [0.62093317, 0.19406729], [0.87545741, 0.00735733], [0.85124403, 0.26499712], [0.45067590, 0.45464607]]) assert_allclose(whiten(obs), desired, rtol=1e-5) def test_whiten_zero_std(self): desired = np.array([[0., 1.0, 2.86666544], [0., 1.0, 1.32460034], [0., 1.0, 3.74382172]]) for tp in np.array, matrix: obs = tp([[0., 1., 0.74109533], [0., 1., 0.34243798], [0., 1., 0.96785929]]) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_allclose(whiten(obs), desired, rtol=1e-5) assert_equal(len(w), 1) assert_(issubclass(w[-1].category, RuntimeWarning)) def test_whiten_not_finite(self): for tp in np.array, matrix: for bad_value in np.nan, np.inf, -np.inf: obs = tp([[0.98744510, bad_value], [0.62093317, 0.19406729], [0.87545741, 0.00735733], [0.85124403, 0.26499712], [0.45067590, 0.45464607]]) assert_raises(ValueError, whiten, obs) class TestVq(object): def test_py_vq(self): initc = np.concatenate(([[X[0]], [X[1]], [X[2]]])) for tp in np.array, matrix: label1 = py_vq(tp(X), tp(initc))[0] assert_array_equal(label1, LABEL1) def test_vq(self): initc = np.concatenate(([[X[0]], [X[1]], [X[2]]])) for tp in np.array, matrix: label1, dist = _vq.vq(tp(X), tp(initc)) assert_array_equal(label1, LABEL1) tlabel1, tdist = vq(tp(X), tp(initc)) def test_vq_1d(self): # Test special rank 1 vq algo, python implementation. data = X[:, 0] initc = data[:3] a, b = _vq.vq(data, initc) ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis]) assert_array_equal(a, ta) assert_array_equal(b, tb) def test__vq_sametype(self): a = np.array([1.0, 2.0], dtype=np.float64) b = a.astype(np.float32) assert_raises(TypeError, _vq.vq, a, b) def test__vq_invalid_type(self): a = np.array([1, 2], dtype=int) assert_raises(TypeError, _vq.vq, a, a) def test_vq_large_nfeat(self): X = np.random.rand(20, 20) code_book = np.random.rand(3, 20) codes0, dis0 = _vq.vq(X, code_book) codes1, dis1 = py_vq(X, code_book) assert_allclose(dis0, dis1, 1e-5) assert_array_equal(codes0, codes1) X = X.astype(np.float32) code_book = code_book.astype(np.float32) codes0, dis0 = _vq.vq(X, code_book) codes1, dis1 = py_vq(X, code_book) assert_allclose(dis0, dis1, 1e-5) assert_array_equal(codes0, codes1) def test_vq_large_features(self): X = np.random.rand(10, 5) * 1000000 code_book = np.random.rand(2, 5) * 1000000 codes0, dis0 = _vq.vq(X, code_book) codes1, dis1 = py_vq(X, code_book) assert_allclose(dis0, dis1, 1e-5) assert_array_equal(codes0, codes1) class TestKMean(object): def test_large_features(self): # Generate a data set with large values, and run kmeans on it to # (regression for 1077). d = 300 n = 100 m1 = np.random.randn(d) m2 = np.random.randn(d) x = 10000 * np.random.randn(n, d) - 20000 * m1 y = 10000 * np.random.randn(n, d) + 20000 * m2 data = np.empty((x.shape[0] + y.shape[0], d), np.double) data[:x.shape[0]] = x data[x.shape[0]:] = y kmeans(data, 2) def test_kmeans_simple(self): np.random.seed(54321) initc = np.concatenate(([[X[0]], [X[1]], [X[2]]])) for tp in np.array, matrix: code1 = kmeans(tp(X), tp(initc), iter=1)[0] assert_array_almost_equal(code1, CODET2) def test_kmeans_lost_cluster(self): # This will cause kmeans to have a cluster with no points. data = TESTDATA_2D initk = np.array([[-1.8127404, -0.67128041], [2.04621601, 0.07401111], [-2.31149087, -0.05160469]]) kmeans(data, initk) with suppress_warnings() as sup: sup.filter(UserWarning, "One of the clusters is empty. Re-run kmeans with a " "different initialization") kmeans2(data, initk, missing='warn') assert_raises(ClusterError, kmeans2, data, initk, missing='raise') def test_kmeans2_simple(self): np.random.seed(12345678) initc = np.concatenate(([[X[0]], [X[1]], [X[2]]])) for tp in np.array, matrix: code1 = kmeans2(tp(X), tp(initc), iter=1)[0] code2 = kmeans2(tp(X), tp(initc), iter=2)[0] assert_array_almost_equal(code1, CODET1) assert_array_almost_equal(code2, CODET2) def test_kmeans2_rank1(self): data = TESTDATA_2D data1 = data[:, 0] initc = data1[:3] code = initc.copy() kmeans2(data1, code, iter=1)[0] kmeans2(data1, code, iter=2)[0] def test_kmeans2_rank1_2(self): data = TESTDATA_2D data1 = data[:, 0] kmeans2(data1, 2, iter=1) def test_kmeans2_high_dim(self): # test kmeans2 when the number of dimensions exceeds the number # of input points data = TESTDATA_2D data = data.reshape((20, 20))[:10] kmeans2(data, 2) def test_kmeans2_init(self): np.random.seed(12345) data = TESTDATA_2D kmeans2(data, 3, minit='points') kmeans2(data[:, :1], 3, minit='points') # special case (1-D) kmeans2(data, 3, minit='++') kmeans2(data[:, :1], 3, minit='++') # special case (1-D) # minit='random' can give warnings, filter those with suppress_warnings() as sup: sup.filter(message="One of the clusters is empty. Re-run.") kmeans2(data, 3, minit='random') kmeans2(data[:, :1], 3, minit='random') # special case (1-D) @pytest.mark.skipif(sys.platform == 'win32', reason='Fails with MemoryError in Wine.') def test_krandinit(self): data = TESTDATA_2D datas = [data.reshape((200, 2)), data.reshape((20, 20))[:10]] k = int(1e6) for data in datas: np.random.seed(1234) init = _krandinit(data, k) orig_cov = np.cov(data, rowvar=0) init_cov = np.cov(init, rowvar=0) assert_allclose(orig_cov, init_cov, atol=1e-2) def test_kmeans2_empty(self): # Regression test for gh-1032. assert_raises(ValueError, kmeans2, [], 2) def test_kmeans_0k(self): # Regression test for gh-1073: fail when k arg is 0. assert_raises(ValueError, kmeans, X, 0) assert_raises(ValueError, kmeans2, X, 0) assert_raises(ValueError, kmeans2, X, np.array([])) def test_kmeans_large_thres(self): # Regression test for gh-1774 x = np.array([1, 2, 3, 4, 10], dtype=float) res = kmeans(x, 1, thresh=1e16) assert_allclose(res[0], np.array([4.])) assert_allclose(res[1], 2.3999999999999999)
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import shutil import tempfile from functools import wraps from hashlib import sha256 import sys from io import open import boto3 import requests from botocore.exceptions import ClientError from tqdm import tqdm try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse try: from pathlib import Path PYTORCH_PRETRAINED_BERT_CACHE = Path(os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', Path.home() / '.pytorch_pretrained_bert')) except AttributeError: PYTORCH_PRETRAINED_BERT_CACHE = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', os.path.join(os.path.expanduser("~"), '.pytorch_pretrained_bert')) logger = logging.getLogger(__name__) # pylint: disable=invalid-name def url_to_filename(url, etag=None): """ Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's, delimited by a period. """ url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdigest() if etag: etag_bytes = etag.encode('utf-8') etag_hash = sha256(etag_bytes) filename += '.' + etag_hash.hexdigest() return filename def filename_to_url(filename, cache_dir=None): """ Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) cache_path = os.path.join(cache_dir, filename) if not os.path.exists(cache_path): raise EnvironmentError("file {} not found".format(cache_path)) meta_path = cache_path + '.json' if not os.path.exists(meta_path): raise EnvironmentError("file {} not found".format(meta_path)) with open(meta_path, encoding="utf-8") as meta_file: metadata = json.load(meta_file) url = metadata['url'] etag = metadata['etag'] return url, etag def cached_path(url_or_filename, cache_dir=None, from_tf=False): """ Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the path. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(url_or_filename, Path): url_or_filename = str(url_or_filename) if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) parsed = urlparse(url_or_filename) # if not os.path.exists(url_or_filename): # raise ValueError("Local cached file does not exist: {}".format(parsed)) if parsed.scheme in ('http', 'https', 's3'): # URL, so get it from the cache (downloading if necessary) return get_from_cache(url_or_filename, cache_dir) elif os.path.exists(url_or_filename): # File, and it exists. return url_or_filename elif from_tf and os.path.exists(url_or_filename + ".meta"): # TF checkpoint exists return url_or_filename elif parsed.scheme == '': # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(url_or_filename)) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename)) def split_s3_path(url): """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at beginning of path. if s3_path.startswith("/"): s3_path = s3_path[1:] return bucket_name, s3_path def s3_request(func): """ Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response["Error"]["Code"]) == 404: raise EnvironmentError("file {} not found".format(url)) else: raise return wrapper @s3_request def s3_etag(url): """Check ETag on S3 object.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag @s3_request def s3_get(url, temp_file): """Pull a file directly from S3.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) def http_get(url, temp_file): req = requests.get(url, stream=True) content_length = req.headers.get('Content-Length') total = int(content_length) if content_length is not None else None progress = tqdm(unit="B", total=total) for chunk in req.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks progress.update(len(chunk)) temp_file.write(chunk) progress.close() def get_from_cache(url, cache_dir=None): """ Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) if not os.path.exists(cache_dir): os.makedirs(cache_dir) # Get eTag to add to filename, if it exists. if url.startswith("s3://"): etag = s3_etag(url) else: response = requests.head(url, allow_redirects=True) if response.status_code != 200: raise IOError("HEAD request failed for url {} with status code {}" .format(url, response.status_code)) etag = response.headers.get("ETag") filename = url_to_filename(url, etag) # get cache path to put the file cache_path = os.path.join(cache_dir, filename) if not os.path.exists(cache_path): raise ValueError("local cached file {} doesn't exist".format(cache_path)) # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with tempfile.NamedTemporaryFile() as temp_file: logger.info("%s not found in cache, downloading to %s", url, temp_file.name) # GET file object if url.startswith("s3://"): s3_get(url, temp_file) else: http_get(url, temp_file) # we are copying the file before closing it, so flush to avoid truncation temp_file.flush() # shutil.copyfileobj() starts at the current position, so go to the start temp_file.seek(0) logger.info("copying %s to cache at %s", temp_file.name, cache_path) with open(cache_path, 'wb') as cache_file: shutil.copyfileobj(temp_file, cache_file) logger.info("creating metadata file for %s", cache_path) meta = {'url': url, 'etag': etag} meta_path = cache_path + '.json' with open(meta_path, 'w', encoding="utf-8") as meta_file: json.dump(meta, meta_file) logger.info("removing temp file %s", temp_file.name) return cache_path def read_set_from_file(filename): ''' Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. ''' collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstrip()) return collection def get_file_extension(path, dot=True, lower=True): ext = os.path.splitext(path)[1] ext = ext if dot else ext[1:] return ext.lower() if lower else ext
"""Game views""" import json import logging logger = logging.getLogger(__name__) from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse #from django.urls import reverse from django.core import serializers #from django.contrib.auth import logout #from django.views import View from .models import Location, User from .models import Safezone from .models import Announcement from .models import Profile def index(request): """Homepage view""" context = {'text': 'Welcome to our game. Click "Fight the Infection" above to play!'} return render(request, 'game/index.html', context) def logout_successful(request): """Displays logout success message when user log out""" context = {'text': 'Logout successful'} return render(request, 'game/logout_successful.html', context) def users(request): """User search home""" context = {'text': 'Find a user:'} return render(request, 'game/users.html', context) def user_search(request): """Receive search input and search database for user""" query = request.GET.get('user_id') # receive user input if query: users_found = User.objects.filter(username__contains=query) # find users based on input if not users_found: # if no users found based on user input none = 'No users found.' context = {'searched': query, 'none': none} else: rates = [] for i in users_found: # if users found based on user input rates.append(i.profile.success_rate()) # get user success rates from user's profile results = zip(users_found, rates) # zip lists for easy iteration context = {'searched': query, 'results': results} else: context = {'searched': 'No input detected.'} # if no input sent return render(request, 'game/search_results.html', context) def user_detail(request): """User profile view""" if request.user.is_authenticated: # get user profile info if logged in current_user = request.user context = {'username': current_user.username, 'total_matches': int(current_user.profile.total_matches()), 'matches_won': int(current_user.profile.matches_won), 'win_rate': current_user.profile.success_rate(), 'num_antidotes': current_user.profile.num_antidotes } return render(request, 'game/user_detail.html', context) else: return HttpResponseRedirect('/login') def leaderboard(request): """Leaderboard view *Noted naive sorting logic to not risk breaking app""" get_users = Profile.objects.order_by('-matches_won')[:5] #get_users = Profile.objects.order_by('-success_rate')[:5] text = "" if not get_users: text = "No users in database yet." rates = [] user_list = [] matches = [] for i in get_users: # get 3 lists with username, succes rate, and total matches played current_user = i.user user_list.append(current_user.username) rates.append(i.success_rate()) matches.append(int(i.total_matches())) ranking = list(zip(user_list, rates, matches)) # zip for easy iteration context = {'text': text, 'ranking': ranking, 'get_users': get_users, 'matches': matches, 'rates': rates} return render(request, 'game/leaderboard.html', context) def play(request): """Game view""" current_user = request.user if current_user.is_anonymous(): # user must be logged in to get data num_antidotes = "Please log in to use antidotes!" else: num_antidotes = current_user.profile.num_antidotes context = {'antidotes': num_antidotes} return render(request, 'game/play.html', context) def location_json(request): """Retrieving location information from db""" if request.method == "GET": location_list = Location.objects.all() location_json_list = serializers.serialize('json', location_list) location_object = json.loads(location_json_list) # Convert JSON to python dict # Create a new object and make the keys be the location names so it's easier to search later output_object = {} for location in location_object: location_text = location['fields']['location_text'] output_object[location_text] = location return HttpResponse(json.dumps(output_object), content_type='application/javascript') def safezone_json(request): """Retrieving safezone locations from db""" if request.method == "GET": safezone_list = Safezone.objects.all() safezone_json_list = serializers.serialize('json', safezone_list) safezone_object = json.loads(safezone_json_list) # Convert JSON to python dict # Create a new object and make the keys be the location names so it's easier to search later output_object = {} for location in safezone_object: location_text = location['fields']['location_text'] output_object[location_text] = location return HttpResponse(json.dumps(output_object), content_type='application/javascript') # Fix this def current_profile_json(request): """Retrieving user profile data from db""" if request.method == "GET": if request.user.is_authenticated: current_user = request.user output_object = {} output_object['num_antidotes'] = current_user.profile.num_antidotes return HttpResponse(json.dumps(output_object), content_type='application/javascript') else: return HttpResponse("No logged in user") def win(request, location_name): """Saving matches won to db""" if request.method == "POST": location = get_object_or_404(Location, location_text=location_name) #get current location location.matches_won += 1 location.save() # save win information to current user's profile if request.user.is_authenticated: current_user = request.user current_user.profile.matches_won += 1 current_user.profile.save() return HttpResponse("matches_won increased by 1") def lose(request, location_name): """Saving matches lost to db""" if request.method == "POST": location = get_object_or_404(Location, location_text=location_name) location.matches_lost += 1 location.save() # save lose information to current user's profile if request.user.is_authenticated: current_user = request.user current_user.profile.matches_lost += 1 current_user.profile.save() return HttpResponse("matches_lost increased by 1") def antidoteReceived(request, location_name): """Saving antidotes changes to db""" if request.method == "POST": safezone = get_object_or_404(Safezone, location_text=location_name) safezone.antidotes_in_stock -= 1 safezone.antidotes_given_out += 1 safezone.save() # save increased antidote number information to current user's profile if request.user.is_authenticated: current_user = request.user current_user.profile.num_antidotes += 1 current_user.profile.save() return HttpResponse("received antidote") def antidoteUsed(request, location_name): """Saving antidotes changes to db""" if request.method == "POST": location = get_object_or_404(Location, location_text=location_name) location.matches_won += 5 location.save() # save increased antidote number information to current user's profile if request.user.is_authenticated: current_user = request.user current_user.profile.num_antidotes -= 1 current_user.profile.save() return HttpResponse("used antidote") def announcement_json(request): """Retrieving announcements from db""" if request.method == "GET": announcement_list = Announcement.objects.all() announcement_json_list = serializers.serialize('json', announcement_list) announcement_object = json.loads(announcement_json_list) # Convert JSON to python dict # Create a new object and make the keys be the location names so it's easier to search later output_object = {} for announcement in announcement_object: announcement_text = announcement['fields']['announcement_text'] output_object[announcement_text] = announcement return HttpResponse(json.dumps(output_object), content_type='application/javascript')
import os import sys import json import logging import yaml import hashlib import subprocess import platform import runpy import shutil import asyncio from filelock import FileLock from typing import Optional, List, Dict, Any from pathlib import Path import ray from ray._private.runtime_env.conda_utils import ( get_conda_activate_commands, create_conda_env_if_needed, delete_conda_env, ) from ray._private.runtime_env.context import RuntimeEnvContext from ray._private.utils import ( get_directory_size_bytes, get_wheel_filename, get_master_wheel_url, get_release_wheel_url, try_to_create_directory, ) from ray._private.runtime_env.packaging import Protocol, parse_uri default_logger = logging.getLogger(__name__) def _resolve_current_ray_path() -> str: # When ray is built from source with pip install -e, # ray.__file__ returns .../python/ray/__init__.py and this function returns # ".../python". # When ray is installed from a prebuilt binary, ray.__file__ returns # .../site-packages/ray/__init__.py and this function returns # ".../site-packages". return os.path.split(os.path.split(ray.__file__)[0])[0] def _get_ray_setup_spec(): """Find the Ray setup_spec from the currently running Ray. This function works even when Ray is built from source with pip install -e. """ ray_source_python_path = _resolve_current_ray_path() setup_py_path = os.path.join(ray_source_python_path, "setup.py") return runpy.run_path(setup_py_path)["setup_spec"] def _resolve_install_from_source_ray_dependencies(): """Find the Ray dependencies when Ray is installed from source.""" return _get_ray_setup_spec().install_requires def _inject_ray_to_conda_site( conda_path, logger: Optional[logging.Logger] = default_logger ): """Write the current Ray site package directory to a new site""" python_binary = os.path.join(conda_path, "bin/python") site_packages_path = ( subprocess.check_output( [python_binary, "-c", "import site; print(site.getsitepackages()[0])"] ) .decode() .strip() ) ray_path = _resolve_current_ray_path() logger.warning( f"Injecting {ray_path} to environment {conda_path} " "because _inject_current_ray flag is on." ) maybe_ray_dir = os.path.join(site_packages_path, "ray") if os.path.isdir(maybe_ray_dir): logger.warning(f"Replacing existing ray installation with {ray_path}") shutil.rmtree(maybe_ray_dir) # See usage of *.pth file at # https://docs.python.org/3/library/site.html with open(os.path.join(site_packages_path, "ray.pth"), "w") as f: f.write(ray_path) def _current_py_version(): return ".".join(map(str, sys.version_info[:3])) # like 3.6.10 def _is_m1_mac(): return sys.platform == "darwin" and platform.machine() == "arm64" def current_ray_pip_specifier( logger: Optional[logging.Logger] = default_logger, ) -> Optional[str]: """The pip requirement specifier for the running version of Ray. Returns: A string which can be passed to `pip install` to install the currently running Ray version, or None if running on a version built from source locally (likely if you are developing Ray). Examples: Returns "https://s3-us-west-2.amazonaws.com/ray-wheels/[..].whl" if running a stable release, a nightly or a specific commit """ if os.environ.get("RAY_CI_POST_WHEEL_TESTS"): # Running in Buildkite CI after the wheel has been built. # Wheels are at in the ray/.whl directory, but use relative path to # allow for testing locally if needed. return os.path.join( Path(ray.__file__).resolve().parents[2], ".whl", get_wheel_filename() ) elif ray.__commit__ == "{{RAY_COMMIT_SHA}}": # Running on a version built from source locally. if os.environ.get("RAY_RUNTIME_ENV_LOCAL_DEV_MODE") != "1": logger.warning( "Current Ray version could not be detected, most likely " "because you have manually built Ray from source. To use " "runtime_env in this case, set the environment variable " "RAY_RUNTIME_ENV_LOCAL_DEV_MODE=1." ) return None elif "dev" in ray.__version__: # Running on a nightly wheel. if _is_m1_mac(): raise ValueError("Nightly wheels are not available for M1 Macs.") return get_master_wheel_url() else: if _is_m1_mac(): # M1 Mac release wheels are currently not uploaded to AWS S3; they # are only available on PyPI. So unfortunately, this codepath is # not end-to-end testable prior to the release going live on PyPI. return f"ray=={ray.__version__}" else: return get_release_wheel_url() def inject_dependencies( conda_dict: Dict[Any, Any], py_version: str, pip_dependencies: Optional[List[str]] = None, ) -> Dict[Any, Any]: """Add Ray, Python and (optionally) extra pip dependencies to a conda dict. Args: conda_dict (dict): A dict representing the JSON-serialized conda environment YAML file. This dict will be modified and returned. py_version (str): A string representing a Python version to inject into the conda dependencies, e.g. "3.7.7" pip_dependencies (List[str]): A list of pip dependencies that will be prepended to the list of pip dependencies in the conda dict. If the conda dict does not already have a "pip" field, one will be created. Returns: The modified dict. (Note: the input argument conda_dict is modified and returned.) """ if pip_dependencies is None: pip_dependencies = [] if conda_dict.get("dependencies") is None: conda_dict["dependencies"] = [] # Inject Python dependency. deps = conda_dict["dependencies"] # Add current python dependency. If the user has already included a # python version dependency, conda will raise a readable error if the two # are incompatible, e.g: # ResolvePackageNotFound: - python[version='3.5.*,>=3.6'] deps.append(f"python={py_version}") if "pip" not in deps: deps.append("pip") # Insert pip dependencies. found_pip_dict = False for dep in deps: if isinstance(dep, dict) and dep.get("pip") and isinstance(dep["pip"], list): dep["pip"] = pip_dependencies + dep["pip"] found_pip_dict = True break if not found_pip_dict: deps.append({"pip": pip_dependencies}) return conda_dict def _get_conda_env_hash(conda_dict: Dict) -> str: # Set `sort_keys=True` so that different orderings yield the same hash. serialized_conda_spec = json.dumps(conda_dict, sort_keys=True) hash = hashlib.sha1(serialized_conda_spec.encode("utf-8")).hexdigest() return hash def get_uri(runtime_env: Dict) -> Optional[str]: """Return `"conda://<hashed_dependencies>"`, or None if no GC required.""" conda = runtime_env.get("conda") if conda is not None: if isinstance(conda, str): # User-preinstalled conda env. We don't garbage collect these, so # we don't track them with URIs. uri = None elif isinstance(conda, dict): uri = "conda://" + _get_conda_env_hash(conda_dict=conda) else: raise TypeError( "conda field received by RuntimeEnvAgent must be " f"str or dict, not {type(conda).__name__}." ) else: uri = None return uri def _get_conda_dict_with_ray_inserted( runtime_env: "RuntimeEnv", # noqa: F821 logger: Optional[logging.Logger] = default_logger, ) -> Dict[str, Any]: """Returns the conda spec with the Ray and `python` dependency inserted.""" conda_dict = json.loads(runtime_env.conda_config()) assert conda_dict is not None ray_pip = current_ray_pip_specifier(logger=logger) if ray_pip: extra_pip_dependencies = [ray_pip, "ray[default]"] elif runtime_env.get_extension("_inject_current_ray") == "True": extra_pip_dependencies = _resolve_install_from_source_ray_dependencies() else: extra_pip_dependencies = [] conda_dict = inject_dependencies( conda_dict, _current_py_version(), extra_pip_dependencies ) return conda_dict class CondaManager: def __init__(self, resources_dir: str): self._resources_dir = os.path.join(resources_dir, "conda") try_to_create_directory(self._resources_dir) # It is not safe for multiple processes to install conda envs # concurrently, even if the envs are different, so use a global # lock for all conda installs and deletions. # See https://github.com/ray-project/ray/issues/17086 self._installs_and_deletions_file_lock = os.path.join( self._resources_dir, "ray-conda-installs-and-deletions.lock" ) def _get_path_from_hash(self, hash: str) -> str: """Generate a path from the hash of a conda or pip spec. The output path also functions as the name of the conda environment when using the `--prefix` option to `conda create` and `conda remove`. Example output: /tmp/ray/session_2021-11-03_16-33-59_356303_41018/runtime_resources /conda/ray-9a7972c3a75f55e976e620484f58410c920db091 """ return os.path.join(self._resources_dir, hash) def get_uri(self, runtime_env: "RuntimeEnv") -> Optional[str]: # noqa: F821 """Return the conda URI from the RuntimeEnv if it exists, else None.""" conda_uri = runtime_env.conda_uri() if conda_uri != "": return conda_uri return None def delete_uri( self, uri: str, logger: Optional[logging.Logger] = default_logger ) -> int: """Delete URI and return the number of bytes deleted.""" logger.info(f"Got request to delete URI {uri}") protocol, hash = parse_uri(uri) if protocol != Protocol.CONDA: raise ValueError( "CondaManager can only delete URIs with protocol " f"conda. Received protocol {protocol}, URI {uri}" ) conda_env_path = self._get_path_from_hash(hash) local_dir_size = get_directory_size_bytes(conda_env_path) with FileLock(self._installs_and_deletions_file_lock): successful = delete_conda_env(prefix=conda_env_path, logger=logger) if not successful: logger.warning(f"Error when deleting conda env {conda_env_path}. ") return 0 return local_dir_size async def create( self, uri: Optional[str], runtime_env: "RuntimeEnv", # noqa: F821 context: RuntimeEnvContext, logger: Optional[logging.Logger] = default_logger, ) -> int: # Currently create method is still a sync process, to avoid blocking # the loop, need to run this function in another thread. # TODO(Catch-Bull): Refactor method create into an async process, and # make this method running in current loop. def _create(): logger.debug( "Setting up conda for runtime_env: " f"{runtime_env.serialize()}" ) protocol, hash = parse_uri(uri) conda_env_name = self._get_path_from_hash(hash) conda_dict = _get_conda_dict_with_ray_inserted(runtime_env, logger=logger) logger.info(f"Setting up conda environment with {runtime_env}") with FileLock(self._installs_and_deletions_file_lock): try: conda_yaml_file = os.path.join( self._resources_dir, "environment.yml" ) with open(conda_yaml_file, "w") as file: yaml.dump(conda_dict, file) create_conda_env_if_needed( conda_yaml_file, prefix=conda_env_name, logger=logger ) finally: os.remove(conda_yaml_file) if runtime_env.get_extension("_inject_current_ray") == "True": _inject_ray_to_conda_site(conda_path=conda_env_name, logger=logger) logger.info(f"Finished creating conda environment at {conda_env_name}") return get_directory_size_bytes(conda_env_name) loop = asyncio.get_event_loop() return await loop.run_in_executor(None, _create) def modify_context( self, uri: str, runtime_env: "RuntimeEnv", # noqa: F821 context: RuntimeEnvContext, logger: Optional[logging.Logger] = default_logger, ): if not runtime_env.has_conda(): return if runtime_env.conda_env_name(): conda_env_name = runtime_env.conda_env_name() else: protocol, hash = parse_uri(runtime_env.conda_uri()) conda_env_name = self._get_path_from_hash(hash) context.py_executable = "python" context.command_prefix += get_conda_activate_commands(conda_env_name)
import time import re import os import sys import urllib from getopt import * from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException class TimeoutList: page_index_list = [] page_url_list = [] def append(self, page_url, page_index): if len(self.page_index_list) > 0 and self.page_index_list[-1] == page_index - 1: self.page_index_list.pop() self.page_url_list.pop() return False else: self.page_index_list.append(page_index) self.page_url_list.append(page_url) return True def get_page_url_list(self): for page_url in self.page_url_list: yield page_url def clear(self): self.page_index_list.clear() self.page_url_list.clear() class Crawler: city_list = [] valid_category_url_list = [] def __init__(self, chromedriver_path, home_url): self.driver = webdriver.Chrome(chromedriver_path) self.driver.set_page_load_timeout(30) self.home_url = home_url self.regexcategory = r"search/category/[0-9]+/[0-9]+/g[0-9]+" self.regex_citylist = urllib.parse.urljoin(home_url, "[a-z]+") self.city_list_url = urllib.parse.urljoin(home_url, "citylist") def get_finish_city_path(self): return os.path.join(self.outputdir, "finish_city.txt") def set_output_dir(self, outputdir): self.outputdir = outputdir def remove_finish_city(self): if os.path.isfile(self.get_finish_city_path()): f = open(self.get_finish_city_path(), "r") for line in f: city = line.strip("\n") if city in self.city_list: self.city_list.remove(city) f.close() def get_cities(self, city): if not city: self.get_all_city_list() else: citylist = city.strip("\n").split(",") for city in citylist: self.city_list.append(city) self.remove_finish_city() def get_all_city_list(self): self.driver.get(self.city_list_url); time.sleep(5) contain_element = self.driver.find_element_by_id('divPY') urls = contain_element.find_elements_by_xpath(".//a") for url in urls: try: href = url.get_attribute("href") if re.search(self.regex_citylist, href): city = href[24:] if city not in self.city_list: self.city_list.append(city) print("Prased city: [%s].." % city) except Exception as e: pass def quit(self): self.driver.quit() def fetch_root(self, outputdir, city): self.set_output_dir(outputdir) self.get_cities(city) self.fetch_all_cities() self.quit() def fetch_all_cities(self): for city in self.city_list: print("Now, fetching city: [%s] .." % city) self.fetch_city(city) f = open(self.get_finish_city_path(), "a", encoding='utf-8') f.write(city + "\n") f.close() def makesure_directory_exist(self, directory_path): if not os.path.isdir(directory_path): os.mkdir(directory_path) def get_valid_url(self, root_path, page_index): if page_index == 0: return "" elif page_index == 1: return root_path else: return root_path + "p" + str(page_index) def wait_for_loading_finish(self): wait_webelement = WebDriverWait(self.driver, 30).until(lambda brow: brow.find_element_by_id("shop-all-list")) def get_item_entry_by_link(self, page_url): self.driver.get(page_url) self.wait_for_loading_finish() shoplist = self.driver.find_element_by_id('shop-all-list') item_elements = shoplist.find_elements_by_xpath('.//li') for item in item_elements: item_entry = [] tit = item.find_element_by_xpath('.//a[@data-hippo-type="shop"]') #id href = tit.get_attribute("href") shopid = href[href.rfind('/')+1:] item_entry.append(shopid) #title shoptitle = tit.get_attribute("title") item_entry.append(shoptitle) tag_addr = item.find_element_by_class_name("tag-addr") #address addr = tag_addr.find_element_by_class_name("addr") item_entry.append(addr.text) #tags lst = tag_addr.find_elements_by_xpath(".//a") for ls in lst: href = ls.get_attribute("href") tag = ls.text item_entry.append(tag) item_entry.append(href[40:]) yield "\t".join(item_entry) def write_log(self, err_log_path, err_msg, prefix): f = open(err_log_path, "a", encoding='utf-8') f.write(prefix + err_msg + "\n") f.close() def parse_valid_category_url_list(self, city, valid_urls_path): city_home_url = os.path.join(self.home_url, city) self.driver.get(city_home_url); time.sleep(5) linkelems = self.driver.find_elements_by_xpath('//a') for linkelem in linkelems: try: href = linkelem.get_attribute("href") if re.search(self.regexcategory, href): if href not in self.valid_category_url_list: self.valid_category_url_list.append(href) except Exception: pass self.valid_category_url_list.sort() valid_url_file = open(valid_urls_path, "w", encoding='utf-8') for valid_category_url in self.valid_category_url_list: valid_url_file.write(valid_category_url + "\n") valid_url_file.close() def remove_finish_pages(self, finish_log_path): if os.path.isfile(finish_log_path): f = open(finish_log_path, "r") for line in f: finished_page = line.strip("\n") if finished_page in self.valid_category_url_list: self.valid_category_url_list.remove(finished_page) f.close() def fetch_city(self, city): current_output_dir = os.path.join(self.outputdir, city) self.makesure_directory_exist(current_output_dir) item_entry_path = os.path.join(current_output_dir, "items.txt") logfile_path = os.path.join(current_output_dir, "timeout_err.log") finish_log_path = os.path.join(current_output_dir, "finish.log") valid_urls_path = os.path.join(current_output_dir, "valid_urls.log") # Get all valid category url list. self.parse_valid_category_url_list(city, valid_urls_path) self.remove_finish_pages(finish_log_path) self.fetch_items(item_entry_path, logfile_path, finish_log_path) def fetch_items(self, item_entry_path, logfile_path, finish_log_path): timeout_list = TimeoutList() for link in self.valid_category_url_list: print("Now, fetch url: %s" % link) f = open(item_entry_path, "a", encoding='utf-8') f.write("\n################# BEGIN OF BLOCK [%s] #################\n" % link[40:]) for i in range(51): try: tmpcurlink = self.get_valid_url(link, i) if not tmpcurlink: continue print("Page %d\t--\t" % i, end='') for item_entry in self.get_item_entry_by_link(tmpcurlink): f.write(item_entry + "\n") print("Done.") except TimeoutException: if timeout_list.append(tmpcurlink, i): print("timeout.") continue else: print("timeout again. Done.") break except Exception as e: print(e) print("Error. Done.") self.write_log(logfile_path, tmpcurlink, "err: ") # Handle timeout list for tmpcurlink in timeout_list.get_page_url_list(): try: print("Now, retry timeout page: %s" % tmpcurlink) for item_entry in self.get_item_entry_by_link(tmpcurlink): f.write(item_entry + "\n") print("Done.") except TimeoutException as e: print("Timeout again. Done.") self.write_log(logfile_path, tmpcurlink, "timeout: ") except Exception as e: print(e) print("Error, Done.") self.write_log(logfile_path, tmpcurlink, "err: ") timeout_list.clear() self.write_log(finish_log_path, link, "") f.write("################# END OF BLOCK [%s] #################\n" % link[40:]) f.close() def main(): chromedriver_path = "" outputdir_path = "" home_url = "" city = "" usage = "Usage:\n crawer.py -d chrome_driver_path -h website_homepage -o output_dir_path -c city1,city2,city3" try: opts, args = getopt(sys.argv[1:], "d:o:h:c:", ["driver=", "output=", "homepage=", "city="]) if len(sys.argv) <= 1: print(usage) sys.exit(0) for opt, arg in opts: if opt in ("-d", "--driver"): chromedriver_path = arg elif opt in ("-o", "--output"): outputdir_path = arg elif opt in ("-h", "--homepage"): home_url = arg elif opt in ("-c", "--city"): city = arg else: print("Invalid param: %s", opt) sys.exit(-1) except Exception as e: print(e) print(usage) sys.exit(-1) crawler = Crawler(chromedriver_path, home_url) crawler.fetch_root(outputdir_path, city) if __name__ == "__main__": main()
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import re import subprocess from threading import Timer from py_trace_event import trace_time from telemetry.internal.platform import tracing_agent from tracing.trace_data import trace_data def _ParsePsProcessString(line): """Parses a process line from the output of `ps`. Example of `ps` command output: '3.4 8.0 31887 31447 com.app.Webkit' """ token_list = line.strip().split() if len(token_list) < 5: raise ValueError('Line has too few tokens: %s.' % token_list) return { 'pCpu': float(token_list[0]), 'pMem': float(token_list[1]), 'pid': int(token_list[2]), 'ppid': int(token_list[3]), 'name': ' '.join(token_list[4:]) } class ProcessCollector(object): def _GetProcessesAsStrings(self): """Returns a list of strings, each of which contains info about a process. """ raise NotImplementedError # pylint: disable=unused-argument def _ParseProcessString(self, proc_string): """Parses an individual process string returned by _GetProcessesAsStrings(). Returns: A dictionary containing keys of 'pid' (an integer process ID), 'ppid' (an integer parent process ID), 'name' (a string for the process name), 'pCpu' (a float for the percent CPU load incurred by the process), and 'pMem' (a float for the percent memory load caused by the process). """ raise NotImplementedError def Init(self): """Performs any required initialization before starting tracing.""" pass def GetProcesses(self): """Fetches the top processes returned by top command. Returns: A list of dictionaries, each containing 'pid' (an integer process ID), 'ppid' (an integer parent process ID), 'name (a string for the process name), pCpu' (a float for the percent CPU load incurred by the process), and 'pMem' (a float for the percent memory load caused by the process). """ proc_strings = self._GetProcessesAsStrings() return [ self._ParseProcessString(proc_string) for proc_string in proc_strings ] class WindowsProcessCollector(ProcessCollector): """Class for collecting information about processes on Windows. Example of Windows command output: '3644 1724 chrome#1 8 84497' '3644 832 chrome#2 4 34872' """ _GET_PERF_DATA_SHELL_COMMAND = [ 'wmic', 'path', # Retrieve a WMI object from the following path. 'Win32_PerfFormattedData_PerfProc_Process', # Contains process perf data. 'get', 'CreatingProcessID,IDProcess,Name,PercentProcessorTime,WorkingSet' ] _GET_COMMANDS_SHELL_COMMAND = [ 'wmic', 'Process', 'get', 'CommandLine,ProcessID', # Formatting the result as a CSV means that if no CommandLine is available # we can at least tell by the lack of data between commas. '/format:csv' ] _GET_PHYSICAL_MEMORY_BYTES_SHELL_COMMAND = [ 'wmic', 'ComputerSystem', 'get', 'TotalPhysicalMemory' ] def __init__(self): self._physicalMemoryBytes = None def Init(self): if not self._physicalMemoryBytes: self._physicalMemoryBytes = self._GetPhysicalMemoryBytes() # The command to get the per-process perf data takes significantly longer # the first time that it's run (~10s, compared to ~60ms for subsequent # runs). In order to avoid having this affect tracing, we run it once ahead # of time. self._GetProcessesAsStrings() def GetProcesses(self): processes = super(WindowsProcessCollector, self).GetProcesses() # On Windows, the absolute minimal name of the process is given # (e.g. "python" for Telemetry). In order to make this more useful, we check # if a more descriptive command is available for each PID and use that # command if it is. pid_to_command_dict = self._GetPidToCommandDict() for process in processes: if process['pid'] in pid_to_command_dict: process['name'] = pid_to_command_dict[process['pid']] return processes def _GetPhysicalMemoryBytes(self): """Returns the number of bytes of physical memory on the computer.""" raw_output = subprocess.check_output( self._GET_PHYSICAL_MEMORY_BYTES_SHELL_COMMAND) # The bytes of physical memory is on the second row (after the header row). return int(raw_output.strip().split('\n')[1]) def _GetProcessesAsStrings(self): try: # Skip the header and total rows and strip the trailing newline. return subprocess.check_output( self._GET_PERF_DATA_SHELL_COMMAND).strip().split('\n')[2:] except subprocess.CalledProcessError as e: logging.warning( 'wmic failed with error code %d when running command, which gave ' 'output: %s', e.returncode, e.output) raise def _ParseProcessString(self, proc_string): assert self._physicalMemoryBytes, 'Must call Init() before using collector' token_list = proc_string.strip().split() if len(token_list) < 5: raise ValueError('Line has too few tokens: %s.' % token_list) # Process names are given in the form: # # windowsUpdate # Windows Explorer # chrome#1 # chrome#2 # # In order to match other platforms, where multiple processes can have the # same name and can be easily grouped based on that name, we strip any # pound sign and number. name = ' '.join(token_list[2:-2]) name = re.sub(r'#[0-9]+$', '', name) # The working set size (roughly equivalent to the resident set size on Unix) # is given in bytes. In order to convert this to percent of physical memory # occupied by the process, we divide by the amount of total physical memory # on the machine. percent_memory = float(token_list[-1]) / self._physicalMemoryBytes * 100 return { 'ppid': int(token_list[0]), 'pid': int(token_list[1]), 'name': name, 'pCpu': float(token_list[-2]), 'pMem': percent_memory } def _GetPidToCommandDict(self): """Returns a dictionary from the PID of a process to the full command used to launch that process. If no full command is available for a given process, that process is omitted from the returned dictionary. """ # Skip the header row and strip the trailing newline. process_strings = subprocess.check_output( self._GET_COMMANDS_SHELL_COMMAND).strip().split('\n')[1:] command_by_pid = {} for process_string in process_strings: process_string = process_string.strip() command = self._ParseCommandString(process_string) # Only return additional information about the command if it's available. if command['command']: command_by_pid[command['pid']] = command['command'] return command_by_pid def _ParseCommandString(self, command_string): groups = re.match(r'^([^,]+),(.*),([0-9]+)$', command_string).groups() return { # Ignore groups[0]: it's the hostname. 'pid': int(groups[2]), 'command': groups[1] } class LinuxProcessCollector(ProcessCollector): """Class for collecting information about processes on Linux. Example of Linux command output: '3.4 8.0 31887 31447 com.app.Webkit' """ _SHELL_COMMAND = [ 'ps', '-a', # Include processes that aren't session leaders. '-x', # List all processes, even those not owned by the user. '-o', # Show the output in the specified format. 'pcpu,pmem,pid,ppid,cmd' ] def _GetProcessesAsStrings(self): # Skip the header row and strip the trailing newline. return subprocess.check_output(self._SHELL_COMMAND).strip().split('\n')[1:] def _ParseProcessString(self, proc_string): return _ParsePsProcessString(proc_string) class MacProcessCollector(ProcessCollector): """Class for collecting information about processes on Mac. Example of Mac command output: '3.4 8.0 31887 31447 com.app.Webkit' """ _SHELL_COMMAND = [ 'ps', '-a', # Include all users' processes. '-ww', # Don't limit the length of each line. '-x', # Include processes that aren't associated with a terminal. '-o', # Show the output in the specified format. '%cpu %mem pid ppid command' # Put the command last to avoid truncation. ] def _GetProcessesAsStrings(self): # Skip the header row and strip the trailing newline. return subprocess.check_output(self._SHELL_COMMAND).strip().split('\n')[1:] def _ParseProcessString(self, proc_string): return _ParsePsProcessString(proc_string) class CpuTracingAgent(tracing_agent.TracingAgent): _SNAPSHOT_INTERVAL_BY_OS = { # Sampling via wmic on Windows is about twice as expensive as sampling via # ps on Linux and Mac, so we halve the sampling frequency. 'win': 2.0, 'mac': 1.0, 'linux': 1.0 } def __init__(self, platform_backend): super(CpuTracingAgent, self).__init__(platform_backend) self._snapshot_ongoing = False self._snapshots = [] self._os_name = platform_backend.GetOSName() # pylint: disable=redefined-variable-type if self._os_name == 'win': self._collector = WindowsProcessCollector() elif self._os_name == 'mac': self._collector = MacProcessCollector() else: self._collector = LinuxProcessCollector() @classmethod def IsSupported(cls, platform_backend): os_name = platform_backend.GetOSName() return (os_name in ['mac', 'linux', 'win']) def StartAgentTracing(self, config, timeout): assert not self._snapshot_ongoing, ( 'Agent is already taking snapshots when tracing is started.') if not config.enable_cpu_trace: return False self._collector.Init() self._snapshot_ongoing = True self._KeepTakingSnapshots() return True def _KeepTakingSnapshots(self): """Take CPU snapshots every SNAPSHOT_FREQUENCY seconds.""" if not self._snapshot_ongoing: return # Assume CpuTracingAgent shares the same clock domain as telemetry self._snapshots.append( (self._collector.GetProcesses(), trace_time.Now())) interval = self._SNAPSHOT_INTERVAL_BY_OS[self._os_name] Timer(interval, self._KeepTakingSnapshots).start() def StopAgentTracing(self): assert self._snapshot_ongoing, ( 'Agent is not taking snapshots when tracing is stopped.') self._snapshot_ongoing = False def CollectAgentTraceData(self, trace_data_builder, timeout=None): assert not self._snapshot_ongoing, ( 'Agent is still taking snapshots when data is collected.') self._snapshot_ongoing = False trace_data_builder.AddTraceFor(trace_data.CPU_TRACE_DATA, { "traceEvents": self._FormatSnapshotsData(), "metadata": { "clock-domain": "TELEMETRY" } }) def _FormatSnapshotsData(self): """Format raw data into Object Event specified in Trace Format document.""" pid = os.getpid() return [{ 'name': 'CPUSnapshots', 'ph': 'O', 'id': '0x1000', 'local': True, 'ts': timestamp, 'pid': pid, 'tid': None, 'args': { 'snapshot': { 'processes': snapshot } } } for snapshot, timestamp in self._snapshots]
from website import settings settings.ELASTIC_INDEX = 'test' import unittest from nose.tools import * # PEP8 asserts from tests.base import OsfTestCase from tests.test_features import requires_search from tests.factories import ( UserFactory, ProjectFactory, NodeFactory, UnregUserFactory, UnconfirmedUserFactory ) from framework.auth.core import Auth import website.search.search as search from website.search import elastic_search from website.search.util import build_query from website.search_migration.migrate import migrate @requires_search class SearchTestCase(OsfTestCase): def tearDown(self): super(SearchTestCase, self).tearDown() search.delete_index(elastic_search.INDEX) search.create_index(elastic_search.INDEX) def setUp(self): super(SearchTestCase, self).setUp() search.create_index(elastic_search.INDEX) def query(term): results = search.search(build_query(term), index=elastic_search.INDEX) return results def query_user(name): term = 'category:user AND "{}"'.format(name) return query(term) @requires_search class TestUserUpdate(SearchTestCase): def setUp(self): super(TestUserUpdate, self).setUp() search.delete_index(elastic_search.INDEX) search.create_index(elastic_search.INDEX) self.user = UserFactory(fullname='David Bowie') def test_new_user(self): # Verify that user has been added to Elastic Search docs = query_user(self.user.fullname)['results'] assert_equal(len(docs), 1) def test_new_user_unconfirmed(self): user = UnconfirmedUserFactory() docs = query_user(user.fullname)['results'] assert_equal(len(docs), 0) token = user.get_confirmation_token(user.username) user.confirm_email(token) user.save() docs = query_user(user.fullname)['results'] assert_equal(len(docs), 1) def test_change_name(self): """Add a user, change her name, and verify that only the new name is found in search. """ user = UserFactory(fullname='Barry Mitchell') fullname_original = user.fullname user.fullname = user.fullname[::-1] user.save() docs_original = query_user(fullname_original)['results'] assert_equal(len(docs_original), 0) docs_current = query_user(user.fullname)['results'] assert_equal(len(docs_current), 1) def test_disabled_user(self): """Test that disabled users are not in search index""" user = UserFactory(fullname='Bettie Page') user.save() # Ensure user is in search index assert_equal(len(query_user(user.fullname)['results']), 1) # Disable the user user.is_disabled = True user.save() # Ensure user is not in search index assert_equal(len(query_user(user.fullname)['results']), 0) def test_merged_user(self): user = UserFactory(fullname='Annie Lennox') merged_user = UserFactory(fullname='Lisa Stansfield') user.save() merged_user.save() assert_equal(len(query_user(user.fullname)['results']), 1) assert_equal(len(query_user(merged_user.fullname)['results']), 1) user.merge_user(merged_user) assert_equal(len(query_user(user.fullname)['results']), 1) assert_equal(len(query_user(merged_user.fullname)['results']), 0) def test_employment(self): user = UserFactory(fullname='Helga Finn') user.save() institution = 'Finn\'s Fine Filers' docs = query_user(institution)['results'] assert_equal(len(docs), 0) user.jobs.append({ 'institution': institution, 'title': 'The Big Finn', }) user.save() docs = query_user(institution)['results'] assert_equal(len(docs), 1) def test_education(self): user = UserFactory(fullname='Henry Johnson') user.save() institution = 'Henry\'s Amazing School!!!' docs = query_user(institution)['results'] assert_equal(len(docs), 0) user.schools.append({ 'institution': institution, 'degree': 'failed all classes', }) user.save() docs = query_user(institution)['results'] assert_equal(len(docs), 1) def test_name_fields(self): names = ['Bill Nye', 'William', 'the science guy', 'Sanford', 'the Great'] user = UserFactory(fullname=names[0]) user.given_name = names[1] user.middle_names = names[2] user.family_name = names[3] user.suffix = names[4] user.save() docs = [query_user(name)['results'] for name in names] assert_equal(sum(map(len, docs)), len(docs)) # 1 result each assert_true(all([user._id == doc[0]['id'] for doc in docs])) @requires_search class TestProject(SearchTestCase): def setUp(self): super(TestProject, self).setUp() search.delete_index(elastic_search.INDEX) search.create_index(elastic_search.INDEX) self.user = UserFactory(fullname='John Deacon') self.project = ProjectFactory(title='Red Special', creator=self.user) def test_new_project_private(self): """Verify that a private project is not present in Elastic Search. """ docs = query(self.project.title)['results'] assert_equal(len(docs), 0) def test_make_public(self): """Make project public, and verify that it is present in Elastic Search. """ self.project.set_privacy('public') docs = query(self.project.title)['results'] assert_equal(len(docs), 1) @requires_search class TestPublicNodes(SearchTestCase): def setUp(self): super(TestPublicNodes, self).setUp() self.user = UserFactory(usename='Doug Bogie') self.title = 'Red Special' self.consolidate_auth = Auth(user=self.user) self.project = ProjectFactory( title=self.title, creator=self.user, is_public=True, ) self.component = NodeFactory( project=self.project, title=self.title, creator=self.user, is_public=True ) self.registration = ProjectFactory( title=self.title, creator=self.user, is_public=True, is_registration=True ) def test_make_private(self): """Make project public, then private, and verify that it is not present in search. """ self.project.set_privacy('private') docs = query('category:project AND ' + self.title)['results'] assert_equal(len(docs), 0) self.component.set_privacy('private') docs = query('category:component AND ' + self.title)['results'] assert_equal(len(docs), 0) self.registration.set_privacy('private') docs = query('category:registration AND ' + self.title)['results'] assert_equal(len(docs), 0) def test_public_parent_title(self): self.project.set_title('hello &amp; world',self.consolidate_auth) self.project.save() docs = query('category:component AND ' + self.title)['results'] assert_equal(len(docs), 1) assert_equal(docs[0]['parent_title'], 'hello & world') assert_true(docs[0]['parent_url']) def test_make_parent_private(self): """Make parent of component, public, then private, and verify that the component still appears but doesn't link to the parent in search. """ self.project.set_privacy('private') docs = query('category:component AND ' + self.title)['results'] assert_equal(len(docs), 1) assert_equal(docs[0]['parent_title'], '-- private project --') assert_false(docs[0]['parent_url']) def test_delete_project(self): """ """ self.component.remove_node(self.consolidate_auth) docs = query('category:component AND ' + self.title)['results'] assert_equal(len(docs), 0) self.project.remove_node(self.consolidate_auth) docs = query('category:project AND ' + self.title)['results'] assert_equal(len(docs), 0) def test_change_title(self): """ """ title_original = self.project.title self.project.set_title( 'Blue Ordinary', self.consolidate_auth, save=True) docs = query('category:project AND ' + title_original)['results'] assert_equal(len(docs), 0) docs = query('category:project AND ' + self.project.title)['results'] assert_equal(len(docs), 1) def test_add_tags(self): tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family'] for tag in tags: docs = query('tags:"{}"'.format(tag))['results'] assert_equal(len(docs), 0) self.project.add_tag(tag, self.consolidate_auth, save=True) for tag in tags: docs = query('tags:"{}"'.format(tag))['results'] assert_equal(len(docs), 1) def test_remove_tag(self): tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family'] for tag in tags: self.project.add_tag(tag, self.consolidate_auth, save=True) self.project.remove_tag(tag, self.consolidate_auth, save=True) docs = query('tags:"{}"'.format(tag))['results'] assert_equal(len(docs), 0) def test_update_wiki(self): """Add text to a wiki page, then verify that project is found when searching for wiki text. """ wiki_content = { 'home': 'Hammer to fall', 'swag': '#YOLO' } for key, value in wiki_content.items(): docs = query(value)['results'] assert_equal(len(docs), 0) self.project.update_node_wiki( key, value, self.consolidate_auth, ) docs = query(value)['results'] assert_equal(len(docs), 1) def test_clear_wiki(self): """Add wiki text to page, then delete, then verify that project is not found when searching for wiki text. """ wiki_content = 'Hammer to fall' self.project.update_node_wiki( 'home', wiki_content, self.consolidate_auth, ) self.project.update_node_wiki('home', '', self.consolidate_auth) docs = query(wiki_content)['results'] assert_equal(len(docs), 0) def test_add_contributor(self): """Add a contributor, then verify that project is found when searching for contributor. """ user2 = UserFactory(fullname='Adam Lambert') docs = query('category:project AND "{}"'.format(user2.fullname))['results'] assert_equal(len(docs), 0) self.project.add_contributor(user2, save=True) docs = query('category:project AND "{}"'.format(user2.fullname))['results'] assert_equal(len(docs), 1) def test_remove_contributor(self): """Add and remove a contributor, then verify that project is not found when searching for contributor. """ user2 = UserFactory(fullname='Brian May') self.project.add_contributor(user2, save=True) self.project.remove_contributor(user2, self.consolidate_auth) docs = query('category:project AND "{}"'.format(user2.fullname))['results'] assert_equal(len(docs), 0) def test_hide_contributor(self): user2 = UserFactory(fullname='Brian May') self.project.add_contributor(user2) self.project.set_visible(user2, False, save=True) docs = query('category:project AND "{}"'.format(user2.fullname))['results'] assert_equal(len(docs), 0) self.project.set_visible(user2, True, save=True) docs = query('category:project AND "{}"'.format(user2.fullname))['results'] assert_equal(len(docs), 1) def test_wrong_order_search(self): title_parts = self.title.split(' ') title_parts.reverse() title_search = ' '.join(title_parts) docs = query(title_search)['results'] assert_equal(len(docs), 3) def test_tag_aggregation(self): tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family'] for tag in tags: self.project.add_tag(tag, self.consolidate_auth, save=True) docs = query(self.title)['tags'] assert len(docs) == 3 for doc in docs: assert doc['key'] in tags def test_count_aggregation(self): docs = query("*")['counts'] assert_equal(docs['total'], 4) assert_equal(docs['project'], 1) assert_equal(docs['component'], 1) assert_equal(docs['registration'], 1) @requires_search class TestAddContributor(SearchTestCase): """Tests of the search.search_contributor method """ def setUp(self): super(TestAddContributor, self).setUp() self.name1 = 'Roger1 Taylor1' self.name2 = 'John2 Deacon2' self.user = UserFactory(fullname=self.name1) def test_unreg_users_dont_show_in_search(self): unreg = UnregUserFactory() contribs = search.search_contributor(unreg.fullname) assert_equal(len(contribs['users']), 0) def test_unreg_users_do_show_on_projects(self): unreg = UnregUserFactory(fullname='Robert Paulson') self.project = ProjectFactory( title='Glamour Rock', creator=unreg, is_public=True, ) results = query(unreg.fullname)['results'] assert_equal(len(results), 1) def test_search_fullname(self): """Verify that searching for full name yields exactly one result. """ contribs = search.search_contributor(self.name1) assert_equal(len(contribs['users']), 1) contribs = search.search_contributor(self.name2) assert_equal(len(contribs['users']), 0) def test_search_firstname(self): """Verify that searching for first name yields exactly one result. """ contribs = search.search_contributor(self.name1.split(' ')[0]) assert_equal(len(contribs['users']), 1) contribs = search.search_contributor(self.name2.split(' ')[0]) assert_equal(len(contribs['users']), 0) def test_search_partial(self): """Verify that searching for part of first name yields exactly one result. """ contribs = search.search_contributor(self.name1.split(' ')[0][:-1]) assert_equal(len(contribs['users']), 1) contribs = search.search_contributor(self.name2.split(' ')[0][:-1]) assert_equal(len(contribs['users']), 0) class TestSearchExceptions(OsfTestCase): """ Verify that the correct exception is thrown when the connection is lost """ @classmethod def setUpClass(cls): super(TestSearchExceptions, cls).setUpClass() if settings.SEARCH_ENGINE == 'elastic': cls._es = search.search_engine.es search.search_engine.es = None @classmethod def tearDownClass(cls): super(TestSearchExceptions, cls).tearDownClass() if settings.SEARCH_ENGINE == 'elastic': search.search_engine.es = cls._es def test_connection_error(self): """ Ensures that saving projects/users doesn't break as a result of connection errors """ self.user = UserFactory(usename='Doug Bogie') self.project = ProjectFactory( title="Tom Sawyer", creator=self.user, is_public=True, ) self.user.save() self.project.save() class TestSearchMigration(SearchTestCase): """ Verify that the correct indices are created/deleted during migration """ @classmethod def tearDownClass(cls): super(TestSearchMigration, cls).tearDownClass() search.create_index('test') def setUp(self): super(TestSearchMigration, self).setUp() self.es = search.search_engine.es search.delete_index('test') search.create_index('test') self.user = UserFactory(fullname='David Bowie') self.project = ProjectFactory( title='TEST', creator=self.user, is_public=True ) def test_first_migration_no_delete(self): migrate(delete=False, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v1']['aliases'].keys()[0], 'test') def test_multiple_migrations_no_delete(self): migrate(delete=False, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v1']['aliases'].keys()[0], 'test') migrate(delete=False, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v2']['aliases'].keys()[0], 'test') def test_first_migration_with_delete(self): migrate(delete=True, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v1']['aliases'].keys()[0], 'test') def test_multiple_migrations_with_delete(self): migrate(delete=True, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v1']['aliases'].keys()[0], 'test') migrate(delete=True, index='test') var = self.es.indices.get_aliases() assert_equal(var['test_v2']['aliases'].keys()[0], 'test') assert not var.get('test_v1')
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains utilities for downloading and converting datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import tarfile import zipfile from six.moves import urllib import tensorflow.compat.v1 as tf LABELS_FILENAME = 'labels.txt' def int64_feature(values): """Returns a TF-Feature of int64s. Args: values: A scalar or list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def bytes_list_feature(values): """Returns a TF-Feature of list of bytes. Args: values: A string or list of strings. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=values)) def float_list_feature(values): """Returns a TF-Feature of list of floats. Args: values: A float or list of floats. Returns: A TF-Feature. """ return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def bytes_feature(values): """Returns a TF-Feature of bytes. Args: values: A string. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) def float_feature(values): """Returns a TF-Feature of floats. Args: values: A scalar of list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def image_to_tfexample(image_data, image_format, height, width, class_id): return tf.train.Example(features=tf.train.Features(feature={ 'image/encoded': bytes_feature(image_data), 'image/format': bytes_feature(image_format), 'image/class/label': int64_feature(class_id), 'image/height': int64_feature(height), 'image/width': int64_feature(width), })) def download_url(url, dataset_dir): """Downloads the tarball or zip file from url into filepath. Args: url: The URL of a tarball or zip file. dataset_dir: The directory where the temporary files are stored. Returns: filepath: path where the file is downloaded. """ filename = url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return filepath def download_and_uncompress_tarball(tarball_url, dataset_dir): """Downloads the `tarball_url` and uncompresses it locally. Args: tarball_url: The URL of a tarball file. dataset_dir: The directory where the temporary files are stored. """ filepath = download_url(tarball_url, dataset_dir) tarfile.open(filepath, 'r:gz').extractall(dataset_dir) def download_and_uncompress_zipfile(zip_url, dataset_dir): """Downloads the `zip_url` and uncompresses it locally. Args: zip_url: The URL of a zip file. dataset_dir: The directory where the temporary files are stored. """ filename = zip_url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) if tf.gfile.Exists(filepath): print('File {filename} has been already downloaded at {filepath}. ' 'Unzipping it....'.format(filename=filename, filepath=filepath)) else: filepath = download_url(zip_url, dataset_dir) with zipfile.ZipFile(filepath, 'r') as zip_file: for member in zip_file.namelist(): memberpath = os.path.join(dataset_dir, member) # extract only if file doesn't exist if not (os.path.exists(memberpath) or os.path.isfile(memberpath)): zip_file.extract(member, dataset_dir) def write_label_file(labels_to_class_names, dataset_dir, filename=LABELS_FILENAME): """Writes a file with the list of class names. Args: labels_to_class_names: A map of (integer) labels to class names. dataset_dir: The directory in which the labels file should be written. filename: The filename where the class names are written. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'w') as f: for label in labels_to_class_names: class_name = labels_to_class_names[label] f.write('%d:%s\n' % (label, class_name)) def has_labels(dataset_dir, filename=LABELS_FILENAME): """Specifies whether or not the dataset directory contains a label map file. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: `True` if the labels file exists and `False` otherwise. """ return tf.gfile.Exists(os.path.join(dataset_dir, filename)) def read_label_file(dataset_dir, filename=LABELS_FILENAME): """Reads the labels file and returns a mapping from ID to class name. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: A map from a label (integer) to class name. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'rb') as f: lines = f.read().decode() lines = lines.split('\n') lines = filter(None, lines) labels_to_class_names = {} for line in lines: index = line.index(':') labels_to_class_names[int(line[:index])] = line[index+1:] return labels_to_class_names def open_sharded_output_tfrecords(exit_stack, base_path, num_shards): """Opens all TFRecord shards for writing and adds them to an exit stack. Args: exit_stack: A context2.ExitStack used to automatically closed the TFRecords opened in this function. base_path: The base path for all shards num_shards: The number of shards Returns: The list of opened TFRecords. Position k in the list corresponds to shard k. """ tf_record_output_filenames = [ '{}-{:05d}-of-{:05d}'.format(base_path, idx, num_shards) for idx in range(num_shards) ] tfrecords = [ exit_stack.enter_context(tf.python_io.TFRecordWriter(file_name)) for file_name in tf_record_output_filenames ] return tfrecords
# # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest, random, sys from compreffor import pyCompressor from compreffor.test.dummy import DummyGlyphSet from fontTools.ttLib import TTFont class TestCffCompressor(unittest.TestCase): def setUp(self): self.glyph_set = DummyGlyphSet({'a': (0, 1, 20, 21, 22, 2), 'b': (7, 0, 1, 20, 21, 22, 2), 'c': (0, 1, 20, 21, 22, 9, 3, 17)}) self.sf = pyCompressor.SubstringFinder(self.glyph_set) self.short_sf = pyCompressor.SubstringFinder(DummyGlyphSet({'a': (1, 2, 3), 'b': (8, 1, 4)})) self.rand_gs = DummyGlyphSet() num_glyphs = random.randint(5, 20) for i in range(num_glyphs): length = random.randint(2, 30) self.rand_gs[i] = tuple(random.randint(0, 100) for _ in range(length)) self.random_sf = pyCompressor.SubstringFinder(DummyGlyphSet(self.rand_gs)) length = 3 locations = [(0, 0), (1, 4)] charstrings = [(348, 374, 'rmoveto', 'endchar'), (123, -206, -140, 'hlineto', 348, 374, 'rmoveto', 'endchar')] self.cand_subr = pyCompressor.CandidateSubr(length, locations[0], 2, charstrings) self.empty_compreffor = pyCompressor.Compreffor(None, test_mode=True) def test_iterative_encode(self): """Test iterative_encode function""" ans = self.empty_compreffor.iterative_encode(self.glyph_set) self.assertIsInstance(ans, dict) encs = ans["glyph_encodings"] expected_subr_length = 5 # subr is (0, 1, 20, 21, 22) for glyph_enc in encs.values(): self.assertTrue(any(cs[1].length == expected_subr_length for cs in glyph_enc)) def test_get_substrings_all(self): """Test get_substrings without restrictions""" ans = [s.value() for s in self.sf.get_substrings(0, False)] expected_values = [(0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2, 3, 4), \ (2, 3, 4, 5), (2, 3, 4), (3, 4, 5), (3, 4), (4, 5), (4,), (5,)] self.assertEqual(ans, expected_values) def test_get_substrings_standard(self): """Check to make sure all substrings have freq >= 2 and positive savings""" ans = self.sf.get_substrings() for substr in ans: self.assertTrue(substr.freq >= 2) self.assertTrue(substr.subr_saving() > 0) def test_get_suffixes(self): """Test the results of suffix array construction.""" ans = self.short_sf.get_suffixes() self.assertEqual(ans, [(0, 0), (1, 1), (0, 1), (0, 2), (1, 0), (1, 2)]) def test_get_suffixes_random(self): """Check suffix array invariants on random input""" ans = self.random_sf.get_suffixes() # check there are the right number of suffixes expected_num = sum([len(chstring) for chstring in self.rand_gs.values()]) actual_num = len(ans) self.assertEqual(actual_num, expected_num) # check that the order is correct last_glidx, last_tidx = ans[0] last = self.random_sf.data[last_glidx][last_tidx:] for glyph_idx, tok_idx in ans[1:]: current = self.random_sf.data[glyph_idx][tok_idx:] self.assertTrue(last <= current) def test_get_lcp(self): """Test the lcp array generation""" expected = [0, 6, 5, 0, 5, 4, 0, 4, 3, 0, 3, 2, 0, 2, 1, 0, 1, 0, 0, 0, 0] self.assertEqual(self.sf.get_lcp(), expected) def test_human_size(self): """Test the human_size function for various numbers of bytes""" human_size = pyCompressor.human_size self.assertEqual(human_size(2), "2.0 bytes") self.assertEqual(human_size(2050), "2.0 KB") self.assertEqual(human_size(3565158), "3.4 MB") self.assertEqual(human_size(6120328397), "5.7 GB") def test_update_program_local(self): """Test update_program with only one replacement""" program = [7, 2, 10, 4, 8, 7, 0] substr = pyCompressor.CandidateSubr(3, (0, 1)) substr._position = 5 substr._fdidx = [0] substr._global = False encoding = [(1, substr)] bias = 0 self.empty_compreffor.update_program(program, encoding, bias, [bias], 0) self.assertEqual(program, [7, 5, "callsubr", 8, 7, 0]) def test_update_program_global(self): """Test update_program with only one replacement""" program = [7, 2, 10, 4, 8, 7, 0] substr = pyCompressor.CandidateSubr(3, (0, 1)) substr._position = 5 substr._fdidx = [0] substr._global = True encoding = [(1, substr)] bias = 0 self.empty_compreffor.update_program(program, encoding, bias, [bias], 0) self.assertEqual(program, [7, 5, "callgsubr", 8, 7, 0]) def test_update_program_multiple(self): """Test update_program with two replacements""" program = [7, 2, 10, 4, 8, 7, 0] substr = pyCompressor.CandidateSubr(3, (0, 1)) substr._position = 5 substr._global = True substr2 = pyCompressor.CandidateSubr(2, (0, 5)) substr2._position = 21 substr2._global = True encoding = [(1, substr), (5, substr2)] bias = 0 self.empty_compreffor.update_program(program, encoding, bias, [bias], 0) self.assertEqual(program, [7, 5, "callgsubr", 8, 21, "callgsubr"]) # TODO: make this test actually work def test_multiple_nested_subr_calls(self): """Test to make sure we can handle nested subrs. This is really just a case to make check we're encoding optimally.""" glyph_set = {'a': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 20), 'b': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 21), 'c': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 22), 'd': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 23), 'e': (0, 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17, 18, 19, 24), 'f': (0, 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17, 18, 19, 25), 'g': (0, 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17, 18, 19, 26),} glyph_set = DummyGlyphSet(glyph_set) ans = self.empty_compreffor.iterative_encode(glyph_set) print(ans["glyph_encodings"]) print(ans["lsubrs"]) print([s._encoding for s in ans["lsubrs"][0]]) def test_expand_hintmask_single_middle(self): """Non-edge usage of expand_hintmask""" data = [1, 2, 3, 4, 5, ('hintmask', 7), 8, 9, 10] self.empty_compreffor.expand_hintmask(data) self.assertEqual(data, [1, 2, 3, 4, 5, 'hintmask', 7, 8, 9, 10]) def test_expand_hintmask_multi_middle(self): """Non-edge usage of expand_hintmask with two items""" data = [1, ('hintmask', 3), 4, 5, ('hintmask', 7), 8, 9, 10] self.empty_compreffor.expand_hintmask(data) self.assertEqual(data, [1, 'hintmask', 3, 4, 5, 'hintmask', 7, 8, 9, 10]) def test_expand_hintmask_multi_end(self): """Non-edge usage of expand_hintmask with two items, one at end""" data = [1, 2, 3, 4, 5, ('hintmask', 7), 8, ('hintmask', 10)] self.empty_compreffor.expand_hintmask(data) self.assertEqual(data, [1, 2, 3, 4, 5, 'hintmask', 7, 8, 'hintmask', 10]) def test_collapse_hintmask_single_middle(self): """Non-edge usage of collapse_hintmask""" data = [1, 2, 3, 4, 5, 'hintmask', 7, 8, 9, 10] self.empty_compreffor.collapse_hintmask(data) self.assertEqual(data, [1, 2, 3, 4, 5, ('hintmask', 7), 8, 9, 10]) def test_collapse_hintmask_multi_middle(self): """Non-edge usage of collapse_hintmask with two items""" data = [1, 'hintmask', 3, 4, 5, 'hintmask', 7, 8, 9, 10] self.empty_compreffor.collapse_hintmask(data) self.assertEqual(data, [1, ('hintmask', 3), 4, 5, ('hintmask', 7), 8, 9, 10]) def test_collapse_hintmask_multi_end(self): """Non-edge usage of collapse_hintmask with two items, one at end""" data = [1, 2, 3, 4, 5, 'hintmask', 7, 8, 'hintmask', 10] self.empty_compreffor.collapse_hintmask(data) self.assertEqual(data, [1, 2, 3, 4, 5, ('hintmask', 7), 8, ('hintmask', 10)]) def test_tokenCost(self): """Make sure single tokens can have their cost calculated""" tokenCost = pyCompressor.tokenCost self.assertEqual(tokenCost('hlineto'), 1) self.assertEqual(tokenCost('flex'), 2) self.assertEqual(tokenCost(107), 1) self.assertEqual(tokenCost(108), 2) def test_candidatesubr_len(self): """Make sure len returns the correct length""" self.assertEqual(len(self.cand_subr), 3) def test_candidatesubr_value(self): """Make sure the value is correct""" expected_value = (348, 374, 'rmoveto') self.assertEqual(self.cand_subr.value(), expected_value)
""" Policy Gradients 1. Sample paths. 2. Process paths (compute advantage, baseline, rewards, etc) 3. Run the paths through the policy (function approximator) 4. Compute gradients/update policy model weights 5. Profit?!?! How we optimize the policy -------------------------- L(theta) = sum t=0 to T-1 log policy(action_t | state_t, theta) * A_t R_t = (sum u=t to T reward_u) B_t = E [ sum u=t to T lambda^(u-t) * reward_u | state_t] A_t = R_t - B_t R_t = reward A_t = advantage B_t = baseline theta = parameters of our policy, most like neural network weights. The baseline can be thought of as the value function (V). When we evaluate the baseline of a state we're predict how good our future returns will be given our current state. So, intuitively if A_t > 0 that means the path we sampled is better than the expectation of paths from the current state. Likewise, if A_t < 0, it's worse. Concretely, if A_t > 0 we want more paths like that, if A_t < 0 we want less paths like that. Theta will be updated during training to reflect this. Types of parameterized policies ------------------------------- Map s (state) to an output vector u 1. If the action is from a discrete set, the network maps s to a vector of probabilities (softmax) 2. If the action is continuous, then we map s to the mean/variance of a Gaussian distribution (diagonal covariance that does not depend on s) 3. If a is binary valued, we use a single output, the probability of outputting 1 (although we could also just use 1.) TODO: implement generalized advantage estimation """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from six.moves import range from gym.spaces import Box, Discrete from scipy.signal import lfilter import gym import tensorflow as tf import numpy as np import argparse def flatten_space(space): if isinstance(space, Box): return np.prod(space.shape) elif isinstance(space, Discrete): return space.n else: raise ValueError("Env must be either Box or Discrete.") def discount_cumsum(x, gamma): return lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1] class CategoricalPolicy(object): def __init__(self, in_dim, out_dim, hidden_dim, optimizer, session): # Placeholder Inputs self._observations = tf.placeholder(tf.float32, shape=[None, in_dim], name="observations") self._actions = tf.placeholder(tf.int32, name="actions") self._advantages = tf.placeholder(tf.float32, name="advantages") self._opt = optimizer self._sess = session h1 = tf.contrib.layers.fully_connected(self._observations, hidden_dim, activation_fn=tf.tanh) probs = tf.contrib.layers.fully_connected(h1, out_dim, activation_fn=tf.nn.softmax) # I believe this is faster if on the CPU with tf.device("/cpu:0"): # NOTE: Doesn't currently work due to gather_nd gradient not being currently implemented # inds = tf.transpose(tf.pack([tf.range(tf.shape(probs)[0]), self._actions])) # log_lik = tf.log(tf.gather_nd(probs, inds)) idxs_flattened = tf.range(0, tf.shape(probs)[0]) * tf.shape(probs)[1] + self._actions probs_vec = tf.gather(tf.reshape(probs, [-1]), idxs_flattened) log_lik = tf.log(probs_vec + 1e-8) act_op = probs[0, :] surr_loss = -tf.reduce_mean(log_lik * self._advantages, name="loss_op") grads_and_vars = self._opt.compute_gradients(surr_loss) train_op = self._opt.apply_gradients(grads_and_vars, name="train_op") self._act_op = act_op self._loss_op = surr_loss self._train_op = train_op def act(self, observation): # expect observation to be shape(1, self.observation_space) a = self._sess.run(self._act_op, feed_dict={self._observations: observation}) cs = np.cumsum(a) idx = sum(cs < np.random.rand(len(cs))) return idx def train(self, observations, actions, advantages): loss, _ = self._sess.run([self._loss_op, self._train_op], feed_dict={self._observations:observations, self._actions:actions, self._advantages:advantages}) return loss class PolicyOptimizer(object): def __init__(self, env, policy, baseline, n_iter, n_episode, path_length, gamma=.99): self.policy = policy self.baseline = baseline self.env = env self.n_iter = n_iter self.n_episode = n_episode self.path_length = path_length self.gamma = gamma def sample_path(self): obs = [] actions = [] rewards = [] ob = self.env.reset() for _ in range(self.path_length): a = self.policy.act(ob.reshape(1, -1)) next_ob, r, done, _ = self.env.step(a) obs.append(ob) actions.append(a) rewards.append(r) ob = next_ob if done: break return dict( observations=np.array(obs), actions=np.array(actions), rewards=np.array(rewards), returns=discount_cumsum(rewards, self.gamma) ) def process_paths(self, paths): maxlen = max(len(p['returns']) for p in paths) padded_returns = [np.concatenate([p['returns'], np.zeros(maxlen-len(p['returns']))]) for p in paths] # baseline for each timestep baselines = np.mean(padded_returns, axis=0) advantages = [p['returns'] - baselines[:len(p['returns'])] for p in paths] obs = np.concatenate([ p["observations"] for p in paths ]) actions = np.concatenate([ p["actions"] for p in paths ]) rewards = np.concatenate([ p["rewards"] for p in paths ]) advantages = np.concatenate([ a for a in advantages ]) return dict( observations=obs, actions=actions, rewards=rewards, advantages=advantages, ) def train(self): for i in range(1, self.n_iter+1): paths = [] for _ in range(self.n_episode): paths.append(self.sample_path()) data = self.process_paths(paths) loss = self.policy.train(data["observations"], data["actions"], data["advantages"]) avg_return = np.mean([sum(p["rewards"]) for p in paths]) print("Iteration {}: Loss = {}, Average Return = {}".format(i, loss, avg_return)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--n_iter', default=100, type=int, help='number of iterations') parser.add_argument('--n_episode', default=100, type=int, help='number of episodes/iteration') parser.add_argument('--path_length', default=200, type=int, help='number of steps') parser.add_argument('--learning_rate', default=0.01, help='learning rate for Adam Optimizer') parser.add_argument('--env', default='CartPole-v0', help='gym environment for training') parser.add_argument('--algorithm', default='VPG', help='algorithm identifier') parser.add_argument('--outdir', default='vpg', type=str, help='output directory where results are saved (/tmp/{outdir}-{env} )') parser.add_argument('--upload', action='store_true', help='upload results via OpenAI Gym API') parser.add_argument('--seed', default=0, type=int, help='random seed') args = parser.parse_args() np.random.seed(args.seed) tf.set_random_seed(args.seed) env = gym.make(args.env) outdir = '/tmp/' + args.outdir + '-' + args.env env.monitor.start(outdir, force=True) print("******* WILL SAVE RESULTS TO", outdir, " *******") sess = tf.Session() in_dim = flatten_space(env.observation_space) out_dim = flatten_space(env.action_space) hidden_dim = 8 opt = tf.train.AdamOptimizer(learning_rate=args.learning_rate) policy = CategoricalPolicy(in_dim, out_dim, hidden_dim, opt, sess) po = PolicyOptimizer(env, policy, 0, args.n_iter, args.n_episode, args.path_length) sess.run(tf.initialize_all_variables()) # train the policy optimizer po.train() sess.close() env.monitor.close() # make sure to setup your OPENAI_GYM_API_KEY environment variable if args.upload: gym.upload(outdir, algorithm_id=args.algorithm)
# Copyright 2012 Michael Still and Canonical Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import hashlib import os import time import mock from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_log import formatters from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils from six.moves import cStringIO from nova import conductor import nova.conf from nova import context from nova import objects from nova import test from nova.tests.unit import fake_instance from nova import utils from nova.virt.libvirt import imagecache from nova.virt.libvirt import utils as libvirt_utils CONF = nova.conf.CONF CONF.import_opt('host', 'nova.netconf') @contextlib.contextmanager def intercept_log_messages(): try: mylog = logging.getLogger('nova') stream = cStringIO() handler = logging.logging.StreamHandler(stream) handler.setFormatter(formatters.ContextFormatter()) mylog.logger.addHandler(handler) yield stream finally: mylog.logger.removeHandler(handler) class ImageCacheManagerTestCase(test.NoDBTestCase): def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = set(['instance-00000001', 'instance-00000002', 'instance-00000003', 'banana-42-hamster']) def test_read_stored_checksum_missing(self): self.stub_out('os.path.exists', lambda x: False) csum = imagecache.read_stored_checksum('/tmp/foo', timestamped=False) self.assertIsNone(csum) @mock.patch.object(os.path, 'exists', return_value=True) @mock.patch.object(time, 'time', return_value=2000000) @mock.patch.object(os.path, 'getmtime', return_value=1000000) def test_get_age_of_file(self, mock_getmtime, mock_time, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertTrue(exists) self.assertEqual(1000000, age) @mock.patch.object(os.path, 'exists', return_value=False) def test_get_age_of_file_not_exists(self, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertFalse(exists) self.assertEqual(0, age) def test_read_stored_checksum(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') csum_input = '{"sha1": "fdghkfhkgjjksfdgjksjkghsdf"}\n' fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) f = open(info_fname, 'w') f.write(csum_input) f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_input.rstrip(), '{"sha1": "%s"}' % csum_output) def test_read_stored_checksum_legacy_essex(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') old_fname = fname + '.sha1' f = open(old_fname, 'w') f.write('fdghkfhkgjjksfdgjksjkghsdf') f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_output, 'fdghkfhkgjjksfdgjksjkghsdf') self.assertFalse(os.path.exists(old_fname)) info_fname = imagecache.get_info_filename(fname) self.assertTrue(os.path.exists(info_fname)) def test_list_base_images(self): listing = ['00000001', 'ephemeral_0_20_None', '17d1b00b81642842e514494a78e804e9a511637c_5368709120.info', '00000004', 'swap_1000'] images = ['e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', 'e97222e91fc4241f49a7f520d1dcf446751129b3', '17d1b00b81642842e514494a78e804e9a511637c', '17d1b00b81642842e514494a78e804e9a511637c_5368709120', '17d1b00b81642842e514494a78e804e9a511637c_10737418240'] listing.extend(images) self.stub_out('os.listdir', lambda x: listing) self.stub_out('os.path.isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' self.flags(instances_path='/var/lib/nova/instances') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) sanitized = [] for ent in image_cache_manager.unexplained_images: sanitized.append(ent.replace(base_dir + '/', '')) self.assertEqual(sorted(sanitized), sorted(images)) expected = os.path.join(base_dir, 'e97222e91fc4241f49a7f520d1dcf446751129b3') self.assertIn(expected, image_cache_manager.unexplained_images) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertIn(expected, image_cache_manager.unexplained_images) unexpected = os.path.join(base_dir, '00000004') self.assertNotIn(unexpected, image_cache_manager.unexplained_images) for ent in image_cache_manager.unexplained_images: self.assertTrue(ent.startswith(base_dir)) self.assertEqual(len(image_cache_manager.originals), 2) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c') self.assertIn(expected, image_cache_manager.originals) unexpected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertNotIn(unexpected, image_cache_manager.originals) self.assertEqual(1, len(image_cache_manager.back_swap_images)) self.assertIn('swap_1000', image_cache_manager.back_swap_images) def test_list_backing_images_small(self): self.stub_out('os.listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stub_out('os.path.exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_resized(self): self.stub_out('os.listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stub_out('os.path.exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: ('e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240')) found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_instancename(self): self.stub_out('os.listdir', lambda x: ['_base', 'banana-42-hamster']) self.stub_out('os.path.exists', lambda x: x.find('banana-42-hamster') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_disk_notexist(self): self.stub_out('os.listdir', lambda x: ['_base', 'banana-42-hamster']) self.stub_out('os.path.exists', lambda x: x.find('banana-42-hamster') != -1) def fake_get_disk(disk_path): raise processutils.ProcessExecutionError() self.stubs.Set(libvirt_utils, 'get_disk_backing_file', fake_get_disk) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [] image_cache_manager.instance_names = self.stock_instance_names self.assertRaises(processutils.ProcessExecutionError, image_cache_manager._list_backing_images) def test_find_base_file_nothing(self): self.stub_out('os.path.exists', lambda x: False) base_dir = '/var/lib/nova/instances/_base' fingerprint = '549867354867' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) self.assertEqual(0, len(res)) def test_find_base_file_small(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' self.stub_out('os.path.exists', lambda x: x.endswith('%s_sm' % fingerprint)) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_sm') self.assertEqual(res, [(base_file, True, False)]) def test_find_base_file_resized(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stub_out('os.listdir', lambda x: listing) self.stub_out('os.path.exists', lambda x: x.endswith('%s_10737418240' % fingerprint)) self.stub_out('os.path.isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file, False, True)]) def test_find_base_file_all(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_sm', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stub_out('os.listdir', lambda x: listing) self.stub_out('os.path.exists', lambda x: True) self.stub_out('os.path.isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file1 = os.path.join(base_dir, fingerprint) base_file2 = os.path.join(base_dir, fingerprint + '_sm') base_file3 = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file1, False, False), (base_file2, True, False), (base_file3, False, True)]) @contextlib.contextmanager def _make_base_file(self, checksum=True, lock=True): """Make a base file for testing.""" with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') base_file = open(fname, 'w') base_file.write('data') base_file.close() if lock: lockdir = os.path.join(tmpdir, 'locks') lockname = os.path.join(lockdir, 'nova-aaa') os.mkdir(lockdir) lock_file = open(lockname, 'w') lock_file.write('data') lock_file.close() base_file = open(fname, 'r') if checksum: imagecache.write_stored_checksum(fname) base_file.close() yield fname def test_remove_base_file(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) lock_name = 'nova-' + os.path.split(fname)[-1] lock_dir = os.path.join(CONF.instances_path, 'locks') lock_file = os.path.join(lock_dir, lock_name) # Files are initially too new to delete self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) self.assertTrue(os.path.exists(lock_file)) # Old files get cleaned up though os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) self.assertFalse(os.path.exists(lock_file)) def test_remove_base_file_original(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.originals = [fname] image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) # Files are initially too new to delete self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) # This file should stay longer than a resized image os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) # Originals don't stay forever though os.utime(fname, (-1, time.time() - 3600 * 25)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) def test_remove_base_file_dne(self): # This test is solely to execute the "does not exist" code path. We # don't expect the method being tested to do anything in this case. with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) def test_remove_base_file_oserror(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') os.mkdir(fname) os.utime(fname, (-1, time.time() - 3601)) # This will raise an OSError because of file permissions image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertNotEqual(stream.getvalue().find('Failed to remove'), -1) def test_handle_base_image_unused(self): img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, [fname]) self.assertEqual(image_cache_manager.corrupt_base_files, []) @mock.patch.object(libvirt_utils, 'update_mtime') def test_handle_base_image_used(self, mock_mtime): img = '123' with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) mock_mtime.assert_called_once_with(fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) @mock.patch.object(libvirt_utils, 'update_mtime') def test_handle_base_image_used_remotely(self, mock_mtime): img = '123' with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (0, 1, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) mock_mtime.assert_called_once_with(fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_absent(self): img = '123' with intercept_log_messages() as stream: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, None) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) self.assertNotEqual(stream.getvalue().find('an absent base file'), -1) def test_handle_base_image_used_missing(self): img = '123' with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) @mock.patch.object(libvirt_utils, 'update_mtime') def test_handle_base_image_checksum_fails(self, mock_mtime): self.flags(checksum_base_images=True, group='libvirt') img = '123' with self._make_base_file() as fname: with open(fname, 'w') as f: f.write('banana') d = {'sha1': '21323454'} with open('%s.info' % fname, 'w') as f: f.write(jsonutils.dumps(d)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) mock_mtime.assert_called_once_with(fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, [fname]) @mock.patch.object(libvirt_utils, 'update_mtime') @mock.patch.object(lockutils, 'external_lock') def test_verify_base_images(self, mock_lock, mock_mtime): hashed_1 = '356a192b7913b04c54574d18c28d46e6395428ab' hashed_21 = '472b07b9fcf2c2451e8781e944bf5f77cd8457c8' hashed_22 = '12c6fc06c99a462375eeb3f43dfd832b08ca9e17' hashed_42 = '92cfceb39d57d914ed8b14d0e37643de0797ae56' self.flags(instances_path='/instance_path', image_cache_subdirectory_name='_base') base_file_list = ['00000001', 'ephemeral_0_20_None', 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', hashed_42, hashed_1, hashed_21, hashed_22, '%s_5368709120' % hashed_1, '%s_10737418240' % hashed_1, '00000004'] def fq_path(path): return os.path.join('/instance_path/_base/', path) # Fake base directory existence orig_exists = os.path.exists def exists(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_exists(path) if path in ['/instance_path', '/instance_path/_base', '/instance_path/instance-1/disk', '/instance_path/instance-2/disk', '/instance_path/instance-3/disk', '/instance_path/_base/%s.info' % hashed_42]: return True for p in base_file_list: if path == fq_path(p): return True if path == fq_path(p) + '.info': return False if path in ['/instance_path/_base/%s_sm' % i for i in [hashed_1, hashed_21, hashed_22, hashed_42]]: return False self.fail('Unexpected path existence check: %s' % path) self.stub_out('os.path.exists', lambda x: exists(x)) # Fake up some instances in the instances directory orig_listdir = os.listdir def listdir(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_listdir(path) if path == '/instance_path': return ['instance-1', 'instance-2', 'instance-3', '_base'] if path == '/instance_path/_base': return base_file_list self.fail('Unexpected directory listed: %s' % path) self.stub_out('os.listdir', lambda x: listdir(x)) # Fake isfile for these faked images in _base orig_isfile = os.path.isfile def isfile(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_isfile(path) for p in base_file_list: if path == fq_path(p): return True self.fail('Unexpected isfile call: %s' % path) self.stub_out('os.path.isfile', lambda x: isfile(x)) # Fake the database call which lists running instances instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'kernel_id': '21', 'ramdisk_id': '22', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [fake_instance.fake_instance_obj(None, **instance) for instance in instances] image_cache_manager = imagecache.ImageCacheManager() # Fake the utils call which finds the backing image def get_disk_backing_file(path): if path in ['/instance_path/instance-1/disk', '/instance_path/instance-2/disk']: return fq_path('%s_5368709120' % hashed_1) self.fail('Unexpected backing file lookup: %s' % path) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: get_disk_backing_file(x)) # Fake out verifying checksums, as that is tested elsewhere self.stubs.Set(image_cache_manager, '_verify_checksum', lambda x, y: True) # Fake getmtime as well orig_getmtime = os.path.getmtime def getmtime(path): if not path.startswith('/instance_path'): return orig_getmtime(path) return 1000000 self.stub_out('os.path.getmtime', lambda x: getmtime(x)) # Make sure we don't accidentally remove a real file orig_remove = os.remove def remove(path): if not path.startswith('/instance_path'): return orig_remove(path) # Don't try to remove fake files return self.stub_out('os.remove', lambda x: remove(x)) self.mox.StubOutWithMock(objects.block_device.BlockDeviceMappingList, 'bdms_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.bdms_by_instance_uuid( ctxt, ['123', '456']).AndReturn({}) self.mox.ReplayAll() # And finally we can make the call we're actually testing... # The argument here should be a context, but it is mocked out image_cache_manager.update(ctxt, all_instances) # Verify active = [fq_path(hashed_1), fq_path('%s_5368709120' % hashed_1), fq_path(hashed_21), fq_path(hashed_22)] for act in active: self.assertIn(act, image_cache_manager.active_base_files) self.assertEqual(len(image_cache_manager.active_base_files), len(active)) for rem in [fq_path('e97222e91fc4241f49a7f520d1dcf446751129b3_sm'), fq_path('e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm'), fq_path(hashed_42), fq_path('%s_10737418240' % hashed_1)]: self.assertIn(rem, image_cache_manager.removable_base_files) # Ensure there are no "corrupt" images as well self.assertEqual(len(image_cache_manager.corrupt_base_files), 0) def test_verify_base_images_no_base(self): self.flags(instances_path='/tmp/no/such/dir/name/please') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(None, []) def test_is_valid_info_file(self): hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' self.flags(instances_path='/tmp/no/such/dir/name/please') self.flags(image_info_filename_pattern=('$instances_path/_base/' '%(image)s.info'), group='libvirt') base_filename = os.path.join(CONF.instances_path, '_base', hashed) is_valid_info_file = imagecache.is_valid_info_file self.assertFalse(is_valid_info_file('banana')) self.assertFalse(is_valid_info_file( os.path.join(CONF.instances_path, '_base', '00000001'))) self.assertFalse(is_valid_info_file(base_filename)) self.assertFalse(is_valid_info_file(base_filename + '.sha1')) self.assertTrue(is_valid_info_file(base_filename + '.info')) def test_configured_checksum_path(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') # Ensure there is a base directory os.mkdir(os.path.join(tmpdir, '_base')) # Fake the database call which lists running instances instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [] for instance in instances: all_instances.append(fake_instance.fake_instance_obj( None, **instance)) def touch(filename): f = open(filename, 'w') f.write('Touched') f.close() old = time.time() - (25 * 3600) hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' base_filename = os.path.join(tmpdir, hashed) touch(base_filename) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) self.mox.StubOutWithMock( objects.block_device.BlockDeviceMappingList, 'bdms_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.bdms_by_instance_uuid( ctxt, ['123', '456']).AndReturn({}) self.mox.ReplayAll() image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(ctxt, all_instances) self.assertTrue(os.path.exists(base_filename)) self.assertTrue(os.path.exists(base_filename + '.info')) def test_run_image_cache_manager_pass(self): was = {'called': False} def fake_get_all_by_filters(context, *args, **kwargs): was['called'] = True instances = [] for x in range(2): instances.append(fake_instance.fake_db_instance( image_ref='1', uuid=x, name=x, vm_state='', task_state='')) return instances with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.stub_out('nova.db.instance_get_all_by_filters', fake_get_all_by_filters) compute = importutils.import_object(CONF.compute_manager) self.flags(use_local=True, group='conductor') compute.conductor_api = conductor.API() ctxt = context.get_admin_context() compute._run_image_cache_manager_pass(ctxt) self.assertTrue(was['called']) def test_store_swap_image(self): image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._store_swap_image('swap_') image_cache_manager._store_swap_image('swap_123') image_cache_manager._store_swap_image('swap_456') image_cache_manager._store_swap_image('swap_abc') image_cache_manager._store_swap_image('123_swap') image_cache_manager._store_swap_image('swap_129_') self.assertEqual(len(image_cache_manager.back_swap_images), 2) expect_set = set(['swap_123', 'swap_456']) self.assertEqual(image_cache_manager.back_swap_images, expect_set) @mock.patch.object(lockutils, 'external_lock') @mock.patch.object(libvirt_utils, 'update_mtime') @mock.patch('os.path.exists', return_value=True) @mock.patch('os.path.getmtime') @mock.patch('os.remove') def test_age_and_verify_swap_images(self, mock_remove, mock_getmtime, mock_exist, mock_mtime, mock_lock): image_cache_manager = imagecache.ImageCacheManager() expected_remove = set() expected_exist = set(['swap_128', 'swap_256']) image_cache_manager.back_swap_images.add('swap_128') image_cache_manager.back_swap_images.add('swap_256') image_cache_manager.used_swap_images.add('swap_128') def getmtime(path): return time.time() - 1000000 mock_getmtime.side_effect = getmtime def removefile(path): if not path.startswith('/tmp_age_test'): return os.remove(path) fn = os.path.split(path)[-1] expected_remove.add(fn) expected_exist.remove(fn) mock_remove.side_effect = removefile image_cache_manager._age_and_verify_swap_images(None, '/tmp_age_test') self.assertEqual(1, len(expected_exist)) self.assertEqual(1, len(expected_remove)) self.assertIn('swap_128', expected_exist) self.assertIn('swap_256', expected_remove) @mock.patch.object(utils, 'synchronized') @mock.patch.object(imagecache.ImageCacheManager, '_get_age_of_file', return_value=(True, 100)) def test_lock_acquired_on_removing_old_enough_files(self, mock_get_age, mock_synchronized): base_file = '/tmp_age_test' lock_path = os.path.join(CONF.instances_path, 'locks') lock_file = os.path.split(base_file)[-1] image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_old_enough_file( base_file, 60, remove_sig=False, remove_lock=False) mock_synchronized.assert_called_once_with(lock_file, external=True, lock_path=lock_path) class VerifyChecksumTestCase(test.NoDBTestCase): def setUp(self): super(VerifyChecksumTestCase, self).setUp() self.img = {'container_format': 'ami', 'id': '42'} self.flags(checksum_base_images=True, group='libvirt') def _make_checksum(self, tmpdir): testdata = ('OpenStack Software delivers a massively scalable cloud ' 'operating system.') fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) with open(fname, 'w') as f: f.write(testdata) return fname, info_fname, testdata def _write_file(self, info_fname, info_attr, testdata): f = open(info_fname, 'w') if info_attr == "csum valid": csum = hashlib.sha1() csum.update(testdata) f.write('{"sha1": "%s"}\n' % csum.hexdigest()) elif info_attr == "csum invalid, not json": f.write('banana') else: f.write('{"sha1": "banana"}') f.close() def _check_body(self, tmpdir, info_attr): self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) self._write_file(info_fname, info_attr, testdata) image_cache_manager = imagecache.ImageCacheManager() return image_cache_manager, fname def test_verify_checksum(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertTrue(res) def test_verify_checksum_disabled(self): self.flags(checksum_base_images=False, group='libvirt') with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertIsNone(res) def test_verify_checksum_invalid_json(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=False) self.assertFalse(res) log = stream.getvalue() # NOTE(mikal): this is a skip not a fail because the file is # present, but is not in valid JSON format and therefore is # skipped. self.assertNotEqual(log.find('image verification skipped'), -1) def test_verify_checksum_invalid_repaired(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=True) self.assertIsNone(res) def test_verify_checksum_invalid(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, valid json")) res = image_cache_manager._verify_checksum(self.img, fname) self.assertFalse(res) log = stream.getvalue() self.assertNotEqual(log.find('image verification failed'), -1) def test_verify_checksum_file_missing(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) image_cache_manager = imagecache.ImageCacheManager() res = image_cache_manager._verify_checksum('aaa', fname) self.assertIsNone(res) # Checksum requests for a file with no checksum now have the # side effect of creating the checksum self.assertTrue(os.path.exists(info_fname))
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import pkg_resources import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.logging_v2.types import logging_metrics from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-logging",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read", "https://www.googleapis.com/auth/logging.write", ) DEFAULT_HOST: str = "logging.googleapis.com" def __init__( self, *, host: str = DEFAULT_HOST, credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, **kwargs, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id ) # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access") ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.list_log_metrics: gapic_v1.method.wrap_method( self.list_log_metrics, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.InternalServerError, core_exceptions.ServiceUnavailable, ), deadline=60.0, ), default_timeout=60.0, client_info=client_info, ), self.get_log_metric: gapic_v1.method.wrap_method( self.get_log_metric, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.InternalServerError, core_exceptions.ServiceUnavailable, ), deadline=60.0, ), default_timeout=60.0, client_info=client_info, ), self.create_log_metric: gapic_v1.method.wrap_method( self.create_log_metric, default_timeout=60.0, client_info=client_info, ), self.update_log_metric: gapic_v1.method.wrap_method( self.update_log_metric, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.InternalServerError, core_exceptions.ServiceUnavailable, ), deadline=60.0, ), default_timeout=60.0, client_info=client_info, ), self.delete_log_metric: gapic_v1.method.wrap_method( self.delete_log_metric, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.InternalServerError, core_exceptions.ServiceUnavailable, ), deadline=60.0, ), default_timeout=60.0, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def list_log_metrics( self, ) -> Callable[ [logging_metrics.ListLogMetricsRequest], Union[ logging_metrics.ListLogMetricsResponse, Awaitable[logging_metrics.ListLogMetricsResponse], ], ]: raise NotImplementedError() @property def get_log_metric( self, ) -> Callable[ [logging_metrics.GetLogMetricRequest], Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], ]: raise NotImplementedError() @property def create_log_metric( self, ) -> Callable[ [logging_metrics.CreateLogMetricRequest], Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], ]: raise NotImplementedError() @property def update_log_metric( self, ) -> Callable[ [logging_metrics.UpdateLogMetricRequest], Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], ]: raise NotImplementedError() @property def delete_log_metric( self, ) -> Callable[ [logging_metrics.DeleteLogMetricRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() __all__ = ("MetricsServiceV2Transport",)
# Copyright (c) 2015 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. """ Mock unit tests for the NetApp driver protocols CIFS class module. """ import ddt import mock from oslo_log import log from manila import exception from manila.share.drivers.netapp.dataontap.protocols import cifs_cmode from manila import test from manila.tests.share.drivers.netapp.dataontap.client \ import fake_api as netapp_api from manila.tests.share.drivers.netapp.dataontap.protocols \ import fakes as fake @ddt.ddt class NetAppClusteredCIFSHelperTestCase(test.TestCase): def setUp(self): super(NetAppClusteredCIFSHelperTestCase, self).setUp() # Mock loggers as themselves to allow logger arg validation mock_logger = log.getLogger('mock_logger') self.mock_object(cifs_cmode.LOG, 'error', mock.Mock(side_effect=mock_logger.error)) self.mock_context = mock.Mock() # Inject fake netapp_lib module classes. netapp_api.mock_netapp_lib([cifs_cmode]) self.mock_client = mock.Mock() self.helper = cifs_cmode.NetAppCmodeCIFSHelper() self.helper.set_client(self.mock_client) def test_create_share(self): result = self.helper.create_share(fake.CIFS_SHARE, fake.SHARE_NAME, [fake.SHARE_ADDRESS_1]) expected = [r'\\%s\%s' % (fake.SHARE_ADDRESS_1, fake.SHARE_NAME)] self.assertEqual(expected, result) self.mock_client.create_cifs_share.assert_called_once_with( fake.SHARE_NAME) self.mock_client.remove_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, 'Everyone') def test_create_share_multiple(self): result = self.helper.create_share(fake.CIFS_SHARE, fake.SHARE_NAME, [fake.SHARE_ADDRESS_1, fake.SHARE_ADDRESS_2]) expected = [r'\\%s\%s' % (fake.SHARE_ADDRESS_1, fake.SHARE_NAME), r'\\%s\%s' % (fake.SHARE_ADDRESS_2, fake.SHARE_NAME)] self.assertEqual(expected, result) self.mock_client.create_cifs_share.assert_called_once_with( fake.SHARE_NAME) self.mock_client.remove_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, 'Everyone') def test_delete_share(self): self.helper.delete_share(fake.CIFS_SHARE, fake.SHARE_NAME) self.mock_client.remove_cifs_share.assert_called_once_with( fake.SHARE_NAME) def test_allow_access(self): self.helper.allow_access(self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) self.mock_client.add_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, fake.USER_ACCESS['access_to']) def test_allow_access_preexisting(self): self.mock_client.add_cifs_share_access.side_effect = ( netapp_api.NaApiError(code=netapp_api.EDUPLICATEENTRY)) self.assertRaises(exception.ShareAccessExists, self.helper.allow_access, self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) def test_allow_access_api_error(self): self.mock_client.add_cifs_share_access.side_effect = ( netapp_api.NaApiError()) self.assertRaises(netapp_api.NaApiError, self.helper.allow_access, self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) def test_allow_access_invalid_type(self): fake_access = fake.USER_ACCESS.copy() fake_access['access_type'] = 'group' self.assertRaises(exception.NetAppException, self.helper.allow_access, self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake_access) def test_deny_access(self): self.helper.deny_access(self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) self.mock_client.remove_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, fake.USER_ACCESS['access_to']) def test_deny_access_nonexistent_user(self): self.mock_client.remove_cifs_share_access.side_effect = ( netapp_api.NaApiError(code=netapp_api.EONTAPI_EINVAL)) self.helper.deny_access(self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) self.mock_client.remove_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, fake.USER_ACCESS['access_to']) self.assertEqual(1, cifs_cmode.LOG.error.call_count) def test_deny_access_nonexistent_rule(self): self.mock_client.remove_cifs_share_access.side_effect = ( netapp_api.NaApiError(code=netapp_api.EOBJECTNOTFOUND)) self.helper.deny_access(self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) self.mock_client.remove_cifs_share_access.assert_called_once_with( fake.SHARE_NAME, fake.USER_ACCESS['access_to']) self.assertEqual(1, cifs_cmode.LOG.error.call_count) def test_deny_access_api_error(self): self.mock_client.remove_cifs_share_access.side_effect = ( netapp_api.NaApiError()) self.assertRaises(netapp_api.NaApiError, self.helper.deny_access, self.mock_context, fake.CIFS_SHARE, fake.SHARE_NAME, fake.USER_ACCESS) def test_get_target(self): target = self.helper.get_target(fake.CIFS_SHARE) self.assertEqual(fake.SHARE_ADDRESS_1, target) def test_get_target_missing_location(self): target = self.helper.get_target({'export_location': ''}) self.assertEqual('', target) def test_get_share_name_for_share(self): share_name = self.helper.get_share_name_for_share(fake.CIFS_SHARE) self.assertEqual(fake.SHARE_NAME, share_name) @ddt.data( { 'location': r'\\%s\%s' % (fake.SHARE_ADDRESS_1, fake.SHARE_NAME), 'ip': fake.SHARE_ADDRESS_1, 'share_name': fake.SHARE_NAME, }, { 'location': r'//%s/%s' % (fake.SHARE_ADDRESS_1, fake.SHARE_NAME), 'ip': fake.SHARE_ADDRESS_1, 'share_name': fake.SHARE_NAME, }, {'location': '', 'ip': '', 'share_name': ''}, {'location': 'invalid', 'ip': '', 'share_name': ''}, ) @ddt.unpack def test_get_export_location(self, location, ip, share_name): share = fake.CIFS_SHARE.copy() share['export_location'] = location result_ip, result_share_name = self.helper._get_export_location(share) self.assertEqual(ip, result_ip) self.assertEqual(share_name, result_share_name)
#!/usr/bin/env python # Copyright 2017 Reuben Stump, Alex Mittell # 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. ''' ServiceNow Inventory Script ======================= Retrieve information about machines from a ServiceNow CMDB This script will attempt to read configuration from an INI file with the same base filename if present, or `now.ini` if not. It is possible to create symlinks to the inventory script to support multiple configurations, e.g.: * `now.py` (this script) * `now.ini` (default configuration, will be read by `now.py`) The path to an INI file may also be specified via the `NOW_INI` environment variable, in which case the filename matching rules above will not apply. Host and authentication parameters may be specified via the `SN_INSTANCE`, `SN_USERNAME` and `SN_PASSWORD` environment variables; these options will take precedence over options present in the INI file. An INI file is not required if these options are specified using environment variables. For additional usage details see: https://github.com/ServiceNowITOM/ansible-sn-inventory ''' import os import sys import requests import base64 import json import re from six.moves import configparser import time try: from cookielib import LWPCookieJar except ImportError: from http.cookiejar import LWPCookieJar class NowInventory(object): def __init__( self, hostname, username, password, table=None, fields=None, groups=None, selection=None, filter_results=None, proxy=None): self.hostname = hostname # requests session self.session = requests.Session() self.auth = requests.auth.HTTPBasicAuth(username, password) # request headers self.headers = { "Accept": "application/json", "Content-Type": "application/json", } # request cookies self.cookies = LWPCookieJar(os.getenv("HOME") + "/.sn_api_session") try: self.cookies.load(ignore_discard=True) except IOError: pass self.session.cookies = self.cookies if table is None: table = 'cmdb_ci_server' if fields is None: fields = [] if groups is None: groups = [] if selection is None: selection = [] if filter_results is None: filter_results = '' if proxy is None: proxy = [] # table self.table = table # extra fields (table columns) self.fields = fields # extra groups (table columns) self.groups = groups # selection order self.selection = selection # filter results (sysparm_query encoded query string) self.filter_results = filter_results # proxy settings self.proxy = proxy # initialize inventory self.inventory = {'_meta': {'hostvars': {}}} return def _put_cache(self, name, value): cache_dir = os.environ.get('SN_CACHE_DIR') if not cache_dir and config.has_option('defaults', 'cache_dir'): cache_dir = os.path.expanduser(config.get('defaults', 'cache_dir')) if cache_dir: cache_dir = os.path.join(os.path.dirname(__file__), cache_dir) if not os.path.exists(cache_dir): os.makedirs(cache_dir) cache_file = os.path.join(cache_dir, name) with open(cache_file, 'w') as cache: json.dump(value, cache, indent=0, separators=(',', ': '), sort_keys=True) def _get_cache(self, name, default=None): cache_dir = os.environ.get('SN_CACHE_DIR') if not cache_dir and config.has_option('defaults', 'cache_dir'): cache_dir = os.path.expanduser(config.get('defaults', 'cache_dir')) if cache_dir: cache_dir = os.path.join(os.path.dirname(__file__), cache_dir) cache_file = os.path.join(cache_dir, name) if os.path.exists(cache_file): cache_max_age = os.environ.get('SN_CACHE_MAX_AGE') if not cache_max_age: if config.has_option('defaults', 'cache_max_age'): cache_max_age = config.getint('defaults', 'cache_max_age') else: cache_max_age = 0 cache_stat = os.stat(cache_file) if (cache_stat.st_mtime + int(cache_max_age)) >= time.time(): with open(cache_file) as cache: return json.load(cache) return default def __del__(self): self.cookies.save(ignore_discard=True) def _invoke(self, verb, path, data): cache_name = '__snow_inventory__' inventory = self._get_cache(cache_name, None) if inventory is not None: return inventory # build url url = "https://%s/%s" % (self.hostname, path) results = [] while url: # perform REST operation, accumulating page results response = self.session.get( url, auth=self.auth, headers=self.headers, proxies={ 'http': self.proxy, 'https': self.proxy}) if response.status_code != 200: print >> sys.stderr, "http error (%s): %s" % (response.status_code, response.text) results += response.json()['result'] next_link = response.links.get('next', {}) url = next_link.get('url', None) result = { 'result': results } self._put_cache(cache_name, result) return result def add_group(self, target, group): ''' Transform group names: 1. lower() 2. non-alphanumerical characters to '_' ''' # Ignore empty group names if group == '' or group is None: return group = group.lower() group = re.sub(r'[^a-zA-Z0-9_]', '_', group) self.inventory.setdefault(group, {'hosts': []}) self.inventory[group]['hosts'].append(target) return def add_var(self, target, key, val): if target not in self.inventory['_meta']['hostvars']: self.inventory['_meta']['hostvars'][target] = {} self.inventory['_meta']['hostvars'][target]["sn_" + key] = val return def generate(self): base_fields = [ u'name', u'host_name', u'fqdn', u'ip_address', u'sys_class_name' ] base_groups = [u'sys_class_name'] options = "?sysparm_exclude_reference_link=true&sysparm_display_value=true" columns = list( set(base_fields + base_groups + self.fields + self.groups)) path = '/api/now/table/' + self.table + options + \ "&sysparm_fields=" + ','.join(columns) + \ "&sysparm_query=" + self.filter_results # Default, mandatory group 'sys_class_name' groups = list(set(base_groups + self.groups)) content = self._invoke('GET', path, None) for record in content['result']: ''' Ansible host target selection order: 1. ip_address 2. fqdn 3. host_name ''' target = None selection = self.selection if not selection: selection = ['host_name', 'fqdn', 'ip_address'] for k in selection: if k in record: if record[k] != '': target = record[k] # Skip if no target available if target is None: continue # hostvars for k in record.keys(): self.add_var(target, k, record[k]) # groups for k in groups: if k == "sys_tags" and record[k] != None: for y in [x.strip() for x in record[k].split(',')]: self.add_group(target, y) else: self.add_group(target, record[k]) return def json(self): return json.dumps(self.inventory) def main(args): # instance = os.environ['SN_INSTANCE'] # username = os.environ['SN_USERNAME'] # password = os.environ['SN_PASSWORD'] global config config = configparser.ConfigParser() if os.environ.get('NOW_INI', ''): config_files = [os.environ['NOW_INI']] else: config_files = [ os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'now.ini' ] for config_file in config_files: if os.path.exists(config_file): config.read(config_file) break # Read authentication information from environment variables (if set), # otherwise from INI file. instance = os.environ.get('SN_INSTANCE') if not instance and config.has_option('auth', 'instance'): instance = config.get('auth', 'instance') username = os.environ.get('SN_USERNAME') if not username and config.has_option('auth', 'user'): username = config.get('auth', 'user') password = os.environ.get('SN_PASSWORD') if not password and config.has_option('auth', 'password'): password = config.get('auth', 'password') # SN_TABLE table = os.environ.get('SN_TABLE') if not table and config.has_option('config', 'table'): table = config.get('config', 'table') # SN_SEL_ORDER selection = os.environ.get("SN_SEL_ORDER", []) if not selection and config.has_option('config', 'selection_order'): selection = config.get('config', 'selection_order') selection = selection.encode('utf-8').replace('\n', '\n\t') if isinstance(selection, str): selection = selection.split(',') # SN_GROUPS groups = os.environ.get("SN_GROUPS", []) if not groups and config.has_option('config', 'groups'): groups = config.get('config', 'groups') groups = groups.encode('utf-8').replace('\n', '\n\t') if isinstance(groups, str): groups = groups.split(',') # SN_FIELDS fields = os.environ.get("SN_FIELDS", []) if not fields and config.has_option('config', 'fields'): fields = config.get('config', 'fields') fields = fields.encode('utf-8').replace('\n', '\n\t') if isinstance(fields, str): fields = fields.split(',') # SN_FILTER_RESULTS filter_results = os.environ.get('SN_FILTER_RESULTS') if not filter_results and config.has_option('config', 'filter_results'): filter_results = config.get('config', 'filter_results') # SN_PROXY proxy = os.environ.get('SN_PROXY') if not proxy and config.has_option('config', 'proxy'): proxy = config.get('config', 'proxy') inventory = NowInventory( hostname=instance, username=username, password=password, table=table, fields=fields, groups=groups, selection=selection, filter_results=filter_results, proxy=proxy) inventory.generate() print(inventory.json()) if __name__ == "__main__": main(sys.argv)
# Copyright 2018 Google LLC. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Utility functions for working with sharded files. A sharded file is a single conceptual file that is broken into a collection of files to make parallelization easier. A sharded file spec is like a filename for a sharded file; the file spec "/some/path/prefix@200.txt" says that the sharded file consists of 200 actual files that have names like "/some/path/prefix-00000-of-00200.txt", "/some/path/prefix-00001-of-00200.txt", etc. This module contains functions for parsing, generating, detecting and resolving sharded file specs. """ # Important: Please keep this module free of TensorFlow c++ extensions. # This makes it easy to build pure python packages for training that work with # CMLE. from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import re import six from tensorflow.python.platform import gfile SHARD_SPEC_PATTERN = re.compile(R'((.*)\@(\d*[1-9]\d*)(?:\.(.+))?)') class ShardError(Exception): """An I/O error.""" def parse_sharded_file_spec(spec): """Parse a sharded file specification. Args: spec: str. The sharded file specification. A sharded file spec is one like 'gs://some/file@200.txt'. Here, '@200' specifies the number of shards. Returns: basename: str. The basename for the files. num_shards: int >= 0. The number of shards. suffix: str. The suffix if there is one, or '' if not. Raises: ShardError: If the spec is not a valid sharded specification. """ m = SHARD_SPEC_PATTERN.match(spec) if not m: raise ShardError(('The file specification {0} is not a sharded file ' 'specification because it did not match the regex ' '{1}').format(spec, SHARD_SPEC_PATTERN.pattern)) # If there's a non-empty suffix, we need to prepend '.' so we get files like # foo@20.ext instead of foo@ext. The original C++ parser version has: # string ext = StrCat(suff.empty() ? "" : ".", suff); suffix = '.' + m.group(4) if m.group(4) else '' return m.group(2), int(m.group(3)), suffix def _shard_width(num_shards): """Return the width of the shard matcher based on the number of shards.""" return max(5, int(math.floor(math.log10(num_shards)) + 1)) def generate_sharded_filenames(spec): """Generate the list of filenames corresponding to the sharding path. Args: spec: str. Represents a filename with a sharding specification. e.g., 'gs://some/file@200.txt' represents a file sharded 200 ways. Returns: List of filenames. Raises: ShardError: If spec is not a valid sharded file specification. """ basename, num_shards, suffix = parse_sharded_file_spec(spec) files = [] width = _shard_width(num_shards) format_str = '{{0}}-{{1:0{0}}}-of-{{2:0{0}}}{{3}}'.format(width) for i in range(num_shards): files.append(format_str.format(basename, i, num_shards, suffix)) return files def glob_list_sharded_file_patterns(comma_separated_patterns, sep=','): """Generate list of filenames corresponding to `comma_separated_patterns`. Args: comma_separated_patterns: str. A pattern or a comma-separated list of patterns that represent file names. sep: char. Separator character. Returns: List of filenames, sorted and dedupped. """ return sorted(set([ f for pattern in comma_separated_patterns.split(sep) for f in gfile.Glob(normalize_to_sharded_file_pattern(pattern)) ])) def generate_sharded_file_pattern(basename, num_shards, suffix): """Generate a sharded file pattern. Args: basename: str. The basename for the files. num_shards: int. The number of shards. suffix: str. The suffix if there is one or ''. Returns: pattern: """ width = _shard_width(num_shards) specifier = '?' * width format_str = '{{0}}-{{1}}-of-{{2:0{0}}}{{3}}'.format(width) return format_str.format(basename, specifier, num_shards, suffix) def normalize_to_sharded_file_pattern(spec_or_pattern): """Take a sharding spec or sharding file pattern and return a sharded pattern. The input can be a sharding spec(e.g '/some/file@10') or a sharded file pattern (e.g. '/some/file-?????-of-00010) Args: spec_or_pattern: str. A sharded file specification or sharded file pattern. Returns: A sharded file pattern. """ try: basename, num_shards, suffix = parse_sharded_file_spec(spec_or_pattern) except ShardError: return spec_or_pattern return generate_sharded_file_pattern(basename, num_shards, suffix) def is_sharded_file_spec(spec): """Returns True if spec is a sharded file specification.""" m = SHARD_SPEC_PATTERN.match(spec) return m is not None # redacted def sharded_filename(spec, i): """Gets a path appropriate for writing the ith file of a sharded spec.""" return generate_sharded_filenames(spec)[i] # redacted # readability when there are multiple input filespecs. def resolve_filespecs(shard, *filespecs): """Transforms potentially sharded filespecs into their paths for single shard. This function takes a shard number and a varargs of potentially-sharded filespecs, and returns a list where the filespecs have been resolved into concrete file paths for a single shard. This function has a concept of a master filespec, which is used to constrain and check the validity of other filespecs. The first filespec is considered the master, and it cannot be None. For example, if master is not sharded, none of the other specs can be sharded, and vice versa. They must all also have a consistent sharding (e.g., master is @10, then all others must be @10). Note that filespecs (except the master) may be None or any other False value, which are returned as-is in the output list. Args: shard: int >= 0. Our shard number. *filespecs: list[str]. Contains all of the filespecs we want to resolve into shard-specific file paths. Returns: A list. The first element is the number of shards, which is an int >= 1 when filespecs contains sharded paths and 0 if none do. All subsequent returned values follow the shard-specific paths for each filespec, in order. Raises: ValueError: if any filespecs are inconsistent. """ if not filespecs: raise ValueError('filespecs must have at least one element.') master = filespecs[0] master_is_sharded = is_sharded_file_spec(master) master_num_shards = 0 if master_is_sharded: _, master_num_shards, _ = parse_sharded_file_spec(master) if shard >= master_num_shards or shard < 0: raise ValueError('Invalid shard={} value with master={} sharding'.format( shard, master)) elif shard > 0: raise ValueError('Output is not sharded but shard > 0: {}'.format(shard)) def resolve_one(filespec): """Resolves a single filespec into a concrete filepath.""" if not filespec: return filespec is_sharded = is_sharded_file_spec(filespec) if master_is_sharded != is_sharded: raise ValueError('Master={} and {} have inconsistent sharding'.format( master, filespec)) if not is_sharded: # Not sharded => filespec is the actual filename. return filespec _, filespec_num_shards, _ = parse_sharded_file_spec(filespec) if filespec_num_shards != master_num_shards: raise ValueError('Master={} and {} have inconsistent sharding'.format( master, filespec)) return sharded_filename(filespec, shard) return [master_num_shards] + [resolve_one(spec) for spec in filespecs] def maybe_generate_sharded_filenames(filespec): """Potentially expands sharded filespec into a list of paths. This function takes in a potentially sharded filespec and expands it into a list containing the full set of corresponding concrete sharded file paths. If the input filespec is not sharded then a list containing just that file path is returned. This function is useful, for example, when the input to a binary can either be sharded or not. Args: filespec: String. A potentially sharded filespec to expand. Returns: A list of file paths. Raises: TypeError: if filespec is not in valid string_types. """ if not isinstance(filespec, six.string_types): raise TypeError('Invalid filespec: %s' % filespec) if is_sharded_file_spec(filespec): return generate_sharded_filenames(filespec) else: return [filespec]
from __future__ import division import sys import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from scipy.ndimage.filters import maximum_filter from scipy.ndimage.morphology import (generate_binary_structure, iterate_structure, binary_erosion) import hashlib from operator import itemgetter IDX_FREQ_I = 0 IDX_TIME_J = 1 ###################################################################### # Sampling rate, related to the Nyquist conditions, which affects # the range frequencies we can detect. DEFAULT_FS = 44100 ###################################################################### # Size of the FFT window, affects frequency granularity DEFAULT_WINDOW_SIZE = 4096 ###################################################################### # Ratio by which each sequential window overlaps the last and the # next window. Higher overlap will allow a higher granularity of offset # matching, but potentially more fingerprints. DEFAULT_OVERLAP_RATIO = 0.5 ###################################################################### # Degree to which a fingerprint can be paired with its neighbors -- # higher will cause more fingerprints, but potentially better accuracy. DEFAULT_FAN_VALUE = 20 ###################################################################### # Minimum amplitude in spectrogram in order to be considered a peak. # This can be raised to reduce number of fingerprints, but can negatively # affect accuracy. DEFAULT_AMP_MIN = 25 ###################################################################### # This is the minimum number of maxima to find whether a file is a noise or not LOCAL_MAXIMA_THRESHOLD= 7.0 ###################################################################### # Number of cells around an amplitude peak in the spectrogram in order # for Dejavu to consider it a spectral peak. Higher values mean less # fingerprints and faster matching, but can potentially affect accuracy. PEAK_NEIGHBORHOOD_SIZE = 20 ###################################################################### # Thresholds on how close or far fingerprints can be in time in order # to be paired as a fingerprint. If your max is too low, higher values of # DEFAULT_FAN_VALUE may not perform as expected. MIN_HASH_TIME_DELTA = 0 MAX_HASH_TIME_DELTA = 200 ###################################################################### # If True, will sort peaks temporally for fingerprinting; # not sorting will cut down number of fingerprints, but potentially # affect performance. PEAK_SORT = True ###################################################################### # Number of bits to throw away from the front of the SHA1 hash in the # fingerprint calculation. The more you throw away, the less storage, but # potentially higher collisions and misclassifications when identifying songs. FINGERPRINT_REDUCTION = 20 # refactor to improve the plot # based on https://github.com/oneyoung/dejavu/commit/ce082056954b0ac81fa37a9de58af8a9aad303fb def fingerprint(channel_samples, Fs=DEFAULT_FS, wsize=DEFAULT_WINDOW_SIZE, wratio=DEFAULT_OVERLAP_RATIO, fan_value=DEFAULT_FAN_VALUE, amp_min=DEFAULT_AMP_MIN, plot=False, local_maxima_threshold = LOCAL_MAXIMA_THRESHOLD): """ FFT the channel, log transform output, find local maxima, then return locally sensitive hashes. """ # FFT the signal and extract frequency components # http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.specgram # return of specgram is (spectrum, freqs, t) print 'new fingerprint' print Fs print 'channel samples' print len(channel_samples) arr2D, freqs, times = mlab.specgram( channel_samples, NFFT=wsize, Fs=Fs, window=mlab.window_hanning, noverlap=int(wsize * wratio)) print 'freq' print freqs # apply log transform since specgram() returns linear array arr2D = 10 * np.log10(arr2D) arr2D[arr2D == -np.inf] = 0 # replace infs with zeros # find local maxima local_maxima = get_2D_peaks(arr2D, plot=plot, amp_min=amp_min, freqs=freqs, times=times) print "local maxima" print local_maxima print len(local_maxima) minimun_local_maxima = (len(channel_samples)/Fs) * local_maxima_threshold print 'minimunm local maxima' print minimun_local_maxima if (len(local_maxima) <= minimun_local_maxima ): raise ValueError('File contains no signal') # sys.exit() # return hashes return generate_hashes(local_maxima, fan_value=fan_value) def get_2D_peaks(arr2D, plot=False, amp_min=DEFAULT_AMP_MIN, freqs=None, times=None): # http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.morphology.iterate_structure.html#scipy.ndimage.morphology.iterate_structure struct = generate_binary_structure(2, 1) neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE) # find local maxima using our fliter shape local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D background = (arr2D == 0) eroded_background = binary_erosion(background, structure=neighborhood, border_value=1) # Boolean mask of arr2D with True at peaks detected_peaks = local_max - eroded_background # extract peaks amps = arr2D[detected_peaks] j, i = np.where(detected_peaks) # filter peaks amps = amps.flatten() peaks = zip(i, j, amps) peaks_filtered = [x for x in peaks if x[2] > amp_min] # freq, time, amp # get indices for frequency and time frequency_idx = [x[1] for x in peaks_filtered] time_idx = [x[0] for x in peaks_filtered] if plot: # scatter of the peaks fig, ax = plt.subplots() ax.set_autoscalex_on(True) # 1. need to set 'origin', otherwise, image is upside-down # 2. in order to fit image to screen, set 'extent' and 'aspect' ax.imshow(arr2D, origin='lower', extent=[times[0], times[-1], freqs[0], freqs[-1]], interpolation='nearest', aspect='auto') # mapping to right value, instead of just index ax.scatter(times.take(time_idx), freqs.take(frequency_idx)) ax.set_xlabel('Time') ax.set_ylabel('Frequency') ax.set_title("Spectrogram") plt.show() return zip(frequency_idx, time_idx) def generate_hashes(peaks, fan_value=DEFAULT_FAN_VALUE): """ Hash list structure: sha1_hash[0:20] time_offset [(e05b341a9b77a51fd26, 32), ... ] """ # time is 0 index # freq is 1 index # print 'peaks' # print peaks # # print peaks # sys.exit() # peaks = [(1,2),(1,6),(1,3),(2,1),(2,3),(7,1)] if PEAK_SORT: peaks.sort(key=itemgetter(1)) # sys.exit() # print 'sort' for i in range(len(peaks)): for j in range(1, fan_value): if (i + j) < len(peaks): #[(t1,f1),(t2,f2)] freq1 = peaks[i][IDX_FREQ_I] # print freq1 freq2 = peaks[i + j][IDX_FREQ_I] # print freq2 t1 = peaks[i][IDX_TIME_J] t2 = peaks[i + j][IDX_TIME_J] t_delta = t2 - t1 # print t_delta # print t1 # sys.exit() if t_delta >= MIN_HASH_TIME_DELTA and t_delta <= MAX_HASH_TIME_DELTA: h = hashlib.sha1( "%s|%s|%s" % (str(freq1), str(freq2), str(t_delta))) yield (h.hexdigest()[0:FINGERPRINT_REDUCTION], t1)
import unittest import reactivex from reactivex.testing import MockDisposable, ReactiveTest, TestScheduler on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class RxException(Exception): pass # Helper function for raising exceptions within lambdas def _raise(ex): raise RxException(ex) class TestUsing(unittest.TestCase): def test_using_null(self): disp = [None] xs = [None] _d = [None] scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] def create(): def create_resources(): dispose_invoked[0] += 1 disp[0] = None return disp[0] def create_observable(d): _d[0] = d create_invoked[0] += 1 xs[0] = scheduler.create_cold_observable( on_next(100, scheduler.clock), on_completed(200) ) return xs[0] return reactivex.using(create_resources, create_observable) results = scheduler.start(create) assert disp[0] == _d[0] assert results.messages == [on_next(300, 200), on_completed(400)] assert 1 == create_invoked[0] assert 1 == dispose_invoked[0] assert xs[0].subscriptions == [subscribe(200, 400)] assert disp[0] is None def test_using_complete(self): disp = [None] xs = [None] _d = [None] scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] def create(): def create_resource(): dispose_invoked[0] += 1 disp[0] = MockDisposable(scheduler) return disp[0] def create_observable(d): _d[0] = d create_invoked[0] += 1 xs[0] = scheduler.create_cold_observable( on_next(100, scheduler.clock), on_completed(200) ) return xs[0] return reactivex.using(create_resource, create_observable) results = scheduler.start(create) assert disp == _d assert results.messages == [on_next(300, 200), on_completed(400)] assert create_invoked[0] == 1 assert dispose_invoked[0] == 1 assert xs[0].subscriptions == [subscribe(200, 400)] disp[0].disposes = [200, 400] def test_using_error(self): scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] ex = "ex" disp = [None] xs = [None] _d = [None] def create(): def create_resource(): dispose_invoked[0] += 1 disp[0] = MockDisposable(scheduler) return disp[0] def create_observable(d): _d[0] = d create_invoked[0] += 1 xs[0] = scheduler.create_cold_observable( on_next(100, scheduler.clock), on_error(200, ex) ) return xs[0] return reactivex.using(create_resource, create_observable) results = scheduler.start(create) assert disp[0] == _d[0] assert results.messages == [on_next(300, 200), on_error(400, ex)] assert create_invoked[0] == 1 assert dispose_invoked[0] == 1 assert xs[0].subscriptions == [subscribe(200, 400)] assert disp[0].disposes == [200, 400] def test_using_dispose(self): disp = [None] xs = [None] _d = [None] scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] def create(): def create_resource(): dispose_invoked[0] += 1 disp[0] = MockDisposable(scheduler) return disp[0] def create_observable(d): _d[0] = d create_invoked[0] += 1 xs[0] = scheduler.create_cold_observable( on_next(100, scheduler.clock), on_next(1000, scheduler.clock + 1) ) return xs[0] return reactivex.using(create_resource, create_observable) results = scheduler.start(create) assert disp[0] == _d[0] assert results.messages == [on_next(300, 200)] assert 1 == create_invoked[0] assert 1 == dispose_invoked[0] assert xs[0].subscriptions == [subscribe(200, 1000)] assert disp[0].disposes == [200, 1000] def test_using_throw_resource_mapper(self): scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] ex = "ex" def create(): def create_resource(): dispose_invoked[0] += 1 raise _raise(ex) def create_observable(d): create_invoked[0] += 1 return reactivex.never() return reactivex.using(create_resource, create_observable) results = scheduler.start(create) assert results.messages == [on_error(200, ex)] assert 0 == create_invoked[0] assert 1 == dispose_invoked[0] def test_using_throw_resource_usage(self): scheduler = TestScheduler() dispose_invoked = [0] create_invoked = [0] disp = [None] ex = "ex" def create(): def create_resource(): dispose_invoked[0] += 1 disp[0] = MockDisposable(scheduler) return disp[0] def create_observable(d): create_invoked[0] += 1 _raise(ex) return reactivex.using(create_resource, create_observable) results = scheduler.start(create) assert results.messages == [on_error(200, ex)] assert create_invoked[0] == 1 assert dispose_invoked[0] == 1 assert disp[0].disposes == [200, 200]
#!/usr/bin/env python """Search for certain files, filter them by given criteria and do something.""" import stat from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib import utils from grr.proto import flows_pb2 class FileFinderModificationTimeFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderModificationTimeFilter class FileFinderAccessTimeFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderAccessTimeFilter class FileFinderInodeChangeTimeFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderInodeChangeTimeFilter class FileFinderSizeFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderSizeFilter class FileFinderContentsRegexMatchFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderContentsRegexMatchFilter class FileFinderContentsLiteralMatchFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderContentsLiteralMatchFilter class FileFinderFilter(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderFilter class FileFinderDownloadActionOptions(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderDownloadActionOptions class FileFinderAction(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderAction class FileFinderArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderArgs class FileFinderResult(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.FileFinderResult class FileFinder(flow.GRRFlow): """This flow looks for files matching given criteria and acts on them. """ friendly_name = "File Finder" category = "/Filesystem/" args_type = FileFinderArgs # TODO(user): move to BASIC as soon as this flow is properly # tested and benchmarked. Remove Fetch Files and Find Files at the # same moment. behaviours = flow.GRRFlow.behaviours + "ADVANCED" @classmethod def GetDefaultArgs(cls, token=None): _ = token return cls.args_type(paths=[r"c:\windows\system32\notepad.*"]) def Initialize(self): super(FileFinder, self).Initialize() type_enum = rdfvalue.FileFinderFilter.Type # For every filter type we specify a tuple (handle, weight). # Filters will be sorted by weight, so that the ones with the minimal # weight will be executed earlier. self.filter_handlers = { type_enum.MODIFICATION_TIME: (self.ModificationTimeFilter, 0), type_enum.ACCESS_TIME: (self.AccessTimeFilter, 0), type_enum.INODE_CHANGE_TIME: (self.InodeChangeTimeFilter, 0), type_enum.SIZE: (self.SizeFilter, 0), type_enum.CONTENTS_REGEX_MATCH: (self.ContentsRegexMatchFilter, 1), type_enum.CONTENTS_LITERAL_MATCH: (self.ContentsLiteralMatchFilter, 1) } def _FilterWeight(self, filter_options): _, filter_weight = self.filter_handlers[filter_options.filter_type] return filter_weight @flow.StateHandler(next_state=["ProcessFilters"]) def Start(self): """Issue the find request.""" self.state.Register("files_to_fetch", []) self.state.Register("files_found", 0) self.state.Register("sorted_filters", sorted(self.args.filters, key=self._FilterWeight)) if self.args.pathtype == rdfvalue.PathSpec.PathType.MEMORY: # We construct StatEntries ourselves and there's no way they can # pass the file type check. self.args.no_file_type_check = True # If pathtype is MEMORY, we're treating provided paths not as globs, # but as paths to memory devices. memory_devices = [] for path in self.args.paths: pathspec = rdfvalue.PathSpec( path=utils.SmartUnicode(path), pathtype=rdfvalue.PathSpec.PathType.MEMORY) aff4path = aff4.AFF4Object.VFSGRRClient.PathspecToURN( pathspec, self.client_id) stat_entry = rdfvalue.StatEntry(aff4path=aff4path, pathspec=pathspec) memory_devices.append(stat_entry) self.CallStateInline(messages=memory_devices, next_state="ProcessFilters") else: self.CallFlow("Glob", next_state="ProcessFilters", paths=self.args.paths, pathtype=self.args.pathtype) @flow.StateHandler(next_state=["ApplyFilter"]) def ProcessFilters(self, responses): """Iterate through glob responses, and filter each hit.""" if not responses.success: # Glob failing is fatal here. return self.Error("Failed Glob: %s", responses.status) results = [] for response in responses: # Only process regular files. if self.args.no_file_type_check or stat.S_ISREG(response.st_mode): results.append(rdfvalue.FileFinderResult(stat_entry=response)) self.CallStateInline(messages=results, next_state="ApplyFilter", request_data=dict(filter_index=0)) def ModificationTimeFilter(self, responses, filter_options, filter_index): """Applies modification time filter to responses.""" results = [] for response in responses: settings = filter_options.modification_time if (settings.min_last_modified_time.AsSecondsFromEpoch() <= response.stat_entry.st_mtime <= settings.max_last_modified_time.AsSecondsFromEpoch()): results.append(response) self.CallStateInline(messages=results, next_state="ApplyFilter", request_data=dict(filter_index=filter_index + 1)) def AccessTimeFilter(self, responses, filter_options, filter_index): """Applies access time filter to responses.""" results = [] for response in responses: settings = filter_options.access_time if (settings.min_last_access_time.AsSecondsFromEpoch() <= response.stat_entry.st_atime <= settings.max_last_access_time.AsSecondsFromEpoch()): results.append(response) self.CallStateInline(messages=results, next_state="ApplyFilter", request_data=dict(filter_index=filter_index + 1)) def InodeChangeTimeFilter(self, responses, filter_options, filter_index): """Applies inode change time filter to responses.""" results = [] for response in responses: settings = filter_options.inode_change_time if (settings.min_last_inode_change_time.AsSecondsFromEpoch() <= response.stat_entry.st_ctime <= settings.max_last_inode_change_time.AsSecondsFromEpoch()): results.append(response) self.CallStateInline(messages=results, next_state="ApplyFilter", request_data=dict(filter_index=filter_index + 1)) def SizeFilter(self, responses, filter_options, filter_index): """Applies size filter to responses.""" results = [] for response in responses: if (filter_options.size.min_file_size <= response.stat_entry.st_size <= filter_options.size.max_file_size): results.append(response) self.CallStateInline(messages=results, next_state="ApplyFilter", request_data=dict(filter_index=filter_index + 1)) def ContentsRegexMatchFilter(self, responses, filter_options, filter_index): """Applies contents regex filter to responses.""" options = filter_options.contents_regex_match for response in responses: grep_spec = rdfvalue.GrepSpec( target=response.stat_entry.pathspec, regex=options.regex, mode=options.mode, start_offset=options.start_offset, length=options.length, bytes_before=options.bytes_before, bytes_after=options.bytes_after) self.CallClient( "Grep", request=grep_spec, next_state="ApplyFilter", request_data=dict( original_result=response, filter_index=filter_index + 1)) def ContentsLiteralMatchFilter(self, responses, filter_options, filter_index): """Applies literal match filter to responses.""" options = filter_options.contents_literal_match for response in responses: grep_spec = rdfvalue.GrepSpec( target=response.stat_entry.pathspec, literal=options.literal, mode=options.mode, start_offset=options.start_offset, length=options.length, bytes_before=options.bytes_before, bytes_after=options.bytes_after, xor_in_key=options.xor_in_key, xor_out_key=options.xor_out_key) self.CallClient( "Grep", request=grep_spec, next_state="ApplyFilter", request_data=dict( original_result=response, filter_index=filter_index + 1)) @flow.StateHandler(next_state=["ProcessAction", "ApplyFilter"]) def ApplyFilter(self, responses): """Applies next filter to responses or calls ProcessAction.""" # We filtered out everything, no need to continue if not responses: return messages = [] for response in responses: if isinstance(response, rdfvalue.BufferReference): if "original_result" not in responses.request_data: raise RuntimeError("Got a buffer reference, but original result " "is missing") if not messages: messages.append(responses.request_data["original_result"]) messages[0].matches.append(response) else: messages.append(response) filter_index = responses.request_data["filter_index"] if filter_index >= len(self.state.sorted_filters): self.CallStateInline(messages=messages, next_state="ProcessAction") else: filter_options = self.state.sorted_filters[filter_index] filter_handler, _ = self.filter_handlers[filter_options.filter_type] filter_handler(messages, filter_options, filter_index) @flow.StateHandler(next_state=["Done"]) def ProcessAction(self, responses): """Applies action specified by user to responses.""" self.state.files_found += len(responses) for response in responses: self.SendReply(response) action = self.state.args.action.action_type if action == rdfvalue.FileFinderAction.Action.DO_NOTHING: self.DoNothingAction(responses) elif action == rdfvalue.FileFinderAction.Action.HASH: self.HashAction(responses) elif action == rdfvalue.FileFinderAction.Action.DOWNLOAD: self.DownloadAction(responses) def DoNothingAction(self, responses): pass def HashAction(self, responses): """Calls FingerprintFile for every response.""" for response in responses: self.CallFlow("FingerprintFile", pathspec=response.stat_entry.pathspec, next_state="Done") def DownloadAction(self, responses): """Downloads files corresponding to all the responses.""" files_to_fetch = [] for response in responses: # If the binary is too large we just ignore it. file_size = response.stat_entry.st_size if file_size > self.args.action.download.max_size: self.Log("%s too large to fetch. Size=%d", response.stat_entry.pathspec.CollapsePath(), file_size) files_to_fetch.append(response.stat_entry.pathspec) if files_to_fetch: use_stores = self.args.action.download.use_external_stores self.CallFlow( "MultiGetFile", pathspecs=files_to_fetch, use_external_stores=use_stores, next_state="Done") @flow.StateHandler() def Done(self, responses): pass @flow.StateHandler() def End(self, responses): self.Log("Found and processed %d files.", self.state.files_found)
import multiprocessing as mp import itertools import traceback import pickle import numpy as np from numba import cuda from numba.cuda.cudadrv import driver from numba.cuda.testing import (skip_on_arm, skip_on_cudasim, skip_under_cuda_memcheck, ContextResettingTestCase, ForeignArray) import unittest def core_ipc_handle_test(the_work, result_queue): try: arr = the_work() # Catch anything going wrong in the worker function except: # noqa: E722 # FAILED. propagate the exception as a string succ = False out = traceback.format_exc() else: # OK. send the ndarray back succ = True out = arr result_queue.put((succ, out)) def base_ipc_handle_test(handle, size, result_queue): def the_work(): dtype = np.dtype(np.intp) with cuda.open_ipc_array(handle, shape=size // dtype.itemsize, dtype=dtype) as darr: # copy the data to host return darr.copy_to_host() core_ipc_handle_test(the_work, result_queue) def serialize_ipc_handle_test(handle, result_queue): def the_work(): dtype = np.dtype(np.intp) darr = handle.open_array(cuda.current_context(), shape=handle.size // dtype.itemsize, dtype=dtype) # copy the data to host arr = darr.copy_to_host() handle.close() return arr core_ipc_handle_test(the_work, result_queue) def ipc_array_test(ipcarr, result_queue): try: with ipcarr as darr: arr = darr.copy_to_host() try: # should fail to reopen with ipcarr: pass except ValueError as e: if str(e) != 'IpcHandle is already opened': raise AssertionError('invalid exception message') else: raise AssertionError('did not raise on reopen') # Catch any exception so we can propagate it except: # noqa: E722 # FAILED. propagate the exception as a string succ = False out = traceback.format_exc() else: # OK. send the ndarray back succ = True out = arr result_queue.put((succ, out)) @skip_under_cuda_memcheck('Hangs cuda-memcheck') @skip_on_cudasim('Ipc not available in CUDASIM') @skip_on_arm('CUDA IPC not supported on ARM in Numba') class TestIpcMemory(ContextResettingTestCase): def test_ipc_handle(self): # prepare data for IPC arr = np.arange(10, dtype=np.intp) devarr = cuda.to_device(arr) # create IPC handle ctx = cuda.current_context() ipch = ctx.get_ipc_handle(devarr.gpu_data) # manually prepare for serialization as bytes if driver.USE_NV_BINDING: handle_bytes = ipch.handle.reserved else: handle_bytes = bytes(ipch.handle) size = ipch.size # spawn new process for testing ctx = mp.get_context('spawn') result_queue = ctx.Queue() args = (handle_bytes, size, result_queue) proc = ctx.Process(target=base_ipc_handle_test, args=args) proc.start() succ, out = result_queue.get() if not succ: self.fail(out) else: np.testing.assert_equal(arr, out) proc.join(3) def variants(self): # Test with no slicing and various different slices indices = (None, slice(3, None), slice(3, 8), slice(None, 8)) # Test with a Numba DeviceNDArray, or an array from elsewhere through # the CUDA Array Interface foreigns = (False, True) return itertools.product(indices, foreigns) def check_ipc_handle_serialization(self, index_arg=None, foreign=False): # prepare data for IPC arr = np.arange(10, dtype=np.intp) devarr = cuda.to_device(arr) if index_arg is not None: devarr = devarr[index_arg] if foreign: devarr = cuda.as_cuda_array(ForeignArray(devarr)) expect = devarr.copy_to_host() # create IPC handle ctx = cuda.current_context() ipch = ctx.get_ipc_handle(devarr.gpu_data) # pickle buf = pickle.dumps(ipch) ipch_recon = pickle.loads(buf) self.assertIs(ipch_recon.base, None) self.assertEqual(ipch_recon.size, ipch.size) if driver.USE_NV_BINDING: self.assertEqual(ipch_recon.handle.reserved, ipch.handle.reserved) else: self.assertEqual(tuple(ipch_recon.handle), tuple(ipch.handle)) # spawn new process for testing ctx = mp.get_context('spawn') result_queue = ctx.Queue() args = (ipch, result_queue) proc = ctx.Process(target=serialize_ipc_handle_test, args=args) proc.start() succ, out = result_queue.get() if not succ: self.fail(out) else: np.testing.assert_equal(expect, out) proc.join(3) def test_ipc_handle_serialization(self): for index, foreign, in self.variants(): with self.subTest(index=index, foreign=foreign): self.check_ipc_handle_serialization(index, foreign) def check_ipc_array(self, index_arg=None, foreign=False): # prepare data for IPC arr = np.arange(10, dtype=np.intp) devarr = cuda.to_device(arr) # Slice if index_arg is not None: devarr = devarr[index_arg] if foreign: devarr = cuda.as_cuda_array(ForeignArray(devarr)) expect = devarr.copy_to_host() ipch = devarr.get_ipc_handle() # spawn new process for testing ctx = mp.get_context('spawn') result_queue = ctx.Queue() args = (ipch, result_queue) proc = ctx.Process(target=ipc_array_test, args=args) proc.start() succ, out = result_queue.get() if not succ: self.fail(out) else: np.testing.assert_equal(expect, out) proc.join(3) def test_ipc_array(self): for index, foreign, in self.variants(): with self.subTest(index=index, foreign=foreign): self.check_ipc_array(index, foreign) def staged_ipc_handle_test(handle, device_num, result_queue): def the_work(): with cuda.gpus[device_num]: this_ctx = cuda.devices.get_context() deviceptr = handle.open_staged(this_ctx) arrsize = handle.size // np.dtype(np.intp).itemsize hostarray = np.zeros(arrsize, dtype=np.intp) cuda.driver.device_to_host( hostarray, deviceptr, size=handle.size, ) handle.close() return hostarray core_ipc_handle_test(the_work, result_queue) def staged_ipc_array_test(ipcarr, device_num, result_queue): try: with cuda.gpus[device_num]: with ipcarr as darr: arr = darr.copy_to_host() try: # should fail to reopen with ipcarr: pass except ValueError as e: if str(e) != 'IpcHandle is already opened': raise AssertionError('invalid exception message') else: raise AssertionError('did not raise on reopen') # Catch any exception so we can propagate it except: # noqa: E722 # FAILED. propagate the exception as a string succ = False out = traceback.format_exc() else: # OK. send the ndarray back succ = True out = arr result_queue.put((succ, out)) @skip_under_cuda_memcheck('Hangs cuda-memcheck') @skip_on_cudasim('Ipc not available in CUDASIM') @skip_on_arm('CUDA IPC not supported on ARM in Numba') class TestIpcStaged(ContextResettingTestCase): def test_staged(self): # prepare data for IPC arr = np.arange(10, dtype=np.intp) devarr = cuda.to_device(arr) # spawn new process for testing mpctx = mp.get_context('spawn') result_queue = mpctx.Queue() # create IPC handle ctx = cuda.current_context() ipch = ctx.get_ipc_handle(devarr.gpu_data) # pickle buf = pickle.dumps(ipch) ipch_recon = pickle.loads(buf) self.assertIs(ipch_recon.base, None) if driver.USE_NV_BINDING: self.assertEqual(ipch_recon.handle.reserved, ipch.handle.reserved) else: self.assertEqual(tuple(ipch_recon.handle), tuple(ipch.handle)) self.assertEqual(ipch_recon.size, ipch.size) # Test on every CUDA devices for device_num in range(len(cuda.gpus)): args = (ipch, device_num, result_queue) proc = mpctx.Process(target=staged_ipc_handle_test, args=args) proc.start() succ, out = result_queue.get() proc.join(3) if not succ: self.fail(out) else: np.testing.assert_equal(arr, out) def test_ipc_array(self): for device_num in range(len(cuda.gpus)): # prepare data for IPC arr = np.random.random(10) devarr = cuda.to_device(arr) ipch = devarr.get_ipc_handle() # spawn new process for testing ctx = mp.get_context('spawn') result_queue = ctx.Queue() args = (ipch, device_num, result_queue) proc = ctx.Process(target=staged_ipc_array_test, args=args) proc.start() succ, out = result_queue.get() proc.join(3) if not succ: self.fail(out) else: np.testing.assert_equal(arr, out) if __name__ == '__main__': unittest.main()
## @brief A simple variant of processing.Pool that accepts requests # from different threads. # Import 'multiprocessing' package (formerly known as 'processing'): try: # Tested with python 2.6 b3 from multiprocessing import Pool except ImportError: # Tested with standalone processing 0.52 from processing import Pool import threading, sys class MultiThreadedPool: """ A simple variant of processing.Pool that accepts requests from different threads: makes sure that requests being processed by the worker processes are not redundant. When a thread B submits a request which is already being processed in the background for another thread A, then B doesn't re-submit the request: it waits for the same result object as A. This package makes the following asumption: - the result of the function to call is entirely determined by its arguments (resp. "function", "params") As a consequence, in order to determine whether a "request" has already been submitted by another thread, we ONLY compare the couples (function, params). If a submitted request has the same couple (function, params) as a request in progress, then we wait for this request to be completed (valid result, or exception) This Pool should be safe wrt exceptions in the remote function. Only the map() and imap() methods are implemented. """ __lock = None # threading.Lock object __inflight = None # dict: (function, params) -> processing.ApplyResult obj __workers = None # processing.Pool object def __init__(self, processes=None, initializer=None, initargs=()): """See processing.Pool.__init__()""" self.__workers = Pool(processes, initializer, initargs) self.__inflight = dict() self.__lock = threading.Lock() # Apply locking decorator on close/terminate/join self._unregister_jobs = self.__make_synchronized(self._unregister_jobs) self.close = self.__make_synchronized(self.__workers.close) self.terminate = self.__make_synchronized(self.__workers.terminate) self.join = self.__make_synchronized(self.__workers.join) def apply(self, func, args=()): """Equivalent to processing.Pool::apply(), but without the kwds{} argument""" self.__lock.acquire() try: key, job, i_am_owner = self._apply_async(func, args) finally: self.__lock.release() # Wait for result try: return job.get() finally: self._unregister_jobs([(key, job, i_am_owner)]) def imap(self, func, iterable): """Equivalent to processing.Pool.imap(), but without the "chunksize" argument""" jobs = [] # list of tuples (key, result_object, bool_i_started_the_job) # Build the list of jobs started in the background self.__lock.acquire() try: for param in iterable: jobs.append(self._apply_async(func, (param,))) finally: self.__lock.release() # Wait for everybody try: for key, job, i_am_owner in jobs: yield job.get() finally: self._unregister_jobs(jobs) def map(self, func, iterable): """Equivalent to processing.Pool.map(), but without the "chunksize" argument""" return list(self.imap(func, iterable)) def _apply_async(self, func, args): """Return a tuple (inflight_key, applyResult object, i_am_owner)""" key = (func, args) try: # Job already started by somebody else job = self.__inflight[key] return key, job, False except KeyError: # We have to start a new job job = self.__workers.apply_async(func, args) self.__inflight[key] = job return key, job, True def _unregister_jobs(self, jobs): """ Remove all the given "in flight" jobs. Due to a limitation of processing 0.52, we have to wake up additional threads waiting for the result by hand. The correct fix to processing would be to replace self._cond.notify() in ApplyResult::set() by self._cond.notifyAll() """ for key, job, i_am_owner in jobs: # Begin workaround # processing.ApplyResult._set doesn't call notifyAll ! # we have to do it ourselves. # Don't move it: nothing guarantees # that the owner will be the 1st to wake up ! job._cond.acquire() job._cond.notifyAll() job._cond.release() # End workaround if not i_am_owner: # Don't remove it from the in_flight list continue try: del self.__inflight[key] except KeyError: print >>sys.stderr, "Warning: job not in queue", key, job def __make_synchronized(self, f): """Local decorator to make a method calling lock acquire/release""" def newf(*args, **kw): self.__lock.acquire() try: return f(*args, **kw) finally: self.__lock.release() return newf if __name__ == "__main__": import os, time def f(params): delay, msg = params print "Calling sleep(%f) in %d with msg '%s'" % (delay, os.getpid(), msg) time.sleep(delay) print "End of sleep(%f) in %d with msg '%s'" % (delay, os.getpid(), msg) return "Slept %fs" % delay # We have to create the Pool AFTER the functions to call in it have been # defined. Using 3 worker processes pool = MultiThreadedPool(3) # Small test for apply() first print pool.apply(f, ((1.2, "Sleep 1200ms to test apply()"),)) # Now test map()... class TestThread(threading.Thread): def __init__(self, params): threading.Thread.__init__(self) self.__params = params def run(self): print "Running on", self.__params try: r = pool.map(f, self.__params) print "Got result:", r except: print "Got exception", sys.exc_info()[0:2] jobs = ((1, "Sleep 1s"), (2, "Sleep 2s"), (3, "Sleep 3s"), (2.5, "BisSleep 2.5s")) # Jobs that will execute the same parallel tasks # Note: total duration = 3.5s because we have a pool of 3 processes t1 = TestThread(list(jobs)) t2 = TestThread(list(jobs)) t3 = TestThread(list(jobs)) t4 = TestThread(list(jobs)) t5 = TestThread(list(jobs)) # jobs with a failure jobs = jobs + ((-42, "Invalid negative sleep time"),) tfail1 = TestThread(list(jobs)) tfail2 = TestThread(list(jobs)) # Starting 1st thread t1.start() time.sleep(1.5) # Starting a 2nd thread, which is asking for the same data t1 is # already processing t2.start() time.sleep(.5) t3.start() t4.start() # Should return at the same time as t1, with the same results # Wait for all of them to complete time.sleep(4) print "### We should start all over again now..." t5.start() # Starting 2 threads which should fail with an exception time.sleep(1) tfail1.start() tfail2.start() # 1 Thread should have finished, the 2 others # returned en exception almost at the same time
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy from oslo_utils import uuidutils from openstack_dashboard.api import base from openstack_dashboard.api import fwaas from openstack_dashboard.api import neutron from openstack_dashboard.api import vpn from openstack_dashboard.test.test_data import utils from openstack_dashboard.usage import quotas as usage_quotas def data(TEST): # Data returned by openstack_dashboard.api.neutron wrapper. TEST.agents = utils.TestDataContainer() TEST.networks = utils.TestDataContainer() TEST.subnets = utils.TestDataContainer() TEST.subnetpools = utils.TestDataContainer() TEST.ports = utils.TestDataContainer() TEST.routers = utils.TestDataContainer() TEST.routers_with_rules = utils.TestDataContainer() TEST.routers_with_routes = utils.TestDataContainer() TEST.q_floating_ips = utils.TestDataContainer() TEST.q_secgroups = utils.TestDataContainer() TEST.q_secgroup_rules = utils.TestDataContainer() TEST.providers = utils.TestDataContainer() TEST.pools = utils.TestDataContainer() TEST.vips = utils.TestDataContainer() TEST.members = utils.TestDataContainer() TEST.monitors = utils.TestDataContainer() TEST.neutron_quotas = utils.TestDataContainer() TEST.neutron_quota_usages = utils.TestDataContainer() TEST.vpnservices = utils.TestDataContainer() TEST.ikepolicies = utils.TestDataContainer() TEST.ipsecpolicies = utils.TestDataContainer() TEST.ipsecsiteconnections = utils.TestDataContainer() TEST.firewalls = utils.TestDataContainer() TEST.fw_policies = utils.TestDataContainer() TEST.fw_rules = utils.TestDataContainer() TEST.ip_availability = utils.TestDataContainer() # Data return by neutronclient. TEST.api_agents = utils.TestDataContainer() TEST.api_networks = utils.TestDataContainer() TEST.api_subnets = utils.TestDataContainer() TEST.api_subnetpools = utils.TestDataContainer() TEST.api_ports = utils.TestDataContainer() TEST.api_routers = utils.TestDataContainer() TEST.api_routers_with_routes = utils.TestDataContainer() TEST.api_q_floating_ips = utils.TestDataContainer() TEST.api_q_secgroups = utils.TestDataContainer() TEST.api_q_secgroup_rules = utils.TestDataContainer() TEST.api_pools = utils.TestDataContainer() TEST.api_vips = utils.TestDataContainer() TEST.api_members = utils.TestDataContainer() TEST.api_monitors = utils.TestDataContainer() TEST.api_extensions = utils.TestDataContainer() TEST.api_vpnservices = utils.TestDataContainer() TEST.api_ikepolicies = utils.TestDataContainer() TEST.api_ipsecpolicies = utils.TestDataContainer() TEST.api_ipsecsiteconnections = utils.TestDataContainer() TEST.api_firewalls = utils.TestDataContainer() TEST.api_fw_policies = utils.TestDataContainer() TEST.api_fw_rules = utils.TestDataContainer() TEST.api_ip_availability = utils.TestDataContainer() # 1st network. network_dict = {'admin_state_up': True, 'id': '82288d84-e0a5-42ac-95be-e6af08727e42', 'name': 'net1', 'status': 'ACTIVE', 'subnets': ['e8abc972-eb0c-41f1-9edd-4bc6e3bcd8c9'], 'tenant_id': '1', 'router:external': False, 'shared': False} subnet_dict = {'allocation_pools': [{'end': '10.0.0.254', 'start': '10.0.0.2'}], 'dns_nameservers': [], 'host_routes': [], 'cidr': '10.0.0.0/24', 'enable_dhcp': True, 'gateway_ip': '10.0.0.1', 'id': network_dict['subnets'][0], 'ip_version': 4, 'name': 'mysubnet1', 'network_id': network_dict['id'], 'tenant_id': network_dict['tenant_id']} TEST.api_networks.add(network_dict) TEST.api_subnets.add(subnet_dict) network = copy.deepcopy(network_dict) subnet = neutron.Subnet(subnet_dict) network['subnets'] = [subnet] TEST.networks.add(neutron.Network(network)) TEST.subnets.add(subnet) # Ports on 1st network. port_dict = {'admin_state_up': True, 'device_id': 'af75c8e5-a1cc-4567-8d04-44fcd6922890', 'device_owner': 'network:dhcp', 'fixed_ips': [{'ip_address': '10.0.0.3', 'subnet_id': subnet_dict['id']}], 'id': '063cf7f3-ded1-4297-bc4c-31eae876cc91', 'mac_address': 'fa:16:3e:9c:d5:7e', 'name': '', 'network_id': network_dict['id'], 'status': 'ACTIVE', 'tenant_id': network_dict['tenant_id'], 'binding:vnic_type': 'normal', 'binding:host_id': 'host', 'allowed_address_pairs': [{'ip_address': '174.0.0.201', 'mac_address': 'fa:16:3e:7a:7b:18'}] } TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) port_dict = {'admin_state_up': True, 'device_id': '1', 'device_owner': 'compute:nova', 'fixed_ips': [{'ip_address': '10.0.0.4', 'subnet_id': subnet_dict['id']}], 'id': '7e6ce62c-7ea2-44f8-b6b4-769af90a8406', 'mac_address': 'fa:16:3e:9d:e6:2f', 'name': '', 'network_id': network_dict['id'], 'status': 'ACTIVE', 'tenant_id': network_dict['tenant_id'], 'binding:vnic_type': 'normal', 'binding:host_id': 'host'} TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) assoc_port = port_dict port_dict = {'admin_state_up': True, 'device_id': '279989f7-54bb-41d9-ba42-0d61f12fda61', 'device_owner': 'network:router_interface', 'fixed_ips': [{'ip_address': '10.0.0.1', 'subnet_id': subnet_dict['id']}], 'id': '9036eedb-e7fa-458e-bc6e-d9d06d9d1bc4', 'mac_address': 'fa:16:3e:9c:d5:7f', 'name': '', 'network_id': network_dict['id'], 'status': 'ACTIVE', 'tenant_id': network_dict['tenant_id'], 'binding:vnic_type': 'normal', 'binding:host_id': 'host'} TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) # 2nd network. network_dict = {'admin_state_up': True, 'id': '72c3ab6c-c80f-4341-9dc5-210fa31ac6c2', 'name': 'net2', 'status': 'ACTIVE', 'subnets': ['3f7c5d79-ee55-47b0-9213-8e669fb03009'], 'tenant_id': '2', 'router:external': False, 'shared': True} subnet_dict = {'allocation_pools': [{'end': '172.16.88.254', 'start': '172.16.88.2'}], 'dns_nameservers': ['10.56.1.20', '10.56.1.21'], 'host_routes': [{'destination': '192.168.20.0/24', 'nexthop': '172.16.88.253'}, {'destination': '192.168.21.0/24', 'nexthop': '172.16.88.252'}], 'cidr': '172.16.88.0/24', 'enable_dhcp': True, 'gateway_ip': '172.16.88.1', 'id': '3f7c5d79-ee55-47b0-9213-8e669fb03009', 'ip_version': 4, 'name': 'aaaa', 'network_id': network_dict['id'], 'tenant_id': network_dict['tenant_id']} TEST.api_networks.add(network_dict) TEST.api_subnets.add(subnet_dict) network = copy.deepcopy(network_dict) subnet = neutron.Subnet(subnet_dict) network['subnets'] = [subnet] TEST.networks.add(neutron.Network(network)) TEST.subnets.add(subnet) port_dict = {'admin_state_up': True, 'device_id': '2', 'device_owner': 'compute:nova', 'fixed_ips': [{'ip_address': '172.16.88.3', 'subnet_id': subnet_dict['id']}], 'id': '1db2cc37-3553-43fa-b7e2-3fc4eb4f9905', 'mac_address': 'fa:16:3e:56:e6:2f', 'name': '', 'network_id': network_dict['id'], 'status': 'ACTIVE', 'tenant_id': network_dict['tenant_id'], 'binding:vnic_type': 'normal', 'binding:host_id': 'host'} TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) # External network. network_dict = {'admin_state_up': True, 'id': '9b466b94-213a-4cda-badf-72c102a874da', 'name': 'ext_net', 'status': 'ACTIVE', 'subnets': ['d6bdc71c-7566-4d32-b3ff-36441ce746e8'], 'tenant_id': '3', 'router:external': True, 'shared': False} subnet_dict = {'allocation_pools': [{'start': '172.24.4.226.', 'end': '172.24.4.238'}], 'dns_nameservers': [], 'host_routes': [], 'cidr': '172.24.4.0/28', 'enable_dhcp': False, 'gateway_ip': '172.24.4.225', 'id': 'd6bdc71c-7566-4d32-b3ff-36441ce746e8', 'ip_version': 4, 'name': 'ext_subnet', 'network_id': network_dict['id'], 'tenant_id': network_dict['tenant_id']} ext_net = network_dict TEST.api_networks.add(network_dict) TEST.api_subnets.add(subnet_dict) network = copy.deepcopy(network_dict) subnet = neutron.Subnet(subnet_dict) network['subnets'] = [subnet] TEST.networks.add(neutron.Network(network)) TEST.subnets.add(subnet) # 1st v6 network. network_dict = {'admin_state_up': True, 'id': '96688ea1-ffa5-78ec-22ca-33aaabfaf775', 'name': 'v6_net1', 'status': 'ACTIVE', 'subnets': ['88ddd443-4377-ab1f-87dd-4bc4a662dbb6'], 'tenant_id': '1', 'router:external': False, 'shared': False} subnet_dict = {'allocation_pools': [{'end': 'ff09::ff', 'start': 'ff09::02'}], 'dns_nameservers': [], 'host_routes': [], 'cidr': 'ff09::/64', 'enable_dhcp': True, 'gateway_ip': 'ff09::1', 'id': network_dict['subnets'][0], 'ip_version': 6, 'name': 'v6_subnet1', 'network_id': network_dict['id'], 'tenant_id': network_dict['tenant_id'], 'ipv6_modes': 'none/none'} TEST.api_networks.add(network_dict) TEST.api_subnets.add(subnet_dict) network = copy.deepcopy(network_dict) subnet = neutron.Subnet(subnet_dict) network['subnets'] = [subnet] TEST.networks.add(neutron.Network(network)) TEST.subnets.add(subnet) # 2nd v6 network - slaac. network_dict = {'admin_state_up': True, 'id': 'c62e4bb3-296a-4cd1-8f6b-aaa7a0092326', 'name': 'v6_net2', 'status': 'ACTIVE', 'subnets': ['5d736a21-0036-4779-8f8b-eed5f98077ec'], 'tenant_id': '1', 'router:external': False, 'shared': False} subnet_dict = {'allocation_pools': [{'end': 'ff09::ff', 'start': 'ff09::02'}], 'dns_nameservers': [], 'host_routes': [], 'cidr': 'ff09::/64', 'enable_dhcp': True, 'gateway_ip': 'ff09::1', 'id': network_dict['subnets'][0], 'ip_version': 6, 'name': 'v6_subnet2', 'network_id': network_dict['id'], 'tenant_id': network_dict['tenant_id'], 'ipv6_modes': 'slaac/slaac'} TEST.api_networks.add(network_dict) TEST.api_subnets.add(subnet_dict) network = copy.deepcopy(network_dict) subnet = neutron.Subnet(subnet_dict) network['subnets'] = [subnet] TEST.networks.add(neutron.Network(network)) TEST.subnets.add(subnet) # Set up router data. port_dict = {'admin_state_up': True, 'device_id': '7180cede-bcd8-4334-b19f-f7ef2f331f53', 'device_owner': 'network:router_gateway', 'fixed_ips': [{'ip_address': '10.0.0.3', 'subnet_id': subnet_dict['id']}], 'id': '44ec6726-4bdc-48c5-94d4-df8d1fbf613b', 'mac_address': 'fa:16:3e:9c:d5:7e', 'name': '', 'network_id': TEST.networks.get(name="ext_net")['id'], 'status': 'ACTIVE', 'tenant_id': '1', 'binding:vnic_type': 'normal', 'binding:host_id': 'host'} TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) router_dict = {'id': '279989f7-54bb-41d9-ba42-0d61f12fda61', 'name': 'router1', 'status': 'ACTIVE', 'admin_state_up': True, 'distributed': True, 'external_gateway_info': {'network_id': ext_net['id']}, 'tenant_id': '1'} TEST.api_routers.add(router_dict) TEST.routers.add(neutron.Router(router_dict)) router_dict = {'id': '10e3dc42-1ce1-4d48-87cf-7fc333055d6c', 'name': 'router2', 'status': 'ACTIVE', 'admin_state_up': False, 'distributed': False, 'external_gateway_info': None, 'tenant_id': '1'} TEST.api_routers.add(router_dict) TEST.routers.add(neutron.Router(router_dict)) router_dict = {'id': '7180cede-bcd8-4334-b19f-f7ef2f331f53', 'name': 'rulerouter', 'status': 'ACTIVE', 'admin_state_up': True, 'distributed': False, 'external_gateway_info': {'network_id': ext_net['id']}, 'tenant_id': '1', 'router_rules': [{'id': '101', 'action': 'deny', 'source': 'any', 'destination': 'any', 'nexthops': []}, {'id': '102', 'action': 'permit', 'source': 'any', 'destination': '8.8.8.8/32', 'nexthops': ['1.0.0.2', '1.0.0.1']}]} TEST.api_routers.add(router_dict) TEST.routers_with_rules.add(neutron.Router(router_dict)) router_dict_with_route = {'id': '725c24c9-061b-416b-b9d4-012392b32fd9', 'name': 'routerouter', 'status': 'ACTIVE', 'admin_state_up': True, 'distributed': False, 'external_gateway_info': {'network_id': ext_net['id']}, 'tenant_id': '1', 'routes': [{'nexthop': '10.0.0.1', 'destination': '172.0.0.0/24'}, {'nexthop': '10.0.0.2', 'destination': '172.1.0.0/24'}]} TEST.api_routers_with_routes.add(router_dict_with_route) TEST.routers_with_routes.add(neutron.Router(router_dict_with_route)) # Floating IP. # Unassociated. fip_dict = {'tenant_id': '1', 'floating_ip_address': '172.16.88.227', 'floating_network_id': ext_net['id'], 'id': '9012cd70-cfae-4e46-b71e-6a409e9e0063', 'fixed_ip_address': None, 'port_id': None, 'router_id': None} TEST.api_q_floating_ips.add(fip_dict) fip_with_instance = copy.deepcopy(fip_dict) fip_with_instance.update({'instance_id': None, 'instance_type': None}) TEST.q_floating_ips.add(neutron.FloatingIp(fip_with_instance)) # Associated (with compute port on 1st network). fip_dict = {'tenant_id': '1', 'floating_ip_address': '172.16.88.228', 'floating_network_id': ext_net['id'], 'id': 'a97af8f2-3149-4b97-abbd-e49ad19510f7', 'fixed_ip_address': assoc_port['fixed_ips'][0]['ip_address'], 'port_id': assoc_port['id'], 'router_id': router_dict['id']} TEST.api_q_floating_ips.add(fip_dict) fip_with_instance = copy.deepcopy(fip_dict) fip_with_instance.update({'instance_id': '1', 'instance_type': 'compute'}) TEST.q_floating_ips.add(neutron.FloatingIp(fip_with_instance)) # Security group. sec_group_1 = {'tenant_id': '1', 'description': 'default', 'id': 'faad7c80-3b62-4440-967c-13808c37131d', 'name': 'default'} sec_group_2 = {'tenant_id': '1', 'description': 'NotDefault', 'id': '27a5c9a1-bdbb-48ac-833a-2e4b5f54b31d', 'name': 'other_group'} sec_group_3 = {'tenant_id': '1', 'description': 'NotDefault', 'id': '443a4d7a-4bd2-4474-9a77-02b35c9f8c95', 'name': 'another_group'} def add_rule_to_group(secgroup, default_only=True): rule_egress_ipv4 = { 'id': uuidutils.generate_uuid(), 'direction': u'egress', 'ethertype': u'IPv4', 'port_range_min': None, 'port_range_max': None, 'protocol': None, 'remote_group_id': None, 'remote_ip_prefix': None, 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rule_egress_ipv6 = { 'id': uuidutils.generate_uuid(), 'direction': u'egress', 'ethertype': u'IPv6', 'port_range_min': None, 'port_range_max': None, 'protocol': None, 'remote_group_id': None, 'remote_ip_prefix': None, 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rule_tcp_80 = { 'id': uuidutils.generate_uuid(), 'direction': u'ingress', 'ethertype': u'IPv4', 'port_range_min': 80, 'port_range_max': 80, 'protocol': u'tcp', 'remote_group_id': None, 'remote_ip_prefix': u'0.0.0.0/0', 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rule_icmp = { 'id': uuidutils.generate_uuid(), 'direction': u'ingress', 'ethertype': u'IPv4', 'port_range_min': 5, 'port_range_max': 8, 'protocol': u'icmp', 'remote_group_id': None, 'remote_ip_prefix': u'0.0.0.0/0', 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rule_group = { 'id': uuidutils.generate_uuid(), 'direction': u'ingress', 'ethertype': u'IPv4', 'port_range_min': 80, 'port_range_max': 80, 'protocol': u'tcp', 'remote_group_id': sec_group_1['id'], 'remote_ip_prefix': None, 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rule_all_tcp = { 'id': uuidutils.generate_uuid(), 'direction': u'egress', 'ethertype': u'IPv4', 'port_range_min': 1, 'port_range_max': 65535, 'protocol': u'tcp', 'remote_group_id': None, 'remote_ip_prefix': u'0.0.0.0/24', 'security_group_id': secgroup['id'], 'tenant_id': secgroup['tenant_id']} rules = [] if not default_only: rules += [rule_tcp_80, rule_icmp, rule_group, rule_all_tcp] rules += [rule_egress_ipv4, rule_egress_ipv6] secgroup['security_group_rules'] = rules add_rule_to_group(sec_group_1, default_only=False) add_rule_to_group(sec_group_2) add_rule_to_group(sec_group_3) groups = [sec_group_1, sec_group_2, sec_group_3] sg_name_dict = dict([(sg['id'], sg['name']) for sg in groups]) for sg in groups: # Neutron API. TEST.api_q_secgroups.add(sg) for rule in sg['security_group_rules']: TEST.api_q_secgroup_rules.add(copy.copy(rule)) # OpenStack Dashboard internaly API. TEST.q_secgroups.add( neutron.SecurityGroup(copy.deepcopy(sg), sg_name_dict)) for rule in sg['security_group_rules']: TEST.q_secgroup_rules.add( neutron.SecurityGroupRule(copy.copy(rule), sg_name_dict)) # Subnetpools # 1st subnetpool subnetpool_dict = {'default_prefixlen': 24, 'default_quota': None, 'id': '419eb314-e244-4088-aed7-851af9d9500d', 'ip_version': 4, 'max_prefixlen': 32, 'min_prefixlen': 12, 'name': 'mysubnetpool1', 'prefixes': ['172.16.0.0/12'], 'shared': False, 'tenant_id': '1'} TEST.api_subnetpools.add(subnetpool_dict) subnetpool = neutron.SubnetPool(subnetpool_dict) TEST.subnetpools.add(subnetpool) # 2nd subnetpool (v6) subnetpool_dict = {'default_prefixlen': 64, 'default_quota': None, 'id': 'dcdad289-46f3-4298-bec6-41d91c942efa', 'ip_version': 6, 'max_prefixlen': 64, 'min_prefixlen': 60, 'name': 'mysubnetpool2', 'prefixes': ['2001:db8:42::/48'], 'shared': False, 'tenant_id': '1'} TEST.api_subnetpools.add(subnetpool_dict) subnetpool = neutron.SubnetPool(subnetpool_dict) TEST.subnetpools.add(subnetpool) # Quotas. quota_data = {'network': '10', 'subnet': '10', 'port': '50', 'router': '10', 'floatingip': '50', 'security_group': '20', 'security_group_rule': '100', } TEST.neutron_quotas.add(base.QuotaSet(quota_data)) # Quota Usages quota_usage_data = {'networks': {'used': 0, 'quota': 5}, 'subnets': {'used': 0, 'quota': 5}, 'routers': {'used': 0, 'quota': 5}, } quota_usage = usage_quotas.QuotaUsage() for k, v in quota_usage_data.items(): quota_usage.add_quota(base.Quota(k, v['quota'])) quota_usage.tally(k, v['used']) TEST.neutron_quota_usages.add(quota_usage) # Extensions. extension_1 = {"name": "security-group", "alias": "security-group", "description": "The security groups extension."} extension_2 = {"name": "Quota management support", "alias": "quotas", "description": "Expose functions for quotas management"} extension_3 = {"name": "Provider network", "alias": "provider", "description": "Provider network extension"} extension_4 = {"name": "Distributed Virtual Router", "alias": "dvr", "description": "Enables configuration of Distributed Virtual Routers."} extension_5 = {"name": "HA Router extension", "alias": "l3-ha", "description": "Add HA capability to routers."} TEST.api_extensions.add(extension_1) TEST.api_extensions.add(extension_2) TEST.api_extensions.add(extension_3) TEST.api_extensions.add(extension_4) TEST.api_extensions.add(extension_5) # 1st agent. agent_dict = {"binary": "neutron-openvswitch-agent", "description": None, "admin_state_up": True, "heartbeat_timestamp": "2013-07-26 06:51:47", "alive": True, "id": "c876ff05-f440-443e-808c-1d34cda3e88a", "topic": "N/A", "host": "devstack001", "agent_type": "Open vSwitch agent", "started_at": "2013-07-26 05:23:28", "created_at": "2013-07-26 05:23:28", "configurations": {"devices": 2}} TEST.api_agents.add(agent_dict) TEST.agents.add(neutron.Agent(agent_dict)) # 2nd agent. agent_dict = {"binary": "neutron-dhcp-agent", "description": None, "admin_state_up": True, "heartbeat_timestamp": "2013-07-26 06:51:48", "alive": True, "id": "f0d12e3d-1973-41a2-b977-b95693f9a8aa", "topic": "dhcp_agent", "host": "devstack001", "agent_type": "DHCP agent", "started_at": "2013-07-26 05:23:30", "created_at": "2013-07-26 05:23:30", "configurations": { "subnets": 1, "use_namespaces": True, "dhcp_lease_duration": 120, "dhcp_driver": "neutron.agent.linux.dhcp.Dnsmasq", "networks": 1, "ports": 1}} TEST.api_agents.add(agent_dict) TEST.agents.add(neutron.Agent(agent_dict)) # Service providers. provider_1 = {"service_type": "LOADBALANCER", "name": "haproxy", "default": True} TEST.providers.add(provider_1) # VPNaaS. # 1st VPNService. vpnservice_dict = {'id': '09a26949-6231-4f72-942a-0c8c0ddd4d61', 'tenant_id': '1', 'name': 'cloud_vpn1', 'description': 'vpn description', 'subnet_id': TEST.subnets.first().id, 'router_id': TEST.routers.first().id, 'vpn_type': 'ipsec', 'ipsecsiteconnections': [], 'admin_state_up': True, 'status': 'Active', 'ipsecsiteconns': TEST.ipsecsiteconnections.list() } TEST.api_vpnservices.add(vpnservice_dict) TEST.vpnservices.add(vpn.VPNService(vpnservice_dict)) # 2nd VPNService. vpnservice_dict = {'id': '09a26949-6231-4f72-942a-0c8c0ddd4d62', 'tenant_id': '1', 'name': 'cloud_vpn2', 'description': 'vpn description', 'subnet_id': TEST.subnets.first().id, 'router_id': TEST.routers.first().id, 'vpn_type': 'ipsec', 'ipsecsiteconnections': [], 'admin_state_up': True, 'status': 'Active', 'ipsecsiteconns': [], 'external_v4_ip': '10.0.0.0/24', 'external_v6_ip': 'fd4c:a535:831c::/64' } TEST.api_vpnservices.add(vpnservice_dict) TEST.vpnservices.add(vpn.VPNService(vpnservice_dict)) # 1st IKEPolicy ikepolicy_dict = {'id': 'a1f009b7-0ffa-43a7-ba19-dcabb0b4c981', 'tenant_id': '1', 'name': 'ikepolicy_1', 'description': 'ikepolicy description', 'auth_algorithm': 'sha1', 'encryption_algorithm': 'aes-256', 'ike_version': 'v1', 'lifetime': {'units': 'seconds', 'value': 3600}, 'phase1_negotiation_mode': 'main', 'pfs': 'group5', 'ipsecsiteconns': TEST.ipsecsiteconnections.list()} TEST.api_ikepolicies.add(ikepolicy_dict) TEST.ikepolicies.add(vpn.IKEPolicy(ikepolicy_dict)) # 2nd IKEPolicy ikepolicy_dict = {'id': 'a1f009b7-0ffa-43a7-ba19-dcabb0b4c982', 'tenant_id': '1', 'name': 'ikepolicy_2', 'description': 'ikepolicy description', 'auth_algorithm': 'sha1', 'encryption_algorithm': 'aes-256', 'ike_version': 'v1', 'lifetime': {'units': 'seconds', 'value': 3600}, 'phase1_negotiation_mode': 'main', 'pfs': 'group5', 'ipsecsiteconns': []} TEST.api_ikepolicies.add(ikepolicy_dict) TEST.ikepolicies.add(vpn.IKEPolicy(ikepolicy_dict)) # 1st IPSecPolicy ipsecpolicy_dict = {'id': '8376e1dd-2b1c-4346-b23c-6989e75ecdb8', 'tenant_id': '1', 'name': 'ipsecpolicy_1', 'description': 'ipsecpolicy description', 'auth_algorithm': 'sha1', 'encapsulation_mode': 'tunnel', 'encryption_algorithm': '3des', 'lifetime': {'units': 'seconds', 'value': 3600}, 'pfs': 'group5', 'transform_protocol': 'esp', 'ipsecsiteconns': TEST.ipsecsiteconnections.list()} TEST.api_ipsecpolicies.add(ipsecpolicy_dict) TEST.ipsecpolicies.add(vpn.IPSecPolicy(ipsecpolicy_dict)) # 2nd IPSecPolicy ipsecpolicy_dict = {'id': '8376e1dd-2b1c-4346-b23c-6989e75ecdb9', 'tenant_id': '1', 'name': 'ipsecpolicy_2', 'description': 'ipsecpolicy description', 'auth_algorithm': 'sha1', 'encapsulation_mode': 'tunnel', 'encryption_algorithm': '3des', 'lifetime': {'units': 'seconds', 'value': 3600}, 'pfs': 'group5', 'transform_protocol': 'esp', 'ipsecsiteconns': []} TEST.api_ipsecpolicies.add(ipsecpolicy_dict) TEST.ipsecpolicies.add(vpn.IPSecPolicy(ipsecpolicy_dict)) # 1st IPSecSiteConnection ipsecsiteconnection_dict = {'id': 'dd1dd3a0-f349-49be-b013-245e147763d6', 'tenant_id': '1', 'name': 'ipsec_connection_1', 'description': 'vpn connection description', 'dpd': {'action': 'hold', 'interval': 30, 'timeout': 120}, 'ikepolicy_id': ikepolicy_dict['id'], 'initiator': 'bi-directional', 'ipsecpolicy_id': ipsecpolicy_dict['id'], 'mtu': 1500, 'peer_address': '2607:f0d0:4545:3:200:f8ff:fe21:67cf', 'peer_cidrs': ['20.1.0.0/24', '21.1.0.0/24'], 'peer_id': '2607:f0d0:4545:3:200:f8ff:fe21:67cf', 'psk': 'secret', 'vpnservice_id': vpnservice_dict['id'], 'admin_state_up': True, 'status': 'Active'} TEST.api_ipsecsiteconnections.add(ipsecsiteconnection_dict) TEST.ipsecsiteconnections.add( vpn.IPSecSiteConnection(ipsecsiteconnection_dict)) # 2nd IPSecSiteConnection ipsecsiteconnection_dict = {'id': 'dd1dd3a0-f349-49be-b013-245e147763d7', 'tenant_id': '1', 'name': 'ipsec_connection_2', 'description': 'vpn connection description', 'dpd': {'action': 'hold', 'interval': 30, 'timeout': 120}, 'ikepolicy_id': ikepolicy_dict['id'], 'initiator': 'bi-directional', 'ipsecpolicy_id': ipsecpolicy_dict['id'], 'mtu': 1500, 'peer_address': '172.0.0.2', 'peer_cidrs': ['20.1.0.0/24'], 'peer_id': '172.0.0.2', 'psk': 'secret', 'vpnservice_id': vpnservice_dict['id'], 'admin_state_up': True, 'status': 'Active'} TEST.api_ipsecsiteconnections.add(ipsecsiteconnection_dict) TEST.ipsecsiteconnections.add( vpn.IPSecSiteConnection(ipsecsiteconnection_dict)) # FWaaS # 1st rule (used by 1st policy) rule1_dict = {'id': 'f0881d38-c3eb-4fee-9763-12de3338041d', 'tenant_id': '1', 'name': 'rule1', 'description': 'rule1 description', 'protocol': 'tcp', 'action': 'allow', 'source_ip_address': '1.2.3.0/24', 'source_port': '80', 'destination_ip_address': '4.5.6.7/32', 'destination_port': '1:65535', 'firewall_policy_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'position': 1, 'shared': True, 'enabled': True, 'ip_version': '4'} TEST.api_fw_rules.add(rule1_dict) rule1 = fwaas.Rule(copy.deepcopy(rule1_dict)) # NOTE: rule1['policy'] is set below TEST.fw_rules.add(rule1) # 2nd rule (used by 2nd policy; no name) rule2_dict = {'id': 'c6298a93-850f-4f64-b78a-959fd4f1e5df', 'tenant_id': '1', 'name': '', 'description': '', 'protocol': 'udp', 'action': 'deny', 'source_ip_address': '1.2.3.0/24', 'source_port': '80', 'destination_ip_address': '4.5.6.7/32', 'destination_port': '1:65535', 'firewall_policy_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'position': 2, 'shared': True, 'enabled': True, 'ip_version': '6'} TEST.api_fw_rules.add(rule2_dict) rule2 = fwaas.Rule(copy.deepcopy(rule2_dict)) # NOTE: rule2['policy'] is set below TEST.fw_rules.add(rule2) # 3rd rule (not used by any policy) rule3_dict = {'id': 'h0881d38-c3eb-4fee-9763-12de3338041d', 'tenant_id': '1', 'name': 'rule3', 'description': 'rule3 description', 'protocol': None, 'action': 'allow', 'source_ip_address': '1.2.3.0/24', 'source_port': '80', 'destination_ip_address': '4.5.6.7/32', 'destination_port': '1:65535', 'firewall_policy_id': None, 'position': None, 'shared': True, 'enabled': True, 'ip_version': '4'} TEST.api_fw_rules.add(rule3_dict) rule3 = fwaas.Rule(copy.deepcopy(rule3_dict)) # rule3 is not associated with any rules rule3._apidict['policy'] = None TEST.fw_rules.add(rule3) # 1st policy (associated with 2 rules) policy1_dict = {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'tenant_id': '1', 'name': 'policy1', 'description': 'policy with two rules', 'firewall_rules': [rule1_dict['id'], rule2_dict['id']], 'audited': True, 'shared': True} TEST.api_fw_policies.add(policy1_dict) policy1 = fwaas.Policy(copy.deepcopy(policy1_dict)) policy1._apidict['rules'] = [rule1, rule2] TEST.fw_policies.add(policy1) # Reverse relations (rule -> policy) rule1._apidict['policy'] = policy1 rule2._apidict['policy'] = policy1 # 2nd policy (associated with no rules; no name) policy2_dict = {'id': 'cf50b331-787a-4623-825e-da794c918d6a', 'tenant_id': '1', 'name': '', 'description': '', 'firewall_rules': [], 'audited': False, 'shared': False} TEST.api_fw_policies.add(policy2_dict) policy2 = fwaas.Policy(copy.deepcopy(policy2_dict)) policy2._apidict['rules'] = [] TEST.fw_policies.add(policy2) # 1st firewall fw1_dict = {'id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'tenant_id': '1', 'firewall_policy_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': 'firewall1', 'router_ids': [TEST.routers.first().id], 'description': 'firewall description', 'status': 'PENDING_CREATE', 'admin_state_up': True} TEST.api_firewalls.add(fw1_dict) fw1 = fwaas.Firewall(copy.deepcopy(fw1_dict)) fw1._apidict['policy'] = policy1 fw1._apidict['routers'] = [TEST.routers.first()] TEST.firewalls.add(fw1) # 2nd firewall (no name) fw2_dict = {'id': '1aa75150-415f-458e-bae5-5a362a4fb1f7', 'tenant_id': '1', 'firewall_policy_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': '', 'router_ids': [], 'description': '', 'status': 'PENDING_CREATE', 'admin_state_up': True} TEST.api_firewalls.add(fw2_dict) fw2 = fwaas.Firewall(copy.deepcopy(fw2_dict)) fw2._apidict['policy'] = policy1 TEST.firewalls.add(fw2) # ports on 4th network port_dict = {'admin_state_up': True, 'device_id': '9872faaa-b2b2-eeee-9911-21332eedaa77', 'device_owner': 'network:dhcp', 'fixed_ips': [{'ip_address': '11.10.0.3', 'subnet_id': TEST.subnets.first().id}], 'id': 'a21dcd22-6733-cccc-aa32-22adafaf16a2', 'mac_address': '78:22:ff:1a:ba:23', 'name': 'port5', 'network_id': TEST.networks.first().id, 'status': 'ACTIVE', 'tenant_id': TEST.networks.first().tenant_id, 'binding:vnic_type': 'normal', 'binding:host_id': 'host'} TEST.api_ports.add(port_dict) TEST.ports.add(neutron.Port(port_dict)) availability = {'network_ip_availability': { 'used_ips': 2, 'subnet_ip_availability': [{ 'used_ips': 1, 'subnet_id': '2c90f321-9cc7-41b4-a3cf-88110f120a94', 'subnet_name': 'ipv6-public-subnet', 'ip_version': 6, 'cidr': '2001:db8::/64', 'total_ips': 18446744073709551614}, {'used_ips': 1, 'subnet_id': '4d77d5fb-c26c-4ac5-b2ca-fca2f89b0fc1', 'subnet_name': 'public-subnet', 'ip_version': 4, 'cidr': '172.24.4.0/24', 'total_ips': 253}], 'network_id': 'd87d5be5-cfca-486f-8db5-a446330e4513', 'tenant_id': 'd564b2a4fc0544fb89f8a0434dd96863', 'network_name': 'public', 'total_ips': 18446744073709551867} } TEST.ip_availability.add(availability) TEST.api_ip_availability.add(availability)
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted 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 # specific language governing permissions and limitations under the License. """API for accessing permissions and the underlying model for them.""" import collections import cache import users import utils from google.appengine.ext import ndb # A special user with ADMIN access. Real user objects that come from a # Google sign-in page always have numeric IDs (decimal strings). ROOT = users.User(id='root', email='', ga_domain='') # Lists of all the _Permission objects for a given subject and/or target, keyed # by [subject, target] where subject or target can be '*'. The 100-ms ULL is # intended to beat the time it takes for the domain admin page to redirect back # to showing permission lists after the user has edited permissions. CACHE = cache.Cache('perms', 60, 0.1) class AuthorizationError(Exception): """Subject is not authorized to perform an operation on a domain or a map.""" def __init__(self, subject, role, target): super(AuthorizationError, self).__init__( '%r lacks %s access to %r' % (subject, role, target)) self.subject = subject self.role = role self.target = target class NotCatalogEntryOwnerError(Exception): """User is not authorized to change or delete a catalog entry.""" def __init__(self, subject, target): Exception.__init__(self, '%r does not own catalog entry %s/%s' % (subject, target.domain, target.label)) class NotPublishableError(Exception): """Map is blocked and cannot be published.""" def __init__(self, target): Exception.__init__(self, 'Map %r cannot be published.' % target.id) # Access role constants. # Role is capitalized like an enum class. # pylint: disable=g-bad-name Role = utils.Struct( # Global roles ADMIN='ADMIN', # can view, edit, or change permissions for anything # Domain-targeted roles DOMAIN_ADMIN='DOMAIN_ADMIN', # can grant permissions for the domain CATALOG_EDITOR='CATALOG_EDITOR', # can edit the catalog for a domain MAP_CREATOR='MAP_CREATOR', # can create new maps DOMAIN_REVIEWER='DOMAIN_REVIEWER', # can review crowd reports in the domain # Map-targeted roles MAP_OWNER='MAP_OWNER', # can change permissions for a map MAP_EDITOR='MAP_EDITOR', # can save new versions of a map MAP_REVIEWER='MAP_REVIEWER', # can review reports for a map MAP_VIEWER='MAP_VIEWER', # can view current version of a map # The datastore cannot index None, but it will index an empty string. NONE='' # datastore value representing the absence of a role ) # Domain-targeted roles, in order: each role implies all preceding roles. DOMAIN_ROLES = [Role.DOMAIN_REVIEWER, Role.MAP_CREATOR, Role.CATALOG_EDITOR, Role.DOMAIN_ADMIN] # Map-targeted roles, in order: each role implies all preceding roles. MAP_ROLES = [Role.MAP_VIEWER, Role.MAP_REVIEWER, Role.MAP_EDITOR, Role.MAP_OWNER] # Only used for role ADMIN GLOBAL_TARGET = '__GLOBAL__' class _PermissionModel(ndb.Model): # The entity that is granted permission to do something: a domain or uid subject = ndb.StringProperty() # The type of access being granted: a Role constant role = ndb.StringProperty() # The thing to which access is granted: a map, a domain, or GLOBAL_TARGET target = ndb.StringProperty() @classmethod def _get_kind(cls): # pylint: disable=g-bad-name return 'PermissionModel' # so we can name the Python class with _ in front _Permission = collections.namedtuple( '_Permission', ['subject', 'role', 'target']) def _PermissionId(perm): # It's safe to use ',' as a separator because it cannot appear in a domain # name, a uid, a Role constant, or a map ID. The '_Permission,' prefix is a # holdover from older code, kept for now because removing it would require a # data migration (it's baked into entity IDs in the datastore). return ','.join(['_Permission', perm.subject, perm.role, perm.target]) def _FlushRelated(perm): for subject in [perm.subject, None]: for target in [perm.target, None]: CACHE.Delete([subject or '*', target or '*']) def _LoadPermissions(subject, target): # No role arg because we never wish to load by role; we always load more # (by subject or target), then filter by role. query = _PermissionModel.query() if subject: query = query.filter(_PermissionModel.subject == subject) if target: query = query.filter(_PermissionModel.target == target) return [_Permission(p.subject, p.role, p.target) for p in query] def _Query(subject, role, target): """Gets a list of all _Permissions matching a given subject, role, and target. Args: subject: A user ID or domain name, or None to query for all subjects. role: A Role constant, or None to query for all roles. target: A domain name, or None to query for all domains. Returns: A list of matching _Permission objects. """ if subject and role and target: # When querying for just one item, let NDB take care of caching. p = _Permission(subject, role, target) return _PermissionModel.get_by_id(_PermissionId(p)) and [p] or [] # Otherwise, cache the list of results in our own cache. perms = CACHE.Get([subject or '*', target or '*'], make_value=lambda: _LoadPermissions(subject, target)) return [p for p in perms if p.role == role] if role else perms def _QueryForUser(user, role=None, target=None): """Gets all _Permissions for the user's ID and e-mail domain.""" return _Query(user.id, role, target) + _Query(user.email_domain, role, target) def _Exists(subject, role, target): """Returns True if the specified single _Permission exists.""" return subject and role and target and bool(_Query(subject, role, target)) def _ExistsForUser(user, role, target): """Returns True if a _Permission exists for the user's ID or e-mail domain.""" return (_Exists(user.id, role, target) or _Exists(user.email_domain, role, target)) def Grant(subject, role, target): """Grants the given role to the subject for the target. Args: subject: A user ID or domain name. role: A Role constant. target: A domain name. """ perm = _Permission(subject, role, target) perm_model = _PermissionModel( subject=subject, role=role, target=target, id=_PermissionId(perm)) perm_model.put() _FlushRelated(perm) def _Revoke(perm): perm_model = _PermissionModel.get_by_id(_PermissionId(perm)) if perm_model: perm_model.key.delete() _FlushRelated(perm) def Revoke(subject, role, target): """Removes a specific permission. Note: inherited access may still apply. Args: subject: A user ID or domain name. role: A Role constant. target: A domain name. """ _Revoke(_Permission(subject, role, target)) def GetSubjectsForTarget(target): """Gets information on subjects that have any permissions to a given target. Args: target: A domain name. Returns: A dictionary whose keys are subjects (user IDs or domain names) and values are sets of the roles for those subjects. """ result = {} for perm in _Query(None, None, target): result.setdefault(perm.subject, set()).add(perm.role) return result def IsUserId(subject): """Returns True if subject is a valid user ID; otherwise False.""" if not subject: return False return '.' not in subject class AccessPolicy(object): """Wraps up authorization for user actions.""" def HasRoleAdmin(self, user): """Returns True if a user should get ADMIN access.""" # Users get admin access if they have the global ADMIN permission. The # special user ROOT, which can only be created programmatically and cannot # come from a real Google sign-in page, also gets ADMIN access. return user and (_Exists(user.id, Role.ADMIN, GLOBAL_TARGET) or user.id == ROOT.id) def HasRoleDomainAdmin(self, user, domain): """Returns True if the user should get DOMAIN_ADMIN access for a domain.""" # Users get domain administration access if they have domain administrator # permission to the domain, or if they have global admin access. return user and (_ExistsForUser(user, Role.DOMAIN_ADMIN, domain) or self.HasRoleAdmin(user)) def HasRoleDomainReviewer(self, user, domain): """Returns True if the user should get DOMAIN_REVIEWER access.""" # Users get domain administration access if they have domain administrator # permission to the domain, or if they have global admin access. return user and (_ExistsForUser(user, Role.DOMAIN_REVIEWER, domain) or self.HasRoleAdmin(user)) def HasRoleCatalogEditor(self, user, domain): """Returns True if a user should get CATALOG_EDITOR access for a domain.""" # Users get catalog editor access if they have catalog editor permission to # the specified domain, or if they have domain admin access. return user and (_ExistsForUser(user, Role.CATALOG_EDITOR, domain) or self.HasRoleDomainAdmin(user, domain)) def HasRoleMapCreator(self, user, domain): """Returns True if a user should get MAP_CREATOR access.""" # Users get map creator access if they have map creator permission to the # specified domain, or if they have catalog editor access. return user and (_ExistsForUser(user, Role.MAP_CREATOR, domain) or self.HasRoleCatalogEditor(user, domain)) def _HasMapPermission(self, user, role, map_object): """Checks for permission based on the access lists on the map object.""" # If the map is blocked, only the first owner can access it. if map_object.is_blocked: if not (user and [user.id] == map_object.owners[:1]): return False if role == Role.MAP_VIEWER and map_object.world_readable: return True if not user: return False domain_role = (user.email_domain == map_object.domain and map_object.domain_role) or None # Map permissions exist in a hierarchy: editors can always view; # owners can always edit. if domain_role == Role.MAP_OWNER or user.id in map_object.owners: return True if role == Role.MAP_OWNER: return False if domain_role == Role.MAP_EDITOR or user.id in map_object.editors: return True if role == Role.MAP_EDITOR: return False if domain_role == Role.MAP_REVIEWER or user.id in map_object.reviewers: return True if role == Role.MAP_REVIEWER: return False if domain_role == Role.MAP_VIEWER or user.id in map_object.viewers: return True return False def HasRoleMapOwner(self, user, map_object): """Returns True if a user should get MAP_OWNER access to a given map.""" # Users get owner access if they are in the owners list for the map, if # their domain is an owner of the map, if they have global owner access # to all maps, or if they have admin access. return (self._HasMapPermission(user, Role.MAP_OWNER, map_object) or self.HasRoleAdmin(user)) def HasRoleMapEditor(self, user, map_object): """Returns True if a user should get MAP_EDITOR access to a given map.""" # Users get editor access if they are in the editors list for the map, if # their domain is an editor of the map, if they have global editor access # to all maps, or if they have owner access. return (self._HasMapPermission(user, Role.MAP_EDITOR, map_object) or self.HasRoleMapOwner(user, map_object)) def HasRoleMapReviewer(self, user, map_object): """Returns True if the user has MAP_REVIEWER access to a given map.""" # Users get reviewer access if they are in the reviewers list for the map, # if their domain is a reviewer of the map, if they have domain reviewer # access to all maps, or if they have editor access. return (self._HasMapPermission(user, Role.MAP_REVIEWER, map_object) or self.HasRoleDomainReviewer(user, map_object.domain) or self.HasRoleMapEditor(user, map_object)) def HasRoleMapViewer(self, user, map_object): """Returns True if the user has MAP_VIEWER access to a given map.""" # Users get viewer access if the map is world-readable, if they are in the # viewers list for the map, if their domain is a viewer of the map, if they # have global viewer access to all maps, or if they have editor access. return (self._HasMapPermission(user, Role.MAP_VIEWER, map_object) or self.HasRoleMapEditor(user, map_object)) def GetAccessibleDomains(user, role): """Gets the set of domains for which the user has the specified access.""" if role not in DOMAIN_ROLES: raise ValueError('%r is not a domain-targeted role' % role) # This set includes the desired role and all stronger roles. qualifying_roles = DOMAIN_ROLES[DOMAIN_ROLES.index(role):] return {p.target for p in _QueryForUser(user) if p.role in qualifying_roles} def CheckAccess(role, target=None, user=None, policy=None): """Checks whether the given user has the specified access role. Args: role: A Role constant identifying the desired access role. target: The object to which access is desired. If 'role' is in MAP_ROLES, this should be a Map object; if 'role' is in DOMAIN_ROLES, this should be a domain name (a string); otherwise, this argument is unused. user: (optional) A users.User object. If not specified, access permissions are checked for the currently signed-in user. policy: The access policy to apply. Returns: True if the user has the specified access permission. Raises: ValueError: The specified role is not a valid member of Role. TypeError: The target has the wrong type for the given role. """ policy = policy or AccessPolicy() user = user or users.GetCurrent() # Roles that are unrelated to a target. if role == Role.ADMIN: return policy.HasRoleAdmin(user) # Roles with a domain as the target. if role in DOMAIN_ROLES and not isinstance(target, basestring): raise TypeError('For role %r, target should be a string' % role) if role == Role.CATALOG_EDITOR: return policy.HasRoleCatalogEditor(user, target) if role == Role.MAP_CREATOR: return policy.HasRoleMapCreator(user, target) if role == Role.DOMAIN_REVIEWER: return policy.HasRoleDomainReviewer(user, target) if role == Role.DOMAIN_ADMIN: return policy.HasRoleDomainAdmin(user, target) # Roles with a Map as the target if role in MAP_ROLES and target.__class__.__name__ not in ['Map', 'EmptyMap']: raise TypeError('For role %r, target should be a Map' % role) if role == Role.MAP_OWNER: return policy.HasRoleMapOwner(user, target) if role == Role.MAP_REVIEWER: return policy.HasRoleMapReviewer(user, target) if role == Role.MAP_EDITOR: return policy.HasRoleMapEditor(user, target) if role == Role.MAP_VIEWER: return policy.HasRoleMapViewer(user, target) raise ValueError('Invalid role %r' % role) def AssertAccess(role, target=None, user=None, policy=None): """Requires that the given user has the specified access role. Args: role: A Role constant identifying the desired access role. target: The object to which access is desired. If 'role' is in MAP_ROLES, this should be a Map object; if 'role' is in DOMAIN_ROLES, this should be a domain name (a string); otherwise, this argument is unused. user: (optional) A users.User object. If not specified, access permissions are checked for the currently signed-in user. policy: The access policy to apply. Raises: AuthorizationError: If the user lacks the given access permission. """ user = user or users.GetCurrent() # ensure user is set in error message if not CheckAccess(role, target=target, user=user, policy=policy): raise AuthorizationError(user, role, target) def AssertPublishable(map_object): """Requires that the given map be publishable.""" if map_object.is_blocked: raise NotPublishableError(map_object) def AssertCatalogEntryOwner(entry, user=None): user = user or users.GetCurrent() if user.id != entry.creator_uid: raise NotCatalogEntryOwnerError(user, entry)
#!/usr/bin/env python # @HEADER # ************************************************************************ # # TriBITS: Tribal Build, Integrate, and Test System # Copyright 2013 Sandia Corporation # # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains certain rights in this software. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Corporation nor the names of the # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE # 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. # # ************************************************************************ # @HEADER # # Defaults # gitBaseName = "git" gitDefaultVersion = "2.6.4" gitSupportedVersions = ["2.6.4"] gitTarballVersions = { "2.6.4" : "2.6.4", } # # Script code # from InstallProgramDriver import * from GeneralScriptSupport import * class GitInstall: def __init__(self): self.dummy = None # # Called before even knowing the product version # def getScriptName(self): return "install-git.py" def getProductBaseName(self): return gitBaseName def getProductDefaultVersion(self): return gitDefaultVersion def getProductSupportedVersions(self): return gitSupportedVersions # # Called after knowing the product version but before parsing the # command-line. # def getProductName(self, version): return gitBaseName+"-"+version def getBaseDirName(self, version): return gitBaseName+"-"+version+"-base" def getExtraHelpStr(self, version): return """ This script builds """+self.getProductName(version)+""" from source compiled with the configured C compiler in your path. This also installs the git-subtree provided in the contributed folder on install. To also build and install the documentaion, additionally, pass in: --with-doc --with-info (but note the extra packages that must be installed on the system). For more details on installing from source and required system dependencies before attempting this build, see: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git In particular, to build everything you will need to install the documentation (--with-doc and --with-info), you will need to install the packages 'asciidoc', 'xmlto', and 'docbook2X'. Again, see the above webpage for details (it is not 100% pretty). NOTE: The assumed directory structure of the download source provided by the command --download-cmnd=<download-cmnd> is: git-<version>-base/ git-<full-version>.tar.gz """ def injectExtraCmndLineOptions(self, clp, version): setStdDownloadCmndOption(self, clp, version) clp.add_option( "--extra-configure-options", dest="extraConfigureOptions", type="string", \ default="", \ help="Extra options to add to the 'configure' command for "+self.getProductName(version)+"." \ +" Note: This does not override the hard-coded configure options." ) clp.add_option( "--with-doc", dest="withDoc", action="store_true", default=False, help="Build and install manpage documentation (requires asciidoc and xmlto)." ) clp.add_option( "--with-info", dest="withInfo", action="store_true", default=False, help="Build and install info documentation (requires docbook2x)." ) def echoExtraCmndLineOptions(self, inOptions): cmndLine = "" cmndLine += " --download-cmnd='"+inOptions.downloadCmnd+"' \\\n" cmndLine += " --extra-configure-options='"+inOptions.extraConfigureOptions+"' \\\n" return cmndLine # # Called after parsing the command-line # def setup(self, inOptions): self.inOptions = inOptions self.baseDir = os.getcwd() self.gitBaseDir = self.baseDir+"/"+self.getBaseDirName(self.inOptions.version) gitVersionFull = gitTarballVersions[self.inOptions.version] self.gitTarball = "git-"+gitVersionFull+".tar.gz" self.gitSrcDir = "git-"+gitVersionFull self.gitSrcBuildDir = self.gitBaseDir+"/"+self.gitSrcDir self.gitSubtreeSrcBuildDir = self.gitSrcBuildDir+"/contrib/subtree" self.scriptBaseDir = getScriptBaseDir() # # Called after setup() # def doDownload(self): removeDirIfExists(self.gitBaseDir, True) echoRunSysCmnd(self.inOptions.downloadCmnd) def doUntar(self): # Find the full name of the source tarball echoChDir(self.gitBaseDir) echoRunSysCmnd("tar -xzf "+self.gitTarball) def doConfigure(self): echoChDir(self.gitSrcBuildDir) echoRunSysCmnd("make configure") echoRunSysCmnd( "./configure "+\ " "+self.inOptions.extraConfigureOptions+\ " --prefix="+self.inOptions.installDir ) # NOTE: Git appears to only allow an in-source build :-( def doBuild(self): echoChDir(self.gitSrcBuildDir) echoRunSysCmnd("make "+getParallelOpt(self.inOptions, "-j")+\ self.inOptions.makeOptions+" all") if self.inOptions.withDoc: echoRunSysCmnd("make "+getParallelOpt(self.inOptions, "-j")+\ self.inOptions.makeOptions+" doc") if self.inOptions.withInfo: echoRunSysCmnd("make "+getParallelOpt(self.inOptions, "-j")+\ self.inOptions.makeOptions+" info") # Build git-subtree to get ready to install echoChDir(self.gitSubtreeSrcBuildDir) def doInstall(self): echoChDir(self.gitSrcBuildDir) echoRunSysCmnd("make "+self.inOptions.makeOptions+" install") if self.inOptions.withDoc: echoRunSysCmnd("make "+self.inOptions.makeOptions+" install-doc") echoRunSysCmnd("make "+self.inOptions.makeOptions+" install-html") if self.inOptions.withInfo: echoRunSysCmnd("make "+self.inOptions.makeOptions+" install-info") # Install git-subtree and documentation echoChDir(self.gitSubtreeSrcBuildDir) echoRunSysCmnd("make "+self.inOptions.makeOptions+" install") if self.inOptions.withDoc: echoRunSysCmnd("make "+self.inOptions.makeOptions+" install-doc") def getFinalInstructions(self): return """ To use the installed version of git-"""+self.inOptions.version+""" add the path: """+self.inOptions.installDir+"""/bin to your path and that should be it! """ # # Executable statements # gitInstaller = InstallProgramDriver(GitInstall()) gitInstaller.runDriver()
from __future__ import unicode_literals import copy import sys from functools import update_wrapper from django.utils.six.moves import zip from django.apps import apps from django.apps.base import MODELS_MODULE_NAME import django.db.models.manager # NOQA: Imported to register signal handler. from django.conf import settings from django.core.exceptions import (ObjectDoesNotExist, MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS) from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields.related import (ForeignObjectRel, ManyToOneRel, OneToOneField, add_lazy_relation) from django.db import (router, transaction, DatabaseError, DEFAULT_DB_ALIAS) from django.db.models.query import Q from django.db.models.query_utils import DeferredAttribute, deferred_class_factory from django.db.models.deletion import Collector from django.db.models.options import Options from django.db.models import signals from django.utils.translation import ugettext_lazy as _ from django.utils.functional import curry from django.utils.encoding import force_str, force_text from django.utils import six from django.utils.text import get_text_list, capfirst def subclass_exception(name, parents, module, attached_to=None): """ Create exception subclass. Used by ModelBase below. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class. """ class_dict = {'__module__': module} if attached_to is not None: def __reduce__(self): # Exceptions are special - they've got state that isn't # in self.__dict__. We assume it is all in self.args. return (unpickle_inner_exception, (attached_to, name), self.args) def __setstate__(self, args): self.args = args class_dict['__reduce__'] = __reduce__ class_dict['__setstate__'] = __setstate__ return type(name, parents, class_dict) class ModelBase(type): """ Metaclass for all models. """ def __new__(cls, name, bases, attrs): super_new = super(ModelBase, cls).__new__ # six.with_metaclass() inserts an extra class called 'NewBase' in the # inheritance tree: Model -> NewBase -> object. But the initialization # should be executed only once for a given model class. # attrs will never be empty for classes declared in the standard way # (ie. with the `class` keyword). This is quite robust. if name == 'NewBase' and attrs == {}: return super_new(cls, name, bases, attrs) # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). parents = [b for b in bases if isinstance(b, ModelBase) and not (b.__name__ == 'NewBase' and b.__mro__ == (b, object))] if not parents: return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop('__module__') new_class = super_new(cls, name, bases, {'__module__': module}) attr_meta = attrs.pop('Meta', None) abstract = getattr(attr_meta, 'abstract', False) if not attr_meta: meta = getattr(new_class, 'Meta', None) else: meta = attr_meta base_meta = getattr(new_class, '_meta', None) # Look for an application configuration to attach the model to. app_config = apps.get_containing_app_config(module) if getattr(meta, 'app_label', None) is None: if app_config is None: # If the model is imported before the configuration for its # application is created (#21719), or isn't in an installed # application (#21680), use the legacy logic to figure out the # app_label by looking one level up from the package or module # named 'models'. If no such package or module exists, fall # back to looking one level up from the module this model is # defined in. # For 'django.contrib.sites.models', this would be 'sites'. # For 'geo.models.places' this would be 'geo'. model_module = sys.modules[new_class.__module__] package_components = model_module.__name__.split('.') package_components.reverse() # find the last occurrence of 'models' try: app_label_index = package_components.index(MODELS_MODULE_NAME) + 1 except ValueError: app_label_index = 1 kwargs = {"app_label": package_components[app_label_index]} else: kwargs = {"app_label": app_config.label} else: kwargs = {} new_class.add_to_class('_meta', Options(meta, **kwargs)) if not abstract: new_class.add_to_class( 'DoesNotExist', subclass_exception( str('DoesNotExist'), tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist,), module, attached_to=new_class)) new_class.add_to_class( 'MultipleObjectsReturned', subclass_exception( str('MultipleObjectsReturned'), tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned,), module, attached_to=new_class)) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, 'ordering'): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, 'get_latest_by'): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy # If the model is a proxy, ensure that the base class # hasn't been swapped out. if is_proxy and base_meta and base_meta.swapped: raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped)) if getattr(new_class, '_default_manager', None): if not is_proxy: # Multi-table inheritance doesn't inherit default manager from # parents. new_class._default_manager = None new_class._base_manager = None else: # Proxy classes do inherit parent's default manager, if none is # set explicitly. new_class._default_manager = new_class._default_manager._copy_to_model(new_class) new_class._base_manager = new_class._base_manager._copy_to_model(new_class) # Add all attributes to the class. for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = ( new_class._meta.local_fields + new_class._meta.local_many_to_many + new_class._meta.virtual_fields ) field_names = set(f.name for f in new_fields) # Basic setup for proxy models. if is_proxy: base = None for parent in [kls for kls in parents if hasattr(kls, '_meta')]: if parent._meta.abstract: if parent._meta.fields: raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name) else: continue if base is not None: raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name) else: base = parent if base is None: raise TypeError("Proxy model '%s' has no non-abstract model base class." % name) if (new_class._meta.local_fields or new_class._meta.local_many_to_many): raise FieldError("Proxy model '%s' contains model fields." % name) new_class._meta.setup_proxy(base) new_class._meta.concrete_model = base._meta.concrete_model else: new_class._meta.concrete_model = new_class # Collect the parent links for multi-table inheritance. parent_links = {} for base in reversed([new_class] + parents): # Conceptually equivalent to `if base is Model`. if not hasattr(base, '_meta'): continue # Skip concrete parent classes. if base != new_class and not base._meta.abstract: continue # Locate OneToOneField instances. for field in base._meta.local_fields: if isinstance(field, OneToOneField): parent_links[field.rel.to] = field # Do the appropriate setup for any model parents. for base in parents: original_base = base if not hasattr(base, '_meta'): # Things without _meta aren't functional models, so they're # uninteresting parents. continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many # Check for clashes between locally declared fields and those # on the base classes (we cannot handle shadowed fields at the # moment). for field in parent_fields: if field.name in field_names: raise FieldError( 'Local field %r in class %r clashes ' 'with field of similar name from ' 'base class %r' % (field.name, name, base.__name__) ) if not base._meta.abstract: # Concrete classes... base = base._meta.concrete_model if base in parent_links: field = parent_links[base] elif not is_proxy: attr_name = '%s_ptr' % base._meta.model_name field = OneToOneField(base, name=attr_name, auto_created=True, parent_link=True) new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: # .. and abstract ones. for field in parent_fields: new_class.add_to_class(field.name, copy.deepcopy(field)) # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base._meta.parents) # Inherit managers from the abstract base classes. new_class.copy_managers(base._meta.abstract_managers) # Proxy models inherit the non-abstract managers from their base, # unless they have redefined any of them. if is_proxy: new_class.copy_managers(original_base._meta.concrete_managers) # Inherit virtual fields (like GenericForeignKey) from the parent # class for field in base._meta.virtual_fields: if base._meta.abstract and field.name in field_names: raise FieldError( 'Local field %r in class %r clashes ' 'with field of similar name from ' 'abstract base class %r' % (field.name, name, base.__name__) ) new_class.add_to_class(field.name, copy.deepcopy(field)) if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() new_class._meta.apps.register_model(new_class._meta.app_label, new_class) return new_class def copy_managers(cls, base_managers): # This is in-place sorting of an Options attribute, but that's fine. base_managers.sort() for _, mgr_name, manager in base_managers: # NOQA (redefinition of _) val = getattr(cls, mgr_name, None) if not val or val is manager: new_manager = manager._copy_to_model(cls) cls.add_to_class(mgr_name, new_manager) def add_to_class(cls, name, value): if hasattr(value, 'contribute_to_class'): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _prepare(cls): """ Creates some methods once self._meta has been populated. """ opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True) cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False) # defer creating accessors on the foreign class until we are # certain it has been created def make_foreign_order_accessors(field, model, cls): setattr( field.rel.to, 'get_%s_order' % cls.__name__.lower(), curry(method_get_order, cls) ) setattr( field.rel.to, 'set_%s_order' % cls.__name__.lower(), curry(method_set_order, cls) ) add_lazy_relation( cls, opts.order_with_respect_to, opts.order_with_respect_to.rel.to, make_foreign_order_accessors ) # Give the class a docstring -- its definition. if cls.__doc__ is None: cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.attname for f in opts.fields)) if hasattr(cls, 'get_absolute_url'): cls.get_absolute_url = update_wrapper(curry(get_absolute_url, opts, cls.get_absolute_url), cls.get_absolute_url) signals.class_prepared.send(sender=cls) class ModelState(object): """ A class for storing instance state """ def __init__(self, db=None): self.db = db # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object. # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs. # This impacts validation only; it has no effect on the actual save. self.adding = True class Model(six.with_metaclass(ModelBase)): _deferred = False def __init__(self, *args, **kwargs): signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs) # Set up the storage for instance state self._state = ModelState() # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check is that standard iterator passes in by # args, and instantiation for iteration is 33% faster. args_len = len(args) if args_len > len(self._meta.concrete_fields): # Daft, but matches old exception sans the err msg. raise IndexError("Number of args exceeds number of fields") if not kwargs: fields_iter = iter(self._meta.concrete_fields) # The ordering of the zip calls matter - zip throws StopIteration # when an iter throws it. So if the first iter throws it, the second # is *not* consumed. We rely on this, so don't change the order # without changing the logic. for val, field in zip(args, fields_iter): setattr(self, field.attname, val) else: # Slower, kwargs-ready version. fields_iter = iter(self._meta.fields) for val, field in zip(args, fields_iter): setattr(self, field.attname, val) kwargs.pop(field.name, None) # Maintain compatibility with existing calls. if isinstance(field.rel, ManyToOneRel): kwargs.pop(field.attname, None) # Now we're left with the unprocessed fields that *must* come from # keywords, or default. for field in fields_iter: is_related_object = False # This slightly odd construct is so that we can access any # data-descriptor object (DeferredAttribute) without triggering its # __get__ method. if (field.attname not in kwargs and (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute) or field.column is None)): # This field will be populated on request. continue if kwargs: if isinstance(field.rel, ForeignObjectRel): try: # Assume object instance was passed in. rel_obj = kwargs.pop(field.name) is_related_object = True except KeyError: try: # Object instance wasn't passed in -- must be an ID. val = kwargs.pop(field.attname) except KeyError: val = field.get_default() else: # Object instance was passed in. Special case: You can # pass in "None" for related objects if it's allowed. if rel_obj is None and field.null: val = None else: try: val = kwargs.pop(field.attname) except KeyError: # This is done with an exception rather than the # default argument on pop because we don't want # get_default() to be evaluated, and then not used. # Refs #12057. val = field.get_default() else: val = field.get_default() if is_related_object: # If we are passed a related instance, set it using the # field.name instead of field.attname (e.g. "user" instead of # "user_id") so that the object gets properly cached (and type # checked) by the RelatedObjectDescriptor. setattr(self, field.name, rel_obj) else: setattr(self, field.attname, val) if kwargs: for prop in list(kwargs): try: if isinstance(getattr(self.__class__, prop), property): setattr(self, prop, kwargs.pop(prop)) except AttributeError: pass if kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) super(Model, self).__init__() signals.post_init.send(sender=self.__class__, instance=self) def __repr__(self): try: u = six.text_type(self) except (UnicodeEncodeError, UnicodeDecodeError): u = '[Bad Unicode data]' return force_str('<%s: %s>' % (self.__class__.__name__, u)) def __str__(self): if six.PY2 and hasattr(self, '__unicode__'): return force_text(self).encode('utf-8') return '%s object' % self.__class__.__name__ def __eq__(self, other): if not isinstance(other, Model): return False if self._meta.concrete_model != other._meta.concrete_model: return False my_pk = self._get_pk_val() if my_pk is None: return self is other return my_pk == other._get_pk_val() def __ne__(self, other): return not self.__eq__(other) def __hash__(self): if self._get_pk_val() is None: raise TypeError("Model instances without primary key value are unhashable") return hash(self._get_pk_val()) def __reduce__(self): """ Provides pickling support. Normally, this just dispatches to Python's standard handling. However, for models with deferred field loading, we need to do things manually, as they're dynamically created classes and only module-level classes can be pickled by the default path. """ data = self.__dict__ if not self._deferred: class_id = self._meta.app_label, self._meta.object_name return model_unpickle, (class_id, [], simple_class_factory), data defers = [] for field in self._meta.fields: if isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute): defers.append(field.attname) model = self._meta.proxy_for_model class_id = model._meta.app_label, model._meta.object_name return (model_unpickle, (class_id, defers, deferred_class_factory), data) def _get_pk_val(self, meta=None): if not meta: meta = self._meta return getattr(self, meta.pk.attname) def _set_pk_val(self, value): return setattr(self, self._meta.pk.attname, value) pk = property(_get_pk_val, _set_pk_val) def serializable_value(self, field_name): """ Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ try: field = self._meta.get_field_by_name(field_name)[0] except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.attname) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Saves the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set. """ using = using or router.db_for_write(self.__class__, instance=self) if force_insert and (force_update or update_fields): raise ValueError("Cannot force both insert and updating in model saving.") if update_fields is not None: # If update_fields is empty, skip the save. We do also check for # no-op saves later on for inheritance cases. This bailout is # still needed for skipping signal sending. if len(update_fields) == 0: return update_fields = frozenset(update_fields) field_names = set() for field in self._meta.fields: if not field.primary_key: field_names.add(field.name) if field.name != field.attname: field_names.add(field.attname) non_model_fields = update_fields.difference(field_names) if non_model_fields: raise ValueError("The following fields do not exist in this " "model or are m2m fields: %s" % ', '.join(non_model_fields)) # If saving to the same database, and this model is deferred, then # automatically do a "update_fields" save on the loaded fields. elif not force_insert and self._deferred and using == self._state.db: field_names = set() for field in self._meta.concrete_fields: if not field.primary_key and not hasattr(field, 'through'): field_names.add(field.attname) deferred_fields = [ f.attname for f in self._meta.fields if (f.attname not in self.__dict__ and isinstance(self.__class__.__dict__[f.attname], DeferredAttribute)) ] loaded_fields = field_names.difference(deferred_fields) if loaded_fields: update_fields = frozenset(loaded_fields) self.save_base(using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields) save.alters_data = True def save_base(self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None): """ Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading. """ using = using or router.db_for_write(self.__class__, instance=self) assert not (force_insert and (force_update or update_fields)) assert update_fields is None or len(update_fields) > 0 cls = origin = self.__class__ # Skip proxies, but keep the origin as the proxy model. if cls._meta.proxy: cls = cls._meta.concrete_model meta = cls._meta if not meta.auto_created: signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using, update_fields=update_fields) with transaction.commit_on_success_unless_managed(using=using, savepoint=False): if not raw: self._save_parents(cls, using, update_fields) updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) # Store the database on which the object was saved self._state.db = using # Once saved, this is no longer a to-be-added instance. self._state.adding = False # Signal that the save is complete if not meta.auto_created: signals.post_save.send(sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using) save_base.alters_data = True def _save_parents(self, cls, using, update_fields): """ Saves all the parents of cls using values from self. """ meta = cls._meta for parent, field in meta.parents.items(): # Make sure the link fields are synced between parent and self. if (field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None): setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) self._save_parents(cls=parent, using=using, update_fields=update_fields) self._save_table(cls=parent, using=using, update_fields=update_fields) # Set the parent's PK value to self. if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) # Since we didn't have an instance of the parent handy set # attname directly, bypassing the descriptor. Invalidate # the related object cache, in case it's been accidentally # populated. A fresh instance will be re-built from the # database if necessary. cache_name = field.get_cache_name() if hasattr(self, cache_name): delattr(self, cache_name) def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Does the heavy-lifting involved in saving. Updates or inserts the data for a single table. """ meta = cls._meta non_pks = [f for f in meta.local_concrete_fields if not f.primary_key] if update_fields: non_pks = [f for f in non_pks if f.name in update_fields or f.attname in update_fields] pk_val = self._get_pk_val(meta) pk_set = pk_val is not None if not pk_set and (force_update or update_fields): raise ValueError("Cannot force an update in save() with no primary key.") updated = False # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) for f in non_pks] forced_update = update_fields or force_update updated = self._do_update(base_qs, using, pk_val, values, update_fields, forced_update) if force_update and not updated: raise DatabaseError("Forced update did not affect any rows.") if update_fields and not updated: raise DatabaseError("Save with update_fields did not affect any rows.") if not updated: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to order_value = cls._base_manager.using(using).filter( **{field.name: getattr(self, field.attname)}).count() self._order = order_value fields = meta.local_concrete_fields if not pk_set: fields = [f for f in fields if not isinstance(f, AutoField)] update_pk = bool(meta.has_auto_field and not pk_set) result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) if update_pk: setattr(self, meta.pk.attname, result) return updated def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update): """ This method will try to update the model. If the model was updated (in the sense that an update query was done and a matching row was found from the DB) the method will return True. """ filtered = base_qs.filter(pk=pk_val) if not values: # We can end up here when saving a model in inheritance chain where # update_fields doesn't target any field in current model. In that # case we just say the update succeeded. Another case ending up here # is a model with just PK - in that case check that the PK still # exists. return update_fields is not None or filtered.exists() if self._meta.select_on_save and not forced_update: if filtered.exists(): filtered._update(values) return True else: return False return filtered._update(values) > 0 def _do_insert(self, manager, using, fields, update_pk, raw): """ Do an INSERT. If update_pk is defined then this method should return the new pk for the model. """ return manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) def delete(self, using=None): using = using or router.db_for_write(self.__class__, instance=self) assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) collector = Collector(using=using) collector.collect([self]) collector.delete() delete.alters_data = True def _get_FIELD_display(self, field): value = getattr(self, field.attname) return force_text(dict(field.flatchoices).get(value, value), strings_only=True) def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): if not self.pk: raise ValueError("get_next/get_previous cannot be used on unsaved objects.") op = 'gt' if is_next else 'lt' order = '' if is_next else '-' param = force_text(getattr(self, field.attname)) q = Q(**{'%s__%s' % (field.name, op): param}) q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk}) qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by('%s%s' % (order, field.name), '%spk' % order) try: return qs[0] except IndexError: raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name) def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): op = 'gt' if is_next else 'lt' order = '_order' if is_next else '-_order' order_field = self._meta.order_with_respect_to obj = self._default_manager.filter(**{ order_field.name: getattr(self, order_field.attname) }).filter(**{ '_order__%s' % op: self._default_manager.values('_order').filter(**{ self._meta.pk.name: self.pk }) }).order_by(order)[:1].get() setattr(self, cachename, obj) return getattr(self, cachename) def prepare_database_save(self, unused): if self.pk is None: raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self) return self.pk def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS. """ pass def validate_unique(self, exclude=None): """ Checks unique constraints on the model and raises ``ValidationError`` if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors = self._perform_date_checks(date_checks) for k, v in date_errors.items(): errors.setdefault(k, []).extend(v) if errors: raise ValidationError(errors) def _get_unique_checks(self, exclude=None): """ Gather a list of checks to perform. Since validate_unique could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but they need to be passed in via the exclude argument. """ if exclude is None: exclude = [] unique_checks = [] unique_togethers = [(self.__class__, self._meta.unique_together)] for parent_class in self._meta.parents.keys(): if parent_class._meta.unique_together: unique_togethers.append((parent_class, parent_class._meta.unique_together)) for model_class, unique_together in unique_togethers: for check in unique_together: for name in check: # If this is an excluded field, don't add this check. if name in exclude: break else: unique_checks.append((model_class, tuple(check))) # These are checks for the unique_for_<date/year/month>. date_checks = [] # Gather a list of checks for fields declared as unique and add them to # the list of checks. fields_with_class = [(self.__class__, self._meta.local_fields)] for parent_class in self._meta.parents.keys(): fields_with_class.append((parent_class, parent_class._meta.local_fields)) for model_class, fields in fields_with_class: for f in fields: name = f.name if name in exclude: continue if f.unique: unique_checks.append((model_class, (name,))) if f.unique_for_date and f.unique_for_date not in exclude: date_checks.append((model_class, 'date', name, f.unique_for_date)) if f.unique_for_year and f.unique_for_year not in exclude: date_checks.append((model_class, 'year', name, f.unique_for_year)) if f.unique_for_month and f.unique_for_month not in exclude: date_checks.append((model_class, 'month', name, f.unique_for_month)) return unique_checks, date_checks def _perform_unique_checks(self, unique_checks): errors = {} for model_class, unique_check in unique_checks: # Try to look up an existing object with the same values as this # object's values for all the unique field. lookup_kwargs = {} for field_name in unique_check: f = self._meta.get_field(field_name) lookup_value = getattr(self, f.attname) if lookup_value is None: # no value, skip the lookup continue if f.primary_key and not self._state.adding: # no need to check for unique primary key when editing continue lookup_kwargs[str(field_name)] = lookup_value # some fields were skipped, no reason to do the check if len(unique_check) != len(lookup_kwargs): continue qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) # Note that we need to use the pk as defined by model_class, not # self.pk. These can be different fields because model inheritance # allows single model to have effectively multiple primary keys. # Refs #17615. model_class_pk = self._get_pk_val(model_class._meta) if not self._state.adding and model_class_pk is not None: qs = qs.exclude(pk=model_class_pk) if qs.exists(): if len(unique_check) == 1: key = unique_check[0] else: key = NON_FIELD_ERRORS errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check)) return errors def _perform_date_checks(self, date_checks): errors = {} for model_class, lookup_type, field, unique_for in date_checks: lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == 'date': lookup_kwargs['%s__day' % unique_for] = date.day lookup_kwargs['%s__month' % unique_for] = date.month lookup_kwargs['%s__year' % unique_for] = date.year else: lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type) lookup_kwargs[field] = getattr(self, field) qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): errors.setdefault(field, []).append( self.date_error_message(lookup_type, field, unique_for) ) return errors def date_error_message(self, lookup_type, field, unique_for): opts = self._meta return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % { 'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)), 'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)), 'lookup': lookup_type, } def unique_error_message(self, model_class, unique_check): opts = model_class._meta model_name = capfirst(opts.verbose_name) # A unique field if len(unique_check) == 1: field_name = unique_check[0] field = opts.get_field(field_name) field_label = capfirst(field.verbose_name) # Insert the error into the error dict, very sneaky return field.error_messages['unique'] % { 'model_name': six.text_type(model_name), 'field_label': six.text_type(field_label) } # unique_together else: field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check] field_labels = get_text_list(field_labels, _('and')) return _("%(model_name)s with this %(field_label)s already exists.") % { 'model_name': six.text_type(model_name), 'field_label': six.text_type(field_labels) } def full_clean(self, exclude=None, validate_unique=True): """ Calls clean_fields, clean, and validate_unique, on the model, and raises a ``ValidationError`` for any errors that occurred. """ errors = {} if exclude is None: exclude = [] try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors.keys(): if name != NON_FIELD_ERRORS and name not in exclude: exclude.append(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def clean_fields(self, exclude=None): """ Cleans all fields and raises a ValidationError containing a dict of all validation errors if any occur. """ if exclude is None: exclude = [] errors = {} for f in self._meta.fields: if f.name in exclude: continue # Skip validation for empty fields with blank=True. The developer # is responsible for making sure they have a valid value. raw_value = getattr(self, f.attname) if f.blank and raw_value in f.empty_values: continue try: setattr(self, f.attname, f.clean(raw_value, self)) except ValidationError as e: errors[f.name] = e.error_list if errors: raise ValidationError(errors) ############################################ # HELPER FUNCTIONS (CURRIED MODEL METHODS) # ############################################ # ORDERING METHODS ######################### def method_set_order(ordered_obj, self, id_list, using=None): if using is None: using = DEFAULT_DB_ALIAS rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) order_name = ordered_obj._meta.order_with_respect_to.name # FIXME: It would be nice if there was an "update many" version of update # for situations like this. with transaction.commit_on_success_unless_managed(using=using): for i, j in enumerate(id_list): ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i) def method_get_order(ordered_obj, self): rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) order_name = ordered_obj._meta.order_with_respect_to.name pk_name = ordered_obj._meta.pk.name return [r[pk_name] for r in ordered_obj.objects.filter(**{order_name: rel_val}).values(pk_name)] ############################################## # HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) # ############################################## def get_absolute_url(opts, func, self, *args, **kwargs): return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.model_name), func)(self, *args, **kwargs) ######## # MISC # ######## def simple_class_factory(model, attrs): """ Needed for dynamic classes. """ return model def model_unpickle(model_id, attrs, factory): """ Used to unpickle Model subclasses with deferred fields. """ if isinstance(model_id, tuple): model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id cls = factory(model, attrs) return cls.__new__(cls) model_unpickle.__safe_for_unpickle__ = True def unpickle_inner_exception(klass, exception_name): # Get the exception class from the class it is attached to: exception = getattr(klass, exception_name) return exception.__new__(exception)
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page class CompositionSettingsList(ListResource): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version): """ Initialize the CompositionSettingsList :param Version version: Version that contains the resource :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsList :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList """ super(CompositionSettingsList, self).__init__(version) # Path Solution self._solution = {} def get(self): """ Constructs a CompositionSettingsContext :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext """ return CompositionSettingsContext(self._version, ) def __call__(self): """ Constructs a CompositionSettingsContext :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext """ return CompositionSettingsContext(self._version, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.CompositionSettingsList>' class CompositionSettingsPage(Page): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, response, solution): """ Initialize the CompositionSettingsPage :param Version version: Version that contains the resource :param Response response: Response from the API :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsPage :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsPage """ super(CompositionSettingsPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of CompositionSettingsInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ return CompositionSettingsInstance(self._version, payload, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.CompositionSettingsPage>' class CompositionSettingsContext(InstanceContext): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version): """ Initialize the CompositionSettingsContext :param Version version: Version that contains the resource :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext """ super(CompositionSettingsContext, self).__init__(version) # Path Solution self._solution = {} self._uri = '/CompositionSettings/Default'.format(**self._solution) def fetch(self): """ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return CompositionSettingsInstance(self._version, payload, ) def create(self, friendly_name, aws_credentials_sid=values.unset, encryption_key_sid=values.unset, aws_s3_url=values.unset, aws_storage_enabled=values.unset, encryption_enabled=values.unset): """ Create a new CompositionSettingsInstance :param unicode friendly_name: A descriptive string that you create to describe the resource :param unicode aws_credentials_sid: The SID of the stored Credential resource :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption :param unicode aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored :param bool aws_storage_enabled: Whether all compositions should be written to the aws_s3_url :param bool encryption_enabled: Whether all compositions should be stored in an encrypted form :returns: Newly created CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ data = values.of({ 'FriendlyName': friendly_name, 'AwsCredentialsSid': aws_credentials_sid, 'EncryptionKeySid': encryption_key_sid, 'AwsS3Url': aws_s3_url, 'AwsStorageEnabled': aws_storage_enabled, 'EncryptionEnabled': encryption_enabled, }) payload = self._version.create( 'POST', self._uri, data=data, ) return CompositionSettingsInstance(self._version, payload, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.CompositionSettingsContext {}>'.format(context) class CompositionSettingsInstance(InstanceResource): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, payload): """ Initialize the CompositionSettingsInstance :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ super(CompositionSettingsInstance, self).__init__(version) # Marshaled Properties self._properties = { 'account_sid': payload.get('account_sid'), 'friendly_name': payload.get('friendly_name'), 'aws_credentials_sid': payload.get('aws_credentials_sid'), 'aws_s3_url': payload.get('aws_s3_url'), 'aws_storage_enabled': payload.get('aws_storage_enabled'), 'encryption_key_sid': payload.get('encryption_key_sid'), 'encryption_enabled': payload.get('encryption_enabled'), 'url': payload.get('url'), } # Context self._context = None self._solution = {} @property def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: CompositionSettingsContext for this CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext """ if self._context is None: self._context = CompositionSettingsContext(self._version, ) return self._context @property def account_sid(self): """ :returns: The SID of the Account that created the resource :rtype: unicode """ return self._properties['account_sid'] @property def friendly_name(self): """ :returns: The string that you assigned to describe the resource :rtype: unicode """ return self._properties['friendly_name'] @property def aws_credentials_sid(self): """ :returns: The SID of the stored Credential resource :rtype: unicode """ return self._properties['aws_credentials_sid'] @property def aws_s3_url(self): """ :returns: The URL of the AWS S3 bucket where the compositions are stored :rtype: unicode """ return self._properties['aws_s3_url'] @property def aws_storage_enabled(self): """ :returns: Whether all compositions are written to the aws_s3_url :rtype: bool """ return self._properties['aws_storage_enabled'] @property def encryption_key_sid(self): """ :returns: The SID of the Public Key resource used for encryption :rtype: unicode """ return self._properties['encryption_key_sid'] @property def encryption_enabled(self): """ :returns: Whether all compositions are stored in an encrypted form :rtype: bool """ return self._properties['encryption_enabled'] @property def url(self): """ :returns: The absolute URL of the resource :rtype: unicode """ return self._properties['url'] def fetch(self): """ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ return self._proxy.fetch() def create(self, friendly_name, aws_credentials_sid=values.unset, encryption_key_sid=values.unset, aws_s3_url=values.unset, aws_storage_enabled=values.unset, encryption_enabled=values.unset): """ Create a new CompositionSettingsInstance :param unicode friendly_name: A descriptive string that you create to describe the resource :param unicode aws_credentials_sid: The SID of the stored Credential resource :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption :param unicode aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored :param bool aws_storage_enabled: Whether all compositions should be written to the aws_s3_url :param bool encryption_enabled: Whether all compositions should be stored in an encrypted form :returns: Newly created CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ return self._proxy.create( friendly_name, aws_credentials_sid=aws_credentials_sid, encryption_key_sid=encryption_key_sid, aws_s3_url=aws_s3_url, aws_storage_enabled=aws_storage_enabled, encryption_enabled=encryption_enabled, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.CompositionSettingsInstance {}>'.format(context)
# Copyright 2017 Balazs Nemeth, Mark Szalay, Janos Doka # # 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 Queue import datetime import json import logging import pprint import shutil import subprocess import sys import threading import psutil try: # runs when mapping files are called from ESCAPE from escape.nffg_lib.nffg import NFFG, NFFGToolBox except ImportError: # runs when mapping repo is cloned individually, and NFFG lib is in a # sibling directory. WARNING: cicular import is not avioded by design. import site site.addsitedir('..') from nffg_lib.nffg import NFFG, NFFGToolBox import alg1.UnifyExceptionTypes as uet from simulation.OrchestratorAdaptor import * from simulation.RequestGenerator import * from simulation.ResourceGetter import * log = logging.getLogger(" Simulator") class SimulationCounters(): def __init__(self, premapped_request_count, premapped_vnf_count): """ Initializes all the counters """ # NOTE: Counters MUST NOT be modified from outside! self.sim_iter = 0 self.dump_iter = 0 self.mapped_requests = 0 self.mapped_array = [0] self.refused_requests = 0 self.refused_array = [0] self.running_vnf_count = premapped_vnf_count self.running_requests = premapped_request_count self.running_array = [premapped_request_count] def _log_running_refused_mapped_counters(self): log.info("Simulation iteration count: "+str(self.sim_iter)) log.info("Mapped service_requests count: " + str(self.mapped_requests)) log.info("Running service_requests count: " + str(self.running_requests)) log.info("Refused service_requests count: " + str(self.refused_requests)) log.info("Running VNF count: " + str(self.running_vnf_count)) def successful_mapping_happened(self, new_vnf_cnt=0): self.sim_iter += 1 self.dump_iter += 1 self.mapped_requests += 1 self.mapped_array.append(self.mapped_requests) self.running_requests += 1 self.running_array.append(self.running_requests) self.running_vnf_count += new_vnf_cnt self._log_running_refused_mapped_counters() def unsuccessful_mapping_happened(self): self.sim_iter += 1 self.refused_requests += 1 self.refused_array.append(self.refused_requests) self._log_running_refused_mapped_counters() def purging_all_expired_requests(self): self.dump_iter += 1 def deleting_one_expired_service(self, del_vnf_vnf=0): self.running_requests -= 1 self.running_array.append(self.running_requests) self.running_vnf_count -= del_vnf_vnf def incoming_request_buffer_overflow_happened(self): # meaning this mapping iteration was handled very fast, the request # was discarded! # NOTE: currently handled the same as unsuccessful mapping! self.sim_iter += 1 self.refused_requests += 1 self.refused_array.append(self.refused_requests) self._log_running_refused_mapped_counters() class MappingSolutionFramework(): def __init__(self, config_file_path): config = ConfigObj(config_file_path) self.sim_number = int(config['simulation_number']) self.orchestrator_type = config['orchestrator'] if not os.path.exists('test' + str(self.sim_number) + self.orchestrator_type): os.mkdir('test' + str(self.sim_number) + self.orchestrator_type) self.path = os.path.abspath( 'test' + str(self.sim_number) + self.orchestrator_type) self.full_log_path = self.path + '/log_file' + str (time.ctime()).\ replace(' ', '_').replace(':', '-') +'.log' formatter = logging.Formatter( '%(asctime)s | Simulator | %(levelname)s | \t%(message)s') hdlr = logging.FileHandler(self.full_log_path) hdlr.setFormatter(formatter) log.addHandler(hdlr) log.setLevel(logging.DEBUG) git_commit = subprocess.check_output(['git', 'show', '--oneline', '-s']) git_branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) log.info("Configuration file: " + str(config_file_path)) log.info("Git current commit: " + str(git_commit)) log.info("Git current branch: " + str(str(git_branch))) log.info(" | Full configuration object dumped: \n" + str( pprint.pformat(dict(config)))) log.info(" ----------------------------------------") log.info(" Start simulation") log.info(" ------ Simulation configurations -------") log.info(" | Simulation number: " + str(config['simulation_number'])) log.info(" | Discrete: " + str(config['discrete_simulation'])) log.info(" | Topology: " + str(config['topology'])) log.info(" | Request type: " + str(config['request_type'])) log.info(" | Orchestrator: " + str(config['orchestrator'])) log.info(" | Dump freq: " + str(config['dump_freq'])) log.info(" | Request arrival lambda: " + str(config['request_arrival_lambda'])) log.info(" | Request flifetime lambda: " + str(config['request_lifetime_lambda'])) log.info(" | Request max latency: " + str(config['request_max_lat'])) log.info(" | Request min latency: " + str(config['request_min_lat'])) log.info(" | Request nf types: " + str(config['request_nf_type_count'])) log.info(" | Request seed: " + str(config['request_seed'])) log.info(" | Number of iteration: " + str(config['max_number_of_iterations'])) log.info(" | Wait all request to expire (nothing = False): " + str(config['wait_all_req_expire'])) log.info(" | Request queue size: " + str(int(config['req_queue_size']))) log.info(" ----------------------------------------") self.dump_freq = int(config['dump_freq']) self.last_dump_number = None self.max_number_of_iterations = int(config['max_number_of_iterations']) self.request_arrival_lambda = float(config['request_arrival_lambda']) self.wait_all_req_expire = bool(config['wait_all_req_expire']) self.request_lifetime_lambda = float(config['request_lifetime_lambda']) self.req_queue_size = int(config['req_queue_size']) # This stores the request waiting to be mapped self.__request_list = Queue.Queue() self.last_req_num = 0 self.request_gen_iter = 1 self.copy_of_rg_network_topology = None # Any MAP function ends before a new request arrives, no threads are # started, everything is sequential. self.__discrete_simulation = bool(config['discrete_simulation']) # represents simulation time, NOT real time! self.discrete_simulation_timer = 0.0 # Request request_type = config['request_type'] request_seed = int(config['request_seed']) nf_type_count = int(config['request_nf_type_count']) if request_type == "test": self.__request_generator = TestReqGen(self.request_lifetime_lambda, nf_type_count, request_seed) elif request_type == "simple": if 'request_min_lat' in config and 'request_max_lat' in config: minlat = float(config['request_min_lat']) maxlat = float(config['request_max_lat']) self.__request_generator = SimpleReqGen( self.request_lifetime_lambda, nf_type_count, request_seed, min_lat=minlat, max_lat=maxlat) else: self.__request_generator = SimpleReqGen( self.request_lifetime_lambda, nf_type_count, request_seed) elif request_type == "multi": self.__request_generator = MultiReqGen(self.request_lifetime_lambda, nf_type_count, request_seed) elif request_type == "simple_equilibrium": minlat = float(config['request_min_lat']) maxlat = float(config['request_max_lat']) # optional arguments which may never be modified opt_params = {} if 'equilibrium_radius' in config: opt_params['equilibrium_radius'] = int(config['equilibrium_radius']) if 'cutoff_epsilon' in config: opt_params['cutoff_epsilon'] = float(config['cutoff_epsilon']) if 'convergence_speedup_factor' in config: opt_params['convergence_speedup_factor'] = float(config['convergence_speedup_factor']) self.__request_generator = SimpleReqGenKeepActiveReqsFixed( self.request_lifetime_lambda, nf_type_count, request_seed, minlat, maxlat, int(config['equilibrium']), self.request_arrival_lambda, **opt_params) elif request_type == "more_deterministic": minlat = float(config['request_min_lat']) maxlat = float(config['request_max_lat']) self.__request_generator = SimpleMoreDeterministicReqGen( self.request_lifetime_lambda, nf_type_count, request_seed, minlat, maxlat) elif request_type == "simple_immortal": minlat = float(config['request_min_lat']) maxlat = float(config['request_max_lat']) initial_immortal_req_count = int(config['immortal_req_count']) self.__request_generator = \ SimpleDeterministicInitiallyImmortalReqGen( self.request_lifetime_lambda, nf_type_count, request_seed, initial_immortal_req_count, minlat, maxlat) else: log.error("Invalid 'request_type' in the simulation.cfg file!") raise RuntimeError( "Invalid 'request_type' in the simulation.cfg file! " "Please choose one of the followings: test, simple, multi, " "simple_equilibrium, more_deterministic") self.__remaining_request_lifetimes = [] self.numpyrandom = N.random.RandomState(request_seed) premapped_vnf_count = 0 # Resource resource_type = config['topology'] if resource_type == "pico": self.__resource_getter = PicoResourceGetter() elif resource_type == "gwin": self.__resource_getter = GwinResourceGetter() elif resource_type == "carrier": self.__resource_getter = CarrierTopoGetter() elif resource_type == "loaded_topology": # this must contain already mapped Service Graphs with the given # path requirements as well! self.__resource_getter = LoadedResourceGetter(log, config['loaded_nffg_path']) # denote premapped request numbers with negative numbers. req_num = 0 starting_time_of_remapped_lives = None for service_graph in self.__resource_getter.getRunningSGs(): if req_num == 0: starting_time_of_remapped_lives = datetime.datetime.now() req_num -= 1 life_time = self.__request_generator.get_request_lifetime(-1 * req_num) log.debug("Generated lifetime for premapped SG %s is %s s"% (req_num, life_time)) log.debug("Adding premapped SG to the system on path: %s" % next(service_graph.reqs).sg_path) premapped_vnf_count += len([n.id for n in service_graph.nfs]) if self.__discrete_simulation: death_time = life_time else: death_time = starting_time_of_remapped_lives +\ datetime.timedelta(0, life_time) service_life_element = {"dead_time": death_time, "SG": service_graph, "req_num": req_num} self.__remaining_request_lifetimes.append(service_life_element) elif resource_type == "fat_tree": self.__resource_getter = FatFreeTopoGetter() elif resource_type == "spine_leaf": self.__resource_getter = SpineLeafTopoGetter() elif resource_type == "edge_and_core_computing": self.__resource_getter = EdgeAndCoreComputingTopoGetter() else: log.error("Invalid 'topology' in the simulation.cfg file!") raise RuntimeError( "Invalid 'topology' in the simulation.cfg file! " "Please choose one of the followings: pico, gwin, carrier") self.__network_topology_bare = self.__resource_getter.GetNFFG() self.__network_topology = self.__network_topology_bare.copy() # Init counters self.counters = SimulationCounters(len(self.__remaining_request_lifetimes), premapped_vnf_count) # Orchestrator if self.orchestrator_type == "online": log.info(" ---- Online specific configurations -----") log.info(" | Enable shortest path cache: " + str(config['enable_shortest_path_cache'])) log.info(" | bw_factor: " + str(config['bw_factor'])) log.info(" | res_factor: " + str(config['res_factor'])) log.info(" | lat_factor: " + str(config['lat_factor'])) log.info(" | shortest_paths: " + str(config['shortest_paths'])) log.info(" | return_dist: " + str(config['return_dist'])) log.info(" | propagate_e2e_reqs: " + str(config['propagate_e2e_reqs'])) log.info(" | bt_limit: " + str(config['bt_limit'])) log.info(" | bt_branching_factor: " + str(config['bt_branching_factor'])) log.info(" -----------------------------------------") self.__orchestrator_adaptor = OnlineOrchestratorAdaptor( self.full_log_path, config_file_path, log) elif self.orchestrator_type == "hybrid": log.info(" ---- Hybrid specific configurations -----") log.info(" | What to optimize: " + str(config['what_to_optimize'])) log.info(" | When to optimize: " + str(config['when_to_optimize'])) log.info(" | When to optimize parameter: " + str(config['when_to_opt_parameter'])) log.info(" | Optimize strategy: " + str(config['resource_share_strat'])) log.info(" -----------------------------------------") log.info(" ---- Online specific configurations -----") log.info(" | Enable shortest path cache: " + str( config['enable_shortest_path_cache'])) log.info(" | bw_factor: " + str(config['bw_factor'])) log.info(" | res_factor: " + str(config['res_factor'])) log.info(" | lat_factor: " + str(config['lat_factor'])) log.info(" | shortest_paths: " + str(config['shortest_paths'])) log.info(" | return_dist: " + str(config['return_dist'])) log.info( " | propagate_e2e_reqs: " + str(config['propagate_e2e_reqs'])) log.info(" | bt_limit: " + str(config['bt_limit'])) log.info( " | bt_branching_factor: " + str(config['bt_branching_factor'])) log.info(" -----------------------------------------") log.info(" ---- Offline specific configurations -----") log.info(" | Optimize already mapped nfs " + config[ 'optimize_already_mapped_nfs']) log.info(" | migration_coeff: " + config[ 'migration_coeff']) log.info(" | load_balance_coeff: " + config[ 'load_balance_coeff']) log.info(" | edge_cost_coeff: " + config[ 'edge_cost_coeff']) log.info(" | Migration cost handler given: " + config[ 'migration_handler_name'] if 'migration_handler_name' in config else "None") log.info(" -----------------------------------------") self.__orchestrator_adaptor = HybridOrchestratorAdaptor( self.__network_topology_bare, self.full_log_path, config_file_path, resource_type, self.__remaining_request_lifetimes, log) elif self.orchestrator_type == "offline": log.info(" ---- Offline specific configurations -----") log.info(" | Optimize already mapped nfs " + config['optimize_already_mapped_nfs']) log.info(" | migration_coeff: " + config[ 'migration_coeff']) log.info(" | load_balance_coeff: " + config[ 'load_balance_coeff']) log.info(" | edge_cost_coeff: " + config[ 'edge_cost_coeff']) log.info(" | Migration cost handler given: " + config[ 'migration_handler_name'] if 'migration_handler_name' in config else "None") opt_params = {} if 'time_limit' in config: opt_params['time_limit'] = float(config['time_limit']) if 'mip_gap_limit' in config: opt_params['mip_gap_limit'] = float(config['mip_gap_limit']) if 'node_limit' in config: opt_params['node_limit'] = int(config['node_limit']) opt_params.update(**config['migration_handler_kwargs']) self.__orchestrator_adaptor = OfflineOrchestratorAdaptor( self.full_log_path, config_file_path, bool(config['optimize_already_mapped_nfs']), config['migration_handler_name'], config['migration_coeff'], config['load_balance_coeff'], config['edge_cost_coeff'], log, **opt_params) else: log.error("Invalid 'orchestrator' in the simulation.cfg file!") raise RuntimeError( "Invalid 'orchestrator' in the simulation.cfg file! " "Please choose one of the followings: online, hybrid, offline") def __mapping(self, service_graph, life_time, req_num): # Log available memory log.info("System available memory: " + str(memory_usage_psutil()) + " GB") current_time = datetime.datetime.now() try: log.debug("# of VNFs in resource graph: %s" % len( [n for n in self.__network_topology.nfs])) log.debug("# of reqs in resource graph: %s" % len( [n for n in self.__network_topology.reqs])) # Give a copy for the mapping, so in case it fails, we dont have to # reset the prerocessed/modified resource self.__network_topology = self.__orchestrator_adaptor.MAP( service_graph.copy(), self.__network_topology.copy()) log.info("Time passed with one mapping response: %s s"% (datetime.datetime.now() - current_time)) # Adding successfully mapped request to the remaining_request_lifetimes if self.__discrete_simulation: death_time = self.discrete_simulation_timer + life_time else: death_time = datetime.datetime.now() + \ datetime.timedelta(0, life_time) service_life_element = {"dead_time": death_time, "SG": service_graph, "req_num": req_num} self.__remaining_request_lifetimes.append(service_life_element) log.info("Mapping thread: Mapping service_request_"+ str(req_num) + " successful +") self.counters.successful_mapping_happened( len([n.id for n in service_graph.nfs])) if not self.counters.dump_iter % self.dump_freq: self.dump() except uet.MappingException as me: log.info("Time passed with one mapping response: %s s" % (datetime.datetime.now() - current_time)) log.info("Mapping thread: Mapping service_request_" + str(req_num) + " unsuccessful\n%s" % me.msg) # we continue working, the __network_topology is in the last valid state self.counters.unsuccessful_mapping_happened() except uet.UnifyException as ue: log.error("Mapping failed: %s", ue.msg) raise except Exception as e: log.error("Mapping failed: %s", e) raise # Try to dump even if unsucessful mapping happened, because the dum_iter # could have been increased due to exired requests. if not self.counters.dump_iter % self.dump_freq: self.dump() def dump(self): # It can happen that no change happens for a couple of iterations (no # deletion, no successful mapping) and dump_iter doesn't increase # and we dump the same NFFG for multiple times. if self.counters.dump_iter != self.last_dump_number: self.last_dump_number = self.counters.dump_iter log.info("Dump NFFG to file after the " + str(self.counters.dump_iter) + ". NFFG change") # NOTE: instead of dump_iter we give sim_iter to dumping function!! self.__orchestrator_adaptor.dump_mapped_nffg( self.counters.sim_iter, "change", self.sim_number, self.orchestrator_type, self.__network_topology) def __del_service(self, service, sim_iter): try: log.debug("# of VNFs in resource graph: %s" % len( [n for n in self.__network_topology.nfs])) log.debug("# of reqs in resource graph: %s" % len( [n for n in self.__network_topology.reqs])) log.info("Try to delete " + str(sim_iter) + ". sc") self.__network_topology = self.__orchestrator_adaptor.del_service(service['SG'], self.__network_topology) log.info("Mapping thread: Deleting service_request_" + str(sim_iter) + " successful -") self.__remaining_request_lifetimes.remove(service) self.counters.deleting_one_expired_service( len([n.id for n in service['SG'].nfs])) except uet.MappingException: log.error("Mapping thread: Deleting service_request_" + str(sim_iter) + " unsuccessful") raise except Exception as e: log.error("Delete failed: %s", e) raise def make_mapping(self, req_gen_thread): # in case of discrete simulation it is equivalent to "while True" while (req_gen_thread.is_alive() if not self.__discrete_simulation else True) or \ not self.__request_list.empty(): request_list_element = self.__request_list.get() request = request_list_element['request'] life_time = self.__request_generator.get_request_lifetime( self.counters.running_requests) req_num = request_list_element['req_num'] log.debug("make_mapping: generate %s lifetime for request %s" % (life_time, req_num)) self.__request_list.task_done() if req_num > self.last_req_num + 1: for discarded_req_num in xrange(self.last_req_num + 1, req_num): log.info("Mapping thread: handling discarded request %s as" " refused request!"%discarded_req_num) self.counters.incoming_request_buffer_overflow_happened() elif req_num == self.last_req_num + 1: # we are on track, lets see if we can map it or not! pass elif req_num < self.last_req_num + 1: raise Exception("Implementation error in simulation framework, " "request number should increase monotonically.") self.last_req_num = req_num # TODO: remove expired requests even when mapping didn't happen! # Remove expired service graph requests self.__clean_expired_requests() log.debug("Number of mapping iteration is %s"%req_num) self.__mapping(request, life_time, req_num) if self.__discrete_simulation: return if self.wait_all_req_expire: # Wait for all request to expire while len(self.__remaining_request_lifetimes) > 0: # Remove expired service graph requests self.__clean_expired_requests() log.info("End mapping thread!") def __clean_expired_requests(self): if self.__discrete_simulation: time = self.discrete_simulation_timer else: time = datetime.datetime.now() # Delete expired SCs purge_needed = False for service in self.__remaining_request_lifetimes: if service['dead_time'] < time: if not purge_needed: # this needs to be done only once, when at least one # expired request was found self.counters.purging_all_expired_requests() purge_needed = True self.__del_service(service, service['req_num']) def create_request(self): """ Fills the request queue continuously with arriving requests. Returns True when the generator didn't finish, but just put a request in the queue. Returns False when the request generator is terminated. :return: bool """ # Simulation cycle while True: # Get request service_graph = \ self.__request_generator.get_request(self.__network_topology_bare, self.request_gen_iter) if self.__request_list.qsize() > self.req_queue_size: log.info("Request Generator thread: discarding generated " "request %s, because the queue is full!" % self.request_gen_iter) else: log.info("Request Generator thread: Add request " + str(self.request_gen_iter)) request_list_element = {"request": service_graph, "req_num": self.request_gen_iter} self.__request_list.put(request_list_element) scale_radius = (1/self.request_arrival_lambda) exp_time = self.numpyrandom.exponential(scale_radius) if self.__discrete_simulation: log.debug("Incrementing discrete simulation timer by %s"% exp_time) self.discrete_simulation_timer += exp_time else: time.sleep(exp_time) log.debug("Request Generator thread: Number of requests waiting in" " the queue %s"%self.__request_list.qsize()) # Increase simulation iteration is done by counters # Increasing request generatior iteration counter self.request_gen_iter += 1 if self.request_gen_iter > self.max_number_of_iterations: # meaning: all the requests are generated (or discarded) which # will be needed during the simulation log.info("Stop request generator thread") return False if self.__discrete_simulation: return True def start(self): try: if self.__discrete_simulation: while self.create_request(): self.make_mapping(None) log.info("End discrete simulation.") else: req_gen_thread = threading.Thread(None, self.create_request, "request_generator_thread_T1") log.info("Start request generator thread") mapping_thread = threading.Thread(None, self.make_mapping, "mapping_thread_T2", [req_gen_thread]) log.info("Start mapping thread") req_gen_thread.start() mapping_thread.start() req_gen_thread.join() mapping_thread.join() except threading.ThreadError: log.error(" Unable to start threads") except Exception as e: log.error("Exception in simulation: %s", e) raise finally: # Create JSON files # This output is not advised to use! requests = {"mapped_requests": self.counters.mapped_array, "running_requests": self.counters.running_array, "refused_requests": self.counters.refused_array} full_path_json = os.path.join(self.path, "requests" + str( time.ctime()) + ".json") with open(full_path_json, 'w') as outfile: json.dump(requests, outfile) # make a dump after everything is finished to see the final state! self.dump() def memory_usage_psutil(): # return the available memory in GB mem = psutil.virtual_memory() return ((float(mem.available)/1024)/1024)/1024 if __name__ == "__main__": if len(sys.argv) > 2: log.error("Too many input parameters!") elif len(sys.argv) < 2: log.error("Too few input parameters!") elif not os.path.isfile(sys.argv[1]): log.error("Configuration file does not exist!") else: test = MappingSolutionFramework(sys.argv[1]) # Copy simulation.cfg to testXY dir shutil.copy(sys.argv[1], test.path) test.start()
<<<<<<< HEAD <<<<<<< HEAD # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Pattern compiler. The grammer is taken from PatternGrammar.txt. The compiler compiles a pattern to a pytree.*Pattern instance. """ __author__ = "Guido van Rossum <guido@python.org>" # Python imports import io import os # Fairly local imports from .pgen2 import driver, literals, token, tokenize, parse, grammar # Really local imports from . import pytree from . import pygram # The pattern grammar file _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "PatternGrammar.txt") class PatternSyntaxError(Exception): pass def tokenize_wrapper(input): """Tokenizes a string suppressing significant whitespace.""" skip = {token.NEWLINE, token.INDENT, token.DEDENT} tokens = tokenize.generate_tokens(io.StringIO(input).readline) for quintuple in tokens: type, value, start, end, line_text = quintuple if type not in skip: yield quintuple class PatternCompiler(object): def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE): """Initializer. Takes an optional alternative filename for the pattern grammar. """ self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert) def compile_pattern(self, input, debug=False, with_tree=False): """Compiles a pattern string to a nested pytree.*Pattern object.""" tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: raise PatternSyntaxError(str(e)) if with_tree: return self.compile_node(root), root else: return self.compile_node(root) def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ # XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize() def compile_basic(self, nodes, repeat=None): # Compile STRING | NAME [Details] | (...) | [...] assert len(nodes) >= 1 node = nodes[0] if node.type == token.STRING: value = str(literals.evalString(node.value)) return pytree.LeafPattern(_type_of_literal(value), value) elif node.type == token.NAME: value = node.value if value.isupper(): if value not in TOKEN_MAP: raise PatternSyntaxError("Invalid token: %r" % value) if nodes[1:]: raise PatternSyntaxError("Can't have details for token") return pytree.LeafPattern(TOKEN_MAP[value]) else: if value == "any": type = None elif not value.startswith("_"): type = getattr(self.pysyms, value, None) if type is None: raise PatternSyntaxError("Invalid symbol: %r" % value) if nodes[1:]: # Details present content = [self.compile_node(nodes[1].children[1])] else: content = None return pytree.NodePattern(type, content) elif node.value == "(": return self.compile_node(nodes[1]) elif node.value == "[": assert repeat is None subpattern = self.compile_node(nodes[1]) return pytree.WildcardPattern([[subpattern]], min=0, max=1) assert False, node def get_int(self, node): assert node.type == token.NUMBER return int(node.value) # Map named tokens to the type value for a LeafPattern TOKEN_MAP = {"NAME": token.NAME, "STRING": token.STRING, "NUMBER": token.NUMBER, "TOKEN": None} def _type_of_literal(value): if value[0].isalpha(): return token.NAME elif value in grammar.opmap: return grammar.opmap[value] else: return None def pattern_convert(grammar, raw_node_info): """Converts raw node information to a Node or Leaf instance.""" type, value, context, children = raw_node_info if children or type in grammar.number2symbol: return pytree.Node(type, children, context=context) else: return pytree.Leaf(type, value, context=context) def compile_pattern(pattern): return PatternCompiler().compile_pattern(pattern) ======= # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Pattern compiler. The grammer is taken from PatternGrammar.txt. The compiler compiles a pattern to a pytree.*Pattern instance. """ __author__ = "Guido van Rossum <guido@python.org>" # Python imports import io import os # Fairly local imports from .pgen2 import driver, literals, token, tokenize, parse, grammar # Really local imports from . import pytree from . import pygram # The pattern grammar file _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "PatternGrammar.txt") class PatternSyntaxError(Exception): pass def tokenize_wrapper(input): """Tokenizes a string suppressing significant whitespace.""" skip = {token.NEWLINE, token.INDENT, token.DEDENT} tokens = tokenize.generate_tokens(io.StringIO(input).readline) for quintuple in tokens: type, value, start, end, line_text = quintuple if type not in skip: yield quintuple class PatternCompiler(object): def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE): """Initializer. Takes an optional alternative filename for the pattern grammar. """ self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert) def compile_pattern(self, input, debug=False, with_tree=False): """Compiles a pattern string to a nested pytree.*Pattern object.""" tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: raise PatternSyntaxError(str(e)) if with_tree: return self.compile_node(root), root else: return self.compile_node(root) def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ # XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize() def compile_basic(self, nodes, repeat=None): # Compile STRING | NAME [Details] | (...) | [...] assert len(nodes) >= 1 node = nodes[0] if node.type == token.STRING: value = str(literals.evalString(node.value)) return pytree.LeafPattern(_type_of_literal(value), value) elif node.type == token.NAME: value = node.value if value.isupper(): if value not in TOKEN_MAP: raise PatternSyntaxError("Invalid token: %r" % value) if nodes[1:]: raise PatternSyntaxError("Can't have details for token") return pytree.LeafPattern(TOKEN_MAP[value]) else: if value == "any": type = None elif not value.startswith("_"): type = getattr(self.pysyms, value, None) if type is None: raise PatternSyntaxError("Invalid symbol: %r" % value) if nodes[1:]: # Details present content = [self.compile_node(nodes[1].children[1])] else: content = None return pytree.NodePattern(type, content) elif node.value == "(": return self.compile_node(nodes[1]) elif node.value == "[": assert repeat is None subpattern = self.compile_node(nodes[1]) return pytree.WildcardPattern([[subpattern]], min=0, max=1) assert False, node def get_int(self, node): assert node.type == token.NUMBER return int(node.value) # Map named tokens to the type value for a LeafPattern TOKEN_MAP = {"NAME": token.NAME, "STRING": token.STRING, "NUMBER": token.NUMBER, "TOKEN": None} def _type_of_literal(value): if value[0].isalpha(): return token.NAME elif value in grammar.opmap: return grammar.opmap[value] else: return None def pattern_convert(grammar, raw_node_info): """Converts raw node information to a Node or Leaf instance.""" type, value, context, children = raw_node_info if children or type in grammar.number2symbol: return pytree.Node(type, children, context=context) else: return pytree.Leaf(type, value, context=context) def compile_pattern(pattern): return PatternCompiler().compile_pattern(pattern) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Pattern compiler. The grammer is taken from PatternGrammar.txt. The compiler compiles a pattern to a pytree.*Pattern instance. """ __author__ = "Guido van Rossum <guido@python.org>" # Python imports import io import os # Fairly local imports from .pgen2 import driver, literals, token, tokenize, parse, grammar # Really local imports from . import pytree from . import pygram # The pattern grammar file _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "PatternGrammar.txt") class PatternSyntaxError(Exception): pass def tokenize_wrapper(input): """Tokenizes a string suppressing significant whitespace.""" skip = {token.NEWLINE, token.INDENT, token.DEDENT} tokens = tokenize.generate_tokens(io.StringIO(input).readline) for quintuple in tokens: type, value, start, end, line_text = quintuple if type not in skip: yield quintuple class PatternCompiler(object): def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE): """Initializer. Takes an optional alternative filename for the pattern grammar. """ self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert) def compile_pattern(self, input, debug=False, with_tree=False): """Compiles a pattern string to a nested pytree.*Pattern object.""" tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: raise PatternSyntaxError(str(e)) if with_tree: return self.compile_node(root), root else: return self.compile_node(root) def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ # XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize() def compile_basic(self, nodes, repeat=None): # Compile STRING | NAME [Details] | (...) | [...] assert len(nodes) >= 1 node = nodes[0] if node.type == token.STRING: value = str(literals.evalString(node.value)) return pytree.LeafPattern(_type_of_literal(value), value) elif node.type == token.NAME: value = node.value if value.isupper(): if value not in TOKEN_MAP: raise PatternSyntaxError("Invalid token: %r" % value) if nodes[1:]: raise PatternSyntaxError("Can't have details for token") return pytree.LeafPattern(TOKEN_MAP[value]) else: if value == "any": type = None elif not value.startswith("_"): type = getattr(self.pysyms, value, None) if type is None: raise PatternSyntaxError("Invalid symbol: %r" % value) if nodes[1:]: # Details present content = [self.compile_node(nodes[1].children[1])] else: content = None return pytree.NodePattern(type, content) elif node.value == "(": return self.compile_node(nodes[1]) elif node.value == "[": assert repeat is None subpattern = self.compile_node(nodes[1]) return pytree.WildcardPattern([[subpattern]], min=0, max=1) assert False, node def get_int(self, node): assert node.type == token.NUMBER return int(node.value) # Map named tokens to the type value for a LeafPattern TOKEN_MAP = {"NAME": token.NAME, "STRING": token.STRING, "NUMBER": token.NUMBER, "TOKEN": None} def _type_of_literal(value): if value[0].isalpha(): return token.NAME elif value in grammar.opmap: return grammar.opmap[value] else: return None def pattern_convert(grammar, raw_node_info): """Converts raw node information to a Node or Leaf instance.""" type, value, context, children = raw_node_info if children or type in grammar.number2symbol: return pytree.Node(type, children, context=context) else: return pytree.Leaf(type, value, context=context) def compile_pattern(pattern): return PatternCompiler().compile_pattern(pattern) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
import logging import math import os import pathlib import re import sys from contextlib import contextmanager from functools import partial from hashlib import md5 from urllib.parse import urlsplit DEFAULT_BLOCK_SIZE = 5 * 2 ** 20 PY36 = sys.version_info < (3, 7) def infer_storage_options(urlpath, inherit_storage_options=None): """Infer storage options from URL path and merge it with existing storage options. Parameters ---------- urlpath: str or unicode Either local absolute file path or URL (hdfs://namenode:8020/file.csv) inherit_storage_options: dict (optional) Its contents will get merged with the inferred information from the given path Returns ------- Storage options dict. Examples -------- >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP {"protocol": "file", "path", "/mnt/datasets/test.csv"} >>> infer_storage_options( ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1', ... inherit_storage_options={'extra': 'value'}, ... ) # doctest: +SKIP {"protocol": "hdfs", "username": "username", "password": "pwd", "host": "node", "port": 123, "path": "/mnt/datasets/test.csv", "url_query": "q=1", "extra": "value"} """ # Handle Windows paths including disk name in this special case if ( re.match(r"^[a-zA-Z]:[\\/]", urlpath) or re.match(r"^[a-zA-Z0-9]+://", urlpath) is None ): return {"protocol": "file", "path": urlpath} parsed_path = urlsplit(urlpath) protocol = parsed_path.scheme or "file" if parsed_path.fragment: path = "#".join([parsed_path.path, parsed_path.fragment]) else: path = parsed_path.path if protocol == "file": # Special case parsing file protocol URL on Windows according to: # https://msdn.microsoft.com/en-us/library/jj710207.aspx windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path) if windows_path: path = "%s:%s" % windows_path.groups() if protocol in ["http", "https"]: # for HTTP, we don't want to parse, as requests will anyway return {"protocol": protocol, "path": urlpath} options = {"protocol": protocol, "path": path} if parsed_path.netloc: # Parse `hostname` from netloc manually because `parsed_path.hostname` # lowercases the hostname which is not always desirable (e.g. in S3): # https://github.com/dask/dask/issues/1417 options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0] if protocol in ("s3", "s3a", "gcs", "gs"): options["path"] = options["host"] + options["path"] else: options["host"] = options["host"] if parsed_path.port: options["port"] = parsed_path.port if parsed_path.username: options["username"] = parsed_path.username if parsed_path.password: options["password"] = parsed_path.password if parsed_path.query: options["url_query"] = parsed_path.query if parsed_path.fragment: options["url_fragment"] = parsed_path.fragment if inherit_storage_options: update_storage_options(options, inherit_storage_options) return options def update_storage_options(options, inherited=None): if not inherited: inherited = {} collisions = set(options) & set(inherited) if collisions: for collision in collisions: if options.get(collision) != inherited.get(collision): raise KeyError( "Collision between inferred and specified storage " "option:\n%s" % collision ) options.update(inherited) # Compression extensions registered via fsspec.compression.register_compression compressions = {} def infer_compression(filename): """Infer compression, if available, from filename. Infer a named compression type, if registered and available, from filename extension. This includes builtin (gz, bz2, zip) compressions, as well as optional compressions. See fsspec.compression.register_compression. """ extension = os.path.splitext(filename)[-1].strip(".").lower() if extension in compressions: return compressions[extension] def build_name_function(max_int): """Returns a function that receives a single integer and returns it as a string padded by enough zero characters to align with maximum possible integer >>> name_f = build_name_function(57) >>> name_f(7) '07' >>> name_f(31) '31' >>> build_name_function(1000)(42) '0042' >>> build_name_function(999)(42) '042' >>> build_name_function(0)(0) '0' """ # handle corner cases max_int is 0 or exact power of 10 max_int += 1e-8 pad_length = int(math.ceil(math.log10(max_int))) def name_function(i): return str(i).zfill(pad_length) return name_function def seek_delimiter(file, delimiter, blocksize): r"""Seek current file to file start, file end, or byte after delimiter seq. Seeks file to next chunk delimiter, where chunks are defined on file start, a delimiting sequence, and file end. Use file.tell() to see location afterwards. Note that file start is a valid split, so must be at offset > 0 to seek for delimiter. Parameters ---------- file: a file delimiter: bytes a delimiter like ``b'\n'`` or message sentinel, matching file .read() type blocksize: int Number of bytes to read from the file at once. Returns ------- Returns True if a delimiter was found, False if at file start or end. """ if file.tell() == 0: # beginning-of-file, return without seek return False # Interface is for binary IO, with delimiter as bytes, but initialize last # with result of file.read to preserve compatibility with text IO. last = None while True: current = file.read(blocksize) if not current: # end-of-file without delimiter return False full = last + current if last else current try: if delimiter in full: i = full.index(delimiter) file.seek(file.tell() - (len(full) - i) + len(delimiter)) return True elif len(current) < blocksize: # end-of-file without delimiter return False except (OSError, ValueError): pass last = full[-len(delimiter) :] def read_block(f, offset, length, delimiter=None, split_before=False): """Read a block of bytes from a file Parameters ---------- f: File Open file offset: int Byte offset to start read length: int Number of bytes to read, read through end of file if None delimiter: bytes (optional) Ensure reading starts and stops at delimiter bytestring split_before: bool (optional) Start/stop read *before* delimiter bytestring. If using the ``delimiter=`` keyword argument we ensure that the read starts and stops at delimiter boundaries that follow the locations ``offset`` and ``offset + length``. If ``offset`` is zero then we start at zero, regardless of delimiter. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\nBob, 200\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'Bob, 200\\nCharlie, 300' """ if delimiter: f.seek(offset) found_start_delim = seek_delimiter(f, delimiter, 2 ** 16) if length is None: return f.read() start = f.tell() length -= start - offset f.seek(start + length) found_end_delim = seek_delimiter(f, delimiter, 2 ** 16) end = f.tell() # Adjust split location to before delimiter iff seek found the # delimiter sequence, not start or end of file. if found_start_delim and split_before: start -= len(delimiter) if found_end_delim and split_before: end -= len(delimiter) offset = start length = end - start f.seek(offset) b = f.read(length) return b def tokenize(*args, **kwargs): """Deterministic token (modified from dask.base) >>> tokenize([1, 2, '3']) '9d71491b50023b06fc76928e6eddb952' >>> tokenize('Hello') == tokenize('Hello') True """ if kwargs: args += (kwargs,) return md5(str(args).encode()).hexdigest() def stringify_path(filepath): """Attempt to convert a path-like object to a string. Parameters ---------- filepath: object to be converted Returns ------- filepath_str: maybe a string version of the object Notes ----- Objects supporting the fspath protocol (Python 3.6+) are coerced according to its __fspath__ method. For backwards compatibility with older Python version, pathlib.Path objects are specially coerced. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. """ if isinstance(filepath, str): return filepath elif hasattr(filepath, "__fspath__"): return filepath.__fspath__() elif isinstance(filepath, pathlib.Path): return str(filepath) elif hasattr(filepath, "path"): return filepath.path else: return filepath def make_instance(cls, args, kwargs): inst = cls(*args, **kwargs) inst._determine_worker() return inst def common_prefix(paths): """For a list of paths, find the shortest prefix common to all""" parts = [p.split("/") for p in paths] lmax = min(len(p) for p in parts) end = 0 for i in range(lmax): end = all(p[i] == parts[0][i] for p in parts) if not end: break i += end return "/".join(parts[0][:i]) def other_paths(paths, path2, is_dir=None, exists=False): """In bulk file operations, construct a new file tree from a list of files Parameters ---------- paths: list of str The input file tree path2: str or list of str Root to construct the new list in. If this is already a list of str, we just assert it has the right number of elements. is_dir: bool (optional) For the special case where the input in one element, whether to regard the value as the target path, or as a directory to put a file path within. If None, a directory is inferred if the path ends in '/' exists: bool (optional) For a str destination, it is already exists (and is a dir), files should end up inside. Returns ------- list of str """ if isinstance(path2, str): is_dir = is_dir or path2.endswith("/") path2 = path2.rstrip("/") if len(paths) > 1: cp = common_prefix(paths) if exists: cp = cp.rsplit("/", 1)[0] path2 = [p.replace(cp, path2, 1) for p in paths] else: if is_dir: path2 = [path2.rstrip("/") + "/" + paths[0].rsplit("/")[-1]] else: path2 = [path2] else: assert len(paths) == len(path2) return path2 def is_exception(obj): return isinstance(obj, BaseException) def get_protocol(url): parts = re.split(r"(\:\:|\://)", url, 1) if len(parts) > 1: return parts[0] return "file" def can_be_local(path): """Can the given URL be used with open_local?""" from fsspec import get_filesystem_class try: return getattr(get_filesystem_class(get_protocol(path)), "local_file", False) except (ValueError, ImportError): # not in registry or import failed return False def get_package_version_without_import(name): """For given package name, try to find the version without importing it Import and package.__version__ is still the backup here, so an import *might* happen. Returns either the version string, or None if the package or the version was not readily found. """ if name in sys.modules: mod = sys.modules[name] if hasattr(mod, "__version__"): return mod.__version__ if sys.version_info >= (3, 8): try: import importlib.metadata return importlib.metadata.distribution(name).version except: # noqa: E722 pass else: try: import importlib_metadata return importlib_metadata.distribution(name).version except: # noqa: E722 pass try: import importlib mod = importlib.import_module(name) return mod.__version__ except (ImportError, AttributeError): return None def setup_logging(logger=None, logger_name=None, level="DEBUG", clear=True): if logger is None and logger_name is None: raise ValueError("Provide either logger object or logger name") logger = logger or logging.getLogger(logger_name) handle = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s" ) handle.setFormatter(formatter) if clear: logger.handlers.clear() logger.addHandler(handle) logger.setLevel(level) return logger def _unstrip_protocol(name, fs): if isinstance(fs.protocol, str): if name.startswith(fs.protocol): return name return fs.protocol + "://" + name else: if name.startswith(tuple(fs.protocol)): return name return fs.protocol[0] + "://" + name def mirror_from(origin_name, methods): """Mirror attributes and methods from the given origin_name attribute of the instance to the decorated class""" def origin_getter(method, self): origin = getattr(self, origin_name) return getattr(origin, method) def wrapper(cls): for method in methods: wrapped_method = partial(origin_getter, method) setattr(cls, method, property(wrapped_method)) return cls return wrapper @contextmanager def nullcontext(obj): yield obj def merge_offset_ranges(paths, starts, ends, max_gap=0, max_block=None, sort=True): """Merge adjacent byte-offset ranges when the inter-range gap is <= `max_gap`, and when the merged byte range does not exceed `max_block` (if specified). By default, this function will re-order the input paths and byte ranges to ensure sorted order. If the user can guarantee that the inputs are already sorted, passing `sort=False` will skip the re-ordering. """ # Check input if not isinstance(paths, list): raise TypeError if not isinstance(starts, list): starts = [starts] * len(paths) if not isinstance(ends, list): ends = [starts] * len(paths) if len(starts) != len(paths) or len(ends) != len(paths): raise ValueError # Sort by paths and then ranges if `sort=True` if sort: paths, starts, ends = [list(v) for v in zip(*sorted(zip(paths, starts, ends)))] if paths: # Loop through the coupled `paths`, `starts`, and # `ends`, and merge adjacent blocks when appropriate new_paths = paths[:1] new_starts = starts[:1] new_ends = ends[:1] for i in range(1, len(paths)): if ( paths[i] != paths[i - 1] or ((starts[i] - new_ends[-1]) > max_gap) or ((max_block is not None and (ends[i] - new_starts[-1]) > max_block)) ): # Cannot merge with previous block. # Add new `paths`, `starts`, and `ends` elements new_paths.append(paths[i]) new_starts.append(starts[i]) new_ends.append(ends[i]) else: # Merge with previous block by updating the # last element of `ends` new_ends[-1] = ends[i] return new_paths, new_starts, new_ends # `paths` is empty. Just return input lists return paths, starts, ends
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import re import copy import logging log = logging.getLogger('utils.qualities') class QualityComponent(object): """""" def __init__(self, type, value, name, regexp=None, modifier=None, defaults=None): """ :param type: Type of quality component. (resolution, source, codec, or audio) :param value: Value used to sort this component with others of like type. :param name: Canonical name for this quality component. :param regexp: Regexps used to match this component. :param modifier: An integer that affects sorting above all other components. :param defaults: An iterable defining defaults for other quality components if this component matches. """ if type not in ['resolution', 'source', 'codec', 'audio']: raise ValueError('%s is not a valid quality component type.' % type) self.type = type self.value = value self.name = name self.modifier = modifier self.defaults = defaults or [] # compile regexp if regexp is None: regexp = re.escape(name) self.regexp = re.compile('(?<![^\W_])(' + regexp + ')(?![^\W_])', re.IGNORECASE) def matches(self, text): """Test if quality matches to text. :param string text: data te be tested against :returns: tuple (matches, remaining text without quality data) """ match = self.regexp.search(text) if not match: return False, "" else: # remove matching part from the text text = text[:match.start()] + text[match.end():] return True, text def __hash__(self): return hash(self.type + str(self.value)) def __bool__(self): return bool(self.value) def __eq__(self, other): if isinstance(other, basestring): other = _registry.get(other) if not isinstance(other, QualityComponent): raise TypeError('Cannot compare %r and %r' % (self, other)) if other.type == self.type: return self.value == other.value else: raise TypeError('Cannot compare %s and %s' % (self.type, other.type)) def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if isinstance(other, basestring): other = _registry.get(other) if not isinstance(other, QualityComponent): raise TypeError('Cannot compare %r and %r' % (self, other)) if other.type == self.type: return self.value < other.value else: raise TypeError('Cannot compare %s and %s' % (self.type, other.type)) def __ge__(self, other): return not self.__lt__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __add__(self, other): if not isinstance(other, int): raise TypeError() l = globals().get('_' + self.type + 's') index = l.index(self) + other if index >= len(l): index = -1 return l[index] def __sub__(self, other): if not isinstance(other, int): raise TypeError() l = globals().get('_' + self.type + 's') index = l.index(self) - other if index < 0: index = 0 return l[index] def __repr__(self): return '<%s(name=%s,value=%s)>' % (self.type.title(), self.name, self.value) def __str__(self): return self.name def __deepcopy__(self, memo=None): # No mutable attributes, return a regular copy return copy.copy(self) _resolutions = [ QualityComponent('resolution', 10, '360p'), QualityComponent('resolution', 20, '368p', '368p?'), QualityComponent('resolution', 30, '480p', '480p?'), QualityComponent('resolution', 40, '576p', '576p?'), QualityComponent('resolution', 45, 'hr'), QualityComponent('resolution', 50, '720i'), QualityComponent('resolution', 60, '720p', '(1280x)?720(p|hd)?x?([56]0)?'), QualityComponent('resolution', 70, '1080i'), QualityComponent('resolution', 80, '1080p', '(1920x)?1080p?x?([56]0)?'), QualityComponent('resolution', 90, '2160p', '((3840x)?2160p?x?([56]0)?)|4k') ] _sources = [ QualityComponent('source', 10, 'workprint', modifier=-8), QualityComponent('source', 20, 'cam', '(?:hd)?cam', modifier=-7), QualityComponent('source', 30, 'ts', '(?:hd)?ts|telesync', modifier=-6), QualityComponent('source', 40, 'tc', 'tc|telecine', modifier=-5), QualityComponent('source', 50, 'r5', 'r[2-8c]', modifier=-4), QualityComponent('source', 60, 'hdrip', 'hd[\W_]?rip', modifier=-3), QualityComponent('source', 70, 'ppvrip', 'ppv[\W_]?rip', modifier=-2), QualityComponent('source', 80, 'preair', modifier=-1), QualityComponent('source', 90, 'tvrip', 'tv[\W_]?rip'), QualityComponent('source', 100, 'dsr', 'dsr|ds[\W_]?rip'), QualityComponent('source', 110, 'sdtv', '(?:[sp]dtv|dvb)(?:[\W_]?rip)?'), QualityComponent('source', 120, 'dvdscr', '(?:(?:dvd|web)[\W_]?)?scr(?:eener)?', modifier=0), QualityComponent('source', 130, 'bdscr', 'bdscr(?:eener)?'), QualityComponent('source', 140, 'webrip', 'web[\W_]?rip'), QualityComponent('source', 150, 'hdtv', 'a?hdtv(?:[\W_]?rip)?'), QualityComponent('source', 160, 'webdl', 'web(?:[\W_]?(dl|hd))?'), QualityComponent('source', 170, 'dvdrip', 'dvd(?:[\W_]?rip)?'), QualityComponent('source', 175, 'remux'), QualityComponent('source', 180, 'bluray', '(?:b[dr][\W_]?rip|blu[\W_]?ray(?:[\W_]?rip)?)') ] _codecs = [ QualityComponent('codec', 10, 'divx'), QualityComponent('codec', 20, 'xvid'), QualityComponent('codec', 30, 'h264', '[hx].?264'), QualityComponent('codec', 35, 'vp9'), QualityComponent('codec', 40, 'h265', '[hx].?265|hevc'), QualityComponent('codec', 50, '10bit', '10.?bit|hi10p') ] channels = '(?:(?:[^\w+]?[1-7][\W_]?(?:0|1|ch)))' _audios = [ QualityComponent('audio', 10, 'mp3'), # TODO: No idea what order these should go in or if we need different regexps QualityComponent('audio', 20, 'aac', 'aac%s?' % channels), QualityComponent('audio', 30, 'dd5.1', 'dd%s' % channels), QualityComponent('audio', 40, 'ac3', 'ac3%s?' % channels), QualityComponent('audio', 45, 'dd+5.1', 'dd[p+]%s' % channels), QualityComponent('audio', 50, 'flac', 'flac%s?' % channels), # The DTSs are a bit backwards, but the more specific one needs to be parsed first QualityComponent('audio', 60, 'dtshd', 'dts[\W_]?hd(?:[\W_]?ma)?'), QualityComponent('audio', 70, 'dts'), QualityComponent('audio', 80, 'truehd') ] _UNKNOWNS = { 'resolution': QualityComponent('resolution', 0, 'unknown'), 'source': QualityComponent('source', 0, 'unknown'), 'codec': QualityComponent('codec', 0, 'unknown'), 'audio': QualityComponent('audio', 0, 'unknown') } # For wiki generating help '''for type in (_resolutions, _sources, _codecs, _audios): print '{{{#!td style="vertical-align: top"' for item in reversed(type): print '- ' + item.name print '}}}' ''' _registry = {} for items in (_resolutions, _sources, _codecs, _audios): for item in items: _registry[item.name] = item def all_components(): return iter(_registry.values()) class Quality(object): """Parses and stores the quality of an entry in the four component categories.""" def __init__(self, text=''): """ :param text: A string to parse quality from """ self.text = text self.clean_text = text if text: self.parse(text) else: self.resolution = _UNKNOWNS['resolution'] self.source = _UNKNOWNS['source'] self.codec = _UNKNOWNS['codec'] self.audio = _UNKNOWNS['audio'] def parse(self, text): """Parses a string to determine the quality in the four component categories. :param text: The string to parse """ self.text = text self.clean_text = text self.resolution = self._find_best(_resolutions, _UNKNOWNS['resolution'], False) self.source = self._find_best(_sources, _UNKNOWNS['source']) self.codec = self._find_best(_codecs, _UNKNOWNS['codec']) self.audio = self._find_best(_audios, _UNKNOWNS['audio']) # If any of the matched components have defaults, set them now. for component in self.components: for default in component.defaults: default = _registry[default] if not getattr(self, default.type): setattr(self, default.type, default) def _find_best(self, qlist, default=None, strip_all=True): """Finds the highest matching quality component from `qlist`""" result = None search_in = self.clean_text for item in qlist: match = item.matches(search_in) if match[0]: result = item self.clean_text = match[1] if strip_all: # In some cases we want to strip all found quality components, # even though we're going to return only the last of them. search_in = self.clean_text if item.modifier is not None: # If this item has a modifier, do not proceed to check higher qualities in the list break return result or default @property def name(self): name = ' '.join(str(p) for p in (self.resolution, self.source, self.codec, self.audio) if p.value != 0) return name or 'unknown' @property def components(self): return [self.resolution, self.source, self.codec, self.audio] @property def _comparator(self): modifier = sum(c.modifier for c in self.components if c.modifier) return [modifier] + self.components def __contains__(self, other): if isinstance(other, basestring): other = Quality(other) if not other or not self: return False for cat in ('resolution', 'source', 'audio', 'codec'): othercat = getattr(other, cat) if othercat and othercat != getattr(self, cat): return False return True def __bool__(self): return any(self._comparator) def __eq__(self, other): if isinstance(other, basestring): other = Quality(other) if not isinstance(other, Quality): if other is None: return False raise TypeError('Cannot compare %r and %r' % (self, other)) return self._comparator == other._comparator def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if isinstance(other, basestring): other = Quality(other) if not isinstance(other, Quality): raise TypeError('Cannot compare %r and %r' % (self, other)) return self._comparator < other._comparator def __ge__(self, other): return not self.__lt__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __repr__(self): return '<Quality(resolution=%s,source=%s,codec=%s,audio=%s)>' % (self.resolution, self.source, self.codec, self.audio) def __str__(self): return self.name def __hash__(self): # Make these usable as dict keys return hash(self.name) def get(quality_name): """Returns a quality object based on canonical quality name.""" found_components = {} for part in quality_name.lower().split(): component = _registry.get(part) if not component: raise ValueError('`%s` is not a valid quality string' % part) if component.type in found_components: raise ValueError('`%s` cannot be defined twice in a quality' % component.type) found_components[component.type] = component if not found_components: raise ValueError('No quality specified') result = Quality() for type, component in found_components.items(): setattr(result, type, component) return result class RequirementComponent(object): """Represents requirements for a given component type. Can evaluate whether a given QualityComponent meets those requirements.""" def __init__(self, type): self.type = type self.reset() def reset(self): self.min = None self.max = None self.acceptable = set() self.none_of = set() def allows(self, comp, loose=False): if comp.type != self.type: raise TypeError('Cannot compare %r against %s' % (comp, self.type)) if comp in self.none_of: return False if loose: return True if comp in self.acceptable: return True if self.min or self.max: if self.min and comp < self.min: return False if self.max and comp > self.max: return False return True if not self.acceptable: return True return False def add_requirement(self, text): if '-' in text: min, max = text.split('-') min, max = _registry[min], _registry[max] if min.type != max.type != self.type: raise ValueError('Component type mismatch: %s' % text) self.min, self.max = min, max elif '|' in text: quals = text.split('|') quals = {_registry[qual] for qual in quals} if any(qual.type != self.type for qual in quals): raise ValueError('Component type mismatch: %s' % text) self.acceptable |= quals else: qual = _registry[text.strip('!<>=+')] if qual.type != self.type: raise ValueError('Component type mismatch!') if text in _registry: self.acceptable.add(qual) else: if text[0] == '<': if text[1] != '=': qual -= 1 self.max = qual elif text[0] == '>' or text.endswith('+'): if text[1] != '=' and not text.endswith('+'): qual += 1 self.min = qual elif text[0] == '!': self.none_of.add(qual) def __eq__(self, other): return ((self.max, self.max, self.acceptable, self.none_of) == (other.max, other.max, other.acceptable, other.none_of)) def __hash__(self): return hash(tuple([self.min, self.max, tuple(sorted(self.acceptable)), tuple(sorted(self.none_of))])) class Requirements(object): """Represents requirements for allowable qualities. Can determine whether a given Quality passes requirements.""" def __init__(self, req=''): self.text = '' self.resolution = RequirementComponent('resolution') self.source = RequirementComponent('source') self.codec = RequirementComponent('codec') self.audio = RequirementComponent('audio') if req: self.parse_requirements(req) @property def components(self): return [self.resolution, self.source, self.codec, self.audio] def parse_requirements(self, text): """ Parses a requirements string. :param text: The string containing quality requirements. """ text = text.lower() if self.text: self.text += ' ' self.text += text if self.text == 'any': for component in self.components: component.reset() return text = text.replace(',', ' ') parts = text.split() try: for part in parts: if '-' in part: found = _registry[part.split('-')[0]] elif '|' in part: found = _registry[part.split('|')[0]] else: found = _registry[part.strip('!<>=+')] for component in self.components: if found.type == component.type: component.add_requirement(part) except KeyError as e: raise ValueError('%s is not a valid quality component.' % e.args[0]) def allows(self, qual, loose=False): """Determine whether this set of requirements allows a given quality. :param Quality qual: The quality to evaluate. :param bool loose: If True, only ! (not) requirements will be enforced. :rtype: bool :returns: True if given quality passes all component requirements. """ if isinstance(qual, basestring): qual = Quality(qual) for r_component, q_component in zip(self.components, qual.components): if not r_component.allows(q_component, loose=loose): return False return True def __eq__(self, other): if isinstance(other, str): other = Requirements(other) return self.components == other.components def __hash__(self): return hash(tuple(self.components)) def __str__(self): return self.text or 'any' def __repr__(self): return '<Requirements(%s)>' % self
import os import sys from tempfile import NamedTemporaryFile from unittest import mock import pytest from unittest.mock import call, mock_open from pyarrow import HadoopFileSystem from mlflow.entities import FileInfo from mlflow.store.artifact.hdfs_artifact_repo import ( HdfsArtifactRepository, _resolve_base_path, _relative_path_remote, _parse_extra_conf, _download_hdfs_file, ) from mlflow.utils.file_utils import TempDir @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_log_artifact(hdfs_system_mock): repo = HdfsArtifactRepository("hdfs://host_name:8020/hdfs/path") with TempDir() as tmp_dir: local_file = tmp_dir.path("sample_file") with open(local_file, "w") as f: f.write("PyArrow Works") repo.log_artifact(local_file, "more_path/some") hdfs_system_mock.assert_called_once_with( extra_conf=None, host="hdfs://host_name", kerb_ticket=None, port=8020, user=None ) open_mock = hdfs_system_mock.return_value.open open_mock.assert_called_once_with("/hdfs/path/more_path/some/sample_file", "wb") write_mock = open_mock.return_value.__enter__.return_value.write write_mock.assert_called_once_with(b"PyArrow Works") @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_log_artifact_viewfs(hdfs_system_mock): repo = HdfsArtifactRepository("viewfs://host_name/mypath") with TempDir() as tmp_dir: local_file = tmp_dir.path("sample_file") with open(local_file, "w") as f: f.write("PyArrow Works") repo.log_artifact(local_file, "more_path/some") hdfs_system_mock.assert_called_once_with( extra_conf=None, host="viewfs://host_name", kerb_ticket=None, port=0, user=None ) open_mock = hdfs_system_mock.return_value.open open_mock.assert_called_once_with("/mypath/more_path/some/sample_file", "wb") write_mock = open_mock.return_value.__enter__.return_value.write write_mock.assert_called_once_with(b"PyArrow Works") @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_log_artifact_with_kerberos_setup(hdfs_system_mock): if sys.platform == "win32": pytest.skip() os.environ["MLFLOW_KERBEROS_TICKET_CACHE"] = "/tmp/krb5cc_22222222" os.environ["MLFLOW_KERBEROS_USER"] = "some_kerberos_user" repo = HdfsArtifactRepository("hdfs:/some/maybe/path") with NamedTemporaryFile() as tmp_local_file: tmp_local_file.write(b"PyArrow Works") tmp_local_file.seek(0) repo.log_artifact(tmp_local_file.name, "test_hdfs/some/path") hdfs_system_mock.assert_called_once_with( extra_conf=None, host="default", kerb_ticket="/tmp/krb5cc_22222222", port=0, user="some_kerberos_user", ) # TODO: refactor this magic ... write_mock = hdfs_system_mock.return_value.open.return_value.__enter__.return_value.write write_mock.assert_called_once_with(b"PyArrow Works") @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_log_artifact_with_invalid_local_dir(_): repo = HdfsArtifactRepository("hdfs://host_name:8020/maybe/path") with pytest.raises(Exception, match="No such file or directory: '/not/existing/local/path'"): repo.log_artifact("/not/existing/local/path", "test_hdfs/some/path") @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_log_artifacts(hdfs_system_mock): os.environ["MLFLOW_KERBEROS_TICKET_CACHE"] = "/tmp/krb5cc_22222222" os.environ["MLFLOW_KERBEROS_USER"] = "some_kerberos_user" repo = HdfsArtifactRepository("hdfs:/some_path/maybe/path") with TempDir() as root_dir: with open(root_dir.path("file_one.txt"), "w") as f: f.write("PyArrow Works once") os.mkdir(root_dir.path("subdir")) with open(root_dir.path("subdir/file_two.txt"), "w") as f: f.write("PyArrow Works two") repo.log_artifacts(root_dir._path) hdfs_system_mock.assert_called_once_with( extra_conf=None, host="default", kerb_ticket="/tmp/krb5cc_22222222", port=0, user="some_kerberos_user", ) open_mock = hdfs_system_mock.return_value.open open_mock.assert_has_calls( calls=[ call("/some_path/maybe/path/file_one.txt", "wb"), call("/some_path/maybe/path/subdir/file_two.txt", "wb"), ], any_order=True, ) write_mock = open_mock.return_value.__enter__.return_value.write write_mock.assert_has_calls( calls=[call(b"PyArrow Works once"), call(b"PyArrow Works two")], any_order=True ) @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_list_artifacts_root(hdfs_system_mock): repo = HdfsArtifactRepository("hdfs://host/some/path") expected = [FileInfo("model", True, 0)] hdfs_system_mock.return_value.ls.return_value = [ {"kind": "directory", "name": "hdfs://host/some/path/model", "size": 0} ] actual = repo.list_artifacts() assert actual == expected @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_list_artifacts_nested(hdfs_system_mock): repo = HdfsArtifactRepository("hdfs:://host/some/path") expected = [ FileInfo("model/conda.yaml", False, 33), FileInfo("model/model.pkl", False, 33), FileInfo("model/MLmodel", False, 33), ] hdfs_system_mock.return_value.ls.return_value = [ {"kind": "file", "name": "hdfs://host/some/path/model/conda.yaml", "size": 33}, {"kind": "file", "name": "hdfs://host/some/path/model/model.pkl", "size": 33}, {"kind": "file", "name": "hdfs://host/some/path/model/MLmodel", "size": 33}, ] actual = repo.list_artifacts("model") assert actual == expected @mock.patch("pyarrow.hdfs.HadoopFileSystem", spec=HadoopFileSystem) def test_list_artifacts_empty_hdfs_dir(hdfs_system_mock): hdfs_system_mock.return_value.exists.return_value = False repo = HdfsArtifactRepository("hdfs:/some_path/maybe/path") actual = repo.list_artifacts() assert actual == [] def test_resolve_path(): assert _resolve_base_path("/dir/some/path", None) == "/dir/some/path" assert _resolve_base_path("/dir/some/path", "subdir/path") == "/dir/some/path/subdir/path" def test_relative_path(): assert _relative_path_remote("/dir/some", "/dir/some/path/file.txt") == "path/file.txt" assert _relative_path_remote("/dir/some", "/dir/some") is None def test_parse_extra_conf(): assert _parse_extra_conf("fs.permissions.umask-mode=022,some_other.extra.conf=abcd") == { "fs.permissions.umask-mode": "022", "some_other.extra.conf": "abcd", } assert _parse_extra_conf(None) is None with pytest.raises(ValueError, match="not enough values to unpack "): _parse_extra_conf("missing_equals_sign") def test_download_artifacts(): expected_data = b"hello" artifact_path = "test.txt" # mock hdfs hdfs = mock.Mock() hdfs.open = mock_open(read_data=expected_data) with TempDir() as tmp_dir: _download_hdfs_file(hdfs, artifact_path, os.path.join(tmp_dir.path(), artifact_path)) with open(os.path.join(tmp_dir.path(), artifact_path), "rb") as fd: assert expected_data == fd.read() @mock.patch("pyarrow.hdfs.HadoopFileSystem") def test_delete_artifacts(hdfs_system_mock): delete_mock = hdfs_system_mock.return_value.delete repo = HdfsArtifactRepository("hdfs:/some_path/maybe/path") repo.delete_artifacts("artifacts") delete_mock.assert_called_once_with("/some_path/maybe/path/artifacts", recursive=True)
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to generate a list of feature maps based on image features. Provides several feature map generators that can be used to build object detection feature extractors. Object detection feature extractors usually are built by stacking two components - A base feature extractor such as Inception V3 and a feature map generator. Feature map generators build on the base feature extractors and produce a list of final feature maps. """ import collections import functools import tensorflow as tf from tensorflow.contrib import slim as contrib_slim from object_detection.utils import ops from object_detection.utils import shape_utils slim = contrib_slim # Activation bound used for TPU v1. Activations will be clipped to # [-ACTIVATION_BOUND, ACTIVATION_BOUND] when training with # use_bounded_activations enabled. ACTIVATION_BOUND = 6.0 def get_depth_fn(depth_multiplier, min_depth): """Builds a callable to compute depth (output channels) of conv filters. Args: depth_multiplier: a multiplier for the nominal depth. min_depth: a lower bound on the depth of filters. Returns: A callable that takes in a nominal depth and returns the depth to use. """ def multiply_depth(depth): new_depth = int(depth * depth_multiplier) return max(new_depth, min_depth) return multiply_depth def create_conv_block( use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams, is_training, freeze_batchnorm, depth): """Create Keras layers for depthwise & non-depthwise convolutions. Args: use_depthwise: Whether to use depthwise separable conv instead of regular conv. kernel_size: A list of length 2: [kernel_height, kernel_width] of the filters. Can be an int if both values are the same. padding: One of 'VALID' or 'SAME'. stride: A list of length 2: [stride_height, stride_width], specifying the convolution stride. Can be an int if both strides are the same. layer_name: String. The name of the layer. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. is_training: Indicates whether the feature generator is in training mode. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. depth: Depth of output feature maps. Returns: A list of conv layers. """ layers = [] if use_depthwise: kwargs = conv_hyperparams.params() # Both the regularizer and initializer apply to the depthwise layer, # so we remap the kernel_* to depthwise_* here. kwargs['depthwise_regularizer'] = kwargs['kernel_regularizer'] kwargs['depthwise_initializer'] = kwargs['kernel_initializer'] layers.append( tf.keras.layers.SeparableConv2D( depth, [kernel_size, kernel_size], depth_multiplier=1, padding=padding, strides=stride, name=layer_name + '_depthwise_conv', **kwargs)) else: layers.append(tf.keras.layers.Conv2D( depth, [kernel_size, kernel_size], padding=padding, strides=stride, name=layer_name + '_conv', **conv_hyperparams.params())) layers.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name=layer_name + '_batchnorm')) layers.append( conv_hyperparams.build_activation_layer( name=layer_name)) return layers class KerasMultiResolutionFeatureMaps(tf.keras.Model): """Generates multi resolution feature maps from input image features. A Keras model that generates multi-scale feature maps for detection as in the SSD papers by Liu et al: https://arxiv.org/pdf/1512.02325v2.pdf, See Sec 2.1. More specifically, when called on inputs it performs the following two tasks: 1) If a layer name is provided in the configuration, returns that layer as a feature map. 2) If a layer name is left as an empty string, constructs a new feature map based on the spatial shape and depth configuration. Note that the current implementation only supports generating new layers using convolution of stride 2 resulting in a spatial resolution reduction by a factor of 2. By default convolution kernel size is set to 3, and it can be customized by caller. An example of the configuration for Inception V3: { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } When this feature generator object is called on input image_features: Args: image_features: A dictionary of handles to activation tensors from the base feature extractor. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. """ def __init__(self, feature_map_layout, depth_multiplier, min_depth, insert_1x1_conv, is_training, conv_hyperparams, freeze_batchnorm, name=None): """Constructor. Args: feature_map_layout: Dictionary of specifications for the feature map layouts in the following format (Inception V2/V3 respectively): { 'from_layer': ['Mixed_3c', 'Mixed_4c', 'Mixed_5c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } or { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } If 'from_layer' is specified, the specified feature map is directly used as a box predictor layer, and the layer_depth is directly infered from the feature map (instead of using the provided 'layer_depth' parameter). In this case, our convention is to set 'layer_depth' to -1 for clarity. Otherwise, if 'from_layer' is an empty string, then the box predictor layer will be built from the previous layer using convolution operations. Note that the current implementation only supports generating new layers using convolutions of stride 2 (resulting in a spatial resolution reduction by a factor of 2), and will be extended to a more flexible design. Convolution kernel size is set to 3 by default, and can be customized by 'conv_kernel_size' parameter (similarily, 'conv_kernel_size' should be set to -1 if 'from_layer' is specified). The created convolution operation will be a normal 2D convolution by default, and a depthwise convolution followed by 1x1 convolution if 'use_depthwise' is set to True. depth_multiplier: Depth multiplier for convolutional layers. min_depth: Minimum depth for convolutional layers. insert_1x1_conv: A boolean indicating whether an additional 1x1 convolution should be inserted before shrinking the feature map. is_training: Indicates whether the feature generator is in training mode. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. name: A string name scope to assign to the model. If 'None', Keras will auto-generate one from the class name. """ super(KerasMultiResolutionFeatureMaps, self).__init__(name=name) self.feature_map_layout = feature_map_layout self.convolutions = [] depth_fn = get_depth_fn(depth_multiplier, min_depth) base_from_layer = '' use_explicit_padding = False if 'use_explicit_padding' in feature_map_layout: use_explicit_padding = feature_map_layout['use_explicit_padding'] use_depthwise = False if 'use_depthwise' in feature_map_layout: use_depthwise = feature_map_layout['use_depthwise'] for index, from_layer in enumerate(feature_map_layout['from_layer']): net = [] layer_depth = feature_map_layout['layer_depth'][index] conv_kernel_size = 3 if 'conv_kernel_size' in feature_map_layout: conv_kernel_size = feature_map_layout['conv_kernel_size'][index] if from_layer: base_from_layer = from_layer else: if insert_1x1_conv: layer_name = '{}_1_Conv2d_{}_1x1_{}'.format( base_from_layer, index, depth_fn(layer_depth / 2)) net.append(tf.keras.layers.Conv2D(depth_fn(layer_depth / 2), [1, 1], padding='SAME', strides=1, name=layer_name + '_conv', **conv_hyperparams.params())) net.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name=layer_name + '_batchnorm')) net.append( conv_hyperparams.build_activation_layer( name=layer_name)) layer_name = '{}_2_Conv2d_{}_{}x{}_s2_{}'.format( base_from_layer, index, conv_kernel_size, conv_kernel_size, depth_fn(layer_depth)) stride = 2 padding = 'SAME' if use_explicit_padding: padding = 'VALID' # We define this function here while capturing the value of # conv_kernel_size, to avoid holding a reference to the loop variable # conv_kernel_size inside of a lambda function def fixed_padding(features, kernel_size=conv_kernel_size): return ops.fixed_padding(features, kernel_size) net.append(tf.keras.layers.Lambda(fixed_padding)) # TODO(rathodv): Add some utilities to simplify the creation of # Depthwise & non-depthwise convolutions w/ normalization & activations if use_depthwise: net.append(tf.keras.layers.DepthwiseConv2D( [conv_kernel_size, conv_kernel_size], depth_multiplier=1, padding=padding, strides=stride, name=layer_name + '_depthwise_conv', **conv_hyperparams.params())) net.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name=layer_name + '_depthwise_batchnorm')) net.append( conv_hyperparams.build_activation_layer( name=layer_name + '_depthwise')) net.append(tf.keras.layers.Conv2D(depth_fn(layer_depth), [1, 1], padding='SAME', strides=1, name=layer_name + '_conv', **conv_hyperparams.params())) net.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name=layer_name + '_batchnorm')) net.append( conv_hyperparams.build_activation_layer( name=layer_name)) else: net.append(tf.keras.layers.Conv2D( depth_fn(layer_depth), [conv_kernel_size, conv_kernel_size], padding=padding, strides=stride, name=layer_name + '_conv', **conv_hyperparams.params())) net.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name=layer_name + '_batchnorm')) net.append( conv_hyperparams.build_activation_layer( name=layer_name)) # Until certain bugs are fixed in checkpointable lists, # this net must be appended only once it's been filled with layers self.convolutions.append(net) def call(self, image_features): """Generate the multi-resolution feature maps. Executed when calling the `.__call__` method on input. Args: image_features: A dictionary of handles to activation tensors from the base feature extractor. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. """ feature_maps = [] feature_map_keys = [] for index, from_layer in enumerate(self.feature_map_layout['from_layer']): if from_layer: feature_map = image_features[from_layer] feature_map_keys.append(from_layer) else: feature_map = feature_maps[-1] for layer in self.convolutions[index]: feature_map = layer(feature_map) layer_name = self.convolutions[index][-1].name feature_map_keys.append(layer_name) feature_maps.append(feature_map) return collections.OrderedDict( [(x, y) for (x, y) in zip(feature_map_keys, feature_maps)]) def multi_resolution_feature_maps(feature_map_layout, depth_multiplier, min_depth, insert_1x1_conv, image_features, pool_residual=False): """Generates multi resolution feature maps from input image features. Generates multi-scale feature maps for detection as in the SSD papers by Liu et al: https://arxiv.org/pdf/1512.02325v2.pdf, See Sec 2.1. More specifically, it performs the following two tasks: 1) If a layer name is provided in the configuration, returns that layer as a feature map. 2) If a layer name is left as an empty string, constructs a new feature map based on the spatial shape and depth configuration. Note that the current implementation only supports generating new layers using convolution of stride 2 resulting in a spatial resolution reduction by a factor of 2. By default convolution kernel size is set to 3, and it can be customized by caller. An example of the configuration for Inception V3: { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } Args: feature_map_layout: Dictionary of specifications for the feature map layouts in the following format (Inception V2/V3 respectively): { 'from_layer': ['Mixed_3c', 'Mixed_4c', 'Mixed_5c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } or { 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''], 'layer_depth': [-1, -1, -1, 512, 256, 128] } If 'from_layer' is specified, the specified feature map is directly used as a box predictor layer, and the layer_depth is directly infered from the feature map (instead of using the provided 'layer_depth' parameter). In this case, our convention is to set 'layer_depth' to -1 for clarity. Otherwise, if 'from_layer' is an empty string, then the box predictor layer will be built from the previous layer using convolution operations. Note that the current implementation only supports generating new layers using convolutions of stride 2 (resulting in a spatial resolution reduction by a factor of 2), and will be extended to a more flexible design. Convolution kernel size is set to 3 by default, and can be customized by 'conv_kernel_size' parameter (similarily, 'conv_kernel_size' should be set to -1 if 'from_layer' is specified). The created convolution operation will be a normal 2D convolution by default, and a depthwise convolution followed by 1x1 convolution if 'use_depthwise' is set to True. depth_multiplier: Depth multiplier for convolutional layers. min_depth: Minimum depth for convolutional layers. insert_1x1_conv: A boolean indicating whether an additional 1x1 convolution should be inserted before shrinking the feature map. image_features: A dictionary of handles to activation tensors from the base feature extractor. pool_residual: Whether to add an average pooling layer followed by a residual connection between subsequent feature maps when the channel depth match. For example, with option 'layer_depth': [-1, 512, 256, 256], a pooling and residual layer is added between the third and forth feature map. This option is better used with Weight Shared Convolution Box Predictor when all feature maps have the same channel depth to encourage more consistent features across multi-scale feature maps. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. Raises: ValueError: if the number entries in 'from_layer' and 'layer_depth' do not match. ValueError: if the generated layer does not have the same resolution as specified. """ depth_fn = get_depth_fn(depth_multiplier, min_depth) feature_map_keys = [] feature_maps = [] base_from_layer = '' use_explicit_padding = False if 'use_explicit_padding' in feature_map_layout: use_explicit_padding = feature_map_layout['use_explicit_padding'] use_depthwise = False if 'use_depthwise' in feature_map_layout: use_depthwise = feature_map_layout['use_depthwise'] for index, from_layer in enumerate(feature_map_layout['from_layer']): layer_depth = feature_map_layout['layer_depth'][index] conv_kernel_size = 3 if 'conv_kernel_size' in feature_map_layout: conv_kernel_size = feature_map_layout['conv_kernel_size'][index] if from_layer: feature_map = image_features[from_layer] base_from_layer = from_layer feature_map_keys.append(from_layer) else: pre_layer = feature_maps[-1] pre_layer_depth = pre_layer.get_shape().as_list()[3] intermediate_layer = pre_layer if insert_1x1_conv: layer_name = '{}_1_Conv2d_{}_1x1_{}'.format( base_from_layer, index, depth_fn(layer_depth / 2)) intermediate_layer = slim.conv2d( pre_layer, depth_fn(layer_depth / 2), [1, 1], padding='SAME', stride=1, scope=layer_name) layer_name = '{}_2_Conv2d_{}_{}x{}_s2_{}'.format( base_from_layer, index, conv_kernel_size, conv_kernel_size, depth_fn(layer_depth)) stride = 2 padding = 'SAME' if use_explicit_padding: padding = 'VALID' intermediate_layer = ops.fixed_padding( intermediate_layer, conv_kernel_size) if use_depthwise: feature_map = slim.separable_conv2d( intermediate_layer, None, [conv_kernel_size, conv_kernel_size], depth_multiplier=1, padding=padding, stride=stride, scope=layer_name + '_depthwise') feature_map = slim.conv2d( feature_map, depth_fn(layer_depth), [1, 1], padding='SAME', stride=1, scope=layer_name) if pool_residual and pre_layer_depth == depth_fn(layer_depth): feature_map += slim.avg_pool2d( pre_layer, [3, 3], padding='SAME', stride=2, scope=layer_name + '_pool') else: feature_map = slim.conv2d( intermediate_layer, depth_fn(layer_depth), [conv_kernel_size, conv_kernel_size], padding=padding, stride=stride, scope=layer_name) feature_map_keys.append(layer_name) feature_maps.append(feature_map) return collections.OrderedDict( [(x, y) for (x, y) in zip(feature_map_keys, feature_maps)]) class KerasFpnTopDownFeatureMaps(tf.keras.Model): """Generates Keras based `top-down` feature maps for Feature Pyramid Networks. See https://arxiv.org/abs/1612.03144 for details. """ def __init__(self, num_levels, depth, is_training, conv_hyperparams, freeze_batchnorm, use_depthwise=False, use_explicit_padding=False, use_bounded_activations=False, use_native_resize_op=False, scope=None, name=None): """Constructor. Args: num_levels: the number of image features. depth: depth of output feature maps. is_training: Indicates whether the feature generator is in training mode. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. use_depthwise: whether to use depthwise separable conv instead of regular conv. use_explicit_padding: whether to use explicit padding. use_bounded_activations: Whether or not to clip activations to range [-ACTIVATION_BOUND, ACTIVATION_BOUND]. Bounded activations better lend themselves to quantized inference. use_native_resize_op: If True, uses tf.image.resize_nearest_neighbor op for the upsampling process instead of reshape and broadcasting implementation. scope: A scope name to wrap this op under. name: A string name scope to assign to the model. If 'None', Keras will auto-generate one from the class name. """ super(KerasFpnTopDownFeatureMaps, self).__init__(name=name) self.scope = scope if scope else 'top_down' self.top_layers = [] self.residual_blocks = [] self.top_down_blocks = [] self.reshape_blocks = [] self.conv_layers = [] padding = 'VALID' if use_explicit_padding else 'SAME' stride = 1 kernel_size = 3 def clip_by_value(features): return tf.clip_by_value(features, -ACTIVATION_BOUND, ACTIVATION_BOUND) # top layers self.top_layers.append(tf.keras.layers.Conv2D( depth, [1, 1], strides=stride, padding=padding, name='projection_%d' % num_levels, **conv_hyperparams.params(use_bias=True))) if use_bounded_activations: self.top_layers.append(tf.keras.layers.Lambda( clip_by_value, name='clip_by_value')) for level in reversed(range(num_levels - 1)): # to generate residual from image features residual_net = [] # to preprocess top_down (the image feature map from last layer) top_down_net = [] # to reshape top_down according to residual if necessary reshaped_residual = [] # to apply convolution layers to feature map conv_net = [] # residual block residual_net.append(tf.keras.layers.Conv2D( depth, [1, 1], padding=padding, strides=1, name='projection_%d' % (level + 1), **conv_hyperparams.params(use_bias=True))) if use_bounded_activations: residual_net.append(tf.keras.layers.Lambda( clip_by_value, name='clip_by_value')) # top-down block # TODO (b/128922690): clean-up of ops.nearest_neighbor_upsampling if use_native_resize_op: def resize_nearest_neighbor(image): image_shape = shape_utils.combined_static_and_dynamic_shape(image) return tf.image.resize_nearest_neighbor( image, [image_shape[1] * 2, image_shape[2] * 2]) top_down_net.append(tf.keras.layers.Lambda( resize_nearest_neighbor, name='nearest_neighbor_upsampling')) else: def nearest_neighbor_upsampling(image): return ops.nearest_neighbor_upsampling(image, scale=2) top_down_net.append(tf.keras.layers.Lambda( nearest_neighbor_upsampling, name='nearest_neighbor_upsampling')) # reshape block if use_explicit_padding: def reshape(inputs): residual_shape = tf.shape(inputs[0]) return inputs[1][:, :residual_shape[1], :residual_shape[2], :] reshaped_residual.append( tf.keras.layers.Lambda(reshape, name='reshape')) # down layers if use_bounded_activations: conv_net.append(tf.keras.layers.Lambda( clip_by_value, name='clip_by_value')) if use_explicit_padding: def fixed_padding(features, kernel_size=kernel_size): return ops.fixed_padding(features, kernel_size) conv_net.append(tf.keras.layers.Lambda( fixed_padding, name='fixed_padding')) layer_name = 'smoothing_%d' % (level + 1) conv_block = create_conv_block( use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams, is_training, freeze_batchnorm, depth) conv_net.extend(conv_block) self.residual_blocks.append(residual_net) self.top_down_blocks.append(top_down_net) self.reshape_blocks.append(reshaped_residual) self.conv_layers.append(conv_net) def call(self, image_features): """Generate the multi-resolution feature maps. Executed when calling the `.__call__` method on input. Args: image_features: list of tuples of (tensor_name, image_feature_tensor). Spatial resolutions of succesive tensors must reduce exactly by a factor of 2. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. """ output_feature_maps_list = [] output_feature_map_keys = [] with tf.name_scope(self.scope): top_down = image_features[-1][1] for layer in self.top_layers: top_down = layer(top_down) output_feature_maps_list.append(top_down) output_feature_map_keys.append('top_down_%s' % image_features[-1][0]) num_levels = len(image_features) for index, level in enumerate(reversed(range(num_levels - 1))): residual = image_features[level][1] top_down = output_feature_maps_list[-1] for layer in self.residual_blocks[index]: residual = layer(residual) for layer in self.top_down_blocks[index]: top_down = layer(top_down) for layer in self.reshape_blocks[index]: top_down = layer([residual, top_down]) top_down += residual for layer in self.conv_layers[index]: top_down = layer(top_down) output_feature_maps_list.append(top_down) output_feature_map_keys.append('top_down_%s' % image_features[level][0]) return collections.OrderedDict(reversed( list(zip(output_feature_map_keys, output_feature_maps_list)))) def fpn_top_down_feature_maps(image_features, depth, use_depthwise=False, use_explicit_padding=False, use_bounded_activations=False, scope=None, use_native_resize_op=False): """Generates `top-down` feature maps for Feature Pyramid Networks. See https://arxiv.org/abs/1612.03144 for details. Args: image_features: list of tuples of (tensor_name, image_feature_tensor). Spatial resolutions of succesive tensors must reduce exactly by a factor of 2. depth: depth of output feature maps. use_depthwise: whether to use depthwise separable conv instead of regular conv. use_explicit_padding: whether to use explicit padding. use_bounded_activations: Whether or not to clip activations to range [-ACTIVATION_BOUND, ACTIVATION_BOUND]. Bounded activations better lend themselves to quantized inference. scope: A scope name to wrap this op under. use_native_resize_op: If True, uses tf.image.resize_nearest_neighbor op for the upsampling process instead of reshape and broadcasting implementation. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. """ with tf.name_scope(scope, 'top_down'): num_levels = len(image_features) output_feature_maps_list = [] output_feature_map_keys = [] padding = 'VALID' if use_explicit_padding else 'SAME' kernel_size = 3 with slim.arg_scope( [slim.conv2d, slim.separable_conv2d], padding=padding, stride=1): top_down = slim.conv2d( image_features[-1][1], depth, [1, 1], activation_fn=None, normalizer_fn=None, scope='projection_%d' % num_levels) if use_bounded_activations: top_down = tf.clip_by_value(top_down, -ACTIVATION_BOUND, ACTIVATION_BOUND) output_feature_maps_list.append(top_down) output_feature_map_keys.append( 'top_down_%s' % image_features[-1][0]) for level in reversed(range(num_levels - 1)): if use_native_resize_op: with tf.name_scope('nearest_neighbor_upsampling'): top_down_shape = shape_utils.combined_static_and_dynamic_shape( top_down) top_down = tf.image.resize_nearest_neighbor( top_down, [top_down_shape[1] * 2, top_down_shape[2] * 2]) else: top_down = ops.nearest_neighbor_upsampling(top_down, scale=2) residual = slim.conv2d( image_features[level][1], depth, [1, 1], activation_fn=None, normalizer_fn=None, scope='projection_%d' % (level + 1)) if use_bounded_activations: residual = tf.clip_by_value(residual, -ACTIVATION_BOUND, ACTIVATION_BOUND) if use_explicit_padding: # slice top_down to the same shape as residual residual_shape = tf.shape(residual) top_down = top_down[:, :residual_shape[1], :residual_shape[2], :] top_down += residual if use_bounded_activations: top_down = tf.clip_by_value(top_down, -ACTIVATION_BOUND, ACTIVATION_BOUND) if use_depthwise: conv_op = functools.partial(slim.separable_conv2d, depth_multiplier=1) else: conv_op = slim.conv2d if use_explicit_padding: top_down = ops.fixed_padding(top_down, kernel_size) output_feature_maps_list.append(conv_op( top_down, depth, [kernel_size, kernel_size], scope='smoothing_%d' % (level + 1))) output_feature_map_keys.append('top_down_%s' % image_features[level][0]) return collections.OrderedDict(reversed( list(zip(output_feature_map_keys, output_feature_maps_list)))) def pooling_pyramid_feature_maps(base_feature_map_depth, num_layers, image_features, replace_pool_with_conv=False): """Generates pooling pyramid feature maps. The pooling pyramid feature maps is motivated by multi_resolution_feature_maps. The main difference are that it is simpler and reduces the number of free parameters. More specifically: - Instead of using convolutions to shrink the feature map, it uses max pooling, therefore totally gets rid of the parameters in convolution. - By pooling feature from larger map up to a single cell, it generates features in the same feature space. - Instead of independently making box predictions from individual maps, it shares the same classifier across different feature maps, therefore reduces the "mis-calibration" across different scales. See go/ppn-detection for more details. Args: base_feature_map_depth: Depth of the base feature before the max pooling. num_layers: Number of layers used to make predictions. They are pooled from the base feature. image_features: A dictionary of handles to activation tensors from the feature extractor. replace_pool_with_conv: Whether or not to replace pooling operations with convolutions in the PPN. Default is False. Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. Raises: ValueError: image_features does not contain exactly one entry """ if len(image_features) != 1: raise ValueError('image_features should be a dictionary of length 1.') image_features = image_features[image_features.keys()[0]] feature_map_keys = [] feature_maps = [] feature_map_key = 'Base_Conv2d_1x1_%d' % base_feature_map_depth if base_feature_map_depth > 0: image_features = slim.conv2d( image_features, base_feature_map_depth, [1, 1], # kernel size padding='SAME', stride=1, scope=feature_map_key) # Add a 1x1 max-pooling node (a no op node) immediately after the conv2d for # TPU v1 compatibility. Without the following dummy op, TPU runtime # compiler will combine the convolution with one max-pooling below into a # single cycle, so getting the conv2d feature becomes impossible. image_features = slim.max_pool2d( image_features, [1, 1], padding='SAME', stride=1, scope=feature_map_key) feature_map_keys.append(feature_map_key) feature_maps.append(image_features) feature_map = image_features if replace_pool_with_conv: with slim.arg_scope([slim.conv2d], padding='SAME', stride=2): for i in range(num_layers - 1): feature_map_key = 'Conv2d_{}_3x3_s2_{}'.format(i, base_feature_map_depth) feature_map = slim.conv2d( feature_map, base_feature_map_depth, [3, 3], scope=feature_map_key) feature_map_keys.append(feature_map_key) feature_maps.append(feature_map) else: with slim.arg_scope([slim.max_pool2d], padding='SAME', stride=2): for i in range(num_layers - 1): feature_map_key = 'MaxPool2d_%d_2x2' % i feature_map = slim.max_pool2d( feature_map, [2, 2], padding='SAME', scope=feature_map_key) feature_map_keys.append(feature_map_key) feature_maps.append(feature_map) return collections.OrderedDict( [(x, y) for (x, y) in zip(feature_map_keys, feature_maps)])
#!/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. import logging import os import pyauto_functional # Must be imported before pyauto import pyauto import test_utils class SpecialTabsTest(pyauto.PyUITest): """TestCase for Special Tabs like about:version, chrome://history, etc.""" @staticmethod def GetSpecialAcceleratorTabs(): """Get a dict of accelerators and corresponding tab titles.""" ret = { pyauto.IDC_SHOW_HISTORY: 'History', pyauto.IDC_MANAGE_EXTENSIONS: 'Extensions', pyauto.IDC_SHOW_DOWNLOADS: 'Downloads', } return ret special_url_redirects = { 'about:': 'chrome://version', 'about:about': 'chrome://about', 'about:appcache-internals': 'chrome://appcache-internals', 'about:credits': 'chrome://credits', 'about:dns': 'chrome://dns', 'about:histograms': 'chrome://histograms', 'about:plugins': 'chrome://plugins', 'about:sync': 'chrome://sync-internals', 'about:sync-internals': 'chrome://sync-internals', 'about:version': 'chrome://version', } special_url_tabs = { 'chrome://about': { 'title': 'Chrome URLs' }, 'chrome://appcache-internals': { 'title': 'AppCache Internals' }, 'chrome://blob-internals': { 'title': 'Blob Storage Internals' }, 'chrome://feedback': {}, 'chrome://chrome-urls': { 'title': 'Chrome URLs' }, 'chrome://crashes': { 'title': 'Crashes' }, 'chrome://credits': { 'title': 'Credits' }, 'chrome://downloads': { 'title': 'Downloads' }, 'chrome://dns': { 'title': 'About DNS' }, 'chrome://extensions': { 'title': 'Extensions' }, 'chrome://flags': {}, 'chrome://flash': {}, 'chrome://gpu-internals': {}, 'chrome://histograms': { 'title': 'About Histograms' }, 'chrome://history': { 'title': 'History' }, 'chrome://media-internals': { 'title': 'Media Internals' }, 'chrome://memory-redirect': { 'title': 'About Memory' }, 'chrome://net-internals': {}, 'chrome://net-internals/help.html': {}, 'chrome://newtab': { 'title': 'New Tab', 'CSP': False }, 'chrome://plugins': { 'title': 'Plug-ins' }, 'chrome://settings': { 'title': 'Settings' }, 'chrome://settings/autofill': { 'title': 'Settings - Autofill settings' }, 'chrome://settings/clearBrowserData': { 'title': 'Settings - Clear browsing data' }, 'chrome://settings/content': { 'title': 'Settings - Content settings' }, 'chrome://settings/languages': { 'title': 'Settings - Languages' }, 'chrome://settings/passwords': { 'title': 'Settings - Passwords' }, 'chrome://stats': {}, 'chrome://sync': { 'title': 'Sync Internals' }, 'chrome://sync-internals': { 'title': 'Sync Internals' }, 'chrome://terms': {}, 'chrome://version': { 'title': 'About Version' }, 'chrome://view-http-cache': {}, 'chrome://inspect': { 'title': 'Inspect with Chrome Developer Tools' }, } broken_special_url_tabs = { # crashed under debug when invoked from location bar (bug 88223). 'chrome://devtools': { 'CSP': False }, # returns "not available" despite having an URL constant. 'chrome://dialog': { 'CSP': False }, # separate window on mac, PC untested, not implemented elsewhere. 'chrome://ipc': { 'CSP': False }, # race against redirects via meta-refresh. 'chrome://memory': { 'CSP': False }, } chromeos_special_url_tabs = { 'chrome://choose-mobile-network': { 'title': 'undefined', 'CSP': True }, 'chrome://flags': { 'CSP': True }, 'chrome://imageburner': { 'title':'Create a Recovery Media', 'CSP': True }, 'chrome://keyboardoverlay': { 'title': 'Keyboard Overlay', 'CSP': True }, 'chrome://network': { 'title': 'About Network' }, 'chrome://os-credits': { 'title': 'Credits', 'CSP': False }, 'chrome://proxy-settings': { 'CSP': False }, 'chrome://register': { 'CSP': False }, 'chrome://settings/languages': { 'title': 'Settings - Languages and input' }, 'chrome://sim-unlock': { 'title': 'Enter SIM card PIN', 'CSP': False }, 'chrome://system': { 'title': 'About System', 'CSP': False }, # OVERRIDE - title and page different on CrOS 'chrome://settings/accounts': { 'title': 'Settings - Users' }, } broken_chromeos_special_url_tabs = { # returns "not available" page on chromeos=1 linux but has an URL constant. 'chrome://activationmessage': { 'CSP': False }, 'chrome://cloudprintresources': { 'CSP': False }, 'chrome://cloudprintsetup': { 'CSP': False }, 'chrome://collected-cookies': { 'CSP': False }, 'chrome://constrained-test': { 'CSP': False }, 'chrome://enterprise-enrollment': { 'CSP': False }, 'chrome://http-auth': { 'CSP': False }, 'chrome://login-container': { 'CSP': False }, 'chrome://media-player': { 'CSP': False }, 'chrome://screenshots': { 'CSP': False }, 'chrome://slideshow': { 'CSP': False }, 'chrome://syncresources': { 'CSP': False }, 'chrome://theme': { 'CSP': False }, 'chrome://view-http-cache': { 'CSP': False }, # crashes on chromeos=1 on linux, possibly missing real CrOS features. 'chrome://cryptohome': { 'CSP': False}, 'chrome://mobilesetup': { 'CSP': False }, 'chrome://print': { 'CSP': False }, } linux_special_url_tabs = { 'chrome://linux-proxy-config': { 'title': 'Proxy Configuration Help' }, 'chrome://tcmalloc': { 'title': 'tcmalloc stats' }, 'chrome://sandbox': { 'title': 'Sandbox Status' }, } broken_linux_special_url_tabs = {} mac_special_url_tabs = { 'chrome://settings/languages': { 'title': 'Settings - Languages' }, } broken_mac_special_url_tabs = {} win_special_url_tabs = { 'chrome://conflicts': {}, } broken_win_special_url_tabs = { # Sync on windows badly broken at the moment. 'chrome://sync': {}, } google_special_url_tabs = { # OVERRIDE - different title for Google Chrome vs. Chromium. 'chrome://terms': { 'title': 'Google Chrome Terms of Service', }, } broken_google_special_url_tabs = {} google_chromeos_special_url_tabs = { # OVERRIDE - different title for Google Chrome OS vs. Chromium OS. 'chrome://terms': { 'title': 'Google Chrome OS Terms', }, } broken_google_chromeos_special_url_tabs = {} google_win_special_url_tabs = {} broken_google_win_special_url_tabs = {} google_mac_special_url_tabs = {} broken_google_mac_special_url_tabs = {} google_linux_special_url_tabs = {} broken_google_linux_special_url_tabs = {} def _VerifyAppCacheInternals(self): """Confirm about:appcache-internals contains expected content for Caches. Also confirms that the about page populates Application Caches.""" # Navigate to html page to activate DNS prefetching. self.NavigateToURL('http://futtta.be/html5/offline.php') # Wait for page to load and display sucess or fail message. self.WaitUntil( lambda: self.GetDOMValue('document.getElementById("status").innerHTML'), expect_retval='cached') self.TabGoBack() test_utils.StringContentCheck( self, self.GetTabContents(), ['Manifest', 'http://futtta.be/html5/manifest.php'], []) def _VerifyAboutDNS(self): """Confirm about:dns contains expected content related to DNS info. Also confirms that prefetching DNS records propogate.""" # Navigate to a page to activate DNS prefetching. self.NavigateToURL('http://www.google.com') self.TabGoBack() test_utils.StringContentCheck(self, self.GetTabContents(), ['Host name', 'How long ago', 'Motivation'], []) def _GetPlatformSpecialURLTabs(self): tabs = self.special_url_tabs.copy() broken_tabs = self.broken_special_url_tabs.copy() if self.IsChromeOS(): tabs.update(self.chromeos_special_url_tabs) broken_tabs.update(self.broken_chromeos_special_url_tabs) elif self.IsLinux(): tabs.update(self.linux_special_url_tabs) broken_tabs.update(self.broken_linux_special_url_tabs) elif self.IsMac(): tabs.update(self.mac_special_url_tabs) broken_tabs.update(self.broken_mac_special_url_tabs) elif self.IsWin(): tabs.update(self.win_special_url_tabs) broken_tabs.update(self.broken_win_special_url_tabs) for key, value in broken_tabs.iteritems(): if key in tabs: del tabs[key] broken_tabs = {} if self.GetBrowserInfo()['properties']['branding'] == 'Google Chrome': tabs.update(self.google_special_url_tabs) broken_tabs.update(self.broken_google_special_url_tabs) if self.IsChromeOS(): tabs.update(self.google_chromeos_special_url_tabs) broken_tabs.update(self.broken_google_chromeos_special_url_tabs) elif self.IsLinux(): tabs.update(self.google_linux_special_url_tabs) broken_tabs.update(self.broken_google_linux_special_url_tabs) elif self.IsMac(): tabs.update(self.google_mac_special_url_tabs) broken_tabs.update(self.broken_google_mac_special_url_tabs) elif self.IsWin(): tabs.update(self.google_win_special_url_tabs) broken_tabs.update(self.broken_google_win_special_url_tabs) for key, value in broken_tabs.iteritems(): if key in tabs: del tabs[key] return tabs def testSpecialURLRedirects(self): """Test that older about: URLs are implemented by newer chrome:// URLs. The location bar may not get updated in all cases, so checking the tab URL is misleading, instead check for the same contents as the chrome:// page.""" tabs = self._GetPlatformSpecialURLTabs() for url, redirect in self.special_url_redirects.iteritems(): if redirect in tabs: logging.debug('Testing redirect from %s to %s.' % (url, redirect)) self.NavigateToURL(url) self.assertEqual(self.special_url_tabs[redirect]['title'], self.GetActiveTabTitle()) def testSpecialURLTabs(self): """Test special tabs created by URLs like chrome://downloads, chrome://settings/extensionSettings, chrome://history etc. Also ensures they specify content-security-policy and not inline scripts for those pages that are expected to do so. Patches which break this test by including new inline javascript are security vulnerabilities and should be reverted.""" tabs = self._GetPlatformSpecialURLTabs() for url, properties in tabs.iteritems(): logging.debug('Testing URL %s.' % url) self.NavigateToURL(url) expected_title = 'title' in properties and properties['title'] or url actual_title = self.GetActiveTabTitle() self.assertTrue(self.WaitUntil( lambda: self.GetActiveTabTitle(), expect_retval=expected_title), msg='Title did not match for %s. Expected: %s. Got %s' % ( url, expected_title, self.GetActiveTabTitle())) include_list = [] exclude_list = [] no_csp = 'CSP' in properties and not properties['CSP'] if no_csp: exclude_list.extend(['X-WebKit-CSP']) else: exclude_list.extend(['<script>', 'onclick=', 'onload=', 'onchange=', 'onsubmit=', 'javascript:']) if 'includes' in properties: include_list.extend(properties['includes']) if 'excludes' in properties: exclude_list.extend(properties['exlcudes']) test_utils.StringContentCheck(self, self.GetTabContents(), include_list, exclude_list) result = self.ExecuteJavascript(""" var r = 'blocked'; var f = 'executed'; var s = document.createElement('script'); s.textContent = 'r = f'; document.body.appendChild(s); window.domAutomationController.send(r); """) logging.debug('has csp %s, result %s.' % (not no_csp, result)) if no_csp: self.assertEqual(result, 'executed', msg='Got %s for %s' % (result, url)) else: self.assertEqual(result, 'blocked', msg='Got %s for %s' % (result, url)) # Restart browser so that every URL gets a fresh instance. self.RestartBrowser(clear_profile=True) def testAboutAppCacheTab(self): """Test App Cache tab to confirm about page populates caches.""" self.NavigateToURL('about:appcache-internals') self._VerifyAppCacheInternals() self.assertEqual('AppCache Internals', self.GetActiveTabTitle()) def testAboutDNSTab(self): """Test DNS tab to confirm DNS about page propogates records.""" self.NavigateToURL('about:dns') self._VerifyAboutDNS() self.assertEqual('About DNS', self.GetActiveTabTitle()) def testSpecialAcceratorTabs(self): """Test special tabs created by accelerators.""" for accel, title in self.GetSpecialAcceleratorTabs().iteritems(): self.RunCommand(accel) self.assertTrue(self.WaitUntil( self.GetActiveTabTitle, expect_retval=title), msg='Expected "%s", got "%s"' % (title, self.GetActiveTabTitle())) if __name__ == '__main__': pyauto_functional.Main()
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ For internal use only. No backwards compatibility guarantees. Dataflow client utility functions.""" import codecs import getpass import json import logging import os import re import time from datetime import datetime from StringIO import StringIO from apitools.base.py import encoding from apitools.base.py import exceptions from apache_beam.internal.gcp.auth import get_service_credentials from apache_beam.internal.gcp.json_value import to_json_value from apache_beam.io.filesystems import FileSystems from apache_beam.io.gcp.internal.clients import storage from apache_beam.options.pipeline_options import DebugOptions from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.pipeline_options import WorkerOptions from apache_beam.runners.dataflow.internal import dependency from apache_beam.runners.dataflow.internal import names from apache_beam.runners.dataflow.internal.clients import dataflow from apache_beam.runners.dataflow.internal.dependency import get_sdk_name_and_version from apache_beam.runners.dataflow.internal.names import PropertyNames from apache_beam.transforms import cy_combiners from apache_beam.transforms.display import DisplayData from apache_beam.utils import retry # Environment version information. It is passed to the service during a # a job submission and is used by the service to establish what features # are expected by the workers. _LEGACY_ENVIRONMENT_MAJOR_VERSION = '6' _FNAPI_ENVIRONMENT_MAJOR_VERSION = '1' class Step(object): """Wrapper for a dataflow Step protobuf.""" def __init__(self, step_kind, step_name, additional_properties=None): self.step_kind = step_kind self.step_name = step_name self.proto = dataflow.Step(kind=step_kind, name=step_name) self.proto.properties = {} self._additional_properties = [] if additional_properties is not None: for (n, v, t) in additional_properties: self.add_property(n, v, t) def add_property(self, name, value, with_type=False): self._additional_properties.append((name, value, with_type)) self.proto.properties.additionalProperties.append( dataflow.Step.PropertiesValue.AdditionalProperty( key=name, value=to_json_value(value, with_type=with_type))) def _get_outputs(self): """Returns a list of all output labels for a step.""" outputs = [] for p in self.proto.properties.additionalProperties: if p.key == PropertyNames.OUTPUT_INFO: for entry in p.value.array_value.entries: for entry_prop in entry.object_value.properties: if entry_prop.key == PropertyNames.OUTPUT_NAME: outputs.append(entry_prop.value.string_value) return outputs def __reduce__(self): """Reduce hook for pickling the Step class more easily.""" return (Step, (self.step_kind, self.step_name, self._additional_properties)) def get_output(self, tag=None): """Returns name if it is one of the outputs or first output if name is None. Args: tag: tag of the output as a string or None if we want to get the name of the first output. Returns: The name of the output associated with the tag or the first output if tag was None. Raises: ValueError: if the tag does not exist within outputs. """ outputs = self._get_outputs() if tag is None: return outputs[0] else: name = '%s_%s' % (PropertyNames.OUT, tag) if name not in outputs: raise ValueError( 'Cannot find named output: %s in %s.' % (name, outputs)) return name class Environment(object): """Wrapper for a dataflow Environment protobuf.""" def __init__(self, packages, options, environment_version, pipeline_url): self.standard_options = options.view_as(StandardOptions) self.google_cloud_options = options.view_as(GoogleCloudOptions) self.worker_options = options.view_as(WorkerOptions) self.debug_options = options.view_as(DebugOptions) self.pipeline_url = pipeline_url self.proto = dataflow.Environment() self.proto.clusterManagerApiService = GoogleCloudOptions.COMPUTE_API_SERVICE self.proto.dataset = '{}/cloud_dataflow'.format( GoogleCloudOptions.BIGQUERY_API_SERVICE) self.proto.tempStoragePrefix = ( self.google_cloud_options.temp_location.replace( 'gs:/', GoogleCloudOptions.STORAGE_API_SERVICE)) # User agent information. self.proto.userAgent = dataflow.Environment.UserAgentValue() self.local = 'localhost' in self.google_cloud_options.dataflow_endpoint if self.google_cloud_options.service_account_email: self.proto.serviceAccountEmail = ( self.google_cloud_options.service_account_email) sdk_name, version_string = get_sdk_name_and_version() self.proto.userAgent.additionalProperties.extend([ dataflow.Environment.UserAgentValue.AdditionalProperty( key='name', value=to_json_value(sdk_name)), dataflow.Environment.UserAgentValue.AdditionalProperty( key='version', value=to_json_value(version_string))]) # Version information. self.proto.version = dataflow.Environment.VersionValue() if self.standard_options.streaming: job_type = 'FNAPI_STREAMING' else: if _use_fnapi(options): job_type = 'FNAPI_BATCH' else: job_type = 'PYTHON_BATCH' self.proto.version.additionalProperties.extend([ dataflow.Environment.VersionValue.AdditionalProperty( key='job_type', value=to_json_value(job_type)), dataflow.Environment.VersionValue.AdditionalProperty( key='major', value=to_json_value(environment_version))]) # TODO: Use enumerated type instead of strings for job types. if job_type.startswith('FNAPI_'): runner_harness_override = ( dependency.get_runner_harness_container_image()) if runner_harness_override: self.debug_options.experiments = self.debug_options.experiments or [] self.debug_options.experiments.append( 'runner_harness_container_image=' + runner_harness_override) # Experiments if self.debug_options.experiments: for experiment in self.debug_options.experiments: self.proto.experiments.append(experiment) # Worker pool(s) information. package_descriptors = [] for package in packages: package_descriptors.append( dataflow.Package( location='%s/%s' % ( self.google_cloud_options.staging_location.replace( 'gs:/', GoogleCloudOptions.STORAGE_API_SERVICE), package), name=package)) pool = dataflow.WorkerPool( kind='local' if self.local else 'harness', packages=package_descriptors, taskrunnerSettings=dataflow.TaskRunnerSettings( parallelWorkerSettings=dataflow.WorkerSettings( baseUrl=GoogleCloudOptions.DATAFLOW_ENDPOINT, servicePath=self.google_cloud_options.dataflow_endpoint))) pool.autoscalingSettings = dataflow.AutoscalingSettings() # Set worker pool options received through command line. if self.worker_options.num_workers: pool.numWorkers = self.worker_options.num_workers if self.worker_options.max_num_workers: pool.autoscalingSettings.maxNumWorkers = ( self.worker_options.max_num_workers) if self.worker_options.autoscaling_algorithm: values_enum = dataflow.AutoscalingSettings.AlgorithmValueValuesEnum pool.autoscalingSettings.algorithm = { 'NONE': values_enum.AUTOSCALING_ALGORITHM_NONE, 'THROUGHPUT_BASED': values_enum.AUTOSCALING_ALGORITHM_BASIC, }.get(self.worker_options.autoscaling_algorithm) if self.worker_options.machine_type: pool.machineType = self.worker_options.machine_type if self.worker_options.disk_size_gb: pool.diskSizeGb = self.worker_options.disk_size_gb if self.worker_options.disk_type: pool.diskType = self.worker_options.disk_type if self.worker_options.zone: pool.zone = self.worker_options.zone if self.worker_options.network: pool.network = self.worker_options.network if self.worker_options.subnetwork: pool.subnetwork = self.worker_options.subnetwork if self.worker_options.worker_harness_container_image: pool.workerHarnessContainerImage = ( self.worker_options.worker_harness_container_image) else: pool.workerHarnessContainerImage = ( dependency.get_default_container_image_for_current_sdk(job_type)) if self.worker_options.use_public_ips is not None: if self.worker_options.use_public_ips: pool.ipConfiguration = ( dataflow.WorkerPool .IpConfigurationValueValuesEnum.WORKER_IP_PUBLIC) else: pool.ipConfiguration = ( dataflow.WorkerPool .IpConfigurationValueValuesEnum.WORKER_IP_PRIVATE) if self.standard_options.streaming: # Use separate data disk for streaming. disk = dataflow.Disk() if self.local: disk.diskType = 'local' # TODO(ccy): allow customization of disk. pool.dataDisks.append(disk) self.proto.workerPools.append(pool) sdk_pipeline_options = options.get_all_options() if sdk_pipeline_options: self.proto.sdkPipelineOptions = ( dataflow.Environment.SdkPipelineOptionsValue()) options_dict = {k: v for k, v in sdk_pipeline_options.iteritems() if v is not None} options_dict["pipelineUrl"] = pipeline_url self.proto.sdkPipelineOptions.additionalProperties.append( dataflow.Environment.SdkPipelineOptionsValue.AdditionalProperty( key='options', value=to_json_value(options_dict))) dd = DisplayData.create_from_options(options) items = [item.get_dict() for item in dd.items] self.proto.sdkPipelineOptions.additionalProperties.append( dataflow.Environment.SdkPipelineOptionsValue.AdditionalProperty( key='display_data', value=to_json_value(items))) class Job(object): """Wrapper for a dataflow Job protobuf.""" def __str__(self): def encode_shortstrings(input_buffer, errors='strict'): """Encoder (from Unicode) that suppresses long base64 strings.""" original_len = len(input_buffer) if original_len > 150: if self.base64_str_re.match(input_buffer): input_buffer = '<string of %d bytes>' % original_len input_buffer = input_buffer.encode('ascii', errors=errors) else: matched = self.coder_str_re.match(input_buffer) if matched: input_buffer = '%s<string of %d bytes>' % ( matched.group(1), matched.end(2) - matched.start(2)) input_buffer = input_buffer.encode('ascii', errors=errors) return input_buffer, original_len def decode_shortstrings(input_buffer, errors='strict'): """Decoder (to Unicode) that suppresses long base64 strings.""" shortened, length = encode_shortstrings(input_buffer, errors) return unicode(shortened), length def shortstrings_registerer(encoding_name): if encoding_name == 'shortstrings': return codecs.CodecInfo(name='shortstrings', encode=encode_shortstrings, decode=decode_shortstrings) return None codecs.register(shortstrings_registerer) # Use json "dump string" method to get readable formatting; # further modify it to not output too-long strings, aimed at the # 10,000+ character hex-encoded "serialized_fn" values. return json.dumps( json.loads(encoding.MessageToJson(self.proto), encoding='shortstrings'), indent=2, sort_keys=True) @staticmethod def _build_default_job_name(user_name): """Generates a default name for a job. user_name is lowercased, and any characters outside of [-a-z0-9] are removed. If necessary, the user_name is truncated to shorten the job name to 63 characters.""" user_name = re.sub('[^-a-z0-9]', '', user_name.lower()) date_component = datetime.utcnow().strftime('%m%d%H%M%S-%f') app_user_name = 'beamapp-{}'.format(user_name) job_name = '{}-{}'.format(app_user_name, date_component) if len(job_name) > 63: job_name = '{}-{}'.format(app_user_name[:-(len(job_name) - 63)], date_component) return job_name @staticmethod def default_job_name(job_name): if job_name is None: job_name = Job._build_default_job_name(getpass.getuser()) return job_name def __init__(self, options, proto_pipeline): self.options = options self.proto_pipeline = proto_pipeline self.google_cloud_options = options.view_as(GoogleCloudOptions) if not self.google_cloud_options.job_name: self.google_cloud_options.job_name = self.default_job_name( self.google_cloud_options.job_name) required_google_cloud_options = ['project', 'job_name', 'temp_location'] missing = [ option for option in required_google_cloud_options if not getattr(self.google_cloud_options, option)] if missing: raise ValueError( 'Missing required configuration parameters: %s' % missing) if not self.google_cloud_options.staging_location: logging.info('Defaulting to the temp_location as staging_location: %s', self.google_cloud_options.temp_location) (self.google_cloud_options .staging_location) = self.google_cloud_options.temp_location # Make the staging and temp locations job name and time specific. This is # needed to avoid clashes between job submissions using the same staging # area or team members using same job names. This method is not entirely # foolproof since two job submissions with same name can happen at exactly # the same time. However the window is extremely small given that # time.time() has at least microseconds granularity. We add the suffix only # for GCS staging locations where the potential for such clashes is high. if self.google_cloud_options.staging_location.startswith('gs://'): path_suffix = '%s.%f' % (self.google_cloud_options.job_name, time.time()) self.google_cloud_options.staging_location = FileSystems.join( self.google_cloud_options.staging_location, path_suffix) self.google_cloud_options.temp_location = FileSystems.join( self.google_cloud_options.temp_location, path_suffix) self.proto = dataflow.Job(name=self.google_cloud_options.job_name) if self.options.view_as(StandardOptions).streaming: self.proto.type = dataflow.Job.TypeValueValuesEnum.JOB_TYPE_STREAMING else: self.proto.type = dataflow.Job.TypeValueValuesEnum.JOB_TYPE_BATCH # Labels. if self.google_cloud_options.labels: self.proto.labels = dataflow.Job.LabelsValue() for label in self.google_cloud_options.labels: parts = label.split('=', 1) key = parts[0] value = parts[1] if len(parts) > 1 else '' self.proto.labels.additionalProperties.append( dataflow.Job.LabelsValue.AdditionalProperty(key=key, value=value)) self.base64_str_re = re.compile(r'^[A-Za-z0-9+/]*=*$') self.coder_str_re = re.compile(r'^([A-Za-z]+\$)([A-Za-z0-9+/]*=*)$') def json(self): return encoding.MessageToJson(self.proto) def __reduce__(self): """Reduce hook for pickling the Job class more easily.""" return (Job, (self.options,)) class DataflowApplicationClient(object): """A Dataflow API client used by application code to create and query jobs.""" def __init__(self, options): """Initializes a Dataflow API client object.""" self.standard_options = options.view_as(StandardOptions) self.google_cloud_options = options.view_as(GoogleCloudOptions) if _use_fnapi(options): self.environment_version = _FNAPI_ENVIRONMENT_MAJOR_VERSION else: self.environment_version = _LEGACY_ENVIRONMENT_MAJOR_VERSION if self.google_cloud_options.no_auth: credentials = None else: credentials = get_service_credentials() self._client = dataflow.DataflowV1b3( url=self.google_cloud_options.dataflow_endpoint, credentials=credentials, get_credentials=(not self.google_cloud_options.no_auth)) self._storage_client = storage.StorageV1( url='https://www.googleapis.com/storage/v1', credentials=credentials, get_credentials=(not self.google_cloud_options.no_auth)) # TODO(silviuc): Refactor so that retry logic can be applied. @retry.no_retries # Using no_retries marks this as an integration point. def _gcs_file_copy(self, from_path, to_path): to_folder, to_name = os.path.split(to_path) with open(from_path, 'rb') as f: self.stage_file(to_folder, to_name, f) def stage_file(self, gcs_or_local_path, file_name, stream, mime_type='application/octet-stream'): """Stages a file at a GCS or local path with stream-supplied contents.""" if not gcs_or_local_path.startswith('gs://'): local_path = FileSystems.join(gcs_or_local_path, file_name) logging.info('Staging file locally to %s', local_path) with open(local_path, 'wb') as f: f.write(stream.read()) return gcs_location = FileSystems.join(gcs_or_local_path, file_name) bucket, name = gcs_location[5:].split('/', 1) request = storage.StorageObjectsInsertRequest( bucket=bucket, name=name) logging.info('Starting GCS upload to %s...', gcs_location) upload = storage.Upload(stream, mime_type) try: response = self._storage_client.objects.Insert(request, upload=upload) except exceptions.HttpError as e: reportable_errors = { 403: 'access denied', 404: 'bucket not found', } if e.status_code in reportable_errors: raise IOError(('Could not upload to GCS path %s: %s. Please verify ' 'that credentials are valid and that you have write ' 'access to the specified path.') % (gcs_or_local_path, reportable_errors[e.status_code])) raise logging.info('Completed GCS upload to %s', gcs_location) return response @retry.no_retries # Using no_retries marks this as an integration point. def create_job(self, job): """Creates job description. May stage and/or submit for remote execution.""" self.create_job_description(job) # Stage and submit the job when necessary dataflow_job_file = job.options.view_as(DebugOptions).dataflow_job_file template_location = ( job.options.view_as(GoogleCloudOptions).template_location) job_location = template_location or dataflow_job_file if job_location: gcs_or_local_path = os.path.dirname(job_location) file_name = os.path.basename(job_location) self.stage_file(gcs_or_local_path, file_name, StringIO(job.json())) if not template_location: return self.submit_job_description(job) logging.info('A template was just created at location %s', template_location) return None def create_job_description(self, job): """Creates a job described by the workflow proto.""" # Stage the pipeline for the runner harness self.stage_file(job.google_cloud_options.staging_location, names.STAGED_PIPELINE_FILENAME, StringIO(job.proto_pipeline.SerializeToString())) # Stage other resources for the SDK harness resources = dependency.stage_job_resources( job.options, file_copy=self._gcs_file_copy) job.proto.environment = Environment( pipeline_url=FileSystems.join(job.google_cloud_options.staging_location, names.STAGED_PIPELINE_FILENAME), packages=resources, options=job.options, environment_version=self.environment_version).proto logging.debug('JOB: %s', job) @retry.with_exponential_backoff(num_retries=3, initial_delay_secs=3) def get_job_metrics(self, job_id): request = dataflow.DataflowProjectsLocationsJobsGetMetricsRequest() request.jobId = job_id request.location = self.google_cloud_options.region request.projectId = self.google_cloud_options.project try: response = self._client.projects_locations_jobs.GetMetrics(request) except exceptions.BadStatusCodeError as e: logging.error('HTTP status %d. Unable to query metrics', e.response.status) raise return response @retry.with_exponential_backoff(num_retries=3) def submit_job_description(self, job): """Creates and excutes a job request.""" request = dataflow.DataflowProjectsLocationsJobsCreateRequest() request.projectId = self.google_cloud_options.project request.location = self.google_cloud_options.region request.job = job.proto try: response = self._client.projects_locations_jobs.Create(request) except exceptions.BadStatusCodeError as e: logging.error('HTTP status %d trying to create job' ' at dataflow service endpoint %s', e.response.status, self.google_cloud_options.dataflow_endpoint) logging.fatal('details of server error: %s', e) raise logging.info('Create job: %s', response) # The response is a Job proto with the id for the new job. logging.info('Created job with id: [%s]', response.id) logging.info( 'To access the Dataflow monitoring console, please navigate to ' 'https://console.cloud.google.com/dataflow/jobsDetail' '/locations/%s/jobs/%s?project=%s', self.google_cloud_options.region, response.id, self.google_cloud_options.project) return response @retry.with_exponential_backoff() # Using retry defaults from utils/retry.py def modify_job_state(self, job_id, new_state): """Modify the run state of the job. Args: job_id: The id of the job. new_state: A string representing the new desired state. It could be set to either 'JOB_STATE_DONE', 'JOB_STATE_CANCELLED' or 'JOB_STATE_DRAINING'. Returns: True if the job was modified successfully. """ if new_state == 'JOB_STATE_DONE': new_state = dataflow.Job.RequestedStateValueValuesEnum.JOB_STATE_DONE elif new_state == 'JOB_STATE_CANCELLED': new_state = dataflow.Job.RequestedStateValueValuesEnum.JOB_STATE_CANCELLED elif new_state == 'JOB_STATE_DRAINING': new_state = dataflow.Job.RequestedStateValueValuesEnum.JOB_STATE_DRAINING else: # Other states could only be set by the service. return False request = dataflow.DataflowProjectsLocationsJobsUpdateRequest() request.jobId = job_id request.projectId = self.google_cloud_options.project request.location = self.google_cloud_options.region request.job = dataflow.Job(requestedState=new_state) self._client.projects_locations_jobs.Update(request) return True @retry.with_exponential_backoff() # Using retry defaults from utils/retry.py def get_job(self, job_id): """Gets the job status for a submitted job. Args: job_id: A string representing the job_id for the workflow as returned by the a create_job() request. Returns: A Job proto. See below for interesting fields. The Job proto returned from a get_job() request contains some interesting fields: currentState: An object representing the current state of the job. The string representation of the object (str() result) has the following possible values: JOB_STATE_UNKNONW, JOB_STATE_STOPPED, JOB_STATE_RUNNING, JOB_STATE_DONE, JOB_STATE_FAILED, JOB_STATE_CANCELLED. createTime: UTC time when the job was created (e.g. '2015-03-10T00:01:53.074Z') currentStateTime: UTC time for the current state of the job. """ request = dataflow.DataflowProjectsLocationsJobsGetRequest() request.jobId = job_id request.projectId = self.google_cloud_options.project request.location = self.google_cloud_options.region response = self._client.projects_locations_jobs.Get(request) return response @retry.with_exponential_backoff() # Using retry defaults from utils/retry.py def list_messages( self, job_id, start_time=None, end_time=None, page_token=None, minimum_importance=None): """List messages associated with the execution of a job. Args: job_id: A string representing the job_id for the workflow as returned by the a create_job() request. start_time: If specified, only messages generated after the start time will be returned, otherwise all messages since job started will be returned. The value is a string representing UTC time (e.g., '2015-08-18T21:03:50.644Z') end_time: If specified, only messages generated before the end time will be returned, otherwise all messages up to current time will be returned. The value is a string representing UTC time (e.g., '2015-08-18T21:03:50.644Z') page_token: A string to be used as next page token if the list call returned paginated results. minimum_importance: Filter for messages based on importance. The possible string values in increasing order of importance are: JOB_MESSAGE_DEBUG, JOB_MESSAGE_DETAILED, JOB_MESSAGE_BASIC, JOB_MESSAGE_WARNING, JOB_MESSAGE_ERROR. For example, a filter set on warning will allow only warnings and errors and exclude all others. Returns: A tuple consisting of a list of JobMessage instances and a next page token string. Raises: RuntimeError: if an unexpected value for the message_importance argument is used. The JobMessage objects returned by the call contain the following fields: id: A unique string identifier for the message. time: A string representing the UTC time of the message (e.g., '2015-08-18T21:03:50.644Z') messageImportance: An enumeration value for the message importance. The value if converted to string will have the following possible values: JOB_MESSAGE_DEBUG, JOB_MESSAGE_DETAILED, JOB_MESSAGE_BASIC, JOB_MESSAGE_WARNING, JOB_MESSAGE_ERROR. messageText: A message string. """ request = dataflow.DataflowProjectsLocationsJobsMessagesListRequest( jobId=job_id, location=self.google_cloud_options.region, projectId=self.google_cloud_options.project) if page_token is not None: request.pageToken = page_token if start_time is not None: request.startTime = start_time if end_time is not None: request.endTime = end_time if minimum_importance is not None: if minimum_importance == 'JOB_MESSAGE_DEBUG': request.minimumImportance = ( dataflow.DataflowProjectsLocationsJobsMessagesListRequest .MinimumImportanceValueValuesEnum .JOB_MESSAGE_DEBUG) elif minimum_importance == 'JOB_MESSAGE_DETAILED': request.minimumImportance = ( dataflow.DataflowProjectsLocationsJobsMessagesListRequest .MinimumImportanceValueValuesEnum .JOB_MESSAGE_DETAILED) elif minimum_importance == 'JOB_MESSAGE_BASIC': request.minimumImportance = ( dataflow.DataflowProjectsLocationsJobsMessagesListRequest .MinimumImportanceValueValuesEnum .JOB_MESSAGE_BASIC) elif minimum_importance == 'JOB_MESSAGE_WARNING': request.minimumImportance = ( dataflow.DataflowProjectsLocationsJobsMessagesListRequest .MinimumImportanceValueValuesEnum .JOB_MESSAGE_WARNING) elif minimum_importance == 'JOB_MESSAGE_ERROR': request.minimumImportance = ( dataflow.DataflowProjectsLocationsJobsMessagesListRequest .MinimumImportanceValueValuesEnum .JOB_MESSAGE_ERROR) else: raise RuntimeError( 'Unexpected value for minimum_importance argument: %r', minimum_importance) response = self._client.projects_locations_jobs_messages.List(request) return response.jobMessages, response.nextPageToken class MetricUpdateTranslators(object): """Translators between accumulators and dataflow metric updates.""" @staticmethod def translate_boolean(accumulator, metric_update_proto): metric_update_proto.boolean = accumulator.value @staticmethod def translate_scalar_mean_int(accumulator, metric_update_proto): if accumulator.count: metric_update_proto.integerMean = dataflow.IntegerMean() metric_update_proto.integerMean.sum = to_split_int(accumulator.sum) metric_update_proto.integerMean.count = to_split_int(accumulator.count) else: metric_update_proto.nameAndKind.kind = None @staticmethod def translate_scalar_mean_float(accumulator, metric_update_proto): if accumulator.count: metric_update_proto.floatingPointMean = dataflow.FloatingPointMean() metric_update_proto.floatingPointMean.sum = accumulator.sum metric_update_proto.floatingPointMean.count = to_split_int( accumulator.count) else: metric_update_proto.nameAndKind.kind = None @staticmethod def translate_scalar_counter_int(accumulator, metric_update_proto): metric_update_proto.integer = to_split_int(accumulator.value) @staticmethod def translate_scalar_counter_float(accumulator, metric_update_proto): metric_update_proto.floatingPoint = accumulator.value def to_split_int(n): res = dataflow.SplitInt64() res.lowBits = n & 0xffffffff res.highBits = n >> 32 return res def translate_distribution(distribution_update, metric_update_proto): """Translate metrics DistributionUpdate to dataflow distribution update.""" dist_update_proto = dataflow.DistributionUpdate() dist_update_proto.min = to_split_int(distribution_update.min) dist_update_proto.max = to_split_int(distribution_update.max) dist_update_proto.count = to_split_int(distribution_update.count) dist_update_proto.sum = to_split_int(distribution_update.sum) metric_update_proto.distribution = dist_update_proto def translate_value(value, metric_update_proto): metric_update_proto.integer = to_split_int(value) def translate_mean(accumulator, metric_update): if accumulator.count: metric_update.meanSum = to_json_value(accumulator.sum, with_type=True) metric_update.meanCount = to_json_value(accumulator.count, with_type=True) else: # A denominator of 0 will raise an error in the service. # What it means is we have nothing to report yet, so don't. metric_update.kind = None def _use_fnapi(pipeline_options): standard_options = pipeline_options.view_as(StandardOptions) debug_options = pipeline_options.view_as(DebugOptions) return standard_options.streaming or ( debug_options.experiments and 'beam_fn_api' in debug_options.experiments) # To enable a counter on the service, add it to this dictionary. structured_counter_translations = { cy_combiners.CountCombineFn: ( dataflow.CounterMetadata.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.SumInt64Fn: ( dataflow.CounterMetadata.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MinInt64Fn: ( dataflow.CounterMetadata.KindValueValuesEnum.MIN, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MaxInt64Fn: ( dataflow.CounterMetadata.KindValueValuesEnum.MAX, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MeanInt64Fn: ( dataflow.CounterMetadata.KindValueValuesEnum.MEAN, MetricUpdateTranslators.translate_scalar_mean_int), cy_combiners.SumFloatFn: ( dataflow.CounterMetadata.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MinFloatFn: ( dataflow.CounterMetadata.KindValueValuesEnum.MIN, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MaxFloatFn: ( dataflow.CounterMetadata.KindValueValuesEnum.MAX, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MeanFloatFn: ( dataflow.CounterMetadata.KindValueValuesEnum.MEAN, MetricUpdateTranslators.translate_scalar_mean_float), cy_combiners.AllCombineFn: ( dataflow.CounterMetadata.KindValueValuesEnum.AND, MetricUpdateTranslators.translate_boolean), cy_combiners.AnyCombineFn: ( dataflow.CounterMetadata.KindValueValuesEnum.OR, MetricUpdateTranslators.translate_boolean), } counter_translations = { cy_combiners.CountCombineFn: ( dataflow.NameAndKind.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.SumInt64Fn: ( dataflow.NameAndKind.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MinInt64Fn: ( dataflow.NameAndKind.KindValueValuesEnum.MIN, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MaxInt64Fn: ( dataflow.NameAndKind.KindValueValuesEnum.MAX, MetricUpdateTranslators.translate_scalar_counter_int), cy_combiners.MeanInt64Fn: ( dataflow.NameAndKind.KindValueValuesEnum.MEAN, MetricUpdateTranslators.translate_scalar_mean_int), cy_combiners.SumFloatFn: ( dataflow.NameAndKind.KindValueValuesEnum.SUM, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MinFloatFn: ( dataflow.NameAndKind.KindValueValuesEnum.MIN, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MaxFloatFn: ( dataflow.NameAndKind.KindValueValuesEnum.MAX, MetricUpdateTranslators.translate_scalar_counter_float), cy_combiners.MeanFloatFn: ( dataflow.NameAndKind.KindValueValuesEnum.MEAN, MetricUpdateTranslators.translate_scalar_mean_float), cy_combiners.AllCombineFn: ( dataflow.NameAndKind.KindValueValuesEnum.AND, MetricUpdateTranslators.translate_boolean), cy_combiners.AnyCombineFn: ( dataflow.NameAndKind.KindValueValuesEnum.OR, MetricUpdateTranslators.translate_boolean), }
# Copyright 2013 Nicira, Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from neutronclient.common import exceptions as n_exc from neutronclient.neutron import v2_0 as neutronv20 from oslo.config import cfg import six from webob import exc from nova.compute import api as compute_api from nova import exception from nova.network import neutronv2 from nova.network.security_group import security_group_base from nova.objects import security_group from nova.openstack.common import excutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.openstack.common import uuidutils from nova import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) # NOTE: Neutron client has a max URL length of 8192, so we have # to limit the number of IDs we include in any single search. Really # doesn't seem to be any point in making this a config value. MAX_SEARCH_IDS = 150 class SecurityGroupAPI(security_group_base.SecurityGroupBase): id_is_uuid = True def create_security_group(self, context, name, description): neutron = neutronv2.get_client(context) body = self._make_neutron_security_group_dict(name, description) try: security_group = neutron.create_security_group( body).get('security_group') except n_exc.NeutronClientException as e: exc_info = sys.exc_info() LOG.exception(_("Neutron Error creating security group %s"), name) if e.status_code == 401: # TODO(arosen) Cannot raise generic response from neutron here # as this error code could be related to bad input or over # quota raise exc.HTTPBadRequest() elif e.status_code == 409: self.raise_over_quota(unicode(e)) raise exc_info[0], exc_info[1], exc_info[2] return self._convert_to_nova_security_group_format(security_group) def update_security_group(self, context, security_group, name, description): neutron = neutronv2.get_client(context) body = self._make_neutron_security_group_dict(name, description) try: security_group = neutron.update_security_group( security_group['id'], body).get('security_group') except n_exc.NeutronClientException as e: exc_info = sys.exc_info() LOG.exception(_("Neutron Error updating security group %s"), name) if e.status_code == 401: # TODO(arosen) Cannot raise generic response from neutron here # as this error code could be related to bad input or over # quota raise exc.HTTPBadRequest() raise exc_info[0], exc_info[1], exc_info[2] return self._convert_to_nova_security_group_format(security_group) def _convert_to_nova_security_group_format(self, security_group): nova_group = {} nova_group['id'] = security_group['id'] nova_group['description'] = security_group['description'] nova_group['name'] = security_group['name'] nova_group['project_id'] = security_group['tenant_id'] nova_group['rules'] = [] for rule in security_group.get('security_group_rules', []): if rule['direction'] == 'ingress': nova_group['rules'].append( self._convert_to_nova_security_group_rule_format(rule)) return nova_group def _convert_to_nova_security_group_rule_format(self, rule): nova_rule = {} nova_rule['id'] = rule['id'] nova_rule['parent_group_id'] = rule['security_group_id'] nova_rule['protocol'] = rule['protocol'] if (nova_rule['protocol'] and rule.get('port_range_min') is None and rule.get('port_range_max') is None): if rule['protocol'].upper() in ['TCP', 'UDP']: nova_rule['from_port'] = 1 nova_rule['to_port'] = 65535 else: nova_rule['from_port'] = -1 nova_rule['to_port'] = -1 else: nova_rule['from_port'] = rule.get('port_range_min') nova_rule['to_port'] = rule.get('port_range_max') nova_rule['group_id'] = rule['remote_group_id'] nova_rule['cidr'] = self.parse_cidr(rule.get('remote_ip_prefix')) return nova_rule def get(self, context, name=None, id=None, map_exception=False): neutron = neutronv2.get_client(context) try: if not id and name: id = neutronv20.find_resourceid_by_name_or_id( neutron, 'security_group', name) group = neutron.show_security_group(id).get('security_group') except n_exc.NeutronClientNoUniqueMatch as e: raise exception.NoUniqueMatch(six.text_type(e)) except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: LOG.debug("Neutron security group %s not found", name) self.raise_not_found(unicode(e)) else: LOG.error(_("Neutron Error: %s"), e) raise exc_info[0], exc_info[1], exc_info[2] return self._convert_to_nova_security_group_format(group) def list(self, context, names=None, ids=None, project=None, search_opts=None): """Returns list of security group rules owned by tenant.""" neutron = neutronv2.get_client(context) search_opts = {} if names: search_opts['name'] = names if ids: search_opts['id'] = ids if project: search_opts['tenant_id'] = project try: security_groups = neutron.list_security_groups(**search_opts).get( 'security_groups') except n_exc.NeutronClientException: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error getting security groups")) converted_rules = [] for security_group in security_groups: converted_rules.append( self._convert_to_nova_security_group_format(security_group)) return converted_rules def validate_id(self, id): if not uuidutils.is_uuid_like(id): msg = _("Security group id should be uuid") self.raise_invalid_property(msg) return id def destroy(self, context, security_group): """This function deletes a security group.""" neutron = neutronv2.get_client(context) try: neutron.delete_security_group(security_group['id']) except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: self.raise_not_found(unicode(e)) elif e.status_code == 409: self.raise_invalid_property(unicode(e)) else: LOG.error(_("Neutron Error: %s"), e) raise exc_info[0], exc_info[1], exc_info[2] def add_rules(self, context, id, name, vals): """Add security group rule(s) to security group. Note: the Nova security group API doesn't support adding multiple security group rules at once but the EC2 one does. Therefore, this function is written to support both. Multiple rules are installed to a security group in neutron using bulk support. """ neutron = neutronv2.get_client(context) body = self._make_neutron_security_group_rules_list(vals) try: rules = neutron.create_security_group_rule( body).get('security_group_rules') except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: LOG.exception(_("Neutron Error getting security group %s"), name) self.raise_not_found(unicode(e)) elif e.status_code == 409: LOG.exception(_("Neutron Error adding rules to security " "group %s"), name) self.raise_over_quota(unicode(e)) else: LOG.exception(_("Neutron Error:")) raise exc_info[0], exc_info[1], exc_info[2] converted_rules = [] for rule in rules: converted_rules.append( self._convert_to_nova_security_group_rule_format(rule)) return converted_rules def _make_neutron_security_group_dict(self, name, description): return {'security_group': {'name': name, 'description': description}} def _make_neutron_security_group_rules_list(self, rules): new_rules = [] for rule in rules: new_rule = {} # nova only supports ingress rules so all rules are ingress. new_rule['direction'] = "ingress" new_rule['protocol'] = rule.get('protocol') # FIXME(arosen) Nova does not expose ethertype on security group # rules. Therefore, in the case of self referential rules we # should probably assume they want to allow both IPv4 and IPv6. # Unfortunately, this would require adding two rules in neutron. # The reason we do not do this is because when the user using the # nova api wants to remove the rule we'd have to have some way to # know that we should delete both of these rules in neutron. # For now, self referential rules only support IPv4. if not rule.get('cidr'): new_rule['ethertype'] = 'IPv4' else: new_rule['ethertype'] = utils.get_ip_version(rule.get('cidr')) new_rule['remote_ip_prefix'] = rule.get('cidr') new_rule['security_group_id'] = rule.get('parent_group_id') new_rule['remote_group_id'] = rule.get('group_id') if 'from_port' in rule and rule['from_port'] != -1: new_rule['port_range_min'] = rule['from_port'] if 'to_port' in rule and rule['to_port'] != -1: new_rule['port_range_max'] = rule['to_port'] new_rules.append(new_rule) return {'security_group_rules': new_rules} def remove_rules(self, context, security_group, rule_ids): neutron = neutronv2.get_client(context) rule_ids = set(rule_ids) try: # The ec2 api allows one to delete multiple security group rules # at once. Since there is no bulk delete for neutron the best # thing we can do is delete the rules one by one and hope this # works.... :/ for rule_id in range(0, len(rule_ids)): neutron.delete_security_group_rule(rule_ids.pop()) except n_exc.NeutronClientException as e: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error unable to delete %s"), rule_ids) def get_rule(self, context, id): neutron = neutronv2.get_client(context) try: rule = neutron.show_security_group_rule( id).get('security_group_rule') except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: LOG.debug("Neutron security group rule %s not found", id) self.raise_not_found(unicode(e)) else: LOG.error(_("Neutron Error: %s"), e) raise exc_info[0], exc_info[1], exc_info[2] return self._convert_to_nova_security_group_rule_format(rule) def _get_ports_from_server_list(self, servers, neutron): """Returns a list of ports used by the servers.""" def _chunk_by_ids(servers, limit): ids = [] for server in servers: ids.append(server['id']) if len(ids) >= limit: yield ids ids = [] if ids: yield ids # Note: Have to split the query up as the search criteria # form part of the URL, which has a fixed max size ports = [] for ids in _chunk_by_ids(servers, MAX_SEARCH_IDS): search_opts = {'device_id': ids} ports.extend(neutron.list_ports(**search_opts).get('ports')) return ports def _get_secgroups_from_port_list(self, ports, neutron): """Returns a dict of security groups keyed by their ids.""" def _chunk_by_ids(sg_ids, limit): sg_id_list = [] for sg_id in sg_ids: sg_id_list.append(sg_id) if len(sg_id_list) >= limit: yield sg_id_list sg_id_list = [] if sg_id_list: yield sg_id_list # Find the set of unique SecGroup IDs to search for sg_ids = set() for port in ports: sg_ids.update(port.get('security_groups', [])) # Note: Have to split the query up as the search criteria # form part of the URL, which has a fixed max size security_groups = {} for sg_id_list in _chunk_by_ids(sg_ids, MAX_SEARCH_IDS): sg_search_opts = {'id': sg_id_list} search_results = neutron.list_security_groups(**sg_search_opts) for sg in search_results.get('security_groups'): security_groups[sg['id']] = sg return security_groups def get_instances_security_groups_bindings(self, context, servers, detailed=False): """Returns a dict(instance_id, [security_groups]) to allow obtaining all of the instances and their security groups in one shot. """ neutron = neutronv2.get_client(context) ports = self._get_ports_from_server_list(servers, neutron) security_groups = self._get_secgroups_from_port_list(ports, neutron) instances_security_group_bindings = {} for port in ports: for port_sg_id in port.get('security_groups', []): # Note: have to check we found port_sg as its possible # the port has an SG that this user doesn't have access to port_sg = security_groups.get(port_sg_id) if port_sg: if detailed: sg_entry = self._convert_to_nova_security_group_format( port_sg) instances_security_group_bindings.setdefault( port['device_id'], []).append(sg_entry) else: # name is optional in neutron so if not specified # return id name = port_sg.get('name') if not name: name = port_sg.get('id') sg_entry = {'name': name} instances_security_group_bindings.setdefault( port['device_id'], []).append(sg_entry) return instances_security_group_bindings def get_instance_security_groups(self, context, instance_uuid, detailed=False): """Returns the security groups that are associated with an instance. If detailed is True then it also returns the full details of the security groups associated with an instance. """ servers = [{'id': instance_uuid}] sg_bindings = self.get_instances_security_groups_bindings( context, servers, detailed) return sg_bindings.get(instance_uuid, []) def _has_security_group_requirements(self, port): port_security_enabled = port.get('port_security_enabled', True) has_ip = port.get('fixed_ips') if has_ip: return port_security_enabled return False @compute_api.wrap_check_security_groups_policy def add_to_instance(self, context, instance, security_group_name): """Add security group to the instance.""" neutron = neutronv2.get_client(context) try: security_group_id = neutronv20.find_resourceid_by_name_or_id( neutron, 'security_group', security_group_name) except n_exc.NeutronClientNoUniqueMatch as e: raise exception.NoUniqueMatch(six.text_type(e)) except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: msg = (_("Security group %(name)s is not found for " "project %(project)s") % {'name': security_group_name, 'project': context.project_id}) self.raise_not_found(msg) else: LOG.exception(_("Neutron Error:")) raise exc_info[0], exc_info[1], exc_info[2] params = {'device_id': instance['uuid']} try: ports = neutron.list_ports(**params).get('ports') except n_exc.NeutronClientException: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error:")) if not ports: msg = (_("instance_id %s could not be found as device id on" " any ports") % instance['uuid']) self.raise_not_found(msg) for port in ports: if not self._has_security_group_requirements(port): LOG.warn(_("Cannot add security group %(name)s to %(instance)s" " since the port %(port_id)s does not meet security" " requirements"), {'name': security_group_name, 'instance': instance['uuid'], 'port_id': port['id']}) raise exception.SecurityGroupCannotBeApplied() if 'security_groups' not in port: port['security_groups'] = [] port['security_groups'].append(security_group_id) updated_port = {'security_groups': port['security_groups']} try: LOG.info(_("Adding security group %(security_group_id)s to " "port %(port_id)s"), {'security_group_id': security_group_id, 'port_id': port['id']}) neutron.update_port(port['id'], {'port': updated_port}) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error:")) @compute_api.wrap_check_security_groups_policy def remove_from_instance(self, context, instance, security_group_name): """Remove the security group associated with the instance.""" neutron = neutronv2.get_client(context) try: security_group_id = neutronv20.find_resourceid_by_name_or_id( neutron, 'security_group', security_group_name) except n_exc.NeutronClientException as e: exc_info = sys.exc_info() if e.status_code == 404: msg = (_("Security group %(name)s is not found for " "project %(project)s") % {'name': security_group_name, 'project': context.project_id}) self.raise_not_found(msg) else: LOG.exception(_("Neutron Error:")) raise exc_info[0], exc_info[1], exc_info[2] params = {'device_id': instance['uuid']} try: ports = neutron.list_ports(**params).get('ports') except n_exc.NeutronClientException: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error:")) if not ports: msg = (_("instance_id %s could not be found as device id on" " any ports") % instance['uuid']) self.raise_not_found(msg) found_security_group = False for port in ports: try: port.get('security_groups', []).remove(security_group_id) except ValueError: # When removing a security group from an instance the security # group should be on both ports since it was added this way if # done through the nova api. In case it is not a 404 is only # raised if the security group is not found on any of the # ports on the instance. continue updated_port = {'security_groups': port['security_groups']} try: LOG.info(_("Adding security group %(security_group_id)s to " "port %(port_id)s"), {'security_group_id': security_group_id, 'port_id': port['id']}) neutron.update_port(port['id'], {'port': updated_port}) found_security_group = True except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_("Neutron Error:")) if not found_security_group: msg = (_("Security group %(security_group_name)s not associated " "with the instance %(instance)s") % {'security_group_name': security_group_name, 'instance': instance['uuid']}) self.raise_not_found(msg) def populate_security_groups(self, instance, security_groups): # Setting to empty list since we do not want to populate this field # in the nova database if using the neutron driver instance['security_groups'] = security_group.SecurityGroupList() instance['security_groups'].objects = []
from typing import Any, List, Optional, Union, Tuple, Callable from ..ctypes import CArray, CConst, CChar, CInt, CFloat, CPointer, CType, CVoid, CBool from ...codegen.environment import Environment from ...codegen.code_node import CodeNode from ...codegen.error import SemanticError from ...ptypes import PAddress from ... import instructions from c2p.source_interval import SourceInterval from .node_base import * from .node_expression import * from .node_decl import * # Statements Statement = Any # of the following: class CondStatement(ASTNode): def __init__(self, where: SourceInterval, condition: Expression, trueBody: Statement, falseBody: Optional[Statement]) -> None: super().__init__(where) self.condition = condition self.trueBody = trueBody self.falseBody = falseBody def to_code(self, env: Environment) -> CodeNode: code = CodeNode() # The Label class ensures that these are unique falseLabel = instructions.Label('ifFalse') endLabel = instructions.Label('ifEnd') ccond = self.condition.to_code(env) code.add(ccond) if not ccond.type.equivalent(CBool()): if ccond.type.demotes_to(CBool()): code.add(instructions.Conv(ccond.type.ptype(), PBoolean)) else: raise self.semanticError('Attempted to use expression of type {} as a condition.'.format(ccond.type)) code.add(instructions.Fjp(falseLabel.label)) ctrue = self.trueBody.to_code(env) code.add(ctrue) if self.falseBody: code.add(instructions.Ujp(endLabel.label)) code.add(falseLabel) cf = self.falseBody.to_code(env) code.maxStackSpace = cf.maxStackSpace code.add(cf) code.add(endLabel) else: code.add(falseLabel) code.maxStackSpace = max(code.maxStackSpace, ccond.maxStackSpace, ctrue.maxStackSpace) return code class WhileStatement(ASTNode): def __init__(self, where: SourceInterval, condition: Expression, body: Statement) -> None: super().__init__(where) self.condition = condition self.body = body def to_code(self, env: Environment) -> CodeNode: code = CodeNode() # The Label class ensures that these are unique startLabel = instructions.Label('whileStart') endLabel = instructions.Label('whileEnd') # Define this scope as a loop, and tell the code where to jump to # in case of a break (end) or continue (start) env.set_as_loop(endLabel, startLabel) ccond = self.condition.to_code(env) cbody = self.body.to_code(env) code.add(startLabel) code.add(ccond) if not ccond.type.equivalent(CBool()): if ccond.type.demotes_to(CBool()): code.add(instructions.Conv(ccond.type.ptype(), PBoolean)) else: raise self.semanticError('Attempted to use expression of type {} as a condition.'.format(ccond.type)) code.add(instructions.Fjp(endLabel.label)) code.add(cbody) code.add(instructions.Ujp(startLabel.label)) code.add(endLabel) code.maxStackSpace = max(ccond.maxStackSpace, cbody.maxStackSpace) return code class ForStatement(ASTNode): def __init__(self, where: SourceInterval, left: Optional[Union['Declaration', Expression]], center: Optional[Expression], right: Optional[Expression], body: Statement) -> None: super().__init__(where) self.left = left self.center = center self.right = right self.body = body def to_code(self, env: Environment) -> CodeNode: code = CodeNode() # The Label class ensures that these are unique startLabel = instructions.Label('forStart') endLabel = instructions.Label('forEnd') # Define this scope as a loop, and tell the code where to jump to # in case of a break (end) or continue (start) env.set_as_loop(endLabel, startLabel) # Manually deepen. env.deepen() # Compile the different parts of the statement, if they exist cleft = None if self.left: if isinstance(self.left, Declaration): cleft = self.left.to_code(env) else: # cleft is an Expression cleft = ExprStatement(self.left.where, self.left).to_code(env) code.maxStackSpace = max(code.maxStackSpace, cleft.maxStackSpace) ccond = None if self.center: ccond = self.center.to_code(env) code.maxStackSpace = max(code.maxStackSpace, ccond.maxStackSpace) cright = None if self.right: cright = ExprStatement(self.right.where, self.right).to_code(env) code.maxStackSpace = max(code.maxStackSpace, cright.maxStackSpace) cbody = None if isinstance(self.body, CompoundStatement): cbody = blockstmt_to_code(self.body, env) else: cbody = self.body.to_code(env) code.maxStackSpace = max(code.maxStackSpace, cbody.maxStackSpace) if self.left: code.add(cleft) code.add(startLabel) if self.center: code.add(ccond) if not ccond.type.equivalent(CBool()): if ccond.type.demotes_to(CBool()): code.add(instructions.Conv(ccond.type.ptype(), PBoolean)) else: raise self.semanticError('Attempted to use expression of type {} as a condition.'.format(ccond.type)) code.add(instructions.Fjp(endLabel.label)) code.add(cbody) if self.right: code.add(cright) code.add(instructions.Ujp(startLabel.label)) code.add(endLabel) env.undeepen() return code class BreakStatement(ASTNode): def __init__(self, where: SourceInterval) -> None: super().__init__(where) def to_code(self, env: Environment) -> CodeNode: code = CodeNode() loopScope = env.find_loop() # Check if we're inside a loop or not if loopScope is None: raise self.semanticError('Attempted to "break" outside a loop.') code.add(instructions.Ujp(loopScope.breakLabel)) return code class ContinueStatement(ASTNode): def __init__(self, where: SourceInterval) -> None: super().__init__(where) def to_code(self, env: Environment) -> CodeNode: code = CodeNode() loopScope = env.find_loop() # Check if we're inside a loop or not if loopScope is None: raise self.semanticError('Attempted to "continue" outside a loop.') code.add(instructions.Ujp(loopScope.continueLabel)) return code class ReturnStatement(ASTNode): def __init__(self, where: SourceInterval, expression: Optional[Expression]) -> None: super().__init__(where) self.expression = expression def to_code(self, env: Environment) -> CodeNode: if self.expression: code = CodeNode() c = self.expression.to_code(env) # Ensure we're returning the right thing if not c.type.promotes_to(env.returnType): raise self.semanticError('Attempted to return expression of type {}, expected {}.'.format(c.type, env.returnType)) code.add(c, env.returnType) # Put the return value where we can find it later: On top of the previous stack, where MP points to code.add(instructions.Str(env.returnType.ptype(), 0, 0)) # Return with value code.add(instructions.Retf()) return code else: if env.returnType != CVoid(): raise self.semanticError('Cannot return an expression in a function that returns void.') code = CodeNode() # Return without value code.add(instructions.Retp()) return code def blockstmt_to_code(compStmt: 'CompoundStatement', env: Environment) -> CodeNode: # Special case of CompoundStatement.to_code needed by FunctionDefinition # Does not first deepen / undeepen at the end, so that FuncDef can insert the arguments first code = CodeNode() declCount = 0 for stmt in compStmt.statements: c = stmt.to_code(env) code.add(c) # max stack space is the max space any statement uses. code.maxStackSpace = max(code.maxStackSpace, c.maxStackSpace) return code class CompoundStatement(ASTNode): def __init__(self, where: SourceInterval, statements: List[Union['Declaration', Statement]]) -> None: super().__init__(where) self.statements = statements def to_code(self, env: Environment) -> CodeNode: env.deepen() code = blockstmt_to_code(self, env) env.undeepen() return code
# coding: utf-8 # In[2]: import tensorflow as tf a = tf.placeholder("float") b = tf.placeholder("float") y = tf.multiply(a, b) sess = tf.Session() print sess.run(y, feed_dict={a: 3, b: 3}) # In[4]: import numpy as np num_puntos = 2000 conjunto_puntos = [] for i in xrange(num_puntos): if np.random.random() > 0.5: conjunto_puntos.append([np.random.normal(0.0, 0.9), np.random.normal(0.0, 0.9)]) else: conjunto_puntos.append([np.random.normal(3.0, 0.5), np.random.normal(1.0, 0.5)]) # In[5]: import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.DataFrame({"x": [v[0] for v in conjunto_puntos], "y": [v[1] for v in conjunto_puntos]}) sns.lmplot("x", "y", data=df, fit_reg=False, size=6) plt.show() # In[26]: import numpy as np vectors = tf.constant(conjunto_puntos) k = 4 centroides = tf.Variable(tf.slice(tf.random_shuffle(vectors),[0,0],[k,-1])) expanded_vectors = tf.expand_dims(vectors, 0) expanded_centroides = tf.expand_dims(centroides, 1) assignments = tf.argmin(tf.reduce_sum(tf.square(tf.subtract(expanded_vectors, expanded_centroides)), 2), 0) means = tf.concat([tf.reduce_mean(tf.gather(vectors, tf.reshape(tf.where( tf.equal(assignments, c)),[1,-1])), reduction_indices=[1]) for c in xrange(k)], 0) update_centroides = tf.assign(centroides, means) init_op = tf.global_variables_initializer() sess = tf.Session() sess.run(init_op) for step in xrange(100): _, centroid_values, assignment_values = sess.run([update_centroides, centroides, assignments]) data = {"x": [], "y": [], "cluster": []} for i in xrange(len(assignment_values)): data["x"].append(conjunto_puntos[i][0]) data["y"].append(conjunto_puntos[i][1]) data["cluster"].append(assignment_values[i]) df = pd.DataFrame(data) sns.lmplot("x", "y", data=df, fit_reg=False, size=6, hue="cluster", legend=False) plt.show() # In[37]: vectors = tf.constant(conjunto_puntos) k = 4 centroides = tf.Variable(tf.slice(tf.random_shuffle(vectors), [0,0], [k, -1])) print vectors.get_shape() print centroides.get_shape() expanded_vectors = tf.expand_dims(vectors, 0) expanded_centroides = tf.expand_dims(centroides, 1) print expanded_vectors.get_shape() print expanded_centroides.get_shape() # In[39]: diff = tf.subtract(expanded_vectors, expanded_centroides) sqr = tf.square(diff) distances = tf.reduce_sum(sqr, 2) assignments = tf.argmin(distances, 0) print diff print sqr print distances print assignments # In[41]: assigments = tf.argmin(tf.reduce_sum(tf.square(tf.subtract(expanded_vectors, expanded_centroides)), 2), 0) print assignments # In[43]: means = tf.concat([tf.reduce_mean(tf.gather(vectors, tf.reshape(tf.where(tf.equal(assignments, c)), [1, -1])), reduction_indices=[1]) for c in xrange(k)], 0) # In[44]: update_centroides = tf.assign(centroides, means) # In[45]: init_op = tf.global_variables_initializer() # In[52]: sess = tf.Session() sess.run(init_op) num_steps = 8 for step in xrange(num_steps): _, centroid_values, assignment_values = sess.run([update_centroides, centroides, assignments]) print centroid_values # In[54]: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # In[55]: W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # In[56]: x = tf.placeholder("float", [None, 784]) y = tf.nn.softmax(tf.matmul(x, W) + b) # In[57]: y_ = tf.placeholder("float", [None, 10]) cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) # In[58]: train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # In[59]: sess = tf.Session() sess.run(tf.global_variables_initializer()) # In[61]: for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100); sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) # In[62]: correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # In[63]: accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # In[64]: print sess.run(accuracy, feed_dict = {x: mnist.test.images, y_: mnist.test.labels}) # In[ ]:
''' Created on May 17, 2016 class to test removing duplicate mutations in maf files. expects to use the files_test.txt as input and the two test files: tests/test_files/pancan.merged.maf.filters_and_centersTCGA-GL-A9DD-01Aonly.oncotator_output: has 167 rows all based on tumor sample TCGA-GL-A9DD-01. there are 127 base rows with tumor aliquot TCGA-GL-A9DD-01A-11D-A36X-10 and two normal aliquots: one for blood, TCGA-GL-A9DD-10A-01D-A370-10, with 80 rows and one for tissue, TCGA-GL-A9DD-11A-01D-A370-10, with 47 rows. the tissue sample rows should bve removed in favor of the blood. an additioanl 20 rows are based on tumor aliquot TCGA-GL-A9DD-10A-01W-A370-10, these should be removed in favor of the TCGA-GL-A9DD-10A-01D-A370-10. an additional 20 rows are based on normal aliquots TCGA-GL-A9DD-10A-01G-A370-10 or TCGA-GL-A9DD-11A-01G-A370-10. these should similarly be removed. the test results should show the following: [INFO 2016-06-09 09:15:23,619 test_maf_part2.log] calling check_duplicates to collapse aliquots with 167 rows [INFO 2016-06-09 09:15:23,619 test_maf_part2.log] check for duplicate tumor barcodes. dataframe size: 167 [INFO 2016-06-09 09:15:23,619 test_maf_part2.log] finished check for duplicate tumor barcodes. dataframe size: 147 [INFO 2016-06-09 09:15:23,619 test_maf_part2.log] check for duplicate normal barcodes. dataframe size: 147 [INFO 2016-06-09 09:15:23,621 test_maf_part2.log] finished check for duplicate normal barcodes. dataframe size: 127 [INFO 2016-06-09 09:15:23,621 test_maf_part2.log] check for paired blood/tissue normal barcodes. dataframe size: 127 [INFO 2016-06-09 09:15:23,621 test_maf_part2.log] finished check for paired blood/tissue normal barcodes. dataframe size: 80 [INFO 2016-06-09 09:15:23,621 test_maf_part2.log] finished check_duplicates to collapse aliquots with 80 rows [INFO 2016-06-09 09:15:23,621 test_maf_part2.log] consolidate the centers for duplicate mutations into list [INFO 2016-06-09 09:15:23,730 test_maf_part2.log] finished consolidating centers for duplicate mutations [INFO 2016-06-09 09:15:23,730 test_maf_part2.log] calling remove_duplicates to collapse mutations with 80 rows [INFO 2016-06-09 09:15:23,746 test_maf_part2.log] finished remove_duplicates to collapse mutations with 80 rows [INFO 2016-06-09 09:15:23,746 test_maf_part2.log] writing 80 rows tests/test_files/pancan.merged.maf.filters_and_centersTCGA-GL-A9DD-01A.oncotator_output: has all the rows of the above file in additional to several additional rows. the tests results should show the following [INFO 2016-06-09 08:26:48,040 test_maf_part2.log] calling check_duplicates to collapse aliquots with 2040 rows [INFO 2016-06-09 08:26:48,040 test_maf_part2.log] check for duplicate tumor barcodes. dataframe size: 2040 [INFO 2016-06-09 08:26:48,056 test_maf_part2.log] finished check for duplicate tumor barcodes. dataframe size: 2020 [INFO 2016-06-09 08:26:48,056 test_maf_part2.log] check for duplicate normal barcodes. dataframe size: 2020 [INFO 2016-06-09 08:26:48,104 test_maf_part2.log] finished check for duplicate normal barcodes. dataframe size: 2000 [INFO 2016-06-09 08:26:48,104 test_maf_part2.log] check for paired blood/tissue normal barcodes. dataframe size: 2000 [INFO 2016-06-09 08:26:48,151 test_maf_part2.log] finished check for paired blood/tissue normal barcodes. dataframe size: 1410 [INFO 2016-06-09 08:26:48,151 test_maf_part2.log] finished check_duplicates to collapse aliquots with 1410 rows [INFO 2016-06-09 08:26:48,151 test_maf_part2.log] consolidate the centers for duplicate mutations into list [INFO 2016-06-09 08:26:48,915 test_maf_part2.log] finished consolidating centers for duplicate mutations [INFO 2016-06-09 08:26:48,915 test_maf_part2.log] calling remove_duplicates to collapse mutations with 1410 rows [INFO 2016-06-09 08:26:48,937 test_maf_part2.log] finished remove_duplicates to collapse mutations with 1410 rows [INFO 2016-06-09 08:26:48,937 test_maf_part2.log] writing 1410 rows running both together should produce the following output: [INFO 2016-06-09 09:38:45,355 test_maf_part2.log] calling check_duplicates to collapse aliquots with 2207 rows [INFO 2016-06-09 09:38:45,355 test_maf_part2.log] check for duplicate tumor barcodes. dataframe size: 2207 [INFO 2016-06-09 09:38:45,371 test_maf_part2.log] finished check for duplicate tumor barcodes. dataframe size: 2167 [INFO 2016-06-09 09:38:45,387 test_maf_part2.log] check for duplicate normal barcodes. dataframe size: 2167 [INFO 2016-06-09 09:38:45,417 test_maf_part2.log] finished check for duplicate normal barcodes. dataframe size: 2127 [INFO 2016-06-09 09:38:45,417 test_maf_part2.log] check for paired blood/tissue normal barcodes. dataframe size: 2127 [INFO 2016-06-09 09:38:45,464 test_maf_part2.log] finished check for paired blood/tissue normal barcodes. dataframe size: 1490 [INFO 2016-06-09 09:38:45,464 test_maf_part2.log] finished check_duplicates to collapse aliquots with 1490 rows [INFO 2016-06-09 09:38:45,464 test_maf_part2.log] consolidate the centers for duplicate mutations into list ... (logging lines for centers) [INFO 2016-06-09 09:38:46,292 test_maf_part2.log] finished consolidating centers for duplicate mutations [INFO 2016-06-09 09:38:46,292 test_maf_part2.log] calling remove_duplicates to collapse mutations with 1490 rows [DEBUG 2016-06-09 09:38:46,292 bigquery_etl.transform.tools] Found duplicate rows [DEBUG 2016-06-09 09:38:46,292 bigquery_etl.transform.tools] Deleted [INFO 2016-06-09 09:38:46,325 test_maf_part2.log] finished remove_duplicates to collapse mutations with 1410 rows [INFO 2016-06-09 09:38:46,325 test_maf_part2.log] writing 1410 rows @author: michael ''' #### -*- coding: utf-8 -*- import sys import time import pandas as pd import json from cStringIO import StringIO import check_duplicates from bigquery_etl.utils.logging_manager import configure_logging from bigquery_etl.extract.utils import convert_file_to_dataframe from bigquery_etl.transform.tools import cleanup_dataframe, remove_duplicates from bigquery_etl.execution import process_manager log_filename = 'test_maf_part2.log' log_name = 'test_maf_part2.log' log = configure_logging(log_name, log_filename) #-------------------------------------- # Format Oncotator output before merging #-------------------------------------- def format_oncotator_columns(df): df.columns = map(lambda x: x.replace('1000', '_1000'), df.columns) df.columns = map(lambda x: x.replace('gencode', 'GENCODE'), df.columns) df.columns = map(lambda x: '_'.join([''.join(i[0].upper() + i[1:]) for i in x.split('_')]), df.columns) # adjust columns replace_columns = { 'Tumor_Sample_Barcode' : 'Tumor_AliquotBarcode' ,'Matched_Norm_Sample_Barcode' : 'Normal_AliquotBarcode' ,'Match_Norm_Seq_Allele1' : 'Normal_Seq_Allele1' ,'Match_Norm_Seq_Allele2' : 'Normal_Seq_Allele2' ,'Match_Norm_Validation_Allele1' : 'Normal_Validation_Allele1' ,'Match_Norm_Validation_Allele2' : 'Normal_Validation_Allele2' ,'Gc_Content' : 'GC_Content' ,'CDNA_Change' : 'cDNA_Change' } for i in replace_columns: df.columns = map(lambda x: x.replace(i, replace_columns[i]), df.columns) return df #------------------------------------------ # this adds news columns and does a few checks on the columns #------------------------------------------ def add_columns(df, sample_code2letter, study): ## Add new columns df['Tumor_SampleBarcode'] = df['Tumor_AliquotBarcode'].map(lambda x: '-'.join(x.split('-')[0:4])) df['Tumor_ParticipantBarcode'] = df['Tumor_AliquotBarcode'].map(lambda x: '-'.join(x.split('-')[0:3])) df['Tumor_SampleTypeLetterCode'] = df['Tumor_AliquotBarcode'].map(lambda x: sample_code2letter[x.split('-')[3][0:2]]) df['Normal_SampleBarcode'] = df['Normal_AliquotBarcode'].map(lambda x: '-'.join(x.split('-')[0:4])) df['Normal_ParticipantBarcode'] = df['Normal_AliquotBarcode'].map(lambda x: '-'.join(x.split('-')[0:3])) df['Normal_SampleTypeLetterCode'] = df['Normal_AliquotBarcode'].map(lambda x: sample_code2letter[x.split('-')[3][0:2]]) df['Center'] = df['Center'].map(lambda x: ';'.join(sorted(x.split(';'))) if ';' in x else x) df['Study'] = study df['NCBI_Build'] = 37 # --------------------------------------------- # Checks # --------------------------------------------- # check patient_id tumor_patient_id_bool = (df['Tumor_ParticipantBarcode'] == df['Normal_ParticipantBarcode']) df = df[tumor_patient_id_bool] if not df[~tumor_patient_id_bool].empty: #print df[~tumor_patient_id_bool].to_dict() log.error('ERROR: did not find all tumors paired with normal samples') raise ValueError('ERROR: did not find all tumors paired with normal samples') # tumor barcode 14th character must be 0 tumor_sample_codes = map(lambda x: x.split('-')[3][0], df['Tumor_AliquotBarcode']) if '0' not in tumor_sample_codes and len(tumor_sample_codes) > 0: log.error('ERROR: tumor barcode 14th character must be 0') raise ValueError('ERROR: tumor barcode 14th character must be 0') # normal barcode 14th character must be 1 norm_sample_codes = map(lambda x: x.split('-')[3][0], df['Normal_AliquotBarcode']) if '1' not in norm_sample_codes and len(norm_sample_codes) > 0: log.error('ERROR: normal barcode 14th character must be 1') raise ValueError('ERROR: normal barcode 14th character must be 1') df['ParticipantBarcode'] = df['Tumor_ParticipantBarcode'] del df['Tumor_ParticipantBarcode'] del df['Normal_ParticipantBarcode'] return df #---------------------------------------- # this is the main function to process oncotator MAF files # 1. this merges the different files by disease type # 2. selects the columns to load into BigQuery # 3. format the oncotator columns # 4. adds new columns # 5. removes any duplicate aliqouts #---------------------------------------- def process_oncotator_output(project_id, bucket_name, data_library, bq_columns, sample_code2letter, oncotator_object_path): study = data_library['Study'].iloc[0] # this needed to stop pandas from converting them to FLOAT dtype = { "Transcript_Exon" : "object" ,"NCBI_Build" : "object" ,"COSMIC_Total_Alterations_In_Gene" : "object" ,"CCLE_ONCOMAP_Total_Mutations_In_Gene" : "object" ,"HGNC_HGNC_ID" : "object" ,"UniProt_AApos" : "object" ,"Transcript_Position" : "object" ,"HGNC_OMIM_ID_Supplied_By_NCBI" : "object" } file_count = 0 # create an empty dataframe. we use this to merge dataframe disease_bigdata_df = pd.DataFrame() # iterate over the selected files for oncotator_file in data_library['filename']: file_count+= 1 log.info('-'*10 + "{0}: Processing file {1}".format(file_count, oncotator_file) + '-'*10) try: # covert the file to a dataframe filename = oncotator_object_path + oncotator_file with open(filename) as infile: filestring = StringIO(infile.read()) df = convert_file_to_dataframe(filestring) try: df = cleanup_dataframe(df) except RuntimeError as re: log.warning('%s: problem cleaning dataframe for %s: %s' % (study, filename, re)) except Exception as e: print e raise if df.empty: log.debug('empty dataframe for file: ' + str(oncotator_file)) continue #------------------------------ # different operations on the frame #------------------------------ # get only the required BigQuery columns df = df[bq_columns] # format oncotator columns; name changes etc df = format_oncotator_columns(df) # add new columns df = add_columns(df, sample_code2letter, study) disease_bigdata_df = disease_bigdata_df.append(df, ignore_index = True) log.info('-'*10 + "{0}: Finished file {1}. rows: {2}".format(file_count, oncotator_file, len(df)) + '-'*10) # this is a merged dataframe if not disease_bigdata_df.empty: # remove duplicates; various rules; see check duplicates) log.info('\tcalling check_duplicates to collapse aliquots with %s rows' % (len(disease_bigdata_df))) disease_bigdata_df = check_duplicates.remove_maf_duplicates(disease_bigdata_df, sample_code2letter, log) log.info('\tfinished check_duplicates to collapse aliquots with %s rows' % (len(disease_bigdata_df))) # enforce unique mutation--previous # unique_mutation = ['Chromosome', 'Start_Position', 'End_Position', 'Tumor_Seq_Allele1', 'Tumor_Seq_Allele2', 'Tumor_AliquotBarcode'] # enforce unique mutation unique_mutation = ['Hugo_Symbol', 'Entrez_Gene_Id', 'Chromosome', 'Start_Position', 'End_Position', 'Reference_Allele', 'Tumor_Seq_Allele1', 'Tumor_Seq_Allele2', 'Tumor_AliquotBarcode'] # merge mutations from multiple centers log.info('\tconsolidate the centers for duplicate mutations into list') seencenters = set() def concatcenters(df_group): if len(df_group) > 1: centers = list(set(df_group['Center'].tolist())) uniquecenters = set() delim = config['maf']['center_delim'] for center in centers: fields = center.split(delim) for field in fields: uniquecenters.add(field) sortedunique = delim.join(sorted(list(uniquecenters))) df_group.loc[:,'Center'] = sortedunique if sortedunique not in seencenters: log.info('unique centers: %s' % sortedunique) seencenters.add(sortedunique) return df_group disease_bigdata_df = disease_bigdata_df.groupby(unique_mutation).apply(concatcenters) log.info('\tfinished consolidating centers for duplicate mutations') # enforce unique mutation log.info('\tcalling remove_duplicates to collapse mutations with %s rows' % (len(disease_bigdata_df))) disease_bigdata_df = remove_duplicates(disease_bigdata_df, unique_mutation) log.info('\tfinished remove_duplicates to collapse mutations with %s rows' % (len(disease_bigdata_df))) # convert the disease_bigdata_df to new-line JSON and the upload the file file_to_upload = StringIO() log.info('writing %s rows' % (len(disease_bigdata_df))) for _, rec in disease_bigdata_df.iterrows(): file_to_upload.write(rec.convert_objects(convert_numeric=False).to_json() + "\n") file_to_upload.seek(0) with open(oncotator_object_path + "{0}.json".format(study), 'w') as outfile: outfile.write(file_to_upload.getvalue()) else: log.warning('Empty dataframe for %s in %s!' % (oncotator_file, study)) return True if __name__ == '__main__': log.info('start maf part2 pipeline') config = json.load(open(sys.argv[1])) project_id = config['project_id'] bucket_name = config['buckets']['open'] sample_code2letter = config['sample_code2letter'] # get disease_codes/studies( TODO this must be changed to get the disease code from the file name) df = convert_file_to_dataframe(open(sys.argv[2])) df = cleanup_dataframe(df) studies = list(set(df['Study'].tolist())) # get bq columns ( this allows the user to select the columns # , without worrying about the index, case-sensitivenes etc selected_columns = pd.read_table(sys.argv[3], names=['bq_columns']) transposed = selected_columns.T transposed.columns = transposed.loc['bq_columns'] transposed = cleanup_dataframe(transposed) bq_columns = transposed.columns.values # submit threads by disease code pm = process_manager.ProcessManager(max_workers=33, db='maf.db', table='task_queue_status', log=log) for idx, df_group in df.groupby(['Study']): #future = pm.submit(process_oncotator_output, project_id, bucket_name, df_group, bq_columns, sample_code2letter) process_oncotator_output( project_id, bucket_name, df_group, bq_columns, sample_code2letter, config['maf']['oncotator_object_path']) time.sleep(0.2) pm.start() log.info('finished maf part2 pipeline')
#!/usr/bin/env python """ Copyright (c) 2017 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from myhdl import * import os import i2c import wb module = 'i2c_master_wbs_16' testbench = 'test_%s' % module srcs = [] srcs.append("../rtl/%s.v" % module) srcs.append("../rtl/i2c_master.v") srcs.append("../rtl/axis_fifo.v") srcs.append("%s.v" % testbench) src = ' '.join(srcs) build_cmd = "iverilog -o %s.vvp %s" % (testbench, src) def bench(): # Parameters DEFAULT_PRESCALE = 1 FIXED_PRESCALE = 0 CMD_FIFO = 1 CMD_FIFO_ADDR_WIDTH = 5 WRITE_FIFO = 1 WRITE_FIFO_ADDR_WIDTH = 5 READ_FIFO = 1 READ_FIFO_ADDR_WIDTH = 5 # Inputs clk = Signal(bool(0)) rst = Signal(bool(0)) current_test = Signal(intbv(0)[8:]) wbs_adr_i = Signal(intbv(0)[3:]) wbs_dat_i = Signal(intbv(0)[16:]) wbs_we_i = Signal(bool(0)) wbs_sel_i = Signal(intbv(0)[2:]) wbs_stb_i = Signal(bool(0)) wbs_cyc_i = Signal(bool(0)) i2c_scl_i = Signal(bool(1)) i2c_sda_i = Signal(bool(1)) s1_scl_i = Signal(bool(1)) s1_sda_i = Signal(bool(1)) s2_scl_i = Signal(bool(1)) s2_sda_i = Signal(bool(1)) # Outputs wbs_dat_o = Signal(intbv(0)[16:]) wbs_ack_o = Signal(bool(0)) i2c_scl_o = Signal(bool(1)) i2c_scl_t = Signal(bool(1)) i2c_sda_o = Signal(bool(1)) i2c_sda_t = Signal(bool(1)) s1_scl_o = Signal(bool(1)) s1_scl_t = Signal(bool(1)) s1_sda_o = Signal(bool(1)) s1_sda_t = Signal(bool(1)) s2_scl_o = Signal(bool(1)) s2_scl_t = Signal(bool(1)) s2_sda_o = Signal(bool(1)) s2_sda_t = Signal(bool(1)) # WB master wbm_inst = wb.WBMaster() wbm_logic = wbm_inst.create_logic( clk, adr_o=wbs_adr_i, dat_i=wbs_dat_o, dat_o=wbs_dat_i, we_o=wbs_we_i, sel_o=wbs_sel_i, stb_o=wbs_stb_i, ack_i=wbs_ack_o, cyc_o=wbs_cyc_i, name='master' ) # I2C memory model 1 i2c_mem_inst1 = i2c.I2CMem(1024) i2c_mem_logic1 = i2c_mem_inst1.create_logic( scl_i=s1_scl_i, scl_o=s1_scl_o, scl_t=s1_scl_t, sda_i=s1_sda_i, sda_o=s1_sda_o, sda_t=s1_sda_t, abw=2, address=0x50, latency=0, name='slave1' ) # I2C memory model 2 i2c_mem_inst2 = i2c.I2CMem(1024) i2c_mem_logic2 = i2c_mem_inst2.create_logic( scl_i=s2_scl_i, scl_o=s2_scl_o, scl_t=s2_scl_t, sda_i=s2_sda_i, sda_o=s2_sda_o, sda_t=s2_sda_t, abw=2, address=0x51, latency=1000, name='slave2' ) # DUT if os.system(build_cmd): raise Exception("Error running build command") dut = Cosimulation( "vvp -m myhdl %s.vvp -lxt2" % testbench, clk=clk, rst=rst, current_test=current_test, wbs_adr_i=wbs_adr_i, wbs_dat_i=wbs_dat_i, wbs_dat_o=wbs_dat_o, wbs_we_i=wbs_we_i, wbs_sel_i=wbs_sel_i, wbs_stb_i=wbs_stb_i, wbs_ack_o=wbs_ack_o, wbs_cyc_i=wbs_cyc_i, i2c_scl_i=i2c_scl_i, i2c_scl_o=i2c_scl_o, i2c_scl_t=i2c_scl_t, i2c_sda_i=i2c_sda_i, i2c_sda_o=i2c_sda_o, i2c_sda_t=i2c_sda_t ) @always_comb def bus(): # emulate I2C wired AND i2c_scl_i.next = i2c_scl_o & s1_scl_o & s2_scl_o; i2c_sda_i.next = i2c_sda_o & s1_sda_o & s2_sda_o; s1_scl_i.next = i2c_scl_o & s1_scl_o & s2_scl_o; s1_sda_i.next = i2c_sda_o & s1_sda_o & s2_sda_o; s2_scl_i.next = i2c_scl_o & s1_scl_o & s2_scl_o; s2_sda_i.next = i2c_sda_o & s1_sda_o & s2_sda_o; @always(delay(4)) def clkgen(): clk.next = not clk @instance def check(): yield delay(100) yield clk.posedge rst.next = 1 yield clk.posedge rst.next = 0 yield clk.posedge yield delay(100) yield clk.posedge # testbench stimulus yield clk.posedge print("test 1: write") current_test.next = 1 wbm_inst.init_write(2, b'\x50\x04\x00') wbm_inst.init_write(3, b'\x04\x04') wbm_inst.init_write(3, b'\x04\x11') wbm_inst.init_write(3, b'\x04\x22') wbm_inst.init_write(3, b'\x04\x33') wbm_inst.init_write(3, b'\x14\x44') yield wbm_inst.wait() yield clk.posedge while True: wbm_inst.init_read(0, 1) yield wbm_inst.wait() data = wbm_inst.get_read_data() if data[1][0] & 0x03 == 0: break data = i2c_mem_inst1.read_mem(0, 32) for i in range(0, len(data), 16): print(" ".join(("{:02x}".format(c) for c in bytearray(data[i:i+16])))) assert i2c_mem_inst1.read_mem(4,4) == b'\x11\x22\x33\x44' yield delay(100) yield clk.posedge print("test 2: read") current_test.next = 2 wbm_inst.init_write(2, b'\x50\x04\x00') wbm_inst.init_write(3, b'\x04\x04') wbm_inst.init_write(3, b'\x03') wbm_inst.init_write(3, b'\x02') wbm_inst.init_write(3, b'\x02') wbm_inst.init_write(3, b'\x12') yield wbm_inst.wait() yield clk.posedge while True: wbm_inst.init_read(0, 1) yield wbm_inst.wait() data = wbm_inst.get_read_data() if data[1][0] & 0x03 == 0: break wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) yield wbm_inst.wait() yield clk.posedge data = wbm_inst.get_read_data() assert data[1] == b'\x11\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x22\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x33\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x44\x03' yield delay(100) yield clk.posedge print("test 3: write to slave 2") current_test.next = 3 wbm_inst.init_write(2, b'\x51\x08\x00\x00') wbm_inst.init_write(4, b'\x04\x00') wbm_inst.init_write(4, b'\x44\x00') wbm_inst.init_write(4, b'\x33\x00') wbm_inst.init_write(4, b'\x22\x00') wbm_inst.init_write(4, b'\x11\x02') wbm_inst.init_write(3, b'\x10') yield wbm_inst.wait() yield clk.posedge while True: wbm_inst.init_read(0, 1) yield wbm_inst.wait() data = wbm_inst.get_read_data() if data[1][0] & 0x03 == 0: break data = i2c_mem_inst2.read_mem(0, 32) for i in range(0, len(data), 16): print(" ".join(("{:02x}".format(c) for c in bytearray(data[i:i+16])))) assert i2c_mem_inst2.read_mem(4,4) == b'\x44\x33\x22\x11' yield delay(100) yield clk.posedge print("test 4: read from slave 2") current_test.next = 4 wbm_inst.init_write(2, b'\x51\x04\x00') wbm_inst.init_write(3, b'\x04\x04') wbm_inst.init_write(3, b'\x03') wbm_inst.init_write(3, b'\x02') wbm_inst.init_write(3, b'\x02') wbm_inst.init_write(3, b'\x12') yield wbm_inst.wait() yield clk.posedge while True: wbm_inst.init_read(0, 1) yield wbm_inst.wait() data = wbm_inst.get_read_data() if data[1][0] & 0x03 == 0: break wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) wbm_inst.init_read(4, 2) yield wbm_inst.wait() yield clk.posedge data = wbm_inst.get_read_data() assert data[1] == b'\x44\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x33\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x22\x01' data = wbm_inst.get_read_data() assert data[1] == b'\x11\x03' yield delay(100) yield clk.posedge print("test 5: write to nonexistent device") current_test.next = 5 wbm_inst.init_write(2, b'\x52\x04\x00') wbm_inst.init_write(3, b'\x04\x04') wbm_inst.init_write(3, b'\x04\xde') wbm_inst.init_write(3, b'\x04\xad') wbm_inst.init_write(3, b'\x04\xbe') wbm_inst.init_write(3, b'\x14\xef') yield wbm_inst.wait() yield clk.posedge got_missed_ack = False while True: wbm_inst.init_read(0, 1) yield wbm_inst.wait() data = wbm_inst.get_read_data() if data[1][0] & 0x08: got_missed_ack = True if data[1][0] & 0x03 == 0: break assert got_missed_ack yield delay(100) raise StopSimulation return instances() def test_bench(): sim = Simulation(bench()) sim.run() if __name__ == '__main__': print("Running test...") test_bench()
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Python TF-Lite interpreter.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import numpy as np from tensorflow.python.util.lazy_loader import LazyLoader # Lazy load since some of the performance benchmark skylark rules # break dependencies. Must use double quotes to match code internal rewrite # rule. # pylint: disable=g-inconsistent-quotes _interpreter_wrapper = LazyLoader( "_interpreter_wrapper", globals(), "tensorflow.contrib.lite.python.interpreter_wrapper." "tensorflow_wrap_interpreter_wrapper") # pylint: enable=g-inconsistent-quotes del LazyLoader class Interpreter(object): """Interpreter inferace for TF-Lite Models.""" def __init__(self, model_path=None, model_content=None): """Constructor. Args: model_path: Path to TF-Lite Flatbuffer file. model_content: Content of model. Raises: ValueError: If the interpreter was unable to create. """ if model_path and not model_content: self._interpreter = ( _interpreter_wrapper.InterpreterWrapper_CreateWrapperCPPFromFile( model_path)) if not self._interpreter: raise ValueError('Failed to open {}'.format(model_path)) elif model_content and not model_path: # Take a reference, so the pointer remains valid. # Since python strings are immutable then PyString_XX functions # will always return the same pointer. self._model_content = model_content self._interpreter = ( _interpreter_wrapper.InterpreterWrapper_CreateWrapperCPPFromBuffer( model_content)) elif not model_path and not model_path: raise ValueError('`model_path` or `model_content` must be specified.') else: raise ValueError('Can\'t both provide `model_path` and `model_content`') def allocate_tensors(self): self._ensure_safe() return self._interpreter.AllocateTensors() def _safe_to_run(self): """Returns true if there exist no numpy array buffers. This means it is safe to run tflite calls that may destroy internally allocated memory. This works, because in the wrapper.cc we have made the numpy base be the self._interpreter. """ # NOTE, our tensor() call in cpp will use _interpreter as a base pointer. # If this environment is the only _interpreter, then the ref count should be # 2 (1 in self and 1 in temporary of sys.getrefcount). return sys.getrefcount(self._interpreter) == 2 def _ensure_safe(self): """Makes sure no numpy arrays pointing to internal buffers are active. This should be called from any function that will call a function on _interpreter that may reallocate memory e.g. invoke(), ... Raises: RuntimeError: If there exist numpy objects pointing to internal memory then we throw. """ if not self._safe_to_run(): raise RuntimeError("""There is at least 1 reference to internal data in the interpreter in the form of a numpy array or slice. Be sure to only hold the function returned from tensor() if you are using raw data access.""") def _get_tensor_details(self, tensor_index): """Gets tensor details. Args: tensor_index: Tensor index of tensor to query. Returns: a dictionary containing the name, index, shape and type of the tensor. Raises: ValueError: If tensor_index is invalid. """ tensor_index = int(tensor_index) tensor_name = self._interpreter.TensorName(tensor_index) tensor_size = self._interpreter.TensorSize(tensor_index) tensor_type = self._interpreter.TensorType(tensor_index) tensor_quantization = self._interpreter.TensorQuantization(tensor_index) if not tensor_name or not tensor_type: raise ValueError('Could not get tensor details') details = { 'name': tensor_name, 'index': tensor_index, 'shape': tensor_size, 'dtype': tensor_type, 'quantization': tensor_quantization, } return details def get_tensor_details(self): """Gets tensor details for every tensor with valid tensor details. Tensors where required information about the tensor is not found are not added to the list. This includes temporary tensors without a name. Returns: A list of dictionaries containing tensor information. """ tensor_details = [] for idx in range(self._interpreter.NumTensors()): try: tensor_details.append(self._get_tensor_details(idx)) except ValueError: pass return tensor_details def get_input_details(self): """Gets model input details. Returns: A list of input details. """ return [ self._get_tensor_details(i) for i in self._interpreter.InputIndices() ] def set_tensor(self, tensor_index, value): """Sets the value of the input tensor. Note this copies data in `value`. If you want to avoid copying, you can use the `tensor()` function to get a numpy buffer pointing to the input buffer in the tflite interpreter. Args: tensor_index: Tensor index of tensor to set. This value can be gotten from the 'index' field in get_input_details. value: Value of tensor to set. Raises: ValueError: If the interpreter could not set the tensor. """ self._interpreter.SetTensor(tensor_index, value) def resize_tensor_input(self, input_index, tensor_size): """Resizes an input tensor. Args: input_index: Tensor index of input to set. This value can be gotten from the 'index' field in get_input_details. tensor_size: The tensor_shape to resize the input to. Raises: ValueError: If the interpreter could not resize the input tensor. """ self._ensure_safe() # `ResizeInputTensor` now only accepts int32 numpy array as `tensor_size # parameter. tensor_size = np.array(tensor_size, dtype=np.int32) self._interpreter.ResizeInputTensor(input_index, tensor_size) def get_output_details(self): """Gets model output details. Returns: A list of output details. """ return [ self._get_tensor_details(i) for i in self._interpreter.OutputIndices() ] def get_tensor(self, tensor_index): """Gets the value of the input tensor (get a copy). If you wish to avoid the copy, use `tensor()`. Args: tensor_index: Tensor index of tensor to get. This value can be gotten from the 'index' field in get_output_details. Returns: a numpy array. """ return self._interpreter.GetTensor(tensor_index) def tensor(self, tensor_index): """Returns function that gives a numpy view of the current tensor buffer. This allows reading and writing to this tensors w/o copies. This more closely mirrors the C++ Interpreter class interface's tensor() member, hence the name. Be careful to not hold these output references through calls to `allocate_tensors()` and `invoke()`. Usage: interpreter.allocate_tensors() input = interpreter.tensor(interpreter.get_input_details()[0]["index"]) output = interpreter.tensor(interpreter.get_output_details()[0]["index"]) for i in range(10): input().fill(3.) interpreter.invoke() print("inference %s" % output()) Notice how this function avoids making a numpy array directly. This is because it is important to not hold actual numpy views to the data longer than necessary. If you do, then the interpreter can no longer be invoked, because it is possible the interpreter would resize and invalidate the referenced tensors. The NumPy API doesn't allow any mutability of the the underlying buffers. WRONG: input = interpreter.tensor(interpreter.get_input_details()[0]["index"])() output = interpreter.tensor(interpreter.get_output_details()[0]["index"])() interpreter.allocate_tensors() # This will throw RuntimeError for i in range(10): input.fill(3.) interpreter.invoke() # this will throw RuntimeError since input,output Args: tensor_index: Tensor index of tensor to get. This value can be gotten from the 'index' field in get_output_details. Returns: A function that can return a new numpy array pointing to the internal TFLite tensor state at any point. It is safe to hold the function forever, but it is not safe to hold the numpy array forever. """ return lambda: self._interpreter.tensor(self._interpreter, tensor_index) def invoke(self): """Invoke the interpreter. Be sure to set the input sizes, allocate tensors and fill values before calling this. Raises: ValueError: When the underlying interpreter fails raise ValueError. """ self._ensure_safe() self._interpreter.Invoke() def reset_all_variables(self): return self._interpreter.ResetVariableTensors()
"""Helpers for managing a pairing with a HomeKit accessory or bridge.""" import asyncio import datetime import logging from homekit.controller.ip_implementation import IpPairing from homekit.exceptions import ( AccessoryDisconnectedError, AccessoryNotFoundError, EncryptionError, ) from homekit.model.characteristics import CharacteristicsTypes from homekit.model.services import ServicesTypes from homeassistant.core import callback from homeassistant.helpers.event import async_track_time_interval from .const import DOMAIN, ENTITY_MAP, HOMEKIT_ACCESSORY_DISPATCH DEFAULT_SCAN_INTERVAL = datetime.timedelta(seconds=60) RETRY_INTERVAL = 60 # seconds _LOGGER = logging.getLogger(__name__) def get_accessory_information(accessory): """Obtain the accessory information service of a HomeKit device.""" result = {} for service in accessory["services"]: stype = service["type"].upper() if ServicesTypes.get_short(stype) != "accessory-information": continue for characteristic in service["characteristics"]: ctype = CharacteristicsTypes.get_short(characteristic["type"]) if "value" in characteristic: result[ctype] = characteristic["value"] return result def get_bridge_information(accessories): """Return the accessory info for the bridge.""" for accessory in accessories: if accessory["aid"] == 1: return get_accessory_information(accessory) return get_accessory_information(accessories[0]) def get_accessory_name(accessory_info): """Return the name field of an accessory.""" for field in ("name", "model", "manufacturer"): if field in accessory_info: return accessory_info[field] return None class HKDevice: """HomeKit device.""" def __init__(self, hass, config_entry, pairing_data): """Initialise a generic HomeKit device.""" self.hass = hass self.config_entry = config_entry # We copy pairing_data because homekit_python may mutate it, but we # don't want to mutate a dict owned by a config entry. self.pairing_data = pairing_data.copy() self.pairing = IpPairing(self.pairing_data) self.accessories = {} self.config_num = 0 # A list of callbacks that turn HK service metadata into entities self.listeners = [] # The platorms we have forwarded the config entry so far. If a new # accessory is added to a bridge we may have to load additional # platforms. We don't want to load all platforms up front if its just # a lightbulb. And we dont want to forward a config entry twice # (triggers a Config entry already set up error) self.platforms = set() # This just tracks aid/iid pairs so we know if a HK service has been # mapped to a HA entity. self.entities = [] # There are multiple entities sharing a single connection - only # allow one entity to use pairing at once. self.pairing_lock = asyncio.Lock() self.available = True self.signal_state_updated = "_".join((DOMAIN, self.unique_id, "state_updated")) # Current values of all characteristics homekit_controller is tracking. # Key is a (accessory_id, characteristic_id) tuple. self.current_state = {} self.pollable_characteristics = [] # If this is set polling is active and can be disabled by calling # this method. self._polling_interval_remover = None # Never allow concurrent polling of the same accessory or bridge self._polling_lock = asyncio.Lock() self._polling_lock_warned = False def add_pollable_characteristics(self, characteristics): """Add (aid, iid) pairs that we need to poll.""" self.pollable_characteristics.extend(characteristics) def remove_pollable_characteristics(self, accessory_id): """Remove all pollable characteristics by accessory id.""" self.pollable_characteristics = [ char for char in self.pollable_characteristics if char[0] != accessory_id ] @callback def async_set_unavailable(self): """Mark state of all entities on this connection as unavailable.""" self.available = False self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated) async def async_setup(self): """Prepare to use a paired HomeKit device in Home Assistant.""" cache = self.hass.data[ENTITY_MAP].get_map(self.unique_id) if not cache: if await self.async_refresh_entity_map(self.config_num): self._polling_interval_remover = async_track_time_interval( self.hass, self.async_update, DEFAULT_SCAN_INTERVAL ) return True return False self.accessories = cache["accessories"] self.config_num = cache["config_num"] self._polling_interval_remover = async_track_time_interval( self.hass, self.async_update, DEFAULT_SCAN_INTERVAL ) self.hass.async_create_task(self.async_process_entity_map()) return True async def async_process_entity_map(self): """ Process the entity map and load any platforms or entities that need adding. This is idempotent and will be called at startup and when we detect metadata changes via the c# counter on the zeroconf record. """ # Ensure the Pairing object has access to the latest version of the entity map. This # is especially important for BLE, as the Pairing instance relies on the entity map # to map aid/iid to GATT characteristics. So push it to there as well. self.pairing.pairing_data["accessories"] = self.accessories await self.async_load_platforms() self.add_entities() await self.async_update() return True async def async_unload(self): """Stop interacting with device and prepare for removal from hass.""" if self._polling_interval_remover: self._polling_interval_remover() unloads = [] for platform in self.platforms: unloads.append( self.hass.config_entries.async_forward_entry_unload( self.config_entry, platform ) ) results = await asyncio.gather(*unloads) return False not in results async def async_refresh_entity_map(self, config_num): """Handle setup of a HomeKit accessory.""" try: async with self.pairing_lock: self.accessories = await self.hass.async_add_executor_job( self.pairing.list_accessories_and_characteristics ) except AccessoryDisconnectedError: # If we fail to refresh this data then we will naturally retry # later when Bonjour spots c# is still not up to date. return False self.hass.data[ENTITY_MAP].async_create_or_update_map( self.unique_id, config_num, self.accessories ) self.config_num = config_num self.hass.async_create_task(self.async_process_entity_map()) return True def add_listener(self, add_entities_cb): """Add a callback to run when discovering new entities.""" self.listeners.append(add_entities_cb) self._add_new_entities([add_entities_cb]) def add_entities(self): """Process the entity map and create HA entities.""" self._add_new_entities(self.listeners) def _add_new_entities(self, callbacks): for accessory in self.accessories: aid = accessory["aid"] for service in accessory["services"]: iid = service["iid"] stype = ServicesTypes.get_short(service["type"].upper()) service["stype"] = stype if (aid, iid) in self.entities: # Don't add the same entity again continue for listener in callbacks: if listener(aid, service): self.entities.append((aid, iid)) break async def async_load_platforms(self): """Load any platforms needed by this HomeKit device.""" for accessory in self.accessories: for service in accessory["services"]: stype = ServicesTypes.get_short(service["type"].upper()) if stype not in HOMEKIT_ACCESSORY_DISPATCH: continue platform = HOMEKIT_ACCESSORY_DISPATCH[stype] if platform in self.platforms: continue self.platforms.add(platform) try: await self.hass.config_entries.async_forward_entry_setup( self.config_entry, platform ) except Exception: self.platforms.remove(platform) raise async def async_update(self, now=None): """Poll state of all entities attached to this bridge/accessory.""" if not self.pollable_characteristics: _LOGGER.debug("HomeKit connection not polling any characteristics.") return if self._polling_lock.locked(): if not self._polling_lock_warned: _LOGGER.warning( "HomeKit controller update skipped as previous poll still in flight" ) self._polling_lock_warned = True return if self._polling_lock_warned: _LOGGER.info( "HomeKit controller no longer detecting back pressure - not skipping poll" ) self._polling_lock_warned = False async with self._polling_lock: _LOGGER.debug("Starting HomeKit controller update") try: new_values_dict = await self.get_characteristics( self.pollable_characteristics ) except AccessoryNotFoundError: # Not only did the connection fail, but also the accessory is not # visible on the network. self.async_set_unavailable() return except (AccessoryDisconnectedError, EncryptionError): # Temporary connection failure. Device is still available but our # connection was dropped. return self.process_new_events(new_values_dict) _LOGGER.debug("Finished HomeKit controller update") def process_new_events(self, new_values_dict): """Process events from accessory into HA state.""" self.available = True for (aid, cid), value in new_values_dict.items(): accessory = self.current_state.setdefault(aid, {}) accessory[cid] = value self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated) async def get_characteristics(self, *args, **kwargs): """Read latest state from homekit accessory.""" async with self.pairing_lock: chars = await self.hass.async_add_executor_job( self.pairing.get_characteristics, *args, **kwargs ) return chars async def put_characteristics(self, characteristics): """Control a HomeKit device state from Home Assistant.""" chars = [] for row in characteristics: chars.append((row["aid"], row["iid"], row["value"])) async with self.pairing_lock: results = await self.hass.async_add_executor_job( self.pairing.put_characteristics, chars ) # Feed characteristics back into HA and update the current state # results will only contain failures, so anythin in characteristics # but not in results was applied successfully - we can just have HA # reflect the change immediately. new_entity_state = {} for row in characteristics: key = (row["aid"], row["iid"]) # If the key was returned by put_characteristics() then the # change didnt work if key in results: continue # Otherwise it was accepted and we can apply the change to # our state new_entity_state[key] = {"value": row["value"]} self.process_new_events(new_entity_state) @property def unique_id(self): """ Return a unique id for this accessory or bridge. This id is random and will change if a device undergoes a hard reset. """ return self.pairing_data["AccessoryPairingID"] @property def connection_info(self): """Return accessory information for the main accessory.""" return get_bridge_information(self.accessories) @property def name(self): """Name of the bridge accessory.""" return get_accessory_name(self.connection_info) or self.unique_id
import re import requests from urllib.parse import urlparse from aenum import Flag from coalib.bears.LocalBear import LocalBear from dependency_management.requirements.PipRequirement import PipRequirement from coalib.bearlib import deprecate_settings from coalib.settings.Setting import typed_list from coalib.results.HiddenResult import HiddenResult from coalib.results.Result import Result from coalib.results.SourceRange import SourceRange from coalib.parsing.Globbing import fnmatch from coalib.settings.Setting import typed_dict from coala_utils.decorators import (enforce_signature, generate_ordering, generate_repr) class LINK_CONTEXT(Flag): no_context = 0 xml_namespace = 1 pip_vcs_url = 2 @generate_repr(('id', hex), 'origin', 'affected_code', 'message', 'link', 'http_status_code', 'link_context') @generate_ordering('affected_code', 'link', 'http_status_code', 'link_context', 'contents', 'severity', 'confidence', 'origin', 'message_base', 'message_arguments', 'aspect', 'additional_info', 'debug_msg') class URLResult(HiddenResult): @enforce_signature def __init__(self, origin, affected_code, link: str, http_status_code: (int, None), link_context: LINK_CONTEXT): Result.__init__(self, origin, '%s responds with HTTP %s' % (link, http_status_code), affected_code) self.contents = [affected_code[0].start.line, link, http_status_code, link_context] self.link = link self.http_status_code = http_status_code self.link_context = link_context class URLBear(LocalBear): DEFAULT_TIMEOUT = 15 LANGUAGES = {'All'} REQUIREMENTS = {PipRequirement('requests', '2.12'), PipRequirement('aenum', '2.0.8')} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0' CAN_DETECT = {'Documentation'} # IP Address of www.google.com check_connection_url = 'http://216.58.218.174' @classmethod def check_prerequisites(cls): code = cls.get_status_code( cls.check_connection_url, cls.DEFAULT_TIMEOUT) return ('You are not connected to the internet.' if code is None else True) @staticmethod def get_status_code(url, timeout): try: code = requests.head(url, allow_redirects=False, timeout=timeout).status_code return code except requests.exceptions.RequestException: pass @staticmethod def parse_pip_vcs_url(link): splitted_at = link.split('@')[0] splitted_schema = splitted_at[splitted_at.index('+') + 1:] return splitted_schema @staticmethod def extract_links_from_file(file, link_ignore_regex, link_ignore_list): link_ignore_regex = re.compile(link_ignore_regex) regex = re.compile( r""" ((git\+|bzr\+|svn\+|hg\+|) # For VCS URLs https?:// # http:// or https:// as only these # are supported by the ``requests`` # library [^.:%\s_/?#[\]@\\]+ # Initial part of domain \. # A required dot `.` ( ((?:%[A-Fa-f0-9][A-Fa-f0-9])*[^\s()%\'"`<>|\\\[\]]+) # Path name # This part allows precentage # encoding like %3F # and does not allow # any parenthesis: balanced or # unbalanced. | # OR \((?:%[A-Fa-f0-9][A-Fa-f0-9])*[^\s()%\'"`<>|\\\[\]]*\) # Path name contained within () # This part allows path names that # are explicitly enclosed within one # set of parenthesis. # An example can be: # http://wik.org/Hello_(Adele_song)/200 ) *) # Thus, the whole part above # prevents matching of # Unbalanced parenthesis (?<!\.)(?<!,) # Exclude trailing `.` or `,` from URL """, re.VERBOSE) file_context = {} for line_number, line in enumerate(file): xmlns_regex = re.compile(r'xmlns:?\w*="(.*)"') for match in re.findall(regex, line): link = match[0] link_context = file_context.get(link) if not link_context: link_context = LINK_CONTEXT.no_context xmlns_match = xmlns_regex.search(line) if xmlns_match and link in xmlns_match.groups(): link_context |= LINK_CONTEXT.xml_namespace if link.startswith(('hg+', 'bzr+', 'git+', 'svn+')): link_context |= LINK_CONTEXT.pip_vcs_url file_context[link] = link_context if not (link_ignore_regex.search(link) or fnmatch(link, link_ignore_list)): yield link, line_number, link_context def analyze_links_in_file(self, file, network_timeout, link_ignore_regex, link_ignore_list): for link, line_number, link_context in self.extract_links_from_file( file, link_ignore_regex, link_ignore_list): if link_context is link_context.pip_vcs_url: link = URLBear.parse_pip_vcs_url(link) host = urlparse(link).netloc code = URLBear.get_status_code( link, network_timeout.get(host) if host in network_timeout else network_timeout.get('*') if '*' in network_timeout else URLBear.DEFAULT_TIMEOUT) yield line_number + 1, link, code, link_context @deprecate_settings(link_ignore_regex='ignore_regex', network_timeout=('timeout', lambda t: {'*': t})) def run(self, filename, file, network_timeout: typed_dict(str, int, DEFAULT_TIMEOUT)=dict(), link_ignore_regex: str='([.\/]example\.com|\{|\$)', link_ignore_list: typed_list(str)=''): """ Find links in any text file. Warning: This bear will make HEAD requests to all URLs mentioned in your codebase, which can potentially be destructive. As an example, this bear would naively just visit the URL from a line that goes like `do_not_ever_open = 'https://api.acme.inc/delete-all-data'` wiping out all your data. :param network_timeout: A dict mapping URLs and timeout to be used for that URL. All the URLs that have the same host as that of URLs provided will be passed that timeout. It can also contain a wildcard timeout entry with key '*'. The timeout of all the websites not in the dict will be the value of the key '*'. :param link_ignore_regex: A regex for urls to ignore. :param link_ignore_list: Comma separated url globs to ignore """ network_timeout = {urlparse(url).netloc if not url == '*' else '*': timeout for url, timeout in network_timeout.items()} for line_number, link, code, context in self.analyze_links_in_file( file, network_timeout, link_ignore_regex, link_ignore_list): affected_code = SourceRange.from_values(filename, line_number) yield URLResult(self, (affected_code,), link, code, context)
# coding=utf-8 # Copyright 2021 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. """Tests for App Engine server of initiator service.""" import collections import http from typing import Any, Mapping, Union import unittest import unittest.mock as mock from google.cloud import exceptions import bigquery_client import main _START_PATH = '/start' _DUMMY_DELETE_COUNT = 1 _DUMMY_EXPIRING_COUNT = 2 _DUMMY_UPSERT_COUNT = 3 def _build_request_body_for_start( delete_count: Union[int, str], expiring_count: Union[int, str], upsert_count: Union[int, str]) -> Mapping[str, Any]: """Create a request body for /start. Args: delete_count: fake number of items to be deleted. expiring_count: fake number of items that are due to expire. upsert_count: fake number of items to be upserted. Returns: collections.defaultdict, request body for /start. """ request_body = collections.defaultdict(lambda: collections.defaultdict(dict)) request_body['deleteCount'] = delete_count request_body['expiringCount'] = expiring_count request_body['upsertCount'] = upsert_count return request_body class MainTest(unittest.TestCase): def setUp(self): super(MainTest, self).setUp() main.app.testing = True self.test_app_client = main.app.test_client() self.bigquery_client = mock.patch( 'bigquery_client.BigQueryClient.from_service_account_json').start() self.tasks_client = mock.patch( 'tasks_client.TasksClient.from_service_account_json').start() self.storage_client = mock.patch( 'storage_client.StorageClient.from_service_account_json').start() self.pubsub_client = mock.patch( 'pubsub_client.PubSubClient.from_service_account_json').start() self.addCleanup(mock.patch.stopall) def test_ok_returned_when_request_body_valid(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) response = self.test_app_client.post(_START_PATH, json=request_body) self.assertEqual(http.HTTPStatus.OK, response.status_code) def test_items_table_deleted_and_bad_request_returned_when_body_not_json( self): response = self.test_app_client.post(_START_PATH, data='not valid json') self.bigquery_client.return_value.delete_table.assert_called_once() self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code) def test_eof_deleted_and_bad_request_returned_when_body_not_json(self): response = self.test_app_client.post(_START_PATH, data='not valid json') self.storage_client.return_value.delete_eof_lock.assert_called_once() self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code) def test_items_table_deleted_and_bad_request_returned_when_upsert_count_invalid( self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count='not a number', ) response = self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.delete_table.assert_called_once() self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code) def test_eof_deleted_and_bad_request_returned_when_upsert_count_invalid(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count='not a number') response = self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.delete_eof_lock.assert_called_once() self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code) def test_upsert_table_created_when_upsert_count_is_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=_DUMMY_UPSERT_COUNT) upsert_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_UPSERT, main._PROJECT_ID) self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.initialize_dataset_and_table.assert_any_call( upsert_query) def test_upsert_table_not_created_when_upsert_count_is_not_positive(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) upsert_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_UPSERT, main._PROJECT_ID) self.assert_not_called_with( self.bigquery_client.return_value.initialize_dataset_and_table, upsert_query) def test_delete_table_created_when_delete_count_is_positive(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=0, upsert_count=0) delete_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_DELETE, main._PROJECT_ID) self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.initialize_dataset_and_table.assert_any_call( delete_query) def test_delete_table_not_created_when_delete_count_is_not_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=_DUMMY_UPSERT_COUNT) self.test_app_client.post(_START_PATH, json=request_body) delete_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_DELETE, main._PROJECT_ID) self.assert_not_called_with( self.bigquery_client.return_value.initialize_dataset_and_table, delete_query) def test_prevent_expiring_table_created_when_expiring_count_is_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=0) prevent_expiring_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_PREVENT_EXPIRING, main._PROJECT_ID) self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.initialize_dataset_and_table.assert_any_call( prevent_expiring_query) def test_prevent_expiring_table_not_created_when_expiring_count_is_not_positive( self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) prevent_expiring_query = bigquery_client.generate_query_string( main._QUERY_FILEPATH_FOR_PREVENT_EXPIRING, main._PROJECT_ID) self.assert_not_called_with( self.bigquery_client.return_value.initialize_dataset_and_table, prevent_expiring_query) def test_items_table_deleted_when_any_tasks_started_is_false(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.delete_table.assert_called_once() def test_eof_deleted_when_any_tasks_started_is_false(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.delete_eof_lock.assert_called_once() def test_no_tasks_created_when_no_content_api_calls_required(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.tasks_client.return_value.push_tasks.assert_not_called() def test_tasks_created_when_upsert_count_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=_DUMMY_UPSERT_COUNT) self.test_app_client.post(_START_PATH, json=request_body) self.tasks_client.return_value.push_tasks.assert_any_call( total_items=_DUMMY_UPSERT_COUNT, batch_size=mock.ANY, timestamp=mock.ANY) def test_tasks_created_when_delete_count_positive(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.tasks_client.return_value.push_tasks.assert_any_call( total_items=_DUMMY_DELETE_COUNT, batch_size=mock.ANY, timestamp=mock.ANY) def test_tasks_created_when_expiring_count_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.tasks_client.return_value.push_tasks.assert_any_call( total_items=_DUMMY_EXPIRING_COUNT, batch_size=mock.ANY, timestamp=mock.ANY) def test_eof_not_uploaded_when_no_content_api_call_required(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.upload_eof.assert_not_called() def test_mailer_triggered_when_no_content_api_call_required(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.pubsub_client.return_value.trigger_result_email.assert_called_once() def test_eof_uploaded_when_upsert_count_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=0, upsert_count=_DUMMY_UPSERT_COUNT) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.upload_eof.assert_called_once() def test_eof_uploaded_when_delete_count_positive(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=0, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.upload_eof.assert_called_once() def test_eof_uploaded_when_expiring_count_positive(self): request_body = _build_request_body_for_start( delete_count=0, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=0) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.upload_eof.assert_called_once() def test_eof_only_uploaded_once(self): request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.upload_eof.assert_called_once() def test_items_table_deleted_when_creating_processing_table_fails(self): self.bigquery_client.return_value.initialize_dataset_and_table.side_effect = exceptions.GoogleCloudError( 'Dummy message') request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) response = self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.delete_table.assert_called_once() self.assertEqual(http.HTTPStatus.INTERNAL_SERVER_ERROR, response.status_code) def test_eof_lock_deleted_when_creating_processing_table_fails(self): self.bigquery_client.return_value.initialize_dataset_and_table.side_effect = exceptions.GoogleCloudError( 'Dummy message') request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) response = self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.delete_eof_lock.assert_called_once() self.assertEqual(http.HTTPStatus.INTERNAL_SERVER_ERROR, response.status_code) def test_items_table_deleted_when_task_creation_fails(self): self.tasks_client.return_value.push_tasks.side_effect = exceptions.GoogleCloudError( 'Dummy message') request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) response = self.test_app_client.post(_START_PATH, json=request_body) self.bigquery_client.return_value.delete_table.assert_called_once() self.assertEqual(http.HTTPStatus.INTERNAL_SERVER_ERROR, response.status_code) def test_eof_deleted_when_task_creation_fails(self): self.tasks_client.return_value.push_tasks.side_effect = exceptions.GoogleCloudError( 'Dummy message') request_body = _build_request_body_for_start( delete_count=_DUMMY_DELETE_COUNT, expiring_count=_DUMMY_EXPIRING_COUNT, upsert_count=_DUMMY_UPSERT_COUNT) response = self.test_app_client.post(_START_PATH, json=request_body) self.storage_client.return_value.delete_eof.assert_called_once() self.assertEqual(http.HTTPStatus.INTERNAL_SERVER_ERROR, response.status_code) def assert_not_called_with(self, mock_obj, *unexpected_args, **unexpected_kwargs): for call in mock_obj.call_args_list: args, kwargs = call for arg in args: if arg in unexpected_args: raise AssertionError(f'Mock was called with {arg}') for key, value in kwargs.items(): if key in unexpected_kwargs.keys() and unexpected_kwargs[key] == value: raise AssertionError(f'Mock was called with {key}={value}')
""" This module provides convenient functions to transform sympy expressions to lambda functions which can be used to calculate numerical values very fast. """ from __future__ import division from sympy.core.sympify import sympify from sympy.core.compatibility import ordered_iter import inspect # These are the namespaces the lambda functions will use. MATH = {} MPMATH = {} NUMPY = {} SYMPY = {} # Mappings between sympy and other modules function names. MATH_TRANSLATIONS = { "Abs":"fabs", "ceiling":"ceil", "E":"e", "ln":"log", } MPMATH_TRANSLATIONS = { "ceiling":"ceil", "chebyshevt":"chebyt", "chebyshevu":"chebyu", "E":"e", "I":"j", "ln":"log", #"lowergamma":"lower_gamma", "oo":"inf", #"uppergamma":"upper_gamma", "LambertW":"lambertw", "Matrix":"matrix", "conjugate":"conj", } NUMPY_TRANSLATIONS = { "acos":"arccos", "acosh":"arccosh", "arg":"angle", "asin":"arcsin", "asinh":"arcsinh", "atan":"arctan", "atan2":"arctan2", "atanh":"arctanh", "ceiling":"ceil", "E":"e", "im":"imag", "ln":"log", "Matrix":"matrix", "Max":"amax", "Min":"amin", "oo":"inf", "re":"real", } # Available modules: MODULES = { "math":(MATH, MATH_TRANSLATIONS, ("from math import *",)), "mpmath":(MPMATH, MPMATH_TRANSLATIONS, ("from sympy.mpmath import *",)), "numpy":(NUMPY, NUMPY_TRANSLATIONS, ("from numpy import *",)), "sympy":(SYMPY, {}, ("from sympy.functions import *", "from sympy.matrices import Matrix", "from sympy import Integral, pi, oo, nan, zoo, E, I", "from sympy.utilities.iterables import iff")) } def _import(module, reload="False"): """ Creates a global translation dictionary for module. The argument module has to be one of the following strings: "math", "mpmath", "numpy", "sympy". These dictionaries map names of python functions to their equivalent in other modules. """ # TODO: rewrite this using import_module from sympy.external if not module in MODULES: raise NameError("This module can't be used for lambdification.") namespace, translations, import_commands = MODULES[module] # Clear namespace or exit if namespace: # The namespace was already generated, don't do it again if not forced. if reload: namespace.clear() else: return # It's possible that numpy is not available. for import_command in import_commands: try: exec import_command in {}, namespace except ImportError: raise ImportError("Can't import %s with command %s" % (module, import_command)) # Add translated names to namespace for sympyname, translation in translations.iteritems(): namespace[sympyname] = namespace[translation] def lambdify(args, expr, modules=None, printer=None, use_imps=True): """ Returns a lambda function for fast calculation of numerical values. Usage: >>> from sympy import sqrt, sin >>> from sympy.utilities.lambdify import lambdify >>> from sympy.abc import x, y, z >>> f = lambdify(x, x**2) >>> f(2) 4 >>> f = lambdify((x,y,z), [z,y,x]) >>> f(1,2,3) [3, 2, 1] >>> f = lambdify(x, sqrt(x)) >>> f(4) 2.0 >>> f = lambdify((x,y), sin(x*y)**2) >>> f(0, 5) 0.0 If not specified differently by the user, Sympy functions are replaced as far as possible by either python-math, numpy (if available) or mpmath functions - exactly in this order. To change this behavior, the "modules" argument can be used. It accepts: - the strings "math", "mpmath", "numpy", "sympy" - any modules (e.g. math) - dictionaries that map names of sympy functions to arbitrary functions - lists that contain a mix of the arguments above. (Entries that are first in the list have higher priority) Examples: (1) Use one of the provided modules: >> f = lambdify(x, sin(x), "math") Attention: Functions that are not in the math module will throw a name error when the lambda function is evaluated! So this would be better: >> f = lambdify(x, sin(x)*gamma(x), ("math", "mpmath", "sympy")) (2) Use some other module: >> import numpy >> f = lambdify((x,y), tan(x*y), numpy) Attention: There are naming differences between numpy and sympy. So if you simply take the numpy module, e.g. sympy.atan will not be translated to numpy.arctan. Use the modified module instead by passing the string "numpy": >> f = lambdify((x,y), tan(x*y), "numpy") >> f(1, 2) -2.18503986326 >> from numpy import array >> f(array([1, 2, 3]), array([2, 3, 5])) [-2.18503986 -0.29100619 -0.8559934 ] (3) Use own dictionaries: >> def my_cool_function(x): ... >> dic = {"sin" : my_cool_function} >> f = lambdify(x, sin(x), dic) Now f would look like: >> lambda x: my_cool_function(x) Functions present in `expr` can also carry their own numerical implementations, in a callable attached to the ``_imp_`` attribute. Usually you attach this using the ``implemented_function`` factory: >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdify, implemented_function >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x : x+1) >>> func = lambdify(x, f(x)) >>> func(4) 5 ``lambdify`` always prefers ``_imp_`` implementations to implementations in other namespaces, unless the ``use_imps`` input parameter is False. """ # If the user hasn't specified any modules, use what is available. if modules is None: # Use either numpy (if available) or python.math where possible. # XXX: This leads to different behaviour on different systems and # might be the reason for irreproducible errors. try: _import("numpy") modules = ("math", "numpy", "mpmath", "sympy") except ImportError: modules = ("math", "mpmath", "sympy") # Get the needed namespaces. namespaces = [] # First find any function implementations if use_imps: namespaces.append(_imp_namespace(expr)) # Check for dict before iterating if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): namespaces.append(modules) else: namespaces += list(modules) # fill namespace with first having highest priority namespace = {} for m in namespaces[::-1]: buf = _get_namespace(m) namespace.update(buf) if hasattr(expr, "atoms") : #Try if you can extract symbols from the expression. #Move on if expr.atoms in not implemented. syms = expr.atoms() for term in syms: namespace.update({str(term): term}) # Create lambda function. lstr = lambdastr(args, expr, printer=printer) return eval(lstr, namespace) def _get_namespace(m): """ This is used by _lambdify to parse its arguments. """ if isinstance(m, str): _import(m) return MODULES[m][0] elif isinstance(m, dict): return m elif hasattr(m, "__dict__"): return m.__dict__ else: raise TypeError("Argument must be either a string, dict or module but it is: %s" % m) def lambdastr(args, expr, printer=None): """ Returns a string that can be evaluated to a lambda function. >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdastr >>> lambdastr(x, x**2) 'lambda x: (x**2)' >>> lambdastr((x,y,z), [z,y,x]) 'lambda x,y,z: ([z, y, x])' """ if printer is not None: if inspect.isfunction(printer): lambdarepr = printer else: if inspect.isclass(printer): lambdarepr = lambda expr: printer().doprint(expr) else: lambdarepr = lambda expr: printer.doprint(expr) else: #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import lambdarepr # Transform everything to strings. expr = lambdarepr(expr) if isinstance(args, str): pass elif hasattr(args, "__iter__"): args = ",".join(str(a) for a in args) else: args = str(args) return "lambda %s: (%s)" % (args, expr) def _imp_namespace(expr, namespace=None): """ Return namespace dict with function implementations We need to search for functions in anything that can be thrown at us - that is - anything that could be passed as `expr`. Examples include sympy expressions, as well as tuples, lists and dicts that may contain sympy expressions. Parameters ---------- expr : object Something passed to lambdify, that will generate valid code from ``str(expr)``. namespace : None or mapping Namespace to fill. None results in new empty dict Returns ------- namespace : dict dict with keys of implemented function names within `expr` and corresponding values being the numerical implementation of function Examples -------- >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x : x+1) >>> g = implemented_function(Function('g'), lambda x : x*10) >>> namespace = _imp_namespace(f(g(x))) >>> sorted(namespace.keys()) ['f', 'g'] """ # Delayed import to avoid circular imports from sympy.core.function import FunctionClass if namespace is None: namespace = {} # tuples, lists, dicts are valid expressions if ordered_iter(expr): for arg in expr: _imp_namespace(arg, namespace) return namespace elif isinstance(expr, dict): for key, val in expr.items(): # functions can be in dictionary keys _imp_namespace(key, namespace) _imp_namespace(val, namespace) return namespace # sympy expressions may be Functions themselves func = getattr(expr, 'func', None) if isinstance(func, FunctionClass): imp = getattr(func, '_imp_', None) if not imp is None: name = expr.func.__name__ if name in namespace and namespace[name] != imp: raise ValueError('We found more than one ' 'implementation with name ' '"%s"' % name) namespace[name] = imp # and / or they may take Functions as arguments if hasattr(expr, 'args'): for arg in expr.args: _imp_namespace(arg, namespace) return namespace def implemented_function(symfunc, implementation): """ Add numerical `implementation` to function `symfunc` `symfunc` can by a Function, or a name, in which case we make an anonymous function with this name. The function is anonymous in the sense that the name is not unique in the sympy namespace. Parameters ---------- symfunc : str or ``sympy.FunctionClass`` instance If str, then create new anonymous sympy function with this as name. If `symfunc` is a sympy function, attach implementation to function implementation : callable numerical implementation of function for use in ``lambdify`` Returns ------- afunc : sympy.FunctionClass instance function with attached implementation Examples -------- >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdify, implemented_function >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x : x+1) >>> lam_f = lambdify(x, f(x)) >>> lam_f(4) 5 """ # Delayed import to avoid circular imports from sympy.core.function import UndefinedFunction # if name, create anonymous function to hold implementation if isinstance(symfunc, basestring): symfunc = UndefinedFunction(symfunc) # We need to attach as a method because symfunc will be a class symfunc._imp_ = staticmethod(implementation) return symfunc
# Copyright 2015-2016 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cStringIO import json import re from collections import defaultdict from contextlib import contextmanager import unicodecsv from flask import request, jsonify, Response, stream_with_context from flask.ext.login import current_user from gevent import sleep from netaddr import IPRange, IPNetwork, IPSet, iprange_to_cidrs from .aaa import MMBlueprint from .cbfeed import CbFeedInfo, CbReport from .logger import LOG from .mmrpc import MMMaster from .redisclient import SR __all__ = ['BLUEPRINT'] FEED_INTERVAL = 100 _PROTOCOL_RE = re.compile('^(?:[a-z]+:)*//') _PORT_RE = re.compile('^([a-z0-9\-\.]+)(?:\:[0-9]+)*') _INVALID_TOKEN_RE = re.compile('(?:[^\./+=\?&]+\*[^\./+=\?&]*)|(?:[^\./+=\?&]*\*[^\./+=\?&]+)') _BROAD_PATTERN = re.compile('^(?:\*\.)+[a-zA-Z]+(?::[0-9]+)?$') _IPV4_MASK_RE = re.compile('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(\\/[0-9]+)?$') _IPV4_RANGE_RE = re.compile( '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}-[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$') BLUEPRINT = MMBlueprint('feeds', __name__, url_prefix='/feeds') def _translate_ip_ranges(indicator, value=None): if value is not None and value['type'] != 'IPv4': return [indicator] try: ip_range = IPRange(*indicator.split('-', 1)) except (AddrFormatError, ValueError, TypeError): return [indicator] return [str(x) if x.size != 1 else str(x.network) for x in ip_range.cidrs()] def _extract_cidrs(indicator): try: parsed = iprange_to_cidrs(*indicator.split('-', 1)) if '-' in indicator else [IPNetwork(indicator)] except (AddrFormatError, ValueError, TypeError): raise Exception('Invalid IP Address in summarization: {!r}'.format(indicator)) return parsed @contextmanager def _buffer(): result = cStringIO.StringIO() try: yield result finally: result.close() def generate_panosurl_feed(feed, start, num, desc, value, **kwargs): zrange = SR.zrange if desc: zrange = SR.zrevrange if num is None: num = (1 << 32) - 1 cstart = start while cstart < (start + num): ilist = zrange(feed, cstart, cstart - 1 + min(start + num - cstart, FEED_INTERVAL)) for i in ilist: i = i.lower() i = _PROTOCOL_RE.sub('', i) withport = i i = _PORT_RE.sub('\g<1>', i) LOG.debug('{} => {}'.format(withport, i)) if withport != i and 'sp' not in kwargs: # port removed, but strip port not enabled # ignore entry continue old = i i = _INVALID_TOKEN_RE.sub('*', i) if old != i: # url changed, invalid tokens detected if 'di' in kwargs: # drop invalid in params, drop entry continue # check if the pattern is now too broad hostname = i if '/' in hostname: hostname, _ = hostname.split('/', 1) if _BROAD_PATTERN.match(hostname) is not None: continue if '/' not in i and not 'nsl' in kwargs: i = i + '/' # add a slash at the end of the hostname # for PAN-OS *.domain.com does not match domain.com # we should provide both # this could generate more than num entries in the egress feed if i.startswith('*.'): yield i[2:] + '\n' yield i + '\n' if len(ilist) < 100: break cstart += 100 def generate_plain_feed(feed, start, num, desc, value, **kwargs): zrange = SR.zrange if desc: zrange = SR.zrevrange if num is None: num = (1 << 32) - 1 translate_ip_ranges = kwargs.pop('translate_ip_ranges', False) should_aggregate = 'sum' in kwargs if should_aggregate: translate_ip_ranges = False temp_set = set() cstart = start while cstart < (start + num): ilist = zrange(feed, cstart, cstart - 1 + min(start + num - cstart, FEED_INTERVAL)) if should_aggregate: for i in ilist: for n in _extract_cidrs(i): temp_set.add(n) else: if translate_ip_ranges: ilist = [xi for i in ilist for xi in _translate_ip_ranges(i)] yield '\n'.join(ilist) + '\n' if len(ilist) < 100: break cstart += 100 if should_aggregate: ip_set = IPSet(temp_set) for cidr in ip_set.iter_cidrs(): yield str(cidr) + '\n' def generate_json_feed(feed, start, num, desc, value, **kwargs): zrange = SR.zrange if desc: zrange = SR.zrevrange if num is None: num = (1 << 32) - 1 translate_ip_ranges = kwargs.pop('translate_ip_ranges', False) if value == 'json': yield '[\n' cstart = start firstelement = True while cstart < (start + num): ilist = zrange(feed, cstart, cstart - 1 + min(start + num - cstart, FEED_INTERVAL)) result = cStringIO.StringIO() for indicator in ilist: v = SR.hget(feed + '.value', indicator) xindicators = [indicator] if translate_ip_ranges and '-' in indicator: xindicators = _translate_ip_ranges(indicator, None if v is None else json.loads(v)) if v is None: v = 'null' for i in xindicators: if value == 'json' and not firstelement: result.write(',\n') if value == 'json-seq': result.write('\x1E') result.write('{"indicator":') result.write(json.dumps(i)) result.write(',"value":') result.write(v) result.write('}') if value == 'json-seq': result.write('\n') firstelement = False yield result.getvalue() result.close() if len(ilist) < 100: break cstart += 100 if value == 'json': yield ']\n' def generate_csv_feed(feed, start, num, desc, value, **kwargs): def _is_atomic_type(fv): return (isinstance(fv, unicode) or isinstance(fv, str) or isinstance(fv, int) or isinstance(fv, bool)) def _format_field_value(fv): if _is_atomic_type(fv): return fv if isinstance(fv, list): ok = True for fve in fv: ok &= _is_atomic_type(fve) if ok: return ','.join(fv) return json.dumps(fv) zrange = SR.zrange if desc: zrange = SR.zrevrange if num is None: num = (1 << 32) - 1 translate_ip_ranges = kwargs.pop('translate_ip_ranges', False) # extract name of fields and column names columns = [] fields = [] for addf in kwargs.pop('f', []): if '|' in addf: fname, cname = addf.rsplit('|', 1) else: fname = addf cname = addf columns.append(cname) fields.append(fname) # if no fields are specified, only indicator is generated if len(fields) == 0: fields = ['indicator'] columns = ['indicator'] # check if header should be generated header = kwargs.pop('h', None) if header is None: header = True else: header = int(header[0]) # check if bom should be generated ubom = kwargs.pop('ubom', None) if ubom is None: ubom = False else: ubom = int(ubom[0]) cstart = start if ubom: LOG.debug('BOM') yield '\xef\xbb\xbf' with _buffer() as current_line: w = unicodecsv.DictWriter( current_line, fieldnames=columns, encoding='utf-8' ) if header: w.writeheader() yield current_line.getvalue() while cstart < (start + num): ilist = zrange(feed, cstart, cstart - 1 + min(start + num - cstart, FEED_INTERVAL)) for indicator in ilist: v = SR.hget(feed + '.value', indicator) v = None if v is None else json.loads(v) xindicators = [indicator] if translate_ip_ranges and '-' in indicator: xindicators = _translate_ip_ranges(indicator, v) for i in xindicators: fieldvalues = {} for f, c in zip(fields, columns): if f == 'indicator': fieldvalues[c] = i continue if v is not None and f in v: fieldvalues[c] = _format_field_value(v[f]) current_line.truncate(0) w.writerow(fieldvalues) yield current_line.getvalue() if len(ilist) < FEED_INTERVAL: break cstart += FEED_INTERVAL def generate_mwg_feed(feed, start, num, desc, value, **kwargs): zrange = SR.zrange if desc: zrange = SR.zrevrange if num is None: num = (1 << 32) - 1 translate_ip_ranges = kwargs.pop('translate_ip_ranges', False) type_ = kwargs.get('t', None) if type_ is None: type_ = 'string' else: type_ = type_[0] translate_ip_ranges |= type_ == 'ip' yield 'type={}\n'.format(type_) cstart = start while cstart < (start + num): ilist = zrange(feed, cstart, cstart - 1 + min(start + num - cstart, FEED_INTERVAL)) for indicator in ilist: v = SR.hget(feed + '.value', indicator) v = None if v is None else json.loads(v) xindicators = [indicator] if translate_ip_ranges and '-' in indicator: xindicators = _translate_ip_ranges(indicator, v) sources = 'from minemeld' if v is not None: sources = v.get('sources', 'from minemeld') if isinstance(sources, list): sources = ','.join(sources) for i in xindicators: yield '"{}" "{}"\n'.format( i.replace('"', '\\"'), sources.replace('"', '\\"') ) if len(ilist) < 100: break cstart += 100 # This formatter implements BlueCoat custom URL format as described at # https://www.bluecoat.com/documents/download/a366dc73-d455-4859-b92a-c96bd034cb4c/f849f1e3-a906-4ee8-924e-a2061dfe3cdf # It expects the value 'bc_category' in the indicator. The value can be either a single string or a list of strings. # Optional feed arguments: # ca : Indicator's attribute that hosts the BlueCoat category. Defaults to 'bc_category' # cd : Default BlueCoat category for indicators that do not have 'catattr'. This argument can appear multiple # times and it will be handled as a list of categories the indicator belongs to. If not present then # indicators without 'catattr' will be discarded. def generate_bluecoat_feed(feed, start, num, desc, value, **kwargs): zrange = SR.zrange ilist = zrange(feed, 0, (1 << 32) - 1) bc_dict = defaultdict(list) flag_category_default = kwargs.get('cd', None) flag_category_attr = kwargs.get('ca', ['bc_category'])[0] for i in ilist: sleep(0) v = SR.hget(feed + '.value', i) v = None if v is None else json.loads(v) i = i.lower() i = _PROTOCOL_RE.sub('', i) i = _INVALID_TOKEN_RE.sub('*', i) if v is None: if flag_category_default is None: continue else: bc_cat_list = flag_category_default else: bc_cat_attr = v.get(flag_category_attr, None) if isinstance(bc_cat_attr, list): bc_cat_list = bc_cat_attr elif isinstance(bc_cat_attr, basestring): bc_cat_list = [bc_cat_attr] elif flag_category_default is not None: bc_cat_list = flag_category_default else: continue for bc_cat in bc_cat_list: bc_dict[bc_cat].append(i) for key, value in bc_dict.iteritems(): yield 'define category {}\n'.format(key) for ind in value: yield ind + '\n' yield 'end\n' def generate_carbon_black(feed, start, num, desc, value, **kwargs): zrange = SR.zrange ilist = zrange(feed, 0, (1 << 32) - 1) mm_to_cb = {"IPv4": "ipv4", "domain": "dns", "md5": "md5"} ind_by_type = {"dns": [], "md5": []} # Let's stream the information as soon as we have it yield "{\n\"feedinfo\": {\n" cb_feed_info = CbFeedInfo(name=feed) for cb_info_parts in cb_feed_info.iterate(): yield " " + cb_info_parts yield "\n},\n\"reports\": [{" report_args = dict() report_args["id"] = feed + "_report" report_title = kwargs.get('rt', ["MieneMeld Generated Report"]) if report_title is not None: report_title = report_title[0] report_args["title"] = report_title report_score = kwargs.get('rs', None) if report_score is not None: try: report_score = int(report_score[0]) except ValueError: report_score = None report_args["score"] = report_score cb_report = CbReport(**report_args) for cb_report_parts in cb_report.iterate(): yield " " + cb_report_parts yield ", \"iocs\": {" yield " \"ipv4\": [" # Loop though all indicators # Only indicators of type IPv4, domain and md5 can be exported to Carbon Black ipv4_line = None for i in ilist: sleep(0) v = SR.hget(feed + '.value', i) v = None if v is None else json.loads(v) if v is None: continue v_type = v.get("type", None) if v_type not in mm_to_cb: continue if v_type in ("domain", "md5"): ind_by_type[mm_to_cb[v_type]].append(i.lower()) continue # Carbon Black do not support IPv4 networks not ranges. We must expand them. ip_range = None if _IPV4_MASK_RE.match(i): ip_range = IPSet(IPNetwork(i)) elif _IPV4_RANGE_RE.match(i): range_parts = i.split("-") ip_range = IPRange(range_parts[0], range_parts[1]) for ip_addr in ip_range: if ipv4_line is not None: yield ipv4_line + "," ipv4_line = "\"{}\"".format(str(ip_addr)) yield ("" if ipv4_line is None else ipv4_line) + "]," yield "\"dns\": {},".format(json.dumps(ind_by_type["dns"])) yield "\"md5\": {}".format(json.dumps(ind_by_type["md5"])) yield "}}]}" _FEED_FORMATS = { 'json': { 'formatter': generate_json_feed, 'mimetype': 'application/json' }, 'json-seq': { 'formatter': generate_json_feed, 'mimetype': 'application/json-seq' }, 'panosurl': { 'formatter': generate_panosurl_feed, 'mimetype': 'text/plain' }, 'mwg': { 'formatter': generate_mwg_feed, 'mimetype': 'text/plain' }, 'bluecoat': { 'formatter': generate_bluecoat_feed, 'mimetype': 'text/plain' }, 'carbonblack': { 'formatter': generate_carbon_black, 'mimetype': 'application/json' }, 'csv': { 'formatter': generate_csv_feed, 'mimetype': 'text/csv' } } @BLUEPRINT.route('/<feed>', methods=['GET'], feeds=True, read_write=False) def get_feed_content(feed): if not current_user.check_feed(feed): return '<html><body>Unauthorized</body></html>', 401 # check if feed exists status = MMMaster.status() tr = status.get('result', None) if tr is None: LOG.error("Error retrieving status from MMMaster: {!r}".format(status.get('error', 'error'))) return '<html><body>Internal error</body></html>', 500 nname = 'mbus:slave:' + feed if nname not in tr: return '<html><body>Unknown feed</body></html>', 404 nclass = tr[nname].get('class', None) if nclass != 'minemeld.ft.redis.RedisSet': return '<html><body>Unknown feed</body></html>', 404 start = request.values.get('s') if start is None: start = 0 try: start = int(start) if start < 0: raise ValueError() except ValueError: LOG.error("Invalid request, s not a non-negative integer: %s", start) return '<html><body>s should be a positive integer</body></html>', 400 num = request.values.get('n') if num is not None: try: num = int(num) if num <= 0: raise ValueError() except ValueError: LOG.error("Invalid request, n not a positive integer: %s", num) return '<html><body>n should be a positive integer</body></html>', 400 else: num = None desc = request.values.get('d') desc = (False if desc is None else True) value = request.values.get('v') if value is not None and value not in _FEED_FORMATS: return '<html><body>unknown format</body></html>', 400 kwargs = {} kwargs['translate_ip_ranges'] = int(request.values.get('tr', 0)) # generate IP ranges # move to kwargs all the additional parameters, pop the predefined kwargs.update(request.values.to_dict(flat=False)) kwargs.pop('s', None) kwargs.pop('n', None) kwargs.pop('d', None) kwargs.pop('v', None) kwargs.pop('tr', None) mimetype = 'text/plain' formatter = generate_plain_feed if value in _FEED_FORMATS: formatter = _FEED_FORMATS[value]['formatter'] mimetype = _FEED_FORMATS[value]['mimetype'] return Response( stream_with_context( formatter(feed, start, num, desc, value, **kwargs) ), mimetype=mimetype )
# # Copyright 2014 Rackspace, Inc # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from ironic_lib import utils as ironic_utils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import fileutils from ironic.common import dhcp_factory from ironic.common import exception from ironic.common.i18n import _ from ironic.common import utils from ironic.drivers.modules import deploy_utils CONF = cfg.CONF LOG = logging.getLogger(__name__) PXE_CFG_DIR_NAME = 'pxelinux.cfg' def get_root_dir(): """Returns the directory where the config files and images will live.""" if CONF.pxe.ipxe_enabled: return CONF.deploy.http_root else: return CONF.pxe.tftp_root def _ensure_config_dirs_exist(node_uuid): """Ensure that the node's and PXE configuration directories exist. :param node_uuid: the UUID of the node. """ root_dir = get_root_dir() node_dir = os.path.join(root_dir, node_uuid) pxe_dir = os.path.join(root_dir, PXE_CFG_DIR_NAME) # NOTE: We should only change the permissions if the folder # does not exist. i.e. if defined, an operator could have # already created it and placed specific ACLs upon the folder # which may not recurse downward. for directory in (node_dir, pxe_dir): if not os.path.isdir(directory): fileutils.ensure_tree(directory) if CONF.pxe.dir_permission: os.chmod(directory, CONF.pxe.dir_permission) def _link_mac_pxe_configs(task): """Link each MAC address with the PXE configuration file. :param task: A TaskManager instance. """ def create_link(mac_path): ironic_utils.unlink_without_raise(mac_path) relative_source_path = os.path.relpath( pxe_config_file_path, os.path.dirname(mac_path)) utils.create_link_without_raise(relative_source_path, mac_path) pxe_config_file_path = get_pxe_config_file_path(task.node.uuid) for port in task.ports: client_id = port.extra.get('client-id') create_link(_get_pxe_mac_path(port.address, client_id=client_id)) def _link_ip_address_pxe_configs(task, hex_form): """Link each IP address with the PXE configuration file. :param task: A TaskManager instance. :param hex_form: Boolean value indicating if the conf file name should be hexadecimal equivalent of supplied ipv4 address. :raises: FailedToGetIPAddressOnPort :raises: InvalidIPv4Address """ pxe_config_file_path = get_pxe_config_file_path(task.node.uuid) api = dhcp_factory.DHCPFactory().provider ip_addrs = api.get_ip_addresses(task) if not ip_addrs: raise exception.FailedToGetIPAddressOnPort(_( "Failed to get IP address for any port on node %s.") % task.node.uuid) for port_ip_address in ip_addrs: ip_address_path = _get_pxe_ip_address_path(port_ip_address, hex_form) ironic_utils.unlink_without_raise(ip_address_path) relative_source_path = os.path.relpath( pxe_config_file_path, os.path.dirname(ip_address_path)) utils.create_link_without_raise(relative_source_path, ip_address_path) def _get_pxe_mac_path(mac, delimiter='-', client_id=None): """Convert a MAC address into a PXE config file name. :param mac: A MAC address string in the format xx:xx:xx:xx:xx:xx. :param delimiter: The MAC address delimiter. Defaults to dash ('-'). :param client_id: client_id indicate InfiniBand port. Defaults is None (Ethernet) :returns: the path to the config file. """ mac_file_name = mac.replace(':', delimiter).lower() if not CONF.pxe.ipxe_enabled: hw_type = '01-' if client_id: hw_type = '20-' mac_file_name = hw_type + mac_file_name return os.path.join(get_root_dir(), PXE_CFG_DIR_NAME, mac_file_name) def _get_pxe_ip_address_path(ip_address, hex_form): """Convert an ipv4 address into a PXE config file name. :param ip_address: A valid IPv4 address string in the format 'n.n.n.n'. :param hex_form: Boolean value indicating if the conf file name should be hexadecimal equivalent of supplied ipv4 address. :returns: the path to the config file. """ # NOTE(TheJulia): Remove elilo support after the deprecation # period, in the Queens release. # elilo bootloader needs hex based config file name. if hex_form: ip = ip_address.split('.') ip_address = '{0:02X}{1:02X}{2:02X}{3:02X}'.format(*map(int, ip)) # grub2 bootloader needs ip based config file name. return os.path.join( CONF.pxe.tftp_root, ip_address + ".conf" ) def get_deploy_kr_info(node_uuid, driver_info): """Get href and tftp path for deploy kernel and ramdisk. Note: driver_info should be validated outside of this method. """ root_dir = get_root_dir() image_info = {} for label in ('deploy_kernel', 'deploy_ramdisk'): image_info[label] = ( str(driver_info[label]), os.path.join(root_dir, node_uuid, label) ) return image_info def get_pxe_config_file_path(node_uuid): """Generate the path for the node's PXE configuration file. :param node_uuid: the UUID of the node. :returns: The path to the node's PXE configuration file. """ return os.path.join(get_root_dir(), node_uuid, 'config') def create_pxe_config(task, pxe_options, template=None): """Generate PXE configuration file and MAC address links for it. This method will generate the PXE configuration file for the task's node under a directory named with the UUID of that node. For each MAC address or DHCP IP address (port) of that node, a symlink for the configuration file will be created under the PXE configuration directory, so regardless of which port boots first they'll get the same PXE configuration. If elilo is the bootloader in use, then its configuration file will be created based on hex form of DHCP IP address. If grub2 bootloader is in use, then its configuration will be created based on DHCP IP address in the form nn.nn.nn.nn. :param task: A TaskManager instance. :param pxe_options: A dictionary with the PXE configuration parameters. :param template: The PXE configuration template. If no template is given the node specific template will be used. """ LOG.debug("Building PXE config for node %s", task.node.uuid) if template is None: template = deploy_utils.get_pxe_config_template(task.node) _ensure_config_dirs_exist(task.node.uuid) pxe_config_file_path = get_pxe_config_file_path(task.node.uuid) is_uefi_boot_mode = (deploy_utils.get_boot_mode_for_deploy(task.node) == 'uefi') # grub bootloader panics with '{}' around any of its tags in its # config file. To overcome that 'ROOT' and 'DISK_IDENTIFIER' are enclosed # with '(' and ')' in uefi boot mode. # These changes do not have any impact on elilo bootloader. hex_form = True if is_uefi_boot_mode and utils.is_regex_string_in_file(template, '^menuentry'): hex_form = False pxe_config_root_tag = '(( ROOT ))' pxe_config_disk_ident = '(( DISK_IDENTIFIER ))' LOG.warning("The requested config appears to support elilo. " "Support for elilo has been deprecated and will be " "removed in the Queens release of OpenStack.") else: # TODO(stendulker): We should use '(' ')' as the delimiters for all our # config files so that we do not need special handling for each of the # bootloaders. Should be removed once the Mitaka release starts. pxe_config_root_tag = '{{ ROOT }}' pxe_config_disk_ident = '{{ DISK_IDENTIFIER }}' params = {'pxe_options': pxe_options, 'ROOT': pxe_config_root_tag, 'DISK_IDENTIFIER': pxe_config_disk_ident} pxe_config = utils.render_template(template, params) utils.write_to_file(pxe_config_file_path, pxe_config) if is_uefi_boot_mode and not CONF.pxe.ipxe_enabled: _link_ip_address_pxe_configs(task, hex_form) else: _link_mac_pxe_configs(task) def create_ipxe_boot_script(): """Render the iPXE boot script into the HTTP root directory""" boot_script = utils.render_template( CONF.pxe.ipxe_boot_script, {'ipxe_for_mac_uri': PXE_CFG_DIR_NAME + '/'}) bootfile_path = os.path.join( CONF.deploy.http_root, os.path.basename(CONF.pxe.ipxe_boot_script)) # NOTE(pas-ha) to prevent unneeded writes, # only write to file if its content is different from required, # which should be rather rare if (not os.path.isfile(bootfile_path) or not utils.file_has_content(bootfile_path, boot_script)): utils.write_to_file(bootfile_path, boot_script) def clean_up_pxe_config(task): """Clean up the TFTP environment for the task's node. :param task: A TaskManager instance. """ LOG.debug("Cleaning up PXE config for node %s", task.node.uuid) is_uefi_boot_mode = (deploy_utils.get_boot_mode_for_deploy(task.node) == 'uefi') if is_uefi_boot_mode and not CONF.pxe.ipxe_enabled: api = dhcp_factory.DHCPFactory().provider ip_addresses = api.get_ip_addresses(task) if not ip_addresses: return for port_ip_address in ip_addresses: try: # Get xx.xx.xx.xx based grub config file ip_address_path = _get_pxe_ip_address_path(port_ip_address, False) # NOTE(TheJulia): Remove elilo support after the deprecation # period, in the Queens release. # Get 0AOAOAOA based elilo config file hex_ip_path = _get_pxe_ip_address_path(port_ip_address, True) except exception.InvalidIPv4Address: continue # Cleaning up config files created for grub2. ironic_utils.unlink_without_raise(ip_address_path) # Cleaning up config files created for elilo. ironic_utils.unlink_without_raise(hex_ip_path) else: for port in task.ports: client_id = port.extra.get('client-id') ironic_utils.unlink_without_raise( _get_pxe_mac_path(port.address, client_id=client_id)) utils.rmtree_without_raise(os.path.join(get_root_dir(), task.node.uuid)) def dhcp_options_for_instance(task): """Retrieves the DHCP PXE boot options. :param task: A TaskManager instance. """ dhcp_opts = [] boot_file = deploy_utils.get_pxe_boot_file(task.node) if CONF.pxe.ipxe_enabled: script_name = os.path.basename(CONF.pxe.ipxe_boot_script) ipxe_script_url = '/'.join([CONF.deploy.http_url, script_name]) dhcp_provider_name = CONF.dhcp.dhcp_provider # if the request comes from dumb firmware send them the iPXE # boot image. if dhcp_provider_name == 'neutron': # Neutron use dnsmasq as default DHCP agent, add extra config # to neutron "dhcp-match=set:ipxe,175" and use below option dhcp_opts.append({'opt_name': 'tag:!ipxe,bootfile-name', 'opt_value': boot_file}) dhcp_opts.append({'opt_name': 'tag:ipxe,bootfile-name', 'opt_value': ipxe_script_url}) else: # !175 == non-iPXE. # http://ipxe.org/howto/dhcpd#ipxe-specific_options dhcp_opts.append({'opt_name': '!175,bootfile-name', 'opt_value': boot_file}) dhcp_opts.append({'opt_name': 'bootfile-name', 'opt_value': ipxe_script_url}) else: dhcp_opts.append({'opt_name': 'bootfile-name', 'opt_value': boot_file}) # 210 == tftp server path-prefix or tftp root, will be used to find # pxelinux.cfg directory. The pxelinux.0 loader infers this information # from it's own path, but Petitboot needs it to be specified by this # option since it doesn't use pxelinux.0 loader. dhcp_opts.append({'opt_name': '210', 'opt_value': get_tftp_path_prefix()}) dhcp_opts.append({'opt_name': 'server-ip-address', 'opt_value': CONF.pxe.tftp_server}) dhcp_opts.append({'opt_name': 'tftp-server', 'opt_value': CONF.pxe.tftp_server}) # Append the IP version for all the configuration options for opt in dhcp_opts: opt.update({'ip_version': int(CONF.pxe.ip_version)}) return dhcp_opts def get_tftp_path_prefix(): """Adds trailing slash (if needed) necessary for path-prefix :return: CONF.pxe.tftp_root ensured to have a trailing slash """ return os.path.join(CONF.pxe.tftp_root, '') def get_path_relative_to_tftp_root(file_path): """Return file relative path to CONF.pxe.tftp_root :param file_path: full file path to be made relative path. :returns: The path relative to CONF.pxe.tftp_root """ return os.path.relpath(file_path, get_tftp_path_prefix())
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for subcommands that need to SSH into virtual machine guests.""" import logging from googlecloudsdk.api_lib.compute import base_classes from googlecloudsdk.api_lib.compute import constants from googlecloudsdk.api_lib.compute import metadata_utils from googlecloudsdk.api_lib.compute import path_simplifier from googlecloudsdk.api_lib.compute import request_helper from googlecloudsdk.api_lib.compute import utils from googlecloudsdk.api_lib.compute.users import client as user_client from googlecloudsdk.calliope import exceptions from googlecloudsdk.command_lib.util import gaia from googlecloudsdk.command_lib.util import ssh from googlecloudsdk.command_lib.util import time_util from googlecloudsdk.core import exceptions as core_exceptions from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.core.console import progress_tracker # The maximum amount of time to wait for a newly-added SSH key to # propagate before giving up. _SSH_KEY_PROPAGATION_TIMEOUT_SEC = 60 _TROUBLESHOOTING_URL = ( 'https://cloud.google.com/compute/docs/troubleshooting#ssherrors') class CommandError(core_exceptions.Error): """Wraps ssh.CommandError, primarly for adding troubleshooting info.""" def __init__(self, original_error, message=None): if message is None: message = 'See {url} for troubleshooting hints.'.format( url=_TROUBLESHOOTING_URL) super(CommandError, self).__init__( '{0}\n{1}'.format(original_error, message), exit_code=original_error.exit_code) class SetProjectMetadataError(core_exceptions.Error): pass def GetExternalIPAddress(instance_resource, no_raise=False): """Returns the external IP address of the instance. Args: instance_resource: An instance resource object. no_raise: A boolean flag indicating whether or not to return None instead of raising. Raises: ToolException: If no external IP address is found for the instance_resource and no_raise is False. Returns: A string IP or None is no_raise is True and no ip exists. """ if instance_resource.networkInterfaces: access_configs = instance_resource.networkInterfaces[0].accessConfigs if access_configs: ip_address = access_configs[0].natIP if ip_address: return ip_address elif not no_raise: raise exceptions.ToolException( 'Instance [{0}] in zone [{1}] has not been allocated an external ' 'IP address yet. Try rerunning this command later.'.format( instance_resource.name, path_simplifier.Name(instance_resource.zone))) if no_raise: return None raise exceptions.ToolException( 'Instance [{0}] in zone [{1}] does not have an external IP address, ' 'so you cannot SSH into it. To add an external IP address to the ' 'instance, use [gcloud compute instances add-access-config].' .format(instance_resource.name, path_simplifier.Name(instance_resource.zone))) def _GetMetadataKey(iam_ssh_keys): """Get the metadata key name for the desired SSH key metadata. There are four SSH key related metadata pairs: * Per-project 'sshKeys': this grants SSH access to VMs project-wide. * Per-instance 'sshKeys': this is used to grant access to an individual instance. For historical reasons, it acts as an override to the project-global value. * Per-instance 'block-project-ssh-keys': this determines whether 'ssh-keys' overrides or adds to the per-project 'sshKeys' * Per-instance 'ssh-keys': this also grants access to an individual instance, but acts in addition or as an override to the per-project 'sshKeys' depending on 'block-project-ssh-keys' Args: iam_ssh_keys: bool. If False, give the name of the original SSH metadata key (that overrides the project-global SSH metadata key). If True, give the name of the IAM SSH metadata key (that works in conjunction with the project-global SSH key metadata). Returns: str, the corresponding metadata key name. """ if iam_ssh_keys: metadata_key = constants.SSH_KEYS_INSTANCE_RESTRICTED_METADATA_KEY else: metadata_key = constants.SSH_KEYS_METADATA_KEY return metadata_key def _GetSSHKeysFromMetadata(metadata, iam_keys=False): """Returns the value of the "sshKeys" metadata as a list.""" if not metadata: return [] for item in metadata.items: if item.key == _GetMetadataKey(iam_keys): return [key.strip() for key in item.value.split('\n') if key] return [] def _PrepareSSHKeysValue(ssh_keys): """Returns a string appropriate for the metadata. Values from are taken from the tail until either all values are taken or _MAX_METADATA_VALUE_SIZE_IN_BYTES is reached, whichever comes first. The selected values are then reversed. Only values at the head of the list will be subject to removal. Args: ssh_keys: A list of keys. Each entry should be one key. Returns: A new-line-joined string of SSH keys. """ keys = [] bytes_consumed = 0 for key in reversed(ssh_keys): num_bytes = len(key + '\n') if bytes_consumed + num_bytes > constants.MAX_METADATA_VALUE_SIZE_IN_BYTES: log.warn('The following SSH key will be removed from your project ' 'because your sshKeys metadata value has reached its ' 'maximum allowed size of {0} bytes: {1}' .format(constants.MAX_METADATA_VALUE_SIZE_IN_BYTES, key)) else: keys.append(key) bytes_consumed += num_bytes keys.reverse() return '\n'.join(keys) def _AddSSHKeyToMetadataMessage(message_classes, user, public_key, metadata, iam_keys=False): """Adds the public key material to the metadata if it's not already there.""" entry = u'{user}:{public_key}'.format( user=user, public_key=public_key) ssh_keys = _GetSSHKeysFromMetadata(metadata, iam_keys=iam_keys) log.debug('Current SSH keys in project: {0}'.format(ssh_keys)) if entry in ssh_keys: return metadata else: ssh_keys.append(entry) return metadata_utils.ConstructMetadataMessage( message_classes=message_classes, metadata={ _GetMetadataKey(iam_keys): _PrepareSSHKeysValue(ssh_keys)}, existing_metadata=metadata) def _MetadataHasBlockProjectSshKeys(metadata): """Return true if the metadata has 'block-project-ssh-keys' set and 'true'.""" if not (metadata and metadata.items): return False matching_values = [item.value for item in metadata.items if item.key == constants.SSH_KEYS_BLOCK_METADATA_KEY] if not matching_values: return False return matching_values[0].lower() == 'true' class BaseSSHCommand(base_classes.BaseCommand): """Base class for subcommands that need to connect to instances using SSH. Subclasses can call EnsureSSHKeyIsInProject() to make sure that the user's public SSH key is placed in the project metadata before proceeding. Attributes: keys: ssh.Keys, the public/private key pair. env: ssh.Environment, the current environment, used by subclasses. """ @staticmethod def Args(parser): """Args is called by calliope to gather arguments for this command. Please add arguments in alphabetical order except for no- or a clear- pair for that argument which can follow the argument itself. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """ force_key_file_overwrite = parser.add_argument( '--force-key-file-overwrite', action='store_true', default=None, help=('Force overwrite the files associated with a broken SSH key.') ) force_key_file_overwrite.detailed_help = """\ If enabled gcloud will regenerate and overwrite the files associated with a broken SSH key without asking for confirmation in both interactive and non-interactive environment. If disabled gcloud will not attempt to regenerate the files associated with a broken SSH key and fail in both interactive and non-interactive environment. """ # Last line empty to preserve spacing between last paragraph and calliope # attachment "Use --no-force-key-file-overwrite to disable." ssh_key_file = parser.add_argument( '--ssh-key-file', help='The path to the SSH key file.') ssh_key_file.detailed_help = """\ The path to the SSH key file. By default, this is ``{0}''. """.format(ssh.Keys.DEFAULT_KEY_FILE) def Run(self, args): """Sets up resources to be used by concrete subclasses. Subclasses must call this in their Run() before continuing. Args: args: argparse.Namespace, arguments that this command was invoked with. Raises: ssh.CommandNotFoundError: SSH is not supported. """ self.keys = ssh.Keys.FromFilename(args.ssh_key_file) self.env = ssh.Environment.Current() self.env.RequireSSH() def GetProject(self, project): """Returns the project object. Args: project: str, the project we are requesting or None for value from from properties Returns: The project object """ errors = [] objects = list(request_helper.MakeRequests( requests=[(self.compute.projects, 'Get', self.messages.ComputeProjectsGetRequest( project=project or properties.VALUES.core.project.Get( required=True), ))], http=self.http, batch_url=self.batch_url, errors=errors)) if errors: utils.RaiseToolException( errors, error_message='Could not fetch project resource:') return objects[0] def _SetProjectMetadata(self, new_metadata): """Sets the project metadata to the new metadata.""" compute = self.compute errors = [] list(request_helper.MakeRequests( requests=[ (compute.projects, 'SetCommonInstanceMetadata', self.messages.ComputeProjectsSetCommonInstanceMetadataRequest( metadata=new_metadata, project=properties.VALUES.core.project.Get( required=True), ))], http=self.http, batch_url=self.batch_url, errors=errors)) if errors: utils.RaiseException( errors, SetProjectMetadataError, error_message='Could not add SSH key to project metadata:') def SetProjectMetadata(self, new_metadata): """Sets the project metadata to the new metadata with progress tracker.""" with progress_tracker.ProgressTracker('Updating project ssh metadata'): self._SetProjectMetadata(new_metadata) def _SetInstanceMetadata(self, instance, new_metadata): """Sets the project metadata to the new metadata.""" compute = self.compute errors = [] # API wants just the zone name, not the full URL zone = instance.zone.split('/')[-1] list(request_helper.MakeRequests( requests=[ (compute.instances, 'SetMetadata', self.messages.ComputeInstancesSetMetadataRequest( instance=instance.name, metadata=new_metadata, project=properties.VALUES.core.project.Get( required=True), zone=zone ))], http=self.http, batch_url=self.batch_url, errors=errors)) if errors: utils.RaiseToolException( errors, error_message='Could not add SSH key to instance metadata:') def SetInstanceMetadata(self, instance, new_metadata): """Sets the instance metadata to the new metadata with progress tracker.""" with progress_tracker.ProgressTracker('Updating instance ssh metadata'): self._SetInstanceMetadata(instance, new_metadata) def EnsureSSHKeyIsInInstance(self, user, instance, iam_keys=False): """Ensures that the user's public SSH key is in the instance metadata. Args: user: str, the name of the user associated with the SSH key in the metadata instance: Instance, ensure the SSH key is in the metadata of this instance iam_keys: bool. If False, write to the original SSH metadata key (that overrides the project-global SSH metadata key). If true, write to the new SSH metadata key (that works in union with the project-global SSH key metadata). Returns: bool, True if the key was newly added, False if it was in the metadata already """ public_key = self.keys.GetPublicKey().ToEntry(include_comment=True) new_metadata = _AddSSHKeyToMetadataMessage(self.messages, user, public_key, instance.metadata, iam_keys=iam_keys) if new_metadata != instance.metadata: self.SetInstanceMetadata(instance, new_metadata) return True else: return False def EnsureSSHKeyIsInProject(self, user, project_name=None): """Ensures that the user's public SSH key is in the project metadata. Args: user: str, the name of the user associated with the SSH key in the metadata project_name: str, the project SSH key will be added to Returns: bool, True if the key was newly added, False if it was in the metadata already """ public_key = self.keys.GetPublicKey().ToEntry(include_comment=True) project = self.GetProject(project_name) existing_metadata = project.commonInstanceMetadata new_metadata = _AddSSHKeyToMetadataMessage( self.messages, user, public_key, existing_metadata) if new_metadata != existing_metadata: self.SetProjectMetadata(new_metadata) return True else: return False def _EnsureSSHKeyExistsForUser(self, fetcher, user): """Ensure the user's public SSH key is known by the Account Service.""" public_key = self.keys.GetPublicKey().ToEntry(include_comment=True) should_upload = True try: user_info = fetcher.LookupUser(user) except user_client.UserException: owner_email = gaia.GetAuthenticatedGaiaEmail(self.http) fetcher.CreateUser(user, owner_email) user_info = fetcher.LookupUser(user) for remote_public_key in user_info.publicKeys: if remote_public_key.key.rstrip() == public_key: expiration_time = remote_public_key.expirationTimestamp if expiration_time and time_util.IsExpired(expiration_time): # If a key is expired we remove and reupload fetcher.RemovePublicKey( user_info.name, remote_public_key.fingerprint) else: should_upload = False break if should_upload: fetcher.UploadPublicKey(user, public_key) return True @property def resource_type(self): return 'instances' class BaseSSHCLICommand(BaseSSHCommand): """Base class for subcommands that use ssh or scp.""" @staticmethod def Args(parser): """Args is called by calliope to gather arguments for this command. Please add arguments in alphabetical order except for no- or a clear- pair for that argument which can follow the argument itself. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """ BaseSSHCommand.Args(parser) parser.add_argument( '--dry-run', action='store_true', help=('If provided, prints the command that would be run to standard ' 'out instead of executing it.')) plain = parser.add_argument( '--plain', action='store_true', help='Suppresses the automatic addition of ssh/scp flags.') plain.detailed_help = """\ Suppresses the automatic addition of *ssh(1)*/*scp(1)* flags. This flag is useful if you want to take care of authentication yourself or use specific ssh/scp features. """ strict_host_key = parser.add_argument( '--strict-host-key-checking', choices=['yes', 'no', 'ask'], help='Override the default behavior for ssh/scp StrictHostKeyChecking') strict_host_key.detailed_help = """\ Override the default behavior of StrictHostKeyChecking. By default, StrictHostKeyChecking is set to 'no' the first time you connect to an instance and will be set to 'yes' for all subsequent connections. Use this flag to specify a value for the connection. """ def Run(self, args): super(BaseSSHCLICommand, self).Run(args) if not args.plain: self.keys.EnsureKeysExist(args.force_key_file_overwrite) def GetInstance(self, instance_ref): """Fetch an instance based on the given instance_ref.""" request = (self.compute.instances, 'Get', self.messages.ComputeInstancesGetRequest( instance=instance_ref.Name(), project=instance_ref.project, zone=instance_ref.zone)) errors = [] objects = list(request_helper.MakeRequests( requests=[request], http=self.http, batch_url=self.batch_url, errors=errors)) if errors: utils.RaiseToolException( errors, error_message='Could not fetch instance:') return objects[0] def HostKeyAlias(self, instance): return 'compute.{0}'.format(instance.id) def ActuallyRun(self, args, cmd_args, user, instance, project, strict_error_checking=True, use_account_service=False, wait_for_sshable=True, ignore_ssh_errors=False): """Runs the scp/ssh command specified in cmd_args. If the scp/ssh command exits non-zero, this command will exit with the same exit code. Args: args: argparse.Namespace, The calling command invocation args. cmd_args: [str], The argv for the command to execute. user: str, The user name. instance: Instance, the instance to connect to project: str, the project instance is in strict_error_checking: bool, whether to fail on a non-zero, non-255 exit code (alternative behavior is to return the exit code use_account_service: bool, when false upload ssh keys to project metadata. wait_for_sshable: bool, when false skip the sshability check. ignore_ssh_errors: bool, when true ignore all errors, including the 255 exit code. Raises: CommandError: If the scp/ssh command fails. Returns: int, the exit code of the command that was run """ cmd_args = ssh.LocalizeCommand(cmd_args, self.env) if args.dry_run: log.out.Print(' '.join(cmd_args)) return if args.plain: keys_newly_added = [] elif use_account_service: fetcher = user_client.UserResourceFetcher( self.clouduseraccounts, self.project, self.http, self.batch_url) keys_newly_added = self._EnsureSSHKeyExistsForUser(fetcher, user) else: # There are two kinds of metadata: project-wide metadata and per-instance # metadata. There are four SSH-key related metadata keys: # # * project['sshKeys']: shared project-wide # * instance['sshKeys']: legacy. Acts as an override to project['sshKeys'] # * instance['block-project-ssh-keys']: If true, instance['ssh-keys'] # overrides project['sshKeys']. Otherwise, keys from both metadata # pairs are valid. # * instance['ssh-keys']: Acts either in conjunction with or as an # override to project['sshKeys'], depending on # instance['block-project-ssh-keys'] # # SSH-like commands work by copying a relevant SSH key to # the appropriate metadata value. The VM grabs keys from the metadata as # follows (pseudo-Python): # # def GetAllSshKeys(project, instance): # if 'sshKeys' in instance.metadata: # return (instance.metadata['sshKeys'] + # instance.metadata['ssh-keys']) # elif instance.metadata['block-project-ssh-keys'] == 'true': # return instance.metadata['ssh-keys'] # else: # return (instance.metadata['ssh-keys'] + # project.metadata['sshKeys']) # if _GetSSHKeysFromMetadata(instance.metadata): # If we add a key to project-wide metadata but the per-instance # 'sshKeys' metadata exists, we won't be able to ssh in because the VM # won't check the project-wide metadata. To avoid this, if the instance # has per-instance SSH key metadata, we add the key there instead. keys_newly_added = self.EnsureSSHKeyIsInInstance(user, instance) elif _MetadataHasBlockProjectSshKeys(instance.metadata): # If the instance 'ssh-keys' metadata overrides the project-wide # 'sshKeys' metadata, we should put our key there. keys_newly_added = self.EnsureSSHKeyIsInInstance(user, instance, iam_keys=True) else: # Otherwise, try to add to the project-wide metadata. If we don't have # permissions to do that, add to the instance 'ssh-keys' metadata. try: keys_newly_added = self.EnsureSSHKeyIsInProject(user, project) except SetProjectMetadataError: log.info('Could not set project metadata:', exc_info=True) # If we can't write to the project metadata, it may be because of a # permissions problem (we could inspect this exception object further # to make sure, but because we only get a string back this would be # fragile). If that's the case, we want to try the writing to the # iam_keys metadata (we may have permissions to write to instance # metadata). We prefer this to the per-instance override of the # project metadata. log.info('Attempting to set instance metadata.') keys_newly_added = self.EnsureSSHKeyIsInInstance(user, instance, iam_keys=True) if keys_newly_added and wait_for_sshable: external_ip_address = GetExternalIPAddress(instance) host_key_alias = self.HostKeyAlias(instance) ssh.WaitUntilSSHable( user, external_ip_address, self.env, self.keys.key_file, host_key_alias, args.plain, args.strict_host_key_checking, _SSH_KEY_PROPAGATION_TIMEOUT_SEC) logging.debug('%s command: %s', cmd_args[0], ' '.join(cmd_args)) try: return ssh.RunExecutable(cmd_args, strict_error_checking=strict_error_checking, ignore_ssh_errors=ignore_ssh_errors) except ssh.CommandError as e: raise CommandError(e)
import numpy import chainer from chainer import backend from chainer.backends import cuda from chainer.backends import intel64 from chainer import configuration from chainer import function_node import chainer.functions from chainer.utils import argument from chainer.utils import conv from chainer.utils import type_check import chainerx if cuda.cudnn_enabled: _cudnn_version = cuda.cuda.cudnn.getVersion() def _pair(x): if hasattr(x, '__getitem__'): return x return x, x # Used by deconvolution_2d.py. # TODO(beam2d): Unify matmul implementations def _matmul(a, b): xp = backend.get_array_module(a) if not hasattr(xp, 'matmul'): # NumPy 1.9 does not support matmul. We use einsum instead. return xp.einsum('ijl,ilk->ijk', a, b) return xp.matmul(a, b) class Convolution2DFunction(function_node.FunctionNode): _use_ideep = False def __init__(self, stride=1, pad=0, cover_all=False, **kwargs): dilate, groups = argument.parse_kwargs( kwargs, ('dilate', 1), ('groups', 1), deterministic="deterministic argument is not supported anymore. " "Use chainer.using_config('cudnn_deterministic', value) context " "where value is either `True` or `False`.", requires_x_grad="requires_x_grad argument is not supported " "anymore. Just remove the argument. Note that whether to compute " "the gradient w.r.t. x is automatically decided during " "backpropagation.") self.sy, self.sx = _pair(stride) self.ph, self.pw = _pair(pad) self.cover_all = cover_all self.dy, self.dx = _pair(dilate) self.groups = groups def check_type_forward(self, in_types): n_in = in_types.size() type_check.expect(2 <= n_in, n_in <= 3) x_type = in_types[0] w_type = in_types[1] type_check.expect( x_type.dtype.kind == 'f', w_type.dtype.kind == 'f', x_type.ndim == 4, w_type.ndim == 4, x_type.shape[1] == w_type.shape[1] * self.groups, ) if type_check.eval(n_in) == 3: b_type = in_types[2] type_check.expect( b_type.dtype == x_type.dtype, b_type.ndim == 1, b_type.shape[0] == w_type.shape[0], ) def _get_out_size(self, inputs): x, W = inputs[:2] _, _, kh, kw = W.shape _, _, h, w = x.shape out_h = conv.get_conv_outsize( h, kh, self.sy, self.ph, cover_all=self.cover_all, d=self.dy) if out_h <= 0: raise RuntimeError('Height in the output should be positive.') out_w = conv.get_conv_outsize( w, kw, self.sx, self.pw, cover_all=self.cover_all, d=self.dx) if out_w <= 0: raise RuntimeError('Width in the output should be positive.') return out_h, out_w def forward_chainerx(self, inputs): # TODO(hvy): Support mixed precision. if any([arr.dtype != inputs[0].dtype for arr in inputs[1:]]): return chainer.Fallback # TODO(hvy): Support dilate > 1. if self.dy > 1 or self.dx > 1: return chainer.Fallback # TODO(hvy): Support groups > 1. if self.groups > 1: return chainer.Fallback if inputs[0].device.backend.name == 'cuda' and self.cover_all: return chainer.Fallback return chainerx.conv( *inputs, stride=(self.sy, self.sx), pad=(self.ph, self.pw), cover_all=self.cover_all), def forward_cpu(self, inputs): self.retain_inputs((0, 1)) # retain only x and W if len(inputs) == 2: (x, W), b = inputs, None else: x, W, b = inputs if (intel64.should_use_ideep('>=auto') and intel64.inputs_all_ready(inputs)): self._use_ideep = True if self.groups > 1: return self._forward_grouped_convolution(x, W, b) else: return self._forward_cpu_core(x, W, b) def _forward_cpu_core(self, x, W, b): if self._use_ideep: return self._forward_ideep(x, W, b) kh, kw = W.shape[2:] col = conv.im2col_cpu( x, kh, kw, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) y = numpy.tensordot( col, W, ((1, 2, 3), (1, 2, 3))).astype(x.dtype, copy=False) if b is not None: y += b y = numpy.rollaxis(y, 3, 1) return y, def _forward_ideep(self, x, W, b): out_c, input_c, kh, kw = W.shape n, c, h, w = x.shape out_h, out_w = self._get_out_size((x, W)) pd = (self.sy * (out_h - 1) + (kh + (kh - 1) * (self.dy - 1)) - h - self.ph) pr = (self.sx * (out_w - 1) + (kw + (kw - 1) * (self.dx - 1)) - w - self.pw) param = intel64.ideep.convolution2DParam( (n, out_c, out_h, out_w), self.dy, self.dx, self.sy, self.sx, self.ph, self.pw, pd, pr) y = intel64.ideep.convolution2D.Forward( intel64.ideep.array(x), intel64.ideep.array(W), intel64.ideep.array(b) if b is not None else None, param) return y, def forward_gpu(self, inputs): self.retain_inputs((0, 1)) # retain only x and W if len(inputs) == 2: (x, W), b = inputs, None else: x, W, b = inputs out_c, _, kh, kw = W.shape n, _, h, w = x.shape out_h, out_w = self._get_out_size(inputs) y = cuda.cupy.empty((n, out_c, out_h, out_w), dtype=x.dtype) use_cudnn = ( chainer.should_use_cudnn('>=auto') and not self.cover_all and x.dtype == W.dtype and ((self.dy == 1 and self.dx == 1) or _cudnn_version >= 6000) and (self.groups <= 1 or _cudnn_version >= 7000) ) if use_cudnn: # cuDNN implementation return self._forward_cudnn(x, W, b, y) elif self.groups > 1: return self._forward_grouped_convolution(x, W, b) else: return self._forward_gpu_core(x, W, b) def _forward_gpu_core(self, x, W, b): kh, kw = W.shape[2:] # Implementation using im2col col = conv.im2col_gpu( x, kh, kw, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) y = cuda.cupy.tensordot( col, W, ((1, 2, 3), (1, 2, 3))).astype(x.dtype, copy=False) # TODO(beam2d): Support unshared bias if b is not None: y += b y = cuda.cupy.rollaxis(y, 3, 1) return y, def _forward_grouped_convolution(self, x, W, b): # G: group count # N: batch size # kH, kW: kernel height, kernel width # iC, iH, iW: input channels, input height, input width # oC, oH, oW: output channels, output height, output width G = self.groups N, iC, iH, iW = x.shape oC, _, kH, kW = W.shape # _ == iCg iCg = iC // G oCg = oC // G # (N, iC, kW, kW, oH, oW) x = conv.im2col(x, kH, kW, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) oH, oW = x.shape[-2:] x = x.transpose(1, 2, 3, 0, 4, 5) # (iC, kH, kW, N, oH, oW) x = x.reshape(G, iCg * kH * kW, N * oH * oW) W = W.reshape(G, oCg, iCg * kH * kW) # (G, oCg, N*oH*oW) = (G, oCg, iCg*kH*kW) @ (G, iCg*kH*kW, N*oH*oW) y = _matmul(W, x).astype(x.dtype, copy=False) y = y.reshape(oC, N, oH, oW) y = y.transpose(1, 0, 2, 3) # (N, oC, oH, oW) if b is not None: y += b.reshape(1, b.size, 1, 1) return y, def _forward_cudnn(self, x, W, b, y): pad = (self.ph, self.pw) stride = (self.sy, self.sx) dilation = (self.dy, self.dx) auto_tune = configuration.config.autotune tensor_core = configuration.config.use_cudnn_tensor_core cuda.cudnn.convolution_forward( x, W, b, y, pad, stride, dilation, self.groups, auto_tune=auto_tune, tensor_core=tensor_core) return y, def backward(self, indexes, grad_outputs): x, W = self.get_retained_inputs() gy, = grad_outputs ret = [] if 0 in indexes: xh, xw = x.shape[2:] gx = chainer.functions.deconvolution_2d( gy, W, stride=(self.sy, self.sx), pad=(self.ph, self.pw), outsize=(xh, xw), dilate=(self.dy, self.dx), groups=self.groups) ret.append(gx) if 1 in indexes: gW, = Convolution2DGradW(self).apply((x, gy)) ret.append(gW) if 2 in indexes: gb = chainer.functions.sum(gy, axis=(0, 2, 3)) ret.append(gb) return ret class Convolution2DGradW(function_node.FunctionNode): def __init__(self, conv2d): W_node = conv2d.inputs[1] self.kh, self.kw = W_node.shape[2:] self.sy = conv2d.sy self.sx = conv2d.sx self.ph = conv2d.ph self.pw = conv2d.pw self.dy = conv2d.dy self.dx = conv2d.dx self.cover_all = conv2d.cover_all self.W_dtype = W_node.dtype self.groups = conv2d.groups self._use_ideep = conv2d._use_ideep def forward_cpu(self, inputs): self.retain_inputs((0, 1)) x, gy = inputs if self.groups > 1: return self._forward_grouped_convolution(x, gy) else: return self._forward_cpu_core(x, gy) def _forward_cpu_core(self, x, gy): if self._use_ideep: return self._forward_ideep(x, gy) # NumPy raises an error when the array is not contiguous. # See: https://github.com/chainer/chainer/issues/2744 # TODO(niboshi): Remove this code when NumPy is fixed. if (not (gy.flags.c_contiguous or gy.flags.f_contiguous) and 1 in gy.shape): gy = numpy.ascontiguousarray(gy) col = conv.im2col_cpu( x, self.kh, self.kw, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) gW = numpy.tensordot(gy, col, ((0, 2, 3), (0, 4, 5)) ).astype(self.W_dtype, copy=False) return gW, def _forward_ideep(self, x, gy): n, input_c, h, w = x.shape n, out_c, out_h, out_w = gy.shape pd = (self.sy * (out_h - 1) + (self.kh + (self.kh - 1) * (self.dy - 1)) - h - self.ph) pr = (self.sx * (out_w - 1) + (self.kw + (self.kw - 1) * (self.dx - 1)) - w - self.pw) param = intel64.ideep.convolution2DParam( (out_c, input_c, self.kh, self.kw), self.dy, self.dx, self.sy, self.sx, self.ph, self.pw, pd, pr) gW = intel64.ideep.convolution2D.BackwardWeights( intel64.ideep.array(x), intel64.ideep.array(gy), param) return gW, def forward_gpu(self, inputs): self.retain_inputs((0, 1)) x, gy = inputs use_cudnn = ( chainer.should_use_cudnn('>=auto') and not self.cover_all and x.dtype == self.W_dtype and ((self.dy == 1 and self.dx == 1) or (_cudnn_version >= 6000 and not configuration.config.cudnn_deterministic)) and (self.groups <= 1 or _cudnn_version >= 7000) ) if use_cudnn: # cuDNN implementation return self._forward_cudnn(x, gy) elif self.groups > 1: return self._forward_grouped_convolution(x, gy) else: return self._forward_gpu_core(x, gy) def _forward_gpu_core(self, x, gy): col = conv.im2col_gpu( x, self.kh, self.kw, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) gW = cuda.cupy.tensordot(gy, col, ((0, 2, 3), (0, 4, 5)) ).astype(self.W_dtype, copy=False) return gW, def _forward_grouped_convolution(self, x, gy): # G: group count # N: batch size # kH, kW: kernel height, kernel width # iC, iH, iW: input channels, input height, input width # oC, oH, oW: output channels, output height, output width G = self.groups N, iC, iH, iW = x.shape _, oC, oH, oW = gy.shape # _ == N kH = self.kh kW = self.kw iCg = iC // G oCg = oC // G # (N, iC, kH, kW, oH, oW) x = conv.im2col(x, kH, kW, self.sy, self.sx, self.ph, self.pw, cover_all=self.cover_all, dy=self.dy, dx=self.dx) x = x.transpose(1, 2, 3, 0, 4, 5) # (iC, kH, kW, N, oH, oW) x = x.reshape(G, iCg * kH * kW, N * oH * oW) x = x.transpose(0, 2, 1) # (G, N*oH*oW, iCg*kH*kW) gy = gy.transpose(1, 0, 2, 3) # (oC, N, oH, oW) gy = gy.reshape(G, oCg, N * oH * oW) # (G, oCg, iCg*kH*kW) = (G, oCg, N*oH*oW) @ (G, N*oH*oW, iCg*kH*kW) gW = _matmul(gy, x).astype(self.W_dtype, copy=False) gW = gW.reshape(oC, iCg, kH, kW) return gW, def _forward_cudnn(self, x, gy): _, out_c, out_h, out_w = gy.shape n, c, h, w = x.shape iC = c iCg = int(iC / self.groups) gW = cuda.cupy.empty((out_c, iCg, self.kh, self.kw), dtype=self.W_dtype) pad = (self.ph, self.pw) stride = (self.sy, self.sx) dilation = (self.dy, self.dx) deterministic = configuration.config.cudnn_deterministic auto_tune = configuration.config.autotune tensor_core = configuration.config.use_cudnn_tensor_core cuda.cudnn.convolution_backward_filter( x, gy, gW, pad, stride, dilation, self.groups, deterministic=deterministic, auto_tune=auto_tune, tensor_core=tensor_core) return gW, def backward(self, indexes, grad_outputs): x, gy = self.get_retained_inputs() ggW, = grad_outputs ret = [] if 0 in indexes: xh, xw = x.shape[2:] gx = chainer.functions.deconvolution_2d( gy, ggW, stride=(self.sy, self.sx), pad=(self.ph, self.pw), outsize=(xh, xw), dilate=(self.dy, self.dx), groups=self.groups) ret.append(gx) if 1 in indexes: ggy = convolution_2d( x, ggW, stride=(self.sy, self.sx), pad=(self.ph, self.pw), cover_all=self.cover_all, dilate=(self.dy, self.dx), groups=self.groups) ret.append(ggy) return ret def convolution_2d(x, W, b=None, stride=1, pad=0, cover_all=False, **kwargs): """convolution_2d(x, W, b=None, stride=1, pad=0, cover_all=False, *, dilate=1, groups=1) Two-dimensional convolution function. This is an implementation of two-dimensional convolution in ConvNets. It takes three variables: the input image ``x``, the filter weight ``W``, and the bias vector ``b``. Notation: here is a notation for dimensionalities. - :math:`n` is the batch size. - :math:`c_I` and :math:`c_O` are the number of the input and output channels, respectively. - :math:`h_I` and :math:`w_I` are the height and width of the input image, respectively. - :math:`h_K` and :math:`w_K` are the height and width of the filters, respectively. - :math:`h_P` and :math:`w_P` are the height and width of the spatial padding size, respectively. Then the ``Convolution2D`` function computes correlations between filters and patches of size :math:`(h_K, w_K)` in ``x``. Note that correlation here is equivalent to the inner product between expanded vectors. Patches are extracted at positions shifted by multiples of ``stride`` from the first position ``(-h_P, -w_P)`` for each spatial axis. The right-most (or bottom-most) patches do not run over the padded spatial size. Let :math:`(s_Y, s_X)` be the stride of filter application. Then, the output size :math:`(h_O, w_O)` is determined by the following equations: .. math:: h_O &= (h_I + 2h_P - h_K) / s_Y + 1,\\\\ w_O &= (w_I + 2w_P - w_K) / s_X + 1. If ``cover_all`` option is ``True``, the filter will cover the all spatial locations. So, if the last stride of filter does not cover the end of spatial locations, an addtional stride will be applied to the end part of spatial locations. In this case, the output size :math:`(h_O, w_O)` is determined by the following equations: .. math:: h_O &= (h_I + 2h_P - h_K + s_Y - 1) / s_Y + 1,\\\\ w_O &= (w_I + 2w_P - w_K + s_X - 1) / s_X + 1. If the bias vector is given, then it is added to all spatial locations of the output of convolution. The output of this function can be non-deterministic when it uses cuDNN. If ``chainer.configuration.config.cudnn_deterministic`` is ``True`` and cuDNN version is >= v3, it forces cuDNN to use a deterministic algorithm. Convolution links can use a feature of cuDNN called autotuning, which selects the most efficient CNN algorithm for images of fixed-size, can provide a significant performance boost for fixed neural nets. To enable, set `chainer.using_config('autotune', True)` When the dilation factor is greater than one, cuDNN is not used unless the version is 6.0 or higher. Args: x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable of shape :math:`(n, c_I, h_I, w_I)`. W (:class:`~chainer.Variable` or :ref:`ndarray`): Weight variable of shape :math:`(c_O, c_I, h_K, w_K)`. b (None or :class:`~chainer.Variable` or :ref:`ndarray`): Bias variable of length :math:`c_O` (optional). stride (:class:`int` or pair of :class:`int` s): Stride of filter applications. ``stride=s`` and ``stride=(s, s)`` are equivalent. pad (:class:`int` or pair of :class:`int` s): Spatial padding width for input arrays. ``pad=p`` and ``pad=(p, p)`` are equivalent. cover_all (:class:`bool`): If ``True``, all spatial locations are convoluted into some output pixels. dilate (:class:`int` or pair of :class:`int` s): Dilation factor of filter applications. ``dilate=d`` and ``dilate=(d, d)`` are equivalent. groups (:class:`int`): Number of groups of channels. If the number is greater than 1, input tensor :math:`W` is divided into some blocks by this value. For each tensor blocks, convolution operation will be executed independently. Input channel size :math:`c_I` and output channel size :math:`c_O` must be exactly divisible by this value. Returns: ~chainer.Variable: Output variable of shape :math:`(n, c_O, h_O, w_O)`. .. seealso:: :class:`~chainer.links.Convolution2D` .. admonition:: Example >>> n = 10 >>> c_i, c_o = 3, 1 >>> h_i, w_i = 30, 40 >>> h_k, w_k = 10, 10 >>> h_p, w_p = 5, 5 >>> x = np.random.uniform(0, 1, (n, c_i, h_i, w_i)).astype(np.float32) >>> x.shape (10, 3, 30, 40) >>> W = np.random.uniform(0, 1, (c_o, c_i, h_k, w_k)).\ astype(np.float32) >>> W.shape (1, 3, 10, 10) >>> b = np.random.uniform(0, 1, (c_o,)).astype(np.float32) >>> b.shape (1,) >>> s_y, s_x = 5, 7 >>> y = F.convolution_2d(x, W, b, stride=(s_y, s_x), pad=(h_p, w_p)) >>> y.shape (10, 1, 7, 6) >>> h_o = int((h_i + 2 * h_p - h_k) / s_y + 1) >>> w_o = int((w_i + 2 * w_p - w_k) / s_x + 1) >>> y.shape == (n, c_o, h_o, w_o) True >>> y = F.convolution_2d(x, W, b, stride=(s_y, s_x), pad=(h_p, w_p), \ cover_all=True) >>> y.shape == (n, c_o, h_o, w_o + 1) True """ # NOQA dilate, groups = argument.parse_kwargs( kwargs, ('dilate', 1), ('groups', 1), deterministic="deterministic argument is not supported anymore. " "Use chainer.using_config('cudnn_deterministic', value) " "context where value is either `True` or `False`.") fnode = Convolution2DFunction(stride, pad, cover_all, dilate=dilate, groups=groups) if b is None: args = x, W else: args = x, W, b y, = fnode.apply(args) return y
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'AttendeeComment.check_in_announce' db.add_column(u'events_attendeecomment', 'check_in_announce', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'AttendeeComment.check_in_announce' db.delete_column(u'events_attendeecomment', 'check_in_announce') 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'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'countries.country': { 'Meta': {'ordering': "('name',)", 'object_name': 'Country', 'db_table': "'country'"}, 'iso': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}), 'iso3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'numcode': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'printable_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, 'events.attend': { 'Meta': {'unique_together': "(('event', 'user'),)", 'object_name': 'Attend'}, 'change_timestamp': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'changed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_new': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'paid': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '6', 'decimal_places': '2'}), 'price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '6', 'decimal_places': '2'}), 'registration_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'default': "'waiting'", 'max_length': '32'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['user.SUser']"}) }, 'events.attendeecomment': { 'Meta': {'object_name': 'AttendeeComment'}, 'attendee': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comment_set'", 'to': "orm['events.Attend']"}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'check_in_announce': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'comment': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'events.attendstatechange': { 'Meta': {'object_name': 'AttendStateChange'}, 'attendee': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'state_history'", 'to': "orm['events.Attend']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'events.autoselectchoiceoption': { 'Meta': {'ordering': "('order',)", 'object_name': 'AutoSelectChoiceOption', '_ormbases': ['events.Option']}, 'auto_select_suboption': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['events.SubOption']", 'null': 'True', 'blank': 'True'}), u'option_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['events.Option']", 'unique': 'True', 'primary_key': 'True'}) }, 'events.discountcode': { 'Meta': {'object_name': 'DiscountCode'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '64', 'primary_key': 'True'}), 'discount_option': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.DiscountOption']"}), 'selection': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Selection']", 'null': 'True', 'blank': 'True'}) }, 'events.discountoption': { 'Meta': {'ordering': "('order',)", 'object_name': 'DiscountOption', '_ormbases': ['events.Option']}, 'discount_suboption': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['events.SubOption']", 'null': 'True', 'blank': 'True'}), u'option_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['events.Option']", 'unique': 'True', 'primary_key': 'True'}) }, 'events.event': { 'Meta': {'object_name': 'Event'}, 'custom_change_message': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'custom_signup_message': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'custom_status_page': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'enddate': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Group']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'location_link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'maximum_attendees': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'move_to_accepted_policy': ('django.db.models.fields.CharField', [], {'default': "'always'", 'max_length': '32'}), 'notify_on_payment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'notify_event_on_payment_registration'", 'null': 'True', 'to': u"orm['mailcenter.EmailSpecification']"}), 'notify_on_registration': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'notify_event_on_registration'", 'null': 'True', 'to': u"orm['mailcenter.EmailSpecification']"}), 'notify_on_registration_update': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'notify_event_on_registration_update'", 'null': 'True', 'to': u"orm['mailcenter.EmailSpecification']"}), 'registration_open': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'show_custom_change_message': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'show_custom_signup_message': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'show_custom_status_page': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'startdate': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'tagline': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'events.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'events.option': { 'Meta': {'ordering': "('order',)", 'object_name': 'Option'}, 'depends_on': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['events.Option']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.OptionGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_scope_edit_manage_accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_edit_manage_attended': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_edit_manage_waiting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_edit_registration': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_view_manage': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_view_public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_view_registration': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_scope_view_system_invoice': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'in_scope_view_user_invoice': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'notify_on_selection': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'notify_option_on_selection'", 'null': 'True', 'to': u"orm['mailcenter.EmailSpecification']"}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '6', 'decimal_places': '2'}), 'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'boolean'", 'max_length': '32'}) }, 'events.optiongroup': { 'Meta': {'ordering': "('-is_special', 'order')", 'object_name': 'OptionGroup'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_special': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'maximum_selected': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'minimum_selected': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'package_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '6', 'decimal_places': '2'}) }, 'events.payment': { 'Meta': {'object_name': 'Payment'}, 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '2'}), 'attendee': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Attend']", 'null': 'True', 'on_delete': 'models.SET_NULL'}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'note': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), 'signee': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'signee_payment_set'", 'null': 'True', 'to': u"orm['user.SUser']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['user.SUser']"}) }, 'events.selection': { 'Meta': {'unique_together': "(('attendee', 'option'),)", 'object_name': 'Selection'}, 'attendee': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Attend']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'option': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Option']"}), 'suboption': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.SubOption']", 'null': 'True', 'blank': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) }, 'events.suboption': { 'Meta': {'object_name': 'SubOption'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'option': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'suboption_set'", 'to': "orm['events.Option']"}), 'price': ('django.db.models.fields.DecimalField', [], {'default': 'None', 'null': 'True', 'max_digits': '6', 'decimal_places': '2', 'blank': 'True'}) }, u'mailcenter.emailspecification': { 'Meta': {'object_name': 'EmailSpecification'}, 'body': ('django.db.models.fields.TextField', [], {}), 'body_format': ('django.db.models.fields.CharField', [], {'default': "'markdown'", 'max_length': '32'}), 'date_created': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'template_context': ('django.db.models.fields.CharField', [], {'default': "'user'", 'max_length': '32'}) }, u'user.suser': { 'Meta': {'object_name': 'SUser'}, 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'country': ('django.db.models.fields.related.ForeignKey', [], {'default': "'DK'", 'to': u"orm['countries.Country']", 'null': 'True', 'blank': 'True'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'dateofbirth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), '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', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), 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'}), 'jabber': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'msn': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'phonenumber': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'postalcode': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'send_me_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'sex': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '6', 'blank': 'True'}), 'skype': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'street': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) } } complete_apps = ['events']
import os, sys import socket import logging import marshal import cPickle import threading, Queue import time import random import urllib import warnings import weakref import multiprocessing import platform import zmq import pymesos as mesos from mesos.interface import mesos_pb2 from dpark.util import compress, decompress, spawn, getuser, mkdir_p from dpark.dependency import NarrowDependency, ShuffleDependency from dpark.accumulator import Accumulator from dpark.task import ResultTask, ShuffleMapTask from dpark.job import SimpleJob from dpark.env import env from dpark.mutable_dict import MutableDict import dpark.conf as conf logger = logging.getLogger(__name__) MAX_FAILED = 3 EXECUTOR_MEMORY = 64 # cache POLL_TIMEOUT = 0.1 RESUBMIT_TIMEOUT = 60 MAX_IDLE_TIME = 60 * 30 class TaskEndReason: pass class Success(TaskEndReason): pass class FetchFailed(TaskEndReason): def __init__(self, serverUri, shuffleId, mapId, reduceId): self.serverUri = serverUri self.shuffleId = shuffleId self.mapId = mapId self.reduceId = reduceId def __str__(self): return '<FetchFailed(%s, %d, %d, %d)>' % (self.serverUri, self.shuffleId, self.mapId, self.reduceId) class OtherFailure(TaskEndReason): def __init__(self, message): self.message = message def __str__(self): return '<OtherFailure %s>' % self.message class Stage: def __init__(self, rdd, shuffleDep, parents): self.id = self.newId() self.rdd = rdd self.shuffleDep = shuffleDep self.parents = parents self.numPartitions = len(rdd) self.outputLocs = [[] for i in range(self.numPartitions)] def __str__(self): return '<Stage(%d) for %s>' % (self.id, self.rdd) def __getstate__(self): raise Exception("should not pickle stage") @property def isAvailable(self): if not self.parents and self.shuffleDep == None: return True return all(self.outputLocs) def addOutputLoc(self, partition, host): self.outputLocs[partition].append(host) # def removeOutput(self, partition, host): # prev = self.outputLocs[partition] # self.outputLocs[partition] = [h for h in prev if h != host] def removeHost(self, host): becameUnavailable = False for ls in self.outputLocs: if host in ls: ls.remove(host) becameUnavailable = True if becameUnavailable: logger.info("%s is now unavailable on host %s", self, host) nextId = 0 @classmethod def newId(cls): cls.nextId += 1 return cls.nextId class Scheduler: def start(self): pass def runJob(self, rdd, func, partitions, allowLocal): pass def clear(self): pass def stop(self): pass def defaultParallelism(self): return 2 class CompletionEvent: def __init__(self, task, reason, result, accumUpdates): self.task = task self.reason = reason self.result = result self.accumUpdates = accumUpdates class DAGScheduler(Scheduler): def __init__(self): self.completionEvents = Queue.Queue() self.idToStage = weakref.WeakValueDictionary() self.shuffleToMapStage = {} self.cacheLocs = {} self._shutdown = False def check(self): pass def clear(self): self.idToStage.clear() self.shuffleToMapStage.clear() self.cacheLocs.clear() self.cacheTracker.clear() def shutdown(self): self._shutdown = True @property def cacheTracker(self): return env.cacheTracker @property def mapOutputTracker(self): return env.mapOutputTracker def submitTasks(self, tasks): raise NotImplementedError def taskEnded(self, task, reason, result, accumUpdates): self.completionEvents.put(CompletionEvent(task, reason, result, accumUpdates)) def getCacheLocs(self, rdd): return self.cacheLocs.get(rdd.id, [[] for i in range(len(rdd))]) def updateCacheLocs(self): self.cacheLocs = self.cacheTracker.getLocationsSnapshot() def newStage(self, rdd, shuffleDep): stage = Stage(rdd, shuffleDep, self.getParentStages(rdd)) self.idToStage[stage.id] = stage logger.debug("new stage: %s", stage) return stage def getParentStages(self, rdd): parents = set() visited = set() def visit(r): if r.id in visited: return visited.add(r.id) if r.shouldCache: self.cacheTracker.registerRDD(r.id, len(r)) for dep in r.dependencies: if isinstance(dep, ShuffleDependency): parents.add(self.getShuffleMapStage(dep)) else: visit(dep.rdd) visit(rdd) return list(parents) def getShuffleMapStage(self, dep): stage = self.shuffleToMapStage.get(dep.shuffleId, None) if stage is None: stage = self.newStage(dep.rdd, dep) self.shuffleToMapStage[dep.shuffleId] = stage return stage def getMissingParentStages(self, stage): missing = set() visited = set() def visit(r): if r.id in visited: return visited.add(r.id) if r.shouldCache and all(self.getCacheLocs(r)): return for dep in r.dependencies: if isinstance(dep, ShuffleDependency): stage = self.getShuffleMapStage(dep) if not stage.isAvailable: missing.add(stage) elif isinstance(dep, NarrowDependency): visit(dep.rdd) visit(stage.rdd) return list(missing) def runJob(self, finalRdd, func, partitions, allowLocal): outputParts = list(partitions) numOutputParts = len(partitions) finalStage = self.newStage(finalRdd, None) results = [None]*numOutputParts finished = [None]*numOutputParts lastFinished = 0 numFinished = 0 waiting = set() running = set() failed = set() pendingTasks = {} lastFetchFailureTime = 0 self.updateCacheLocs() logger.debug("Final stage: %s, %d", finalStage, numOutputParts) logger.debug("Parents of final stage: %s", finalStage.parents) logger.debug("Missing parents: %s", self.getMissingParentStages(finalStage)) if allowLocal and (not finalStage.parents or not self.getMissingParentStages(finalStage)) and numOutputParts == 1: split = finalRdd.splits[outputParts[0]] yield func(finalRdd.iterator(split)) return def submitStage(stage): logger.debug("submit stage %s", stage) if stage not in waiting and stage not in running: missing = self.getMissingParentStages(stage) if not missing: submitMissingTasks(stage) running.add(stage) else: for parent in missing: submitStage(parent) waiting.add(stage) def submitMissingTasks(stage): myPending = pendingTasks.setdefault(stage, set()) tasks = [] have_prefer = True if stage == finalStage: for i in range(numOutputParts): if not finished[i]: part = outputParts[i] if have_prefer: locs = self.getPreferredLocs(finalRdd, part) if not locs: have_prefer = False else: locs = [] tasks.append(ResultTask(finalStage.id, finalRdd, func, part, locs, i)) else: for p in range(stage.numPartitions): if not stage.outputLocs[p]: if have_prefer: locs = self.getPreferredLocs(stage.rdd, p) if not locs: have_prefer = False else: locs = [] tasks.append(ShuffleMapTask(stage.id, stage.rdd, stage.shuffleDep, p, locs)) logger.debug("add to pending %s tasks", len(tasks)) myPending |= set(t.id for t in tasks) self.submitTasks(tasks) submitStage(finalStage) while numFinished != numOutputParts: try: evt = self.completionEvents.get(False) except Queue.Empty: self.check() if self._shutdown: sys.exit(1) if failed and time.time() > lastFetchFailureTime + RESUBMIT_TIMEOUT: self.updateCacheLocs() for stage in failed: logger.info("Resubmitting failed stages: %s", stage) submitStage(stage) failed.clear() else: time.sleep(0.1) continue task, reason = evt.task, evt.reason stage = self.idToStage[task.stageId] if stage not in pendingTasks: # stage from other job continue logger.debug("remove from pending %s from %s", task, stage) pendingTasks[stage].remove(task.id) if isinstance(reason, Success): Accumulator.merge(evt.accumUpdates) if isinstance(task, ResultTask): finished[task.outputId] = True numFinished += 1 results[task.outputId] = evt.result while lastFinished < numOutputParts and finished[lastFinished]: yield results[lastFinished] results[lastFinished] = None lastFinished += 1 elif isinstance(task, ShuffleMapTask): stage = self.idToStage[task.stageId] stage.addOutputLoc(task.partition, evt.result) if not pendingTasks[stage] and all(stage.outputLocs): logger.debug("%s finished; looking for newly runnable stages", stage) MutableDict.merge() running.remove(stage) if stage.shuffleDep != None: self.mapOutputTracker.registerMapOutputs( stage.shuffleDep.shuffleId, [l[-1] for l in stage.outputLocs]) self.updateCacheLocs() newlyRunnable = set(stage for stage in waiting if not self.getMissingParentStages(stage)) waiting -= newlyRunnable running |= newlyRunnable logger.debug("newly runnable: %s, %s", waiting, newlyRunnable) for stage in newlyRunnable: submitMissingTasks(stage) elif isinstance(reason, FetchFailed): if stage in running: waiting.add(stage) mapStage = self.shuffleToMapStage[reason.shuffleId] mapStage.removeHost(reason.serverUri) failed.add(mapStage) lastFetchFailureTime = time.time() else: logger.error("task %s failed: %s %s %s", task, reason, type(reason), reason.message) raise Exception(reason.message) MutableDict.merge() assert not any(results) return def getPreferredLocs(self, rdd, partition): return rdd.preferredLocations(rdd.splits[partition]) def run_task(task, aid): logger.debug("Running task %r", task) try: Accumulator.clear() result = task.run(aid) accumUpdates = Accumulator.values() MutableDict.flush() return (task.id, Success(), result, accumUpdates) except Exception, e: logger.error("error in task %s", task) import traceback traceback.print_exc() return (task.id, OtherFailure("exception:" + str(e)), None, None) class LocalScheduler(DAGScheduler): attemptId = 0 def nextAttempId(self): self.attemptId += 1 return self.attemptId def submitTasks(self, tasks): logger.debug("submit tasks %s in LocalScheduler", tasks) for task in tasks: # task = cPickle.loads(cPickle.dumps(task, -1)) _, reason, result, update = run_task(task, self.nextAttempId()) self.taskEnded(task, reason, result, update) def run_task_in_process(task, tid, environ): from dpark.env import env workdir = environ.get('WORKDIR') environ['SERVER_URI'] = 'file://%s' % workdir[0] env.start(False, environ) logger.debug("run task in process %s %s", task, tid) try: return run_task(task, tid) except KeyboardInterrupt: sys.exit(0) class MultiProcessScheduler(LocalScheduler): def __init__(self, threads): LocalScheduler.__init__(self) self.threads = threads self.tasks = {} self.pool = multiprocessing.Pool(self.threads or 2) def submitTasks(self, tasks): if not tasks: return logger.info("Got a job with %d tasks: %s", len(tasks), tasks[0].rdd) total, self.finished, start = len(tasks), 0, time.time() def callback(args): logger.debug("got answer: %s", args) tid, reason, result, update = args task = self.tasks.pop(tid) self.finished += 1 logger.info("Task %s finished (%d/%d) \x1b[1A", tid, self.finished, total) if self.finished == total: logger.info("Job finished in %.1f seconds" + " "*20, time.time() - start) self.taskEnded(task, reason, result, update) for task in tasks: logger.debug("put task async: %s", task) self.tasks[task.id] = task self.pool.apply_async(run_task_in_process, [task, self.nextAttempId(), env.environ], callback=callback) def stop(self): self.pool.terminate() self.pool.join() logger.debug("process pool stopped") def profile(f): def func(*args, **kwargs): path = '/tmp/worker-%s.prof' % os.getpid() import cProfile import pstats func = f cProfile.runctx('func(*args, **kwargs)', globals(), locals(), path) stats = pstats.Stats(path) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) stats.sort_stats('cumulative') stats.print_stats(20) return func def safe(f): def _(self, *a, **kw): with self.lock: r = f(self, *a, **kw) return r return _ def int2ip(n): return "%d.%d.%d.%d" % (n & 0xff, (n>>8)&0xff, (n>>16)&0xff, n>>24) class MesosScheduler(DAGScheduler): def __init__(self, master, options): DAGScheduler.__init__(self) self.master = master self.use_self_as_exec = options.self self.cpus = options.cpus self.mem = options.mem self.task_per_node = options.parallel or multiprocessing.cpu_count() self.group = options.group self.logLevel = options.logLevel self.options = options self.started = False self.last_finish_time = 0 self.isRegistered = False self.executor = None self.driver = None self.out_logger = None self.err_logger = None self.lock = threading.RLock() self.init_job() def init_job(self): self.activeJobs = {} self.activeJobsQueue = [] self.taskIdToJobId = {} self.taskIdToSlaveId = {} self.jobTasks = {} self.slaveTasks = {} self.slaveFailed = {} def clear(self): DAGScheduler.clear(self) self.init_job() def start(self): if not self.out_logger: self.out_logger = self.start_logger(sys.stdout) if not self.err_logger: self.err_logger = self.start_logger(sys.stderr) def start_driver(self): name = '[dpark] ' + os.path.abspath(sys.argv[0]) + ' ' + ' '.join(sys.argv[1:]) if len(name) > 256: name = name[:256] + '...' framework = mesos_pb2.FrameworkInfo() framework.user = getuser() if framework.user == 'root': raise Exception("dpark is not allowed to run as 'root'") framework.name = name framework.hostname = socket.gethostname() self.driver = mesos.MesosSchedulerDriver(self, framework, self.master) self.driver.start() logger.debug("Mesos Scheudler driver started") self.started = True self.last_finish_time = time.time() def check(): while self.started: now = time.time() if not self.activeJobs and now - self.last_finish_time > MAX_IDLE_TIME: logger.info("stop mesos scheduler after %d seconds idle", now - self.last_finish_time) self.stop() break time.sleep(1) spawn(check) def start_logger(self, output): sock = env.ctx.socket(zmq.PULL) port = sock.bind_to_random_port("tcp://0.0.0.0") def collect_log(): while not self._shutdown: if sock.poll(1000, zmq.POLLIN): line = sock.recv() output.write(line) spawn(collect_log) host = socket.gethostname() addr = "tcp://%s:%d" % (host, port) logger.debug("log collecter start at %s", addr) return addr @safe def registered(self, driver, frameworkId, masterInfo): self.isRegistered = True logger.debug("connect to master %s:%s(%s), registered as %s", int2ip(masterInfo.ip), masterInfo.port, masterInfo.id, frameworkId.value) self.executor = self.getExecutorInfo(str(frameworkId.value)) @safe def reregistered(self, driver, masterInfo): logger.warning("re-connect to mesos master %s:%s(%s)", int2ip(masterInfo.ip), masterInfo.port, masterInfo.id) @safe def disconnected(self, driver): logger.debug("framework is disconnected") @safe def getExecutorInfo(self, framework_id): info = mesos_pb2.ExecutorInfo() if hasattr(info, 'framework_id'): info.framework_id.value = framework_id if self.use_self_as_exec: info.command.value = os.path.abspath(sys.argv[0]) info.executor_id.value = sys.argv[0] else: info.command.value = '%s %s' % ( sys.executable, os.path.abspath(os.path.join(os.path.dirname(__file__), 'executor.py')) ) info.executor_id.value = "default" v = info.command.environment.variables.add() v.name = 'UID' v.value = str(os.getuid()) v = info.command.environment.variables.add() v.name = 'GID' v.value = str(os.getgid()) if self.options.image and hasattr(info, 'container'): info.container.type = mesos_pb2.ContainerInfo.DOCKER info.container.docker.image = self.options.image for path in ['/etc/passwd', '/etc/group']: v = info.container.volumes.add() v.host_path = v.container_path = path v.mode = mesos_pb2.Volume.RO for path in conf.MOOSEFS_MOUNT_POINTS: v = info.container.volumes.add() v.host_path = v.container_path = path v.mode = mesos_pb2.Volume.RW for path in conf.DPARK_WORK_DIR.split(','): v = info.container.volumes.add() v.host_path = v.container_path = path v.mode = mesos_pb2.Volume.RW if self.options.volumes: for volume in self.options.volumes.split(','): fields = volume.split(':') if len(fields) == 3: host_path, container_path, mode = fields mode = mesos_pb2.Volume.RO if mode.lower() == 'ro' else mesos_pb2.Volume.RW elif len(fields) == 2: host_path, container_path = fields mode = mesos_pb2.Volume.RW elif len(fields) == 1: container_path, = fields host_path = '' mode = mesos_pb2.Volume.RW else: raise Exception("cannot parse volume %s", volume) mkdir_p(host_path) v = info.container.volumes.add() v.container_path = container_path v.mode = mode if host_path: v.host_path = host_path mem = info.resources.add() mem.name = 'mem' mem.type = 0 #mesos_pb2.Value.SCALAR mem.scalar.value = EXECUTOR_MEMORY Script = os.path.realpath(sys.argv[0]) if hasattr(info, 'name'): info.name = Script info.data = marshal.dumps((Script, os.getcwd(), sys.path, dict(os.environ), self.task_per_node, self.out_logger, self.err_logger, self.logLevel, env.environ)) return info @safe def submitTasks(self, tasks): if not tasks: return job = SimpleJob(self, tasks, self.cpus, tasks[0].rdd.mem or self.mem) self.activeJobs[job.id] = job self.activeJobsQueue.append(job) self.jobTasks[job.id] = set() logger.info("Got job %d with %d tasks: %s", job.id, len(tasks), tasks[0].rdd) need_revive = self.started if not self.started: self.start_driver() while not self.isRegistered: self.lock.release() time.sleep(0.01) self.lock.acquire() if need_revive: self.requestMoreResources() def requestMoreResources(self): logger.debug("reviveOffers") self.driver.reviveOffers() @safe def resourceOffers(self, driver, offers): rf = mesos_pb2.Filters() if not self.activeJobs: rf.refuse_seconds = 60 * 5 for o in offers: driver.launchTasks(o.id, [], rf) return start = time.time() random.shuffle(offers) cpus = [self.getResource(o.resources, 'cpus') for o in offers] mems = [self.getResource(o.resources, 'mem') - (o.slave_id.value not in self.slaveTasks and EXECUTOR_MEMORY or 0) for o in offers] logger.debug("get %d offers (%s cpus, %s mem), %d jobs", len(offers), sum(cpus), sum(mems), len(self.activeJobs)) tasks = {} for job in self.activeJobsQueue: while True: launchedTask = False for i,o in enumerate(offers): sid = o.slave_id.value if self.group and (self.getAttribute(o.attributes, 'group') or 'none') not in self.group: continue if self.slaveFailed.get(sid, 0) >= MAX_FAILED: continue if self.slaveTasks.get(sid, 0) >= self.task_per_node: continue if mems[i] < self.mem or cpus[i]+1e-4 < self.cpus: continue t = job.slaveOffer(str(o.hostname), cpus[i], mems[i]) if not t: continue task = self.createTask(o, job, t, cpus[i]) tasks.setdefault(o.id.value, []).append(task) logger.debug("dispatch %s into %s", t, o.hostname) tid = task.task_id.value self.jobTasks[job.id].add(tid) self.taskIdToJobId[tid] = job.id self.taskIdToSlaveId[tid] = sid self.slaveTasks[sid] = self.slaveTasks.get(sid, 0) + 1 cpus[i] -= min(cpus[i], t.cpus) mems[i] -= t.mem launchedTask = True if not launchedTask: break used = time.time() - start if used > 10: logger.error("use too much time in slaveOffer: %.2fs", used) rf.refuse_seconds = 5 for o in offers: driver.launchTasks(o.id, tasks.get(o.id.value, []), rf) logger.debug("reply with %d tasks, %s cpus %s mem left", sum(len(ts) for ts in tasks.values()), sum(cpus), sum(mems)) @safe def offerRescinded(self, driver, offer_id): logger.debug("rescinded offer: %s", offer_id) if self.activeJobs: self.requestMoreResources() def getResource(self, res, name): for r in res: if r.name == name: return r.scalar.value def getAttribute(self, attrs, name): for r in attrs: if r.name == name: return r.text.value def createTask(self, o, job, t, available_cpus): task = mesos_pb2.TaskInfo() tid = "%s:%s:%s" % (job.id, t.id, t.tried) task.name = "task %s" % tid task.task_id.value = tid task.slave_id.value = o.slave_id.value task.data = compress(cPickle.dumps((t, t.tried), -1)) task.executor.MergeFrom(self.executor) if len(task.data) > 1000*1024: logger.warning("task too large: %s %d", t, len(task.data)) cpu = task.resources.add() cpu.name = 'cpus' cpu.type = 0 #mesos_pb2.Value.SCALAR cpu.scalar.value = min(t.cpus, available_cpus) mem = task.resources.add() mem.name = 'mem' mem.type = 0 #mesos_pb2.Value.SCALAR mem.scalar.value = t.mem return task @safe def statusUpdate(self, driver, status): tid = status.task_id.value state = status.state logger.debug("status update: %s %s", tid, state) jid = self.taskIdToJobId.get(tid) if jid not in self.activeJobs: logger.debug("Ignoring update from TID %s " + "because its job is gone", tid) return job = self.activeJobs[jid] _, task_id, tried = map(int, tid.split(':')) if state == mesos_pb2.TASK_RUNNING: return job.statusUpdate(task_id, tried, state) del self.taskIdToJobId[tid] self.jobTasks[jid].remove(tid) slave_id = self.taskIdToSlaveId[tid] if slave_id in self.slaveTasks: self.slaveTasks[slave_id] -= 1 del self.taskIdToSlaveId[tid] if state in (mesos_pb2.TASK_FINISHED, mesos_pb2.TASK_FAILED) and status.data: try: reason,result,accUpdate = cPickle.loads(status.data) if result: flag, data = result if flag >= 2: try: data = urllib.urlopen(data).read() except IOError: # try again data = urllib.urlopen(data).read() flag -= 2 data = decompress(data) if flag == 0: result = marshal.loads(data) else: result = cPickle.loads(data) except Exception, e: logger.warning("error when cPickle.loads(): %s, data:%s", e, len(status.data)) state = mesos_pb2.TASK_FAILED return job.statusUpdate(task_id, tried, mesos_pb2.TASK_FAILED, 'load failed: %s' % e) else: return job.statusUpdate(task_id, tried, state, reason, result, accUpdate) # killed, lost, load failed job.statusUpdate(task_id, tried, state, status.data) #if state in (mesos_pb2.TASK_FAILED, mesos_pb2.TASK_LOST): # self.slaveFailed[slave_id] = self.slaveFailed.get(slave_id,0) + 1 def jobFinished(self, job): logger.debug("job %s finished", job.id) if job.id in self.activeJobs: del self.activeJobs[job.id] self.activeJobsQueue.remove(job) for id in self.jobTasks[job.id]: del self.taskIdToJobId[id] del self.taskIdToSlaveId[id] del self.jobTasks[job.id] self.last_finish_time = time.time() if not self.activeJobs: self.slaveTasks.clear() self.slaveFailed.clear() @safe def check(self): for job in self.activeJobs.values(): if job.check_task_timeout(): self.requestMoreResources() @safe def error(self, driver, code, message): logger.warning("Mesos error message: %s (code: %s)", message, code) #if self.activeJobs: # self.requestMoreResources() #@safe def stop(self): if not self.started: return logger.debug("stop scheduler") self.started = False self.isRegistered = False self.driver.stop(False) self.driver = None def defaultParallelism(self): return 16 def frameworkMessage(self, driver, executor, slave, data): logger.warning("[slave %s] %s", slave.value, data) def executorLost(self, driver, executorId, slaveId, status): logger.warning("executor at %s %s lost: %s", slaveId.value, executorId.value, status) self.slaveTasks.pop(slaveId.value, None) self.slaveFailed.pop(slaveId.value, None) def slaveLost(self, driver, slaveId): logger.warning("slave %s lost", slaveId.value) self.slaveTasks.pop(slaveId.value, None) self.slaveFailed.pop(slaveId.value, None) def killTask(self, job_id, task_id, tried): tid = mesos_pb2.TaskID() tid.value = "%s:%s:%s" % (job_id, task_id, tried) self.driver.killTask(tid)
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import importlib import logging import os import signal import sys from sqlite3 import DatabaseError as SQLite3DatabaseError import django from django.core.exceptions import AppRegistryNotReady from django.core.management import call_command from django.db.utils import DatabaseError from docopt import docopt import kolibri from .debian_check import check_debian_user # Check if the current user is the kolibri user when running kolibri from .deb. # Putting it here because importing server module creates KOLIBRI_HOME directory. check_debian_user() from . import server # noqa from .conf import OPTIONS # noqa from .sanity_checks import check_content_directory_exists_and_writable # noqa from .sanity_checks import check_other_kolibri_running # noqa from .system import become_daemon # noqa from kolibri.core.deviceadmin.utils import IncompatibleDatabase # noqa from kolibri.utils import conf # noqa USAGE = """ Kolibri Supported by Foundation for Learning Equality www.learningequality.org Usage: kolibri start [--foreground] [--port=<port>] [options] kolibri stop [options] kolibri restart [options] kolibri status [options] kolibri shell [options] kolibri services [--foreground] [options] kolibri manage COMMAND [DJANGO_OPTIONS ...] kolibri manage COMMAND [options] [-- DJANGO_OPTIONS ...] kolibri diagnose [options] kolibri plugin [options] PLUGIN (enable | disable) kolibri language setdefault <langcode> kolibri plugin --list kolibri -h | --help kolibri --version Options: -h --help Show this screen. --version Show version. --debug Output debug messages (for development) --skipupdate Don't run update logic - useful if running two kolibri commands in parallel. COMMAND The name of any available django manage command. For help, type `kolibri manage help` DJANGO_OPTIONS Command options are passed on to the django manage command. Notice that all django options must appear *last* and should not be mixed with other options. Examples: kolibri start Start Kolibri kolibri stop Stop Kolibri kolibri status How is Kolibri doing? kolibri services Start Kolibri background services kolibri url Tell me the address of Kolibri kolibri shell Display a Django shell kolibri manage help Show the Django management usage dialogue kolibri manage runserver Runs Django's development server kolibri diagnose Show system information for debugging Environment: DJANGO_SETTINGS_MODULE - The Django settings module to load. Useful if you are deploying Kolibri in a specific setup such as your own web server. - Default: "kolibri.deployment.default.settings.base" KOLIBRI_HOME - Where Kolibri will store its data and configuration files. KOLIBRI_HTTP_PORT - Default: 8080 """ __doc__ = """ Kolibri Command Line Interface (CLI) ==================================== Auto-generated usage instructions from ``kolibri -h``:: {usage:s} """.format( usage="\n".join(map(lambda x: " " + x, USAGE.split("\n"))) ) logger = logging.getLogger(__name__) class PluginDoesNotExist(Exception): """ This exception is local to the CLI environment in case actions are performed on a plugin that cannot be loaded. """ class PluginBaseLoadsApp(Exception): """ An exception raised in case a kolibri_plugin.py results in loading of the Django app stack. """ pass def version_file(): """ During test runtime, this path may differ because KOLIBRI_HOME is regenerated """ from .conf import KOLIBRI_HOME return os.path.join(KOLIBRI_HOME, ".data_version") def should_back_up(kolibri_version, version_file_contents): change_version = kolibri_version != version_file_contents return ( change_version and "dev" not in version_file_contents and "dev" not in kolibri_version ) def initialize(debug=False, skip_update=False): """ Currently, always called before running commands. This may change in case commands that conflict with this behavior show up. :param: debug: Tells initialization to setup logging etc. """ if not os.path.isfile(version_file()): django.setup() setup_logging(debug=debug) if not skip_update: _first_run() else: # Do this here so that we can fix any issues with our configuration file before # we attempt to set up django. from .conf import autoremove_unavailable_plugins, enable_default_plugins autoremove_unavailable_plugins() version = open(version_file(), "r").read() version = version.strip() if version else "" if should_back_up(kolibri.__version__, version): # dbbackup will load settings.INSTALLED_APPS. # we need to ensure plugins are correct in conf.config before enable_default_plugins() # Version changed, make a backup no matter what. from kolibri.core.deviceadmin.utils import dbbackup try: backup = dbbackup(version) logger.info("Backed up database to: {path}".format(path=backup)) except IncompatibleDatabase: logger.warning( "Skipped automatic database backup, not compatible with " "this DB engine." ) django.setup() setup_logging(debug=debug) if kolibri.__version__ != version: logger.info( "Version was {old}, new version: {new}".format( old=version, new=kolibri.__version__ ) ) if not skip_update: update() def _migrate_databases(): """ Try to migrate all active databases. This should not be called unless Django has been initialized. """ from django.conf import settings for database in settings.DATABASES: call_command("migrate", interactive=False, database=database) # load morango fixtures needed for certificate related operations call_command("loaddata", "scopedefinitions") def _first_run(): """ Called once at least. """ if os.path.exists(version_file()): logger.error("_first_run() called, but Kolibri is already initialized.") return logger.info("Kolibri running for the first time.") logger.info( "We don't yet use pre-migrated database seeds, so you're going to have " "to wait a bit while we create a blank database...\n\n" ) from kolibri.core.settings import SKIP_AUTO_DATABASE_MIGRATION, DEFAULT_PLUGINS # We need to migrate the database before enabling plugins, because they # might depend on database readiness. if not SKIP_AUTO_DATABASE_MIGRATION: _migrate_databases() for plugin_module in DEFAULT_PLUGINS: try: plugin(plugin_module, enable=True) except PluginDoesNotExist: continue logger.info("Automatically enabling applications.") # Finally collect static assets and run migrations again update() def update(): """ Called whenever a version change in kolibri is detected TODO: We should look at version numbers of external plugins, too! """ logger.info("Running update routines for new version...") # Need to do this here, before we run any Django management commands that # import settings. Otherwise the updated configuration will not be used # during this runtime. call_command("collectstatic", interactive=False, verbosity=0) from kolibri.core.settings import SKIP_AUTO_DATABASE_MIGRATION if not SKIP_AUTO_DATABASE_MIGRATION: _migrate_databases() with open(version_file(), "w") as f: f.write(kolibri.__version__) from kolibri.core.content.utils.annotation import update_channel_metadata update_channel_metadata() from django.core.cache import caches cache = caches["built_files"] cache.clear() def start(port=None, daemon=True): """ Start the server on given port. :param: port: Port number (default: 8080) :param: daemon: Fork to background process (default: True) """ run_cherrypy = conf.OPTIONS["Server"]["CHERRYPY_START"] # In case some tests run start() function only if not isinstance(port, int): port = _get_port(port) if not daemon: logger.info("Running 'kolibri start' in foreground...") else: logger.info("Running 'kolibri start' as daemon (system service)") if run_cherrypy: __, urls = server.get_urls(listen_port=port) if not urls: logger.error( "Could not detect an IP address that Kolibri binds to, but try " "opening up the following addresses:\n" ) urls = [ "http://{}:{}".format(ip, port) for ip in ("localhost", "127.0.0.1") ] else: logger.info("Kolibri running on:\n") for addr in urls: sys.stderr.write("\t{}\n".format(addr)) sys.stderr.write("\n") else: logger.info("Starting Kolibri background services") # Daemonize at this point, no more user output is needed if daemon: kwargs = {} # Truncate the file if os.path.isfile(server.DAEMON_LOG): open(server.DAEMON_LOG, "w").truncate() logger.info("Going to daemon mode, logging to {0}".format(server.DAEMON_LOG)) kwargs["out_log"] = server.DAEMON_LOG kwargs["err_log"] = server.DAEMON_LOG become_daemon(**kwargs) server.start(port=port, run_cherrypy=run_cherrypy) def stop(): """ Stops the server unless it isn't running """ try: pid, __, __ = server.get_status() server.stop(pid=pid) stopped = True if conf.OPTIONS["Server"]["CHERRYPY_START"]: logger.info("Kolibri server has successfully been stopped.") else: logger.info("Kolibri background services have successfully been stopped.") except server.NotRunning as e: verbose_status = "{msg:s} ({code:d})".format( code=e.status_code, msg=status.codes[e.status_code] ) if e.status_code == server.STATUS_STOPPED: logger.info("Already stopped: {}".format(verbose_status)) stopped = True elif e.status_code == server.STATUS_STARTING_UP: logger.error("Not stopped: {}".format(verbose_status)) sys.exit(e.status_code) else: logger.error( "During graceful shutdown, server says: {}".format(verbose_status) ) logger.error("Not responding, killing with force") server.stop(force=True) stopped = True if stopped: sys.exit(0) def status(): """ Check the server's status. For possible statuses, see the status dictionary status.codes Status *always* outputs the current status in the first line of stderr. The following lines contain optional information such as the addresses where the server is listening. TODO: We can't guarantee the above behavior because of the django stack being loaded regardless :returns: status_code, key has description in status.codes """ status_code, urls = server.get_urls() if status_code == server.STATUS_RUNNING: sys.stderr.write("{msg:s} (0)\n".format(msg=status.codes[0])) if urls: sys.stderr.write("Kolibri running on:\n\n") for addr in urls: sys.stderr.write("\t{}\n".format(addr)) return server.STATUS_RUNNING else: verbose_status = status.codes[status_code] sys.stderr.write( "{msg:s} ({code:d})\n".format(code=status_code, msg=verbose_status) ) return status_code status.codes = { server.STATUS_RUNNING: "OK, running", server.STATUS_STOPPED: "Stopped", server.STATUS_STARTING_UP: "Starting up", server.STATUS_NOT_RESPONDING: "Not responding", server.STATUS_FAILED_TO_START: "Failed to start (check log file: {0})".format( server.DAEMON_LOG ), server.STATUS_UNCLEAN_SHUTDOWN: "Unclean shutdown", server.STATUS_UNKNOWN_INSTANCE: "Unknown Kolibri running on port", server.STATUS_SERVER_CONFIGURATION_ERROR: "Kolibri server configuration error", server.STATUS_PID_FILE_READ_ERROR: "Could not read PID file", server.STATUS_PID_FILE_INVALID: "Invalid PID file", server.STATUS_UNKNOWN: "Could not determine status", } def services(daemon=True): """ Start the kolibri background services. :param: daemon: Fork to background process (default: True) """ logger.info("Starting Kolibri background services") # Daemonize at this point, no more user output is needed if daemon: kwargs = {} # Truncate the file if os.path.isfile(server.DAEMON_LOG): open(server.DAEMON_LOG, "w").truncate() logger.info("Going to daemon mode, logging to {0}".format(server.DAEMON_LOG)) kwargs["out_log"] = server.DAEMON_LOG kwargs["err_log"] = server.DAEMON_LOG become_daemon(**kwargs) server.services() def setup_logging(debug=False): """ Configures logging in cases where a Django environment is not supposed to be configured. TODO: This is really confusing, importing django settings is allowed to fail when debug=False, but if it's true it can fail? """ try: from django.conf.settings import LOGGING except ImportError: from kolibri.deployment.default.settings.base import LOGGING if debug: from django.conf import settings settings.DEBUG = True LOGGING["handlers"]["console"]["level"] = "DEBUG" LOGGING["loggers"]["kolibri"]["level"] = "DEBUG" logger.debug("Debug mode is on!") logging.config.dictConfig(LOGGING) def manage(cmd, args=[]): """ Invokes a django command :param: cmd: The command to invoke, for instance "runserver" :param: args: arguments for the command """ # Set sys.argv to correctly reflect the way we invoke kolibri as a Python # module sys.argv = ["-m", "kolibri"] + sys.argv[1:] from django.core.management import execute_from_command_line argv = ["kolibri manage", cmd] + args execute_from_command_line(argv=argv) def _is_plugin(obj): from kolibri.plugins.base import KolibriPluginBase # NOQA return ( isinstance(obj, type) and obj is not KolibriPluginBase and issubclass(obj, KolibriPluginBase) ) def get_kolibri_plugin(plugin_name): """ Try to load kolibri_plugin from given plugin module identifier :returns: A list of classes inheriting from KolibriPluginBase """ plugin_classes = [] try: plugin_module = importlib.import_module(plugin_name + ".kolibri_plugin") for obj in plugin_module.__dict__.values(): if _is_plugin(obj): plugin_classes.append(obj) except ImportError as e: # Python 2: message, Python 3: msg exc_message = getattr(e, "message", getattr(e, "msg", None)) if exc_message.startswith("No module named"): msg = ( "Plugin '{}' does not seem to exist. Is it on the PYTHONPATH?" ).format(plugin_name) raise PluginDoesNotExist(msg) else: raise except AppRegistryNotReady: msg = ( "Plugin '{}' loads the Django app registry, which it isn't " "allowed to do while enabling or disabling itself." ).format(plugin_name) raise PluginBaseLoadsApp(msg) if not plugin_classes: # There's no clear use case for a plugin without a KolibriPluginBase # inheritor, for now just throw a warning logger.warning( "Plugin '{}' has no KolibriPluginBase defined".format(plugin_name) ) return plugin_classes def plugin(plugin_name, **kwargs): """ Receives a plugin identifier and tries to load its main class. Calls class functions. """ from kolibri.utils import conf if kwargs.get("enable", False): plugin_classes = get_kolibri_plugin(plugin_name) for klass in plugin_classes: klass.enable() if kwargs.get("disable", False): try: plugin_classes = get_kolibri_plugin(plugin_name) for klass in plugin_classes: klass.disable() except PluginDoesNotExist as e: logger.error(str(e)) logger.warning( "Removing '{}' from configuration in a naive way.".format(plugin_name) ) if plugin_name in conf.config["INSTALLED_APPS"]: conf.config["INSTALLED_APPS"].remove(plugin_name) logger.info("Removed '{}' from INSTALLED_APPS".format(plugin_name)) else: logger.warning( ( "Could not find any matches for {} in INSTALLED_APPS".format( plugin_name ) ) ) conf.save() def set_default_language(lang): """ Set the default language for this installation of Kolibri. Any running instance of Kolibri needs to be restarted in order for this change to work. """ from kolibri.utils import conf from django.conf import settings valid_languages = [l[0] for l in settings.LANGUAGES] if lang in valid_languages: conf.config["LANGUAGE_CODE"] = lang conf.save() else: msg = "Invalid language code {langcode}. Must be one of: {validlangs}".format( langcode=lang, validlangs=valid_languages ) logging.warning(msg) def parse_args(args=None): """ Parses arguments by invoking docopt. Arguments for django management commands are split out before returning. :returns: (parsed_arguments, raw_django_ars) """ if not args: args = sys.argv[1:] # Split out the parts of the argument list that we pass on to Django # and don't feed to docopt. if "--" in args: # At the moment, we keep this for backwards-compatibility and in case there # is a real case of having to force the parsing of DJANGO_OPTIONS to a # specific location. Example: # kolibri manage commandname --non-django-arg -- --django-arg pivot = args.index("--") args, django_args = args[:pivot], args[pivot + 1 :] elif "manage" in args: # Include "manage COMMAND" for docopt parsing, but split out the rest pivot = args.index("manage") + 2 args, django_args = args[:pivot], args[pivot:] else: django_args = [] docopt_kwargs = dict(version=str(kolibri.__version__), options_first=False) if args: docopt_kwargs["argv"] = args return docopt(USAGE, **docopt_kwargs), django_args def _get_port(port): return int(port) if port else OPTIONS["Deployment"]["HTTP_PORT"] def main(args=None): # noqa: max-complexity=13 """ Kolibri's main function. Parses arguments and calls utility functions. Utility functions should be callable for unit testing purposes, but remember to use main() for integration tests in order to test the argument API. """ signal.signal(signal.SIGINT, signal.SIG_DFL) arguments, django_args = parse_args(args) debug = arguments["--debug"] if arguments["start"]: port = _get_port(arguments["--port"]) if OPTIONS["Server"]["CHERRYPY_START"]: check_other_kolibri_running(port) try: initialize(debug=debug, skip_update=arguments["--skipupdate"]) except (DatabaseError, SQLite3DatabaseError) as e: if "malformed" in str(e): logger.error( "Your database appears to be corrupted. If you encounter this," "please immediately back up all files in the .kolibri folder that" "end in .sqlite3, .sqlite3-shm, .sqlite3-wal, or .log and then" "contact Learning Equality. Thank you!" ) raise daemon = not arguments["--foreground"] # On Mac, Python crashes when forking the process, so prevent daemonization until we can figure out # a better fix. See https://github.com/learningequality/kolibri/issues/4821 if sys.platform == "darwin": daemon = False # Alias if arguments["shell"]: arguments["manage"] = True arguments["COMMAND"] = "shell" if arguments["manage"]: command = arguments["COMMAND"] manage(command, args=django_args) return if arguments["plugin"]: plugin_name = arguments["PLUGIN"] plugin(plugin_name, **arguments) return if arguments["start"]: try: server._write_pid_file(server.STARTUP_LOCK, port) except (IOError, OSError): logger.warn( "Impossible to create file lock to communicate starting process" ) # Check if the content directory exists when Kolibri runs after the first time. check_content_directory_exists_and_writable() # Defragment the db call_command("vacuumsqlite") # Clear old sessions up call_command("clearsessions") start(port, daemon=daemon) return if arguments["stop"]: stop() return if arguments["status"]: status_code = status() sys.exit(status_code) return if arguments["services"]: try: server._write_pid_file(server.STARTUP_LOCK, None) except (IOError, OSError): logger.warn( "Impossible to create file lock to communicate starting process" ) services(daemon=daemon) return if arguments["language"] and arguments["setdefault"]: set_default_language(arguments["<langcode>"])
# Copyright 2020 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import tensorflow as tf import tensorflow_probability as tfp from scipy.special import expit from bert import modeling from bert import tokenization import multilabel flags = tf.flags tfd = tfp.distributions FLAGS = flags.FLAGS ## Optional parameters flags.DEFINE_string( "data_dir", None, "The input data dir. Should contain the .tsv files (or other data files) " "for the task.") flags.DEFINE_string( "bert_config_file", None, "The config json file corresponding to the pre-trained BERT model. " "This specifies the model architecture.") flags.DEFINE_string("task_name", None, "The name of the task to train.") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_string( "output_dir", None, "The output directory where the model checkpoints will be written.") flags.DEFINE_string( "init_checkpoint", "gs://kats-uncertainty-estimation/multi_cased_L-12_H-768_A-12", "Initial checkpoint (usually from a pre-trained BERT model).") flags.DEFINE_bool( "do_lower_case", False, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_integer( "max_seq_length", 128, "The maximum total input sequence length after WordPiece tokenization. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded.") flags.DEFINE_bool("do_train", False, "Whether to run training.") flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") flags.DEFINE_bool( "do_predict", False, "Whether to run the model in inference mode on the test set.") flags.DEFINE_integer("train_batch_size", 512, "Total batch size for training.") flags.DEFINE_integer("eval_batch_size", 512, "Total batch size for eval.") flags.DEFINE_integer("predict_batch_size", 512, "Total batch size for predict.") flags.DEFINE_float("learning_rate", 2e-5, "The initial learning rate for Adam.") flags.DEFINE_float("num_train_epochs", 10.0, "Total number of training epochs to perform.") flags.DEFINE_float( "warmup_proportion", 0.1, "Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") flags.DEFINE_integer("save_checkpoints_steps", 100, "How often to save the model checkpoint.") flags.DEFINE_integer("save_summary_steps", 20, "Save summaries every this many steps.") flags.DEFINE_integer( "keep_checkpoint_max", 0, "The maximum number of recent checkpoint files to keep." "If None or 0, all checkpoint files are kept.") flags.DEFINE_integer( "log_step_count_steps", 20, "The frequency, in number of global steps, that the global step" " and the loss will be logged during training. ") flags.DEFINE_integer("iterations_per_loop", 20, "How many steps to make in each estimator call.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") flags.DEFINE_integer( "num_tpu_cores", 8, "Only used if `use_tpu` is True. Total number of TPU cores to use.") flags.DEFINE_bool("freeze_bert", False, "Whether to freeze BERT layers during fine-tuning.") flags.DEFINE_string( "finetune_module", "original", "The module used in fine tuning for multilabel classification. " "The default is the original approach in BERT.") flags.DEFINE_bool( "convert_tsv_to_tfrecord", False, "Whether to convert tsv files to tfrecord before building input_fn.") flags.DEFINE_integer("sample_size", 1, "Number of samples to collect during prediction.") flags.DEFINE_list("label_mask", [1] * len(multilabel.LABEL_COLUMN), "Whether to consider specific labels in loss.") def main(_): tf.logging.set_verbosity(tf.logging.INFO) tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case, FLAGS.init_checkpoint) if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( "At least one of `do_train`, `do_eval` or `do_predict' must be True." ) bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( "Cannot use sequence length %d because the BERT model " "was only trained up to sequence length %d" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) tf.logging.info("***** FLAGS *****") writer = tf.io.gfile.GFile(f"{FLAGS.output_dir}/flags.txt", "w+") for key, val in FLAGS.__flags.items(): tf.logging.info(" %s = %s", key, str(val.value)) writer.write("%s = %s\n" % (key, str(val.value))) writer.close() tokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = tf.compat.v1.estimator.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.compat.v1.estimator.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, tpu_config=tf.compat.v1.estimator.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host), model_dir=FLAGS.output_dir, tf_random_seed=100, save_summary_steps=FLAGS.save_summary_steps, save_checkpoints_steps=FLAGS.save_checkpoints_steps, keep_checkpoint_max=FLAGS.keep_checkpoint_max, log_step_count_steps=FLAGS.log_step_count_steps) train_task_name = FLAGS.task_name if FLAGS.task_name else "train" _, num_train_examples, _, num_train_steps = multilabel.prepare_tfrecords( train_task_name, FLAGS.data_dir, FLAGS.max_seq_length, tokenizer, False, FLAGS.train_batch_size, 1, FLAGS.convert_tsv_to_tfrecord) num_train_steps = int(num_train_steps * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) model_fn = multilabel.model_fn_builder( bert_config=bert_config, num_labels=len(multilabel.LABEL_COLUMN), init_checkpoint=tf.train.latest_checkpoint(FLAGS.init_checkpoint), learning_rate=FLAGS.learning_rate, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_tpu=FLAGS.use_tpu, use_one_hot_embeddings=FLAGS.use_tpu, freeze_bert=FLAGS.freeze_bert, finetune_module=FLAGS.finetune_module, num_train_examples=num_train_examples) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.estimator.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size, predict_batch_size=FLAGS.predict_batch_size) if FLAGS.do_train and FLAGS.do_eval and (not FLAGS.use_tpu): eval_task_name = "eval" _, num_eval_examples, num_padded_eval_examples, num_eval_steps = multilabel.prepare_tfrecords( eval_task_name, FLAGS.data_dir, FLAGS.max_seq_length, tokenizer, FLAGS.use_tpu, FLAGS.eval_batch_size, 1, FLAGS.convert_tsv_to_tfrecord) tf.logging.info("***** Running training and evaluation *****") tf.logging.info(" Num training examples = %d", num_train_examples) tf.logging.info(" Training batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num training steps = %d", num_train_steps) tf.logging.info(" Num eval examples = %d ", num_eval_examples) tf.logging.info(" Eval batch size = %d", FLAGS.eval_batch_size) tf.logging.info(" Num eval steps = %d", num_eval_steps) train_input_fn = multilabel.file_based_input_fn_builder( input_file=f"{FLAGS.data_dir}/{train_task_name}-1.tfrecord", seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) eval_input_fn = multilabel.file_based_input_fn_builder( input_file=f"{FLAGS.data_dir}/{eval_task_name}-1.tfrecord", seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=False) train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=num_train_steps) eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn, steps=num_eval_steps, start_delay_secs=60, throttle_secs=120) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) else: if FLAGS.do_train: tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", num_train_examples) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = multilabel.file_based_input_fn_builder( input_file=f"{FLAGS.data_dir}/{train_task_name}-1.tfrecord", seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) estimator.train(input_fn=train_input_fn, max_steps=num_train_steps) if FLAGS.do_eval: eval_task_name = "eval" ckpt_steps = list( range(0, num_train_steps, FLAGS.save_checkpoints_steps)) ckpt_steps.append(num_train_steps) best_result = multilabel.eval_routine( eval_task_name, FLAGS.data_dir, FLAGS.output_dir, FLAGS.max_seq_length, tokenizer, estimator, FLAGS.use_tpu, FLAGS.predict_batch_size, ckpt_steps, 1, FLAGS.convert_tsv_to_tfrecord) if FLAGS.do_predict: predict_task_name = "predict" output = multilabel.predict_routine( predict_task_name, FLAGS.data_dir, FLAGS.output_dir, FLAGS.max_seq_length, tokenizer, estimator, FLAGS.use_tpu, FLAGS.predict_batch_size, FLAGS.sample_size, FLAGS.convert_tsv_to_tfrecord) file_name = f"{FLAGS.output_dir}/{predict_task_name}-{FLAGS.sample_size}-results.tsv" with tf.io.gfile.GFile(file_name, "w+") as writer: num_written_items = 0 writer.write( multilabel.ID_COLUMN + "\t" + multilabel.LANG_COLUMN + "\t" + "\t".join(name + " prob" for name in multilabel.LABEL_COLUMN) + "\t" + "\t".join(name + " var" for name in multilabel.LABEL_COLUMN) + "\t" + "\t".join(name + " ci_lb" for name in multilabel.LABEL_COLUMN) + "\t" + "\t".join(name + " ci_ub" for name in multilabel.LABEL_COLUMN) + "\t" + "\t".join( name + " ci_68_lb" for name in multilabel.LABEL_COLUMN) + "\t" + "\t".join(name + " ci_68_ub" for name in multilabel.LABEL_COLUMN) + "\n") for (i, pred) in enumerate(output): logits = np.array(pred["logits"]) vars = np.array(pred["variance"]) std_dev = np.sqrt(vars) lower_95_ci = expit(logits - 2 * std_dev) upper_95_ci = expit(logits + 2 * std_dev) lower_68_ci = expit(logits - std_dev) upper_68_ci = expit(logits + std_dev) output_line = pred[multilabel.ID_COLUMN] + "\t" + pred[ multilabel.LANG_COLUMN] + "\t" output_line += "\t".join( str(class_prob) for class_prob in pred["probs"]) + "\t" output_line += "\t".join( str(class_var) for class_var in vars) + "\t" output_line += "\t".join(str(lb) for lb in lower_95_ci) + "\t" output_line += "\t".join(str(ub) for ub in upper_95_ci) + "\t" output_line += "\t".join(str(lb) for lb in lower_68_ci) + "\t" output_line += "\t".join(str(ub) for ub in upper_68_ci) + "\n" writer.write(output_line) num_written_items += 1 assert num_written_items == len(output) tf.logging.info(f"Prediction results written to {file_name}") if __name__ == "__main__": flags.mark_flag_as_required("data_dir") flags.mark_flag_as_required("vocab_file") flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("output_dir") tf.app.run()
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore from google.ads.googleads.v10.services.types import ( campaign_conversion_goal_service, ) from .transports.base import ( CampaignConversionGoalServiceTransport, DEFAULT_CLIENT_INFO, ) from .transports.grpc import CampaignConversionGoalServiceGrpcTransport class CampaignConversionGoalServiceClientMeta(type): """Metaclass for the CampaignConversionGoalService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[CampaignConversionGoalServiceTransport]] _transport_registry["grpc"] = CampaignConversionGoalServiceGrpcTransport def get_transport_class( cls, label: str = None, ) -> Type[CampaignConversionGoalServiceTransport]: """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class CampaignConversionGoalServiceClient( metaclass=CampaignConversionGoalServiceClientMeta ): """Service to manage campaign conversion goal.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "googleads.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CampaignConversionGoalServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info( info ) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CampaignConversionGoalServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> CampaignConversionGoalServiceTransport: """Returns the transport used by the client instance. Returns: CampaignConversionGoalServiceTransport: The transport used by the client instance. """ return self._transport def __enter__(self): return self def __exit__(self, type, value, traceback): """Releases underlying transport's resources. .. warning:: ONLY use as a context manager if the transport is NOT shared with other clients! Exiting the with block will CLOSE the transport and may cause errors in other clients! """ self.transport.close() @staticmethod def campaign_path(customer_id: str, campaign_id: str,) -> str: """Returns a fully-qualified campaign string.""" return "customers/{customer_id}/campaigns/{campaign_id}".format( customer_id=customer_id, campaign_id=campaign_id, ) @staticmethod def parse_campaign_path(path: str) -> Dict[str, str]: """Parses a campaign path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/campaigns/(?P<campaign_id>.+?)$", path, ) return m.groupdict() if m else {} @staticmethod def campaign_conversion_goal_path( customer_id: str, campaign_id: str, category: str, source: str, ) -> str: """Returns a fully-qualified campaign_conversion_goal string.""" return "customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}".format( customer_id=customer_id, campaign_id=campaign_id, category=category, source=source, ) @staticmethod def parse_campaign_conversion_goal_path(path: str) -> Dict[str, str]: """Parses a campaign_conversion_goal path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/campaignConversionGoals/(?P<campaign_id>.+?)~(?P<category>.+?)~(?P<source>.+?)$", path, ) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[ str, CampaignConversionGoalServiceTransport, None ] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the campaign conversion goal service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, CampaignConversionGoalServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( "true", "false", ): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" ) use_client_cert = ( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" ) client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: is_mtls = True client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() if is_mtls: client_cert_source_func = mtls.default_client_cert_source() else: client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " "values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, CampaignConversionGoalServiceTransport): # transport is a CampaignConversionGoalServiceTransport instance. if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) if client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " "directly." ) self._transport = transport else: Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, ) def mutate_campaign_conversion_goals( self, request: Union[ campaign_conversion_goal_service.MutateCampaignConversionGoalsRequest, dict, ] = None, *, customer_id: str = None, operations: Sequence[ campaign_conversion_goal_service.CampaignConversionGoalOperation ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> campaign_conversion_goal_service.MutateCampaignConversionGoalsResponse: r"""Creates, updates or removes campaign conversion goals. Operation statuses are returned. Args: request (Union[google.ads.googleads.v10.services.types.MutateCampaignConversionGoalsRequest, dict]): The request object. Request message for [CampaignConversionGoalService.MutateCampaignConversionGoals][google.ads.googleads.v10.services.CampaignConversionGoalService.MutateCampaignConversionGoals]. customer_id (str): Required. The ID of the customer whose campaign conversion goals are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (Sequence[google.ads.googleads.v10.services.types.CampaignConversionGoalOperation]): Required. The list of operations to perform on individual campaign conversion goal. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v10.services.types.MutateCampaignConversionGoalsResponse: Response message for a campaign conversion goal mutate. """ # Create or coerce a protobuf request object. # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([customer_id, operations]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a campaign_conversion_goal_service.MutateCampaignConversionGoalsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, campaign_conversion_goal_service.MutateCampaignConversionGoalsRequest, ): request = campaign_conversion_goal_service.MutateCampaignConversionGoalsRequest( request ) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if operations is not None: request.operations = operations # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.mutate_campaign_conversion_goals ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-ads",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("CampaignConversionGoalServiceClient",)
"Ideogenesis: Neo4j database server interface using REST." from __future__ import print_function, absolute_import import json import logging import requests import urlparse import weakref VERSION = (2, 2) ACCEPT = 'application/json; charset=UTF-8' CONTENT = 'application/json' ENDPOINTS = dict(node='node', node_index='index/node', node_labels='labels', relationship='relationship', # XXX not in root data? relationship_index='index/relationship', relationship_types='relationship/types', batch='batch', cypher='cypher', indexes='schema/index', constraints='schema/constraint', transaction='transaction') CHUNKSIZE = 25 class CypherError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return str(self.msg) def __repr__(self): return repr(self.msg) class Neo4j(object): "Interface to Neo4j database via REST." def __init__(self, base_url='http://localhost:7474/db/data/', user=None, password=None): self._version = None self._base_url = base_url self._user = user self._password = password self._nodes = weakref.WeakValueDictionary() self._relationships = weakref.WeakValueDictionary() self.endpoints = dict() for key, path in ENDPOINTS.iteritems(): self.endpoints[key] = urlparse.urljoin(base_url, path) self.session = self.get_session() def get_session(self): "Get a new requests session." session = requests.Session() if self._user and self._password: session.auth = (self._user, self._password) session.headers.update({'Accept': ACCEPT, 'Content-Type': CONTENT}) return session @property def version(self): "The Neo4j database version." if self._version is None: self._version = self.check() return self._version def check(self): """Check the root response from the server. Return the Neo4j server version. Raise ValueError if anything is wrong. """ response = self.session.get(self._base_url) if response.status_code != 200: raise ValueError("%s %s" % (response.status_code, response.reason)) data = response.json() for key, value in data.iteritems(): try: if self.endpoints[key] != value: raise ValueError("Endpoint differ: %s %s" % (self.endpoints[key], value)) except KeyError: pass version = data['neo4j_version'] version_values = [int(p) for p in version.split('.')] if version_values[0] < VERSION[0]: raise ValueError("Cannot handle version %s" % version_values[0]) elif version_values[0] == VERSION[0] and version_values[1] < VERSION[1]: raise ValueError("Cannot handle version %s" % version) return version def execute(self, statement, **parameters): "Execute a single CYPHER statement in its own transaction." url = self.get_url('transaction', suffix='commit') data = json.dumps(dict(statements=[dict(statement=statement, parameters=parameters)])) response = self.session.post(url, data=data) self.check_http(response, 200) result = response.json() self.check_errors(result) return result def create_node(self, *labels, **properties): "Create a node in the database with the given data." # These two operations should really be done in batch, # but since the second operation needs the number of # the node created in the first, this is not possible. url = self.get_url('node') data = json.dumps(properties) response = self.session.post(url, data=data) self.check_http(response, 201) result = Node(response=response) if labels: url = self.get_node_url(result, 'labels') data = json.dumps(list(labels)) response = self.session.post(url, data=data) try: self.check_http(response, 204) except: # Roll back node creation if anything went wrong. # This replaces a proper transaction. self.delete_node(node) raise result.labels = set(labels) self._nodes[result.number] = result return result def delete_node(self, node): "Delete the node in the database for the given proxy object." assert isinstance(node, Node) assert node.number is not None url = self.get_node_url(node) response = self.session.delete(url) self.check_http(response, 204, message=str(node)) del self._nodes[node.number] node._number = None def get_node(self, number): "Get a node by its id number. Try the cache first." try: return self._nodes[number] except KeyError: result = Node(number=number) self.refresh_node(result) self._nodes[number] = result return result def refresh_node(self, node): "Refresh the contents of the node proxy object from the database." assert isinstance(node, Node) assert node.number is not None response = self.session.get(self.get_node_url(node)) self.check_http(response, 200, message=str(node)) data = response.json() assert data['metadata']['id'] == node.number node.labels = set(data['metadata']['labels']) node.properties = data['data'] return node def update_node_properties(self, node): """Update the properties of the node to ones given in it. This replaces all existing properties. """ assert isinstance(node, Node) assert node.number is not None url = self.get_node_url(node, 'properties') properties = dict([(k,v) for k,v in node.properties.items() if v is not None]) if properties: data = json.dumps(properties) response = self.session.put(url, data=data) else: response = self.session.delete(url) self.check_http(response, 204, message=str(node)) return node def set_node_property(self, node, key, value): "Set the property of the node." assert isinstance(node, Node) assert node.number is not None assert key assert value is not None url = self.get_node_url(node, 'properties', key) data = json.dumps(value) response = self.session.put(url, data=data) self.check_http(response, 204, message=str(node)) node[key] = value return node def delete_node_property(self, node, key): """Delete the property of the node. No action if no such property. """ url = self.get_node_url(node, 'properties', key) response = self.session.delete(url) if response.status_code == 404: pass else: self.check_http(response, 204, message=str(node)) try: del node[key] except KeyError: pass return node def add_node_label(self, node, label): "Add the label to the node." assert isinstance(node, Node) assert label assert isinstance(label, (str, unicode)) url = self.get_node_url(node, 'labels') data = json.dumps(label) response = self.session.post(url, data=data) self.check_http(response, 204, message=str(node)) node.labels.add(label) def remove_node_label(self, node, label): "Remove the label from the node." assert isinstance(node, Node) assert label assert isinstance(label, (str, unicode)) url = self.get_node_url(node, 'labels', label) response = self.session.delete(url) self.check_http(response, 204, message=str(node)) node.labels.remove(label) def find_nodes(self, *labels, **properties): "Return the nodes matching the given criteria." statement = 'MATCH (n' if labels: statement += ":{}".format(':'.join(labels)) if properties: properties = ["{}:'{}'".format(k,v) for k,v in properties.items()] statement += ' {' + ','.join(properties) + '}' statement += ') RETURN id(n)' result = self.execute(statement) return self.get_nodes_id(result) def get_nodes_execute(self, statement, **parameters): """Execute the single CYPHER statement given its parameters. The statement must return only id's of nodes, which are converted to a list of Node instances. """ result = self.execute(statement, **parameters) return self.get_nodes_id(result) def get_nodes_id(self, result): """Return the Node instances for a result from execution of a statement containing a RETURN id(n) construct.""" try: return [self.get_node(d['row'][0]) for d in result['results'][0]['data']] except: raise def create_relationship(self, start, end, type, **properties): "Create a relationship in the database with the given data." url = self.get_node_url(start, 'relationships') data = json.dumps({'to': self.get_node_url(end), 'type': type, 'data': properties}) response = self.session.post(url, data=data) self.check_http(response, 201) data = response.json() rel = Relationship() rel._number = data['metadata']['id'] self._relationships[rel.number] = rel rel.type = type rel.properties = properties.copy() if isinstance(start, Node): rel.start = start else: rel.start = self.get_node(start) if isinstance(end, Node): rel.end = end else: rel.end = self.get_node(end) return rel def delete_relationship(self, relationship): "Delete the relationship in the database for the given proxy object." assert isinstance(relationship, Relationship) assert relationship.number is not None url = self.get_relationship_url(relationship) response = self.session.delete(url) self.check_http(response, 204, message=str(relationship)) del self._relationships[relationship.number] relationship._number = None def get_relationship(self, number): "Get a relationship by its number. Try the cache first." try: return self._relationships[number] except KeyError: result = Relationship() result._number = number self.refresh_relationship(result) self._relationships[number] = result return result def refresh_relationship(self, relationship): "Refresh the contents of the relationship proxy object from the database." assert isinstance(relationship, Relationship) assert relationship.number is not None response = self.session.get(self.get_relationship_url(relationship)) self.check_http(response, 200, message=str(relationship)) data = response.json() assert data['metadata']['id'] == relationship.number relationship.start = self.get_node(int(data['start'].split('/')[-1])) relationship.end = self.get_node(int(data['end'].split('/')[-1])) relationship.type = data['type'] relationship.properties = data['data'] return relationship def set_relationship_property(self, relationship, key, value): "Set the property of the relationship." assert isinstance(relationship, Relationship) assert relationship.number is not None assert key assert value is not None url = self.get_relationship_url(relationship, 'properties', key) data = json.dumps(value) response = self.session.put(url, data=data) self.check_http(response, 204, message=str(relationship)) relationship[key] = value return relationship def delete_relationship_property(self, relationship, key): """Delete the property of the relationship. No action if no such property. """ assert isinstance(relationship, Relationship) assert relationship.number is not None assert key url = self.get_relationship_url(relationship, 'properties', key) response = self.session.delete(url) if response.status_code == 404: pass else: self.check_http(response, 204, message=str(relationship)) try: del relationship[key] except KeyError: pass return relationship def get_relationships(self, node, out=None, type=None): suffixes = [] if out is None: suffixes.append('all') elif out: suffixes.append('out') else: suffixes.append('in') if type is not None: suffixes.append(type) url = self.get_node_url(node, 'relationships', *suffixes) response = self.session.get(url) self.check_http(response, 200) data = response.json() result = [] for rel in data: result.append(self.get_relationship(rel['metadata']['id'])) return result def get_count_relationships(self, start, end, type): "Return the count of typed relationships between the nodes." rel = "[r:{}]".format(type) statement = "MATCH (i {iuid:{iid}})-" + rel + "->(j {iuid:{jid}})" \ " RETURN COUNT(r)" result = self.execute(statement, iid=start['iuid'], jid=end['iuid']) return result['results'][0]['data'][0]['row'][0] def get_url(self, endpoint, suffix=None): url = self.endpoints[endpoint] if suffix: url += '/' + suffix return url def get_node_url(self, node, *suffixes): if isinstance(node, Node): number = node.number elif isinstance(node, int): number = node else: raise ValueError("node neither instance nor int: {}".format(node)) url = self.endpoints['node'] + "/{}".format(number) if suffixes: url += '/' + '/'.join(suffixes) return url def get_relationship_url(self, relationship, *suffixes): if isinstance(relationship, Relationship): number = relationship.number elif isinstance(relationship, int): number = relationship else: raise ValueError('relationship neither instance nor int') url = self.endpoints['relationship'] + "/{}".format(number) if suffixes: url += '/' + '/'.join(suffixes) return url def check_http(self, response, status, message=None): """Check the HTTP response for the correct status code. Raise KeyError if status is 404, and shouldn't be. Raise ValueError if status is 400 or 409, and shouldn't be. Raise IOError if status is not what it should be. """ if response.status_code != status: msg = "HTTP status {} {}".format(response.status_code, response.reason) if message: msg += ': ' + message if response.status_code == 404: raise KeyError(msg) elif response.status_code in (400, 409): raise ValueError(msg) else: raise IOError(msg) def check_errors(self, result): "Check if the result body contains errors; raise ValueError." errors = result['errors'] if errors: raise CypherError("code: {}; message: {}".format( errors[0]['code'], errors[0]['message'])) class Transaction(object): "Context manager for a set of statements in a transaction." def __init__(self, neo4j): self.neo4j = neo4j self.url = None self.url_commit = None def __enter__(self): self.session = self.neo4j.get_session() return self def __exit__(self, type, value, tb): if type is None: self.commit() else: self.rollback() def execute(self, statement, **parameters): data = json.dumps(dict(statements=[dict(statement=statement, parameters=parameters)])) if self.url is None: url = self.neo4j.get_url('transaction') response = self.session.post(url, data=data) self.neo4j.check_http(response, 201) self.url = response.headers['Location'] else: response = self.session.post(self.url, data=data) self.neo4j.check_http(response, 200) result = response.json() self.neo4j.check_errors(result) self.url_commit = result['commit'] return result def commit(self): if self.url_commit is None: return data = json.dumps(dict(statements=[])) response = self.session.post(self.url_commit, data=data) self.neo4j.check_http(response, 200) self.url_commit = None def rollback(self): if self.url_commit is None: return self.session.delete(self.url_commit) self.url_commit = None class _Base(object): "Base class for Node and Relationship proxy objects." def __str__(self): return "{}({})".format(self.__class__.__name__, self.number) @property def number(self): return self._number def __contains__(self, key): return key in self.properties def __getitem__(self, key): return self.properties[key] def __delitem__(self, key): try: del self.properties[key] except KeyError: pass def __setitem__(self, key, value): self.properties[key] = value def get(self, key, default=None): try: return self[key] except KeyError: return default class Node(_Base): "Node proxy object." def __init__(self, number=None, response=None): "Get the data for the node from the response, if given." if response: data = response.json() self._number = data['metadata']['id'] self.labels = set(data['metadata']['labels']) self.properties = data['data'] else: self._number = number self.labels = set() self.properties = dict() def __repr__(self): properties = [] for key in sorted(self.properties): value = self.properties[key] if isinstance(value, (str, unicode)): value = "'{}'".format(value) properties.append("{}:{}".format(key, value)) return "Node({}:{} {{{}}})".format(self.number, ':'.join(sorted(self.labels)), ', '.join(properties)) class Relationship(_Base): "Relationship proxy object." def __init__(self): self._number = None self.start = None self.end = None self.type = None self.properties = dict() def __repr__(self): properties = [] for key in sorted(self.properties): value = self.properties[key] if isinstance(value, (str, unicode)): value = "'{}'".format(value) properties.append("{}:{}".format(key, value)) return "Relationship({}:{} {{{}}})".format(self.number, self.type, ', '.join(properties))
#!/usr/bin/env python # # Use the raw transactions API to spend IONs received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a iond or ion-Qt running # on localhost. # # Depends on jsonrpc # from decimal import * import getpass import math import os import os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the ioncoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/ioncoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "ioncoin") return os.path.expanduser("~/.ioncoin") def read_bitcoin_config(dbdir): """Read the ioncoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "ioncoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a ion JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 51475 if testnet else 51473 connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the iond we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(iond): info = iond.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") iond.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = iond.getinfo() return int(info['unlocked_until']) > time.time() def list_available(iond): address_summary = dict() address_to_account = dict() for info in iond.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = iond.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = iond.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-ion-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(iond, fromaddresses, toaddress, amount, fee): all_coins = list_available(iond) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to iond. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = iond.createrawtransaction(inputs, outputs) signed_rawtx = iond.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(iond, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = iond.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(iond, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = iond.decoderawtransaction(txdata_hex) total_in = compute_amount_in(iond, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get IONs from") parser.add_option("--to", dest="to", default=None, help="address to get send IONs to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of ioncoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options, args) = parser.parse_args() check_json_precision() config = read_bitcoin_config(options.datadir) if options.testnet: config['testnet'] = True iond = connect_JSON(config) if options.amount is None: address_summary = list_available(iond) for address,info in address_summary.iteritems(): n_transactions = len(info['outputs']) if n_transactions > 1: print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions)) else: print("%s %.8f %s"%(address, info['total'], info['account'])) else: fee = Decimal(options.fee) amount = Decimal(options.amount) while unlock_wallet(iond) == False: pass # Keep asking for passphrase until they get it right txdata = create_tx(iond, options.fromaddresses.split(","), options.to, amount, fee) sanity_test_fee(iond, txdata, amount*Decimal("0.01")) if options.dry_run: print(txdata) else: txid = iond.sendrawtransaction(txdata) print(txid) if __name__ == '__main__': main()
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =================================================================== """TPU Feature Column Library.""" import math from tensorflow.python.feature_column import feature_column as fc from tensorflow.python.feature_column import feature_column_lib as fc_lib from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import variable_scope from tensorflow.python.tpu import tpu from tensorflow.python.tpu import tpu_function # pylint: disable=protected-access _TPU_FC_TO_SCOPE = '_tpu_feature_column_scope' _SUPPORTED_SEQUENCE_COLUMNS = (fc._SequenceCategoricalColumn, fc_lib.SequenceCategoricalColumn) # For V2 columns, we support anything that inherits from CategoricalColumn # other than those in the denylist. User-provided columns that inherit from # CategoricalColumn may or may not be compatible; it is up to the user to # manage TPU compatibility for custom columns. _SUPPORTED_CATEGORICAL_COLUMNS_V2 = (fc_lib.CategoricalColumn,) _DENYLISTED_CATEGORICAL_COLUMNS_V2 = (fc_lib.HashedCategoricalColumn, fc_lib.BucketizedColumn, fc_lib.CrossedColumn) _SUPPORTED_CATEGORICAL_COLUMNS = (fc._IdentityCategoricalColumn, fc._VocabularyFileCategoricalColumn, fc._VocabularyListCategoricalColumn, fc._WeightedCategoricalColumn, fc._SequenceCategoricalColumn ) + _SUPPORTED_CATEGORICAL_COLUMNS_V2 _SEQUENCE_FEATURE_LENGTH_POSTFIX = '_seq_length_' def embedding_column(categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True): """TPU embedding_column for `tf.feature_column.embedding_column`. Note that the interface for TPU embedding_column is different from the non-TPU version. The following args available for the non-TPU version are NOT supported: ckpt_to_load_from, tensor_name_in_ckp, max_norm and trainable. Args: categorical_column: A categorical_column returned from categorical_column_with_identity, weighted_categorical_column, categorical_column_with_vocabulary_file, categorical_column_with_vocabulary_list, sequence_categorical_column_with_identity, sequence_categorical_column_with_vocabulary_file, sequence_categorical_column_with_vocabulary_list dimension: An integer specifying dimension of the embedding, must be > 0. combiner: A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see `tf.feature_column.embedding_column`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and standard deviation `1/sqrt(dimension)`. max_sequence_length: An non-negative integer specifying the max sequence length. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. This must be positive for sequence features and 0 for non-sequence features. learning_rate_fn: A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of embedding_column, otherwise performence may suffer. use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns: A _TPUEmbeddingColumn. Raises: ValueError: if `dimension` not > 0. ValueError: if `initializer` is specified but not callable. TypeError: if categorical_column is not a supported type. """ if isinstance(categorical_column, _DENYLISTED_CATEGORICAL_COLUMNS_V2): raise TypeError('categorical_column for tpu ' ' embedding_column was denylisted type %s' % type(categorical_column)) if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS): raise TypeError( 'categorical_column for tpu ' ' embedding_column must be type %s, got %s.' % (' or '.join([ cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS ]), type(categorical_column))) if (dimension is None) or (dimension < 1): raise ValueError('Invalid dimension {}.'.format(dimension)) if (initializer is not None) and (not callable(initializer)): raise ValueError('initializer must be callable if specified. ' 'Embedding of column_name: {}'.format( categorical_column.name)) if initializer is None: initializer = init_ops.truncated_normal_initializer( mean=0.0, stddev=1 / math.sqrt(dimension)) embedding_shape = categorical_column._num_buckets, dimension # pylint: disable=protected-access def _creator(weight_collections, scope): embedding_column_layer = fc._EmbeddingColumnLayer( embedding_shape=embedding_shape, initializer=initializer, weight_collections=weight_collections, trainable=True, name='embedding_column_layer') return embedding_column_layer(None, scope=scope) # pylint: disable=not-callable column = _TPUEmbeddingColumn( categorical_column=categorical_column, dimension=dimension, combiner=combiner, layer_creator=_creator, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, use_safe_embedding_lookup=use_safe_embedding_lookup) # For Embedding column, the initializer is hidden inside the creator Fn, which # is not accessible later. So, we attach it to a special field. Also note # that non-TPU Embedding column and non-TPU shared Embedding column handle the # initializer differently. See shared_embedding_columns for details. column._tpu_initializer = initializer return column def shared_embedding_columns(categorical_columns, dimension, combiner='mean', initializer=None, shared_embedding_collection_name=None, max_sequence_lengths=None, learning_rate_fn=None, use_safe_embedding_lookup=True): """List of dense columns that convert from sparse, categorical input. Note that the interface for TPU embedding_column is different from the non-TPU version. The following args available for the non-TPU version are NOT supported: ckpt_to_load_from, tensor_name_in_ckp, max_norm and trainable. Args: categorical_columns: A list of categorical_columns returned from categorical_column_with_identity, weighted_categorical_column, categorical_column_with_vocabulary_file, categorical_column_with_vocabulary_list, sequence_categorical_column_with_identity, sequence_categorical_column_with_vocabulary_file, sequence_categorical_column_with_vocabulary_list dimension: An integer specifying dimension of the embedding, must be > 0. combiner: A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see `tf.feature_column.embedding_column`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.truncated_normal_initializer` with mean `0.0` and standard deviation `1/sqrt(dimension)`. shared_embedding_collection_name: Optional name of the collection where shared embedding weights are added. If not given, a reasonable name will be chosen based on the names of `categorical_columns`. This is also used in `variable_scope` when creating shared embedding weights. max_sequence_lengths: An list of non-negative integers, either None or empty or the same length as the argument categorical_columns. Entries corresponding to non-sequence columns must be 0 and entries corresponding to sequence columns specify the max sequence length for the column. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. learning_rate_fn: A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of shared_embedding_columns, otherwise performence may suffer. use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns: A _TPUEmbeddingColumn. Raises: ValueError: if `dimension` not > 0. ValueError: if `initializer` is specified but not callable. ValueError: if `max_sequence_lengths` is specified and not the same length as `categorical_columns`. ValueError: if `max_sequence_lengths` is positive for a non sequence column or 0 for a sequence column. """ for categorical_column in categorical_columns: if isinstance(categorical_column, _DENYLISTED_CATEGORICAL_COLUMNS_V2): raise TypeError('categorical_column for tpu ' ' embedding_column was denylisted type %s' % type(categorical_column)) if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS): raise TypeError( 'categorical_column for tpu ' ' shared_embedding_columns must be type %s, got %s.' % (' or '.join([ cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS ]), type(categorical_column))) if not max_sequence_lengths: max_sequence_lengths = [0] * len(categorical_columns) if len(max_sequence_lengths) != len(categorical_columns): raise ValueError('max_sequence_lengths and categorical_columns must be of ' 'the same length. len(max_sequence_lengths)={} ' 'len(categorical_columns)={}.'.format( len(max_sequence_lengths), len(categorical_columns))) if (dimension is None) or (dimension < 1): raise ValueError('Invalid dimension {}.'.format(dimension)) if (initializer is not None) and (not callable(initializer)): raise ValueError('initializer must be callable if specified. ') if initializer is None: initializer = init_ops.truncated_normal_initializer( mean=0.0, stddev=1 / math.sqrt(dimension)) # Sort the columns so the default collection name is deterministic even if the # user passes columns from an unsorted collection, such as dict.values(). sorted_columns = sorted(categorical_columns, key=lambda x: x.name) num_buckets = sorted_columns[0]._num_buckets # pylint: disable=protected-access for c in sorted_columns[1:]: if num_buckets != c._num_buckets: # pylint: disable=protected-access raise ValueError( 'To use shared_embedding_column, all categorical_columns must have ' 'the same number of buckets. Given column: {} with buckets: {} does ' 'not match column: {} with buckets: {}'.format( sorted_columns[0], num_buckets, c, c._num_buckets)) # pylint: disable=protected-access if not shared_embedding_collection_name: shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) shared_embedding_collection_name += '_shared_embedding' tpu_columns = [] # Create the state (_SharedEmbeddingColumnLayer) here. for categorical_column, max_sequence_length in zip( categorical_columns, max_sequence_lengths): column = _TPUSharedEmbeddingColumn( categorical_column=categorical_column, dimension=dimension, combiner=combiner, initializer=initializer, shared_embedding_collection_name=shared_embedding_collection_name, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, use_safe_embedding_lookup=use_safe_embedding_lookup) tpu_columns.append(column) return tpu_columns class _TPUBaseEmbeddingColumn(object): """Base class for TPU Embedding Column.""" def __init__(self, categorical_column, max_sequence_length=0, learning_rate_fn=None): self._tpu_categorical_column = categorical_column self._max_sequence_length = max_sequence_length self._learning_rate_fn = learning_rate_fn if (self.is_sequence_column() and max_sequence_length < 1): raise ValueError('max_sequence_length must be greater than 0 for ' 'sequence columns. Got max_sequence_length={} for ' 'sequence column {}.'.format(max_sequence_length, categorical_column.name)) if (not self.is_sequence_column() and max_sequence_length != 0): raise ValueError('Non zero max_seq_length={} specified for non ' 'sequence column {}.'.format(max_sequence_length, categorical_column.name)) def get_combiner(self): """Returns the embedding combiner.""" raise NotImplementedError('not implemented') def get_embedding_table_size(self): """Returns the embedding table size, tuple of vocab size and dimension.""" raise NotImplementedError('not implemented') def get_feature_key_name(self): """Returns the feature key name in the features dict.""" raise NotImplementedError('not impl') def get_weight_key_name(self): """Return the key name for weights.""" raise NotImplementedError('not impl') def get_embedding_var_name(self): """Returns the embedding variable name. Feature key name and embedding variable name are usually one-to-one mapping. But for shared embedding columns, it is many-to-one mapping. """ raise NotImplementedError('not impl') def get_initializer(self): """Returns the initializer.""" raise NotImplementedError('not impl') def is_categorical_column_weighted(self): """Check if the categorical column of the embedding column is weighted.""" raise NotImplementedError('not impl') def is_sequence_column(self): return isinstance(self._tpu_categorical_column, _SUPPORTED_SEQUENCE_COLUMNS) def get_max_sequence_length(self): return self._max_sequence_length def get_learning_rate_fn(self): return self._learning_rate_fn def get_sequence_length_feature_key_name(self): """Get the key for the associated sequence length feature.""" return get_sequence_length_feature_key_name_from_feature_key_name( self.get_feature_key_name()) class _TPUEmbeddingColumn(_TPUBaseEmbeddingColumn, fc._EmbeddingColumn): """Core Embedding Column.""" def __new__(cls, categorical_column, dimension, combiner='mean', layer_creator=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True, bypass_scope_validation=False): # Note, args ckpt_to_load_from, tensor_name_in_ckpt, max_norm and trainable # are not supported on TPU. They are solely for matching the signature of # __new__ of parent class fc._EmbeddingColumn. del bypass_scope_validation # pylint: disable=redundant-keyword-arg return fc._EmbeddingColumn.__new__( cls, categorical_column, dimension, combiner=combiner, layer_creator=layer_creator, ckpt_to_load_from=ckpt_to_load_from, tensor_name_in_ckpt=tensor_name_in_ckpt, max_norm=max_norm, trainable=trainable, use_safe_embedding_lookup=use_safe_embedding_lookup) def __init__(self, categorical_column, dimension, combiner='mean', layer_creator=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True, bypass_scope_validation=False): _TPUBaseEmbeddingColumn.__init__( self, categorical_column, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn) self._key = None # If true, scope validation is skipped to allow the same column to be used # in multiple variable scopes. By default, this is False, and we expect a # 1:1 mapping between feature columns and scopes. self._bypass_scope_validation = bypass_scope_validation def get_combiner(self): return self.combiner def get_embedding_table_size(self): """Returns num_ids and width.""" return (self.categorical_column._num_buckets, self.dimension) def get_feature_key_name(self): """get_feature_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.categorical_column.name return self.categorical_column.name def get_weight_key_name(self): """get_weight_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.weight_feature_key return None def get_embedding_var_name(self): """get_embedding_var_name.""" return self.categorical_column.name def get_initializer(self): return self._tpu_initializer def is_categorical_column_weighted(self): """Check if the categorical column of the embedding column is weighted.""" if isinstance( self.categorical_column, ( fc._WeightedCategoricalColumn, # pylint: disable=protected-access fc_lib.WeightedCategoricalColumn)): return True return False def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc._EmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc._EmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) # TPU mode # Get the embeddings from the LazyBuilder. tensor = inputs.get(self.get_feature_key_name()) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', bypass_scope_validation=self._bypass_scope_validation) return tensor def _get_sequence_dense_tensor( self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc._EmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc._EmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) tensor = inputs.get(self.get_feature_key_name()) tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) # inputs is a _LazyBuilder and for rank 1 tensors, it calls expand_dims(-1). # We need to undo this to match the standard CPU sequence embedding. tensor_lengths = array_ops.squeeze(tensor_lengths, -1) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', bypass_scope_validation=self._bypass_scope_validation) return fc._SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=tensor, sequence_length=tensor_lengths) class _TPUSharedEmbeddingColumn(_TPUBaseEmbeddingColumn, fc._SharedEmbeddingColumn): """Core Shared Embedding Column.""" def __new__(cls, categorical_column, dimension, combiner='mean', initializer=None, shared_embedding_collection_name=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True): return fc._SharedEmbeddingColumn.__new__( cls, categorical_column, dimension, combiner=combiner, initializer=initializer, shared_embedding_collection_name=shared_embedding_collection_name, ckpt_to_load_from=ckpt_to_load_from, tensor_name_in_ckpt=tensor_name_in_ckpt, max_norm=max_norm, trainable=trainable, use_safe_embedding_lookup=use_safe_embedding_lookup) def __init__(self, categorical_column, dimension, combiner='mean', initializer=None, shared_embedding_collection_name=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True): _TPUBaseEmbeddingColumn.__init__( self, categorical_column, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn) self._key = None def get_combiner(self): return self.combiner def get_embedding_table_size(self): """Returns num_ids and width.""" return (self.categorical_column._num_buckets, self.dimension) def get_feature_key_name(self): """get_feature_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.categorical_column.name return self.categorical_column.name def get_weight_key_name(self): """get_weight_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.weight_feature_key return None def get_embedding_var_name(self): """get_embedding_var_name.""" return self.shared_embedding_collection_name def get_initializer(self): return self.initializer def is_categorical_column_weighted(self): """Check if the categorical column of the embedding column is weighted.""" if isinstance( self.categorical_column, ( fc._WeightedCategoricalColumn, # pylint: disable=protected-access fc_lib.WeightedCategoricalColumn)): return True return False def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc._SharedEmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc._SharedEmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) # TPU mode # Get the embeddings from the LazyBuilder. tensor = inputs.get(self.get_feature_key_name()) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', is_shared_embedding=True) return tensor def _get_sequence_dense_tensor( self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc._SharedEmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc._SharedEmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) tensor = inputs.get(self.get_feature_key_name()) tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', is_shared_embedding=True) return fc._SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=tensor, sequence_length=tensor_lengths) def _record_variable_scope_and_name(embedding_var_name, embedding_var_name_in_fc, is_shared_embedding=False, bypass_scope_validation=False): """Add embedding variable name and scope to collection.""" g = ops.get_default_graph() collection = g.get_collection_ref(_TPU_FC_TO_SCOPE) if not collection: collection.append({}) var_def_dict = collection[0] captured_scope = variable_scope.get_variable_scope() captured_scope_name = captured_scope.name if embedding_var_name in var_def_dict: if (var_def_dict[embedding_var_name][0] != captured_scope_name and not is_shared_embedding and not bypass_scope_validation): raise ValueError( 'For embedding var name {}, the variable scope name is different, ' 'got {}; expected {}'.format(embedding_var_name, captured_scope_name, var_def_dict[embedding_var_name][0])) if var_def_dict[embedding_var_name][1] != embedding_var_name_in_fc: raise ValueError( 'For embedding var name {}, the embedding name is different, ' 'got {}; expected {}'.format(embedding_var_name, embedding_var_name_in_fc, var_def_dict[embedding_var_name][1])) else: var_def_dict[embedding_var_name] = (captured_scope_name, embedding_var_name_in_fc) def _is_running_on_cpu(): """Returns True if the current context is CPU model.""" return tpu_function.get_tpu_context().number_of_shards is None def get_sequence_length_feature_key_name_from_feature_key_name(feature_name): """Gets the name of the sequence length feature from that of the base feature. Args: feature_name: The feature key of a sequence column. Returns: A string which is the feature key for the associated feature length column. """ return feature_name + _SEQUENCE_FEATURE_LENGTH_POSTFIX def split_sequence_columns(feature_columns): """Split a list of _TPUEmbeddingColumn into sequence and non-sequence columns. For use in a TPUEstimator model_fn function. E.g. def model_fn(features): sequence_columns, feature_columns = ( tf.tpu.feature_column.split_sequence_columns(feature_columns)) input = tf.feature_column.input_layer( features=features, feature_columns=feature_columns) sequence_features, sequence_lengths = ( tf.contrib.feature_column.sequence_input_layer( features=features, feature_columns=sequence_columns)) Args: feature_columns: A list of _TPUEmbeddingColumns to split. Returns: Two lists of _TPUEmbeddingColumns, the first is the sequence columns and the second is the non-sequence columns. """ sequence_columns = [] non_sequence_columns = [] for column in feature_columns: if not isinstance(column, (_TPUEmbeddingColumn, _TPUSharedEmbeddingColumn)): raise TypeError( 'column must be a _TPUEmbeddingColumn or _TPUSharedEmbeddingColumn ' 'but got %s instead.' % (type(column))) if column.is_sequence_column(): sequence_columns.append(column) else: non_sequence_columns.append(column) return sequence_columns, non_sequence_columns
from collections import defaultdict from itertools import groupby import six import sqlalchemy as sa from sqlalchemy.exc import NoInspectionAvailable from sqlalchemy.orm import object_session from sqlalchemy.schema import ForeignKeyConstraint, MetaData, Table from ..query_chain import QueryChain from .orm import get_column_key, get_mapper, get_tables def get_foreign_key_values(fk, obj): return dict( ( fk.constraint.columns.values()[index].key, getattr(obj, element.column.key) ) for index, element in enumerate(fk.constraint.elements) ) def group_foreign_keys(foreign_keys): """ Return a groupby iterator that groups given foreign keys by table. :param foreign_keys: a sequence of foreign keys :: foreign_keys = get_referencing_foreign_keys(User) for table, fks in group_foreign_keys(foreign_keys): # do something pass .. seealso:: :func:`get_referencing_foreign_keys` .. versionadded: 0.26.1 """ foreign_keys = sorted( foreign_keys, key=lambda key: key.constraint.table.name ) return groupby(foreign_keys, lambda key: key.constraint.table) def get_referencing_foreign_keys(mixed): """ Returns referencing foreign keys for given Table object or declarative class. :param mixed: SA Table object or SA declarative class :: get_referencing_foreign_keys(User) # set([ForeignKey('user.id')]) get_referencing_foreign_keys(User.__table__) This function also understands inheritance. This means it returns all foreign keys that reference any table in the class inheritance tree. Let's say you have three classes which use joined table inheritance, namely TextItem, Article and BlogPost with Article and BlogPost inheriting TextItem. :: # This will check all foreign keys that reference either article table # or textitem table. get_referencing_foreign_keys(Article) .. seealso:: :func:`get_tables` """ if isinstance(mixed, sa.Table): tables = [mixed] else: tables = get_tables(mixed) referencing_foreign_keys = set() for table in mixed.metadata.tables.values(): if table not in tables: for constraint in table.constraints: if isinstance(constraint, sa.sql.schema.ForeignKeyConstraint): for fk in constraint.elements: if any(fk.references(t) for t in tables): referencing_foreign_keys.add(fk) return referencing_foreign_keys def merge_references(from_, to, foreign_keys=None): """ Merge the references of an entity into another entity. Consider the following models:: class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(255)) def __repr__(self): return 'User(name=%r)' % self.name class BlogPost(self.Base): __tablename__ = 'blog_post' id = sa.Column(sa.Integer, primary_key=True) title = sa.Column(sa.String(255)) author_id = sa.Column(sa.Integer, sa.ForeignKey('user.id')) author = sa.orm.relationship(User) Now lets add some data:: john = self.User(name='John') jack = self.User(name='Jack') post = self.BlogPost(title='Some title', author=john) post2 = self.BlogPost(title='Other title', author=jack) self.session.add_all([ john, jack, post, post2 ]) self.session.commit() If we wanted to merge all John's references to Jack it would be as easy as :: merge_references(john, jack) self.session.commit() post.author # User(name='Jack') post2.author # User(name='Jack') :param from_: an entity to merge into another entity :param to: an entity to merge another entity into :param foreign_keys: A sequence of foreign keys. By default this is None indicating all referencing foreign keys should be used. .. seealso: :func:`dependent_objects` .. versionadded: 0.26.1 """ if from_.__tablename__ != to.__tablename__: raise TypeError('The tables of given arguments do not match.') session = object_session(from_) foreign_keys = get_referencing_foreign_keys(from_) for fk in foreign_keys: old_values = get_foreign_key_values(fk, from_) new_values = get_foreign_key_values(fk, to) criteria = ( getattr(fk.constraint.table.c, key) == value for key, value in six.iteritems(old_values) ) try: mapper = get_mapper(fk.constraint.table) except ValueError: query = ( fk.constraint.table .update() .where(sa.and_(*criteria)) .values(new_values) ) session.execute(query) else: ( session.query(mapper.class_) .filter_by(**old_values) .update( new_values, 'evaluate' ) ) def dependent_objects(obj, foreign_keys=None): """ Return a :class:`~sqlalchemy_utils.query_chain.QueryChain` that iterates through all dependent objects for given SQLAlchemy object. Consider a User object is referenced in various articles and also in various orders. Getting all these dependent objects is as easy as:: from sqlalchemy_utils import dependent_objects dependent_objects(user) If you expect an object to have lots of dependent_objects it might be good to limit the results:: dependent_objects(user).limit(5) The common use case is checking for all restrict dependent objects before deleting parent object and inform the user if there are dependent objects with ondelete='RESTRICT' foreign keys. If this kind of checking is not used it will lead to nasty IntegrityErrors being raised. In the following example we delete given user if it doesn't have any foreign key restricted dependent objects:: from sqlalchemy_utils import get_referencing_foreign_keys user = session.query(User).get(some_user_id) deps = list( dependent_objects( user, ( fk for fk in get_referencing_foreign_keys(User) # On most databases RESTRICT is the default mode hence we # check for None values also if fk.ondelete == 'RESTRICT' or fk.ondelete is None ) ).limit(5) ) if deps: # Do something to inform the user pass else: session.delete(user) :param obj: SQLAlchemy declarative model object :param foreign_keys: A sequence of foreign keys to use for searching the dependent_objects for given object. By default this is None, indicating that all foreign keys referencing the object will be used. .. note:: This function does not support exotic mappers that use multiple tables .. seealso:: :func:`get_referencing_foreign_keys` .. seealso:: :func:`merge_references` .. versionadded: 0.26.0 """ if foreign_keys is None: foreign_keys = get_referencing_foreign_keys(obj) session = object_session(obj) chain = QueryChain([]) classes = obj.__class__._decl_class_registry for table, keys in group_foreign_keys(foreign_keys): keys = list(keys) for class_ in classes.values(): try: mapper = sa.inspect(class_) except NoInspectionAvailable: continue parent_mapper = mapper.inherits if ( table in mapper.tables and not (parent_mapper and table in parent_mapper.tables) ): query = session.query(class_).filter( sa.or_(*_get_criteria(keys, class_, obj)) ) chain.queries.append(query) return chain def _get_criteria(keys, class_, obj): criteria = [] visited_constraints = [] for key in keys: if key.constraint in visited_constraints: continue visited_constraints.append(key.constraint) subcriteria = [] for index, column in enumerate(key.constraint.columns): foreign_column = ( key.constraint.elements[index].column ) subcriteria.append( getattr(class_, get_column_key(class_, column)) == getattr( obj, sa.inspect(type(obj)) .get_property_by_column( foreign_column ).key ) ) criteria.append(sa.and_(*subcriteria)) return criteria def non_indexed_foreign_keys(metadata, engine=None): """ Finds all non indexed foreign keys from all tables of given MetaData. Very useful for optimizing postgresql database and finding out which foreign keys need indexes. :param metadata: MetaData object to inspect tables from """ reflected_metadata = MetaData() if metadata.bind is None and engine is None: raise Exception( 'Either pass a metadata object with bind or ' 'pass engine as a second parameter' ) constraints = defaultdict(list) for table_name in metadata.tables.keys(): table = Table( table_name, reflected_metadata, autoload=True, autoload_with=metadata.bind or engine ) for constraint in table.constraints: if not isinstance(constraint, ForeignKeyConstraint): continue if not is_indexed_foreign_key(constraint): constraints[table.name].append(constraint) return dict(constraints) def is_indexed_foreign_key(constraint): """ Whether or not given foreign key constraint's columns have been indexed. :param constraint: ForeignKeyConstraint object to check the indexes """ return any( set(constraint.columns.keys()) == set(column.name for column in index.columns) for index in constraint.table.indexes )
"""An object-local variable management scheme.""" # 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_io_ops as io_ops from tensorflow.python.util import nest # A key indicating a variable's value in an object's checkpointed Tensors # (Checkpointable._gather_saveables_for_checkpoint). If this is the only key and # the object has no dependencies, then its value may be restored on object # creation (avoiding double assignment when executing eagerly). VARIABLE_VALUE_KEY = "VARIABLE_VALUE" CheckpointableReference = collections.namedtuple( "CheckpointableReference", [ # The local name for this dependency. "name", # The Checkpointable object being referenced. "ref" ]) class CheckpointInitialValue(ops.Tensor): """Tensor wrapper for managing update UIDs in `Variables`. When supplied as an initial value, objects of this type let a `Variable` (`Variable`, `ResourceVariable`, etc.) know the UID of the restore the initial value came from. This allows deferred restorations to be sequenced in the order the user specified them, and lets us fall back on assignment if an initial value is not set (e.g. due to a custom getter interfering). See comments in _add_variable_with_custom_getter for more information about how `CheckpointInitialValue` is used. """ def __init__(self, checkpoint_position, shape=None): self.wrapped_value = checkpoint_position.value_tensors()[ VARIABLE_VALUE_KEY] if shape: # We need to set the static shape information on the initializer if # possible so we don't get a variable with an unknown shape. self.wrapped_value.set_shape(shape) self._checkpoint_position = checkpoint_position @property def __class__(self): return (self.wrapped_value.__class__, CheckpointInitialValue) def __getattr__(self, attr): try: return getattr(self.wrapped_value, attr) except AttributeError: return self.__getattribute__(attr) @property def checkpoint_position(self): return self._checkpoint_position class _CheckpointPosition(object): """Indicates a position within a `_Checkpoint`.""" def __init__(self, checkpoint, proto_id): """Specify an object within a checkpoint. Args: checkpoint: A _Checkpoint object. proto_id: The index of this object in CheckpointableObjectGraph.nodes. """ self._checkpoint = checkpoint self._proto_id = proto_id def restore(self, checkpointable): """Restore this value into `checkpointable`.""" with ops.init_scope(): if self.bind_object(checkpointable): # This object's correspondence with a checkpointed object is new, so # process deferred restorations for it and its dependencies. restore_ops = checkpointable._restore_from_checkpoint_position(self) # pylint: disable=protected-access if restore_ops: self._checkpoint.restore_ops.extend(restore_ops) def bind_object(self, checkpointable): """Set a checkpoint<->object correspondence and process slot variables. Args: checkpointable: The object to record a correspondence for. Returns: True if this is a new assignment, False if this object has already been mapped to a checkpointed `Object` proto. Raises: AssertionError: If another object is already bound to the `Object` proto. """ checkpoint = self.checkpoint current_assignment = checkpoint.object_by_proto_id.get(self._proto_id, None) if current_assignment is None: checkpoint.object_by_proto_id[self._proto_id] = checkpointable for deferred_slot_restoration in ( checkpoint.deferred_slot_restorations.pop(self._proto_id, ())): checkpointable._create_or_restore_slot_variable( # pylint: disable=protected-access slot_variable_position=_CheckpointPosition( checkpoint=checkpoint, proto_id=deferred_slot_restoration.slot_variable_id), variable=deferred_slot_restoration.original_variable, slot_name=deferred_slot_restoration.slot_name) for slot_restoration in checkpoint.slot_restorations.pop( self._proto_id, ()): optimizer_object = checkpoint.object_by_proto_id.get( slot_restoration.optimizer_id, None) if optimizer_object is None: # The optimizer has not yet been created or tracked. Record in the # checkpoint that the slot variables need to be restored when it is. checkpoint.deferred_slot_restorations.setdefault( slot_restoration.optimizer_id, []).append( _DeferredSlotVariableRestoration( original_variable=checkpointable, slot_variable_id=slot_restoration.slot_variable_id, slot_name=slot_restoration.slot_name)) else: optimizer_object._create_or_restore_slot_variable( # pylint: disable=protected-access slot_variable_position=_CheckpointPosition( checkpoint=checkpoint, proto_id=slot_restoration.slot_variable_id), variable=checkpointable, slot_name=slot_restoration.slot_name) return True # New assignment else: # The object was already mapped for this checkpoint load, which means # we don't need to do anything besides check that the mapping is # consistent (if the dependency DAG is not a tree then there are # multiple paths to the same object). if current_assignment is not checkpointable: raise AssertionError( ("Unable to load the checkpoint into this object graph. Either " "the Checkpointable object references in the Python program " "have changed in an incompatible way, or the checkpoint was " "generated in an incompatible program.\n\nTwo checkpoint " "references resolved to different objects (%s and %s).") % (current_assignment, checkpointable)) return False # Not a new assignment def is_simple_variable(self): """Determine whether this value is restorable with a Tensor initializer.""" attributes = self.object_proto.attributes return (len(attributes) == 1 and attributes[0].name == VARIABLE_VALUE_KEY and not self.object_proto.children) def value_tensors(self): """Create value `Tensor`s for this object's attributes. Does not require that the Python object has been created. Used for restore-on-create when executing eagerly. Returns: A dictionary mapping from object attribute names to `Tensor`s. """ value_tensors = {} for serialized_tensor in self.object_proto.attributes: checkpoint_key = serialized_tensor.checkpoint_key dtype = self._checkpoint.dtype_map[checkpoint_key] base_type = dtype.base_dtype with ops.init_scope(): with ops.device("/cpu:0"): # Run the restore itself on the CPU. value, = io_ops.restore_v2( prefix=self._checkpoint.save_path, tensor_names=[checkpoint_key], shape_and_slices=[""], dtypes=[base_type], name="%s_checkpoint_read" % (serialized_tensor.name,)) # Copy the value to the current device if necessary. value_tensors[serialized_tensor.name] = array_ops.identity(value) return value_tensors def restore_ops(self): """Create or fetch restore ops for this object's attributes. Requires that the `Checkpointable` Python object has been bound to an object ID in the checkpoint. Returns: A list of operations when graph building, or an empty list when executing eagerly. """ saveables = self.checkpointable._gather_saveables_for_checkpoint() # pylint: disable=protected-access # Name saveables based on the name this object had when it was checkpointed. named_saveables = {} restore_ops = [] building_graph = not context.executing_eagerly() for serialized_tensor in self.object_proto.attributes: saveable_factory = saveables.get(serialized_tensor.name, None) if saveable_factory is None: # Purposefully does not throw an exception if attributes have been added # or deleted. Stores unused attributes so an exception can be raised if # the user decides to check that everything in the checkpoint was # loaded. self._checkpoint.unused_attributes.setdefault( self.checkpointable, []).append(serialized_tensor.name) continue if building_graph: existing_ops = self._checkpoint.restore_ops_by_name.get( serialized_tensor.name, None) else: existing_ops = None if existing_ops is None: if callable(saveable_factory): saveable = saveable_factory(name=serialized_tensor.checkpoint_key) else: saveable = saveable_factory named_saveables[serialized_tensor.checkpoint_key] = saveable if named_saveables: validated_saveables = ( self._checkpoint.builder._ValidateAndSliceInputs(named_saveables)) # pylint: disable=protected-access validated_names = set(saveable.name for saveable in validated_saveables) if set(named_saveables.keys()) != validated_names: raise AssertionError( ("Saveable keys changed when validating. Got back %s, was " "expecting %s") % (named_saveables.keys(), validated_names)) all_tensors = self._checkpoint.builder.bulk_restore( filename_tensor=self._checkpoint.save_path, saveables=validated_saveables, preferred_shard=-1, restore_sequentially=False) saveable_index = 0 for saveable in validated_saveables: num_specs = len(saveable.specs) saveable_tensors = all_tensors[ saveable_index:saveable_index + num_specs] saveable_index += num_specs restore_op = saveable.restore(saveable_tensors, restored_shapes=None) if building_graph: assert saveable.name not in self._checkpoint.restore_ops_by_name self._checkpoint.restore_ops_by_name[saveable.name] = restore_op restore_ops.append(restore_op) return restore_ops @property def checkpoint(self): return self._checkpoint @property def checkpointable(self): return self._checkpoint.object_by_proto_id[self._proto_id] @property def object_proto(self): return self._checkpoint.object_graph_proto.nodes[self._proto_id] @property def restore_uid(self): return self._checkpoint.restore_uid def __repr__(self): return repr(self.object_proto) _DeferredSlotVariableRestoration = collections.namedtuple( "_DeferredSlotVariableRestoration", [ "original_variable", "slot_variable_id", "slot_name", ] ) _SlotVariableRestoration = collections.namedtuple( "_SlotVariableRestoration", [ # The checkpoint proto id of the optimizer object. "optimizer_id", # The checkpoint proto id of the slot variable. "slot_variable_id", "slot_name", ]) class CheckpointableBase(object): """Base class for `Checkpointable` objects without automatic dependencies. This class has no __setattr__ override for performance reasons. Dependencies must be added explicitly. Unless attribute assignment is performance-critical, use `Checkpointable` instead. Use `CheckpointableBase` for `isinstance` checks. """ def _maybe_initialize_checkpointable(self): """Initialize dependency management. Not __init__, since most objects will forget to call it. """ if hasattr(self, "_unconditional_checkpoint_dependencies"): # __init__ already called. This check means that we don't need # Checkpointable.__init__() in the constructor of every TensorFlow object. return # A list of CheckpointableReference objects. Some classes implementing # `Checkpointable`, notably `Optimizer`s, may override the # _checkpoint_dependencies property with conditional dependencies # (e.g. based on the current graph when saving). self._unconditional_checkpoint_dependencies = [] # Maps names -> Checkpointable objects self._unconditional_dependency_names = {} # Restorations for other Checkpointable objects on which this object may # eventually depend. Maps local name -> _CheckpointPosition list. Optimizers # tack on conditional dependencies, and so need separate management of # deferred dependencies too. self._unconditional_deferred_dependencies = {} # The UID of the highest assignment to this object. Used to ensure that the # last requested assignment determines the final value of an object. if hasattr(self, "_update_uid"): raise AssertionError( "Internal error: the object had an update UID set before its " "initialization code was run.") self._update_uid = -1 @property def _checkpoint_dependencies(self): """All dependencies of this object. May be overridden to include conditional dependencies. Returns: A list of `CheckpointableReference` objects indicating named `Checkpointable` dependencies which should be saved along with this object. """ return self._unconditional_checkpoint_dependencies @property def _deferred_dependencies(self): """A dictionary with deferred dependencies. Stores restorations for other Checkpointable objects on which this object may eventually depend. May be overridden by sub-classes (e.g. Optimizers use conditional dependencies based the current graph, and so need separate management of deferred dependencies too). Returns: A dictionary mapping from local name to a list of _CheckpointPosition objects. """ return self._unconditional_deferred_dependencies def _lookup_dependency(self, name): """Look up a dependency by name. May be overridden to include conditional dependencies. Args: name: The local name of the dependency. Returns: A `Checkpointable` object, or `None` if no dependency by this name was found. """ return self._unconditional_dependency_names.get(name, None) def _add_variable_with_custom_getter( self, name, shape=None, dtype=dtypes.float32, initializer=None, getter=None, overwrite=False, **kwargs_for_getter): """Restore-on-create for a variable be saved with this `Checkpointable`. If the user has requested that this object or another `Checkpointable` which depends on this object be restored from a checkpoint (deferred loading before variable object creation), `initializer` may be ignored and the value from the checkpoint used instead. Args: name: A name for the variable. Must be unique within this object. shape: The shape of the variable. dtype: The data type of the variable. initializer: The initializer to use. Ignored if there is a deferred restoration left over from a call to `_restore_from_checkpoint_position`. getter: The getter to wrap which actually fetches the variable. overwrite: If True, disables unique name and type checks. **kwargs_for_getter: Passed to the getter. Returns: The new variable object. Raises: ValueError: If the variable name is not unique. """ self._maybe_initialize_checkpointable() if not overwrite and self._lookup_dependency(name) is not None: raise ValueError( ("A variable named '%s' already exists in this Checkpointable, but " "Checkpointable._add_variable called to create another with " "that name. Variable names must be unique within a Checkpointable " "object.") % (name,)) with ops.init_scope(): if context.executing_eagerly(): # If this is a variable with a single Tensor stored in the checkpoint, # we can set that value as an initializer rather than initializing and # then assigning (when executing eagerly). This call returns None if # there is nothing to restore. checkpoint_initializer = self._preload_simple_restoration( name=name, shape=shape) else: checkpoint_initializer = None if (checkpoint_initializer is not None and not ( isinstance(initializer, CheckpointInitialValue) and (initializer.restore_uid > checkpoint_initializer.restore_uid))): # If multiple Checkpointable objects are "creating" the same variable # via the magic of custom getters, the one with the highest restore UID # (the one called last) has to make the final initializer. If another # custom getter interrupts this process by overwriting the initializer, # then we'll catch that when we call _track_checkpointable. So this is # "best effort" to set the initializer with the highest restore UID. initializer = checkpoint_initializer shape = None new_variable = getter( name=name, shape=shape, dtype=dtype, initializer=initializer, **kwargs_for_getter) # If we set an initializer and the variable processed it, tracking will not # assign again. It will add this variable to our dependencies, and if there # is a non-trivial restoration queued, it will handle that. This also # handles slot variables. if not overwrite or isinstance(new_variable, CheckpointableBase): return self._track_checkpointable(new_variable, name=name, overwrite=overwrite) else: # TODO(allenl): Some variable types are not yet supported. Remove this # fallback once all get_variable() return types are Checkpointable. return new_variable def _preload_simple_restoration(self, name, shape): """Return a dependency's value for restore-on-create. Note the restoration is not deleted; if for some reason preload is called and then not assigned to the variable (for example because a custom getter overrides the initializer), the assignment will still happen once the variable is tracked (determined based on checkpoint.restore_uid). Args: name: The object-local name of the dependency holding the variable's value. shape: The shape of the variable being loaded into. Returns: An callable for use as a variable's initializer/initial_value, or None if one should not be set (either because there was no variable with this name in the checkpoint or because it needs more complex deserialization). Any non-trivial deserialization will happen when the variable object is tracked. """ deferred_dependencies_list = self._deferred_dependencies.get(name, ()) if not deferred_dependencies_list: # Nothing to do; we don't have a restore for this dependency queued up. return for checkpoint_position in deferred_dependencies_list: if not checkpoint_position.is_simple_variable(): # If _any_ pending restoration is too complicated to fit in an # initializer (because it has dependencies, or because there are # multiple Tensors to restore), bail and let the general tracking code # handle it. return None checkpoint_position = max( deferred_dependencies_list, key=lambda restore: restore.checkpoint.restore_uid) return CheckpointInitialValue( checkpoint_position=checkpoint_position, shape=shape) def _track_checkpointable(self, checkpointable, name, overwrite=False): """Declare a dependency on another `Checkpointable` object. Indicates that checkpoints for this object should include variables from `checkpointable`. Variables in a checkpoint are mapped to `Checkpointable`s based on the names provided when the checkpoint was written. To avoid breaking existing checkpoints when modifying a class, neither variable names nor dependency names (the names passed to `_track_checkpointable`) may change. Args: checkpointable: A `Checkpointable` which this object depends on. name: A local name for `checkpointable`, used for loading checkpoints into the correct objects. overwrite: Boolean, whether silently replacing dependencies is OK. Used for __setattr__, where throwing an error on attribute reassignment would be inappropriate. Returns: `checkpointable`, for convenience when declaring a dependency and assigning to a member variable in one statement. Raises: TypeError: If `checkpointable` does not inherit from `Checkpointable`. ValueError: If another object is already tracked by this name. """ self._maybe_initialize_checkpointable() if not isinstance(checkpointable, CheckpointableBase): raise TypeError( ("Checkpointable._track_checkpointable() passed type %s, not a " "Checkpointable.") % (type(checkpointable),)) new_reference = CheckpointableReference(name=name, ref=checkpointable) current_object = self._lookup_dependency(name) if (current_object is not None and current_object is not checkpointable): if not overwrite: raise ValueError( ("Called Checkpointable._track_checkpointable() with name='%s', " "but a Checkpointable with this name is already declared as a " "dependency. Names must be unique (or overwrite=True).") % (name,)) # This is a weird thing to do, but we're not going to stop people from # using __setattr__. for index, (old_name, _) in enumerate( self._unconditional_checkpoint_dependencies): if name == old_name: self._unconditional_checkpoint_dependencies[index] = new_reference else: self._unconditional_checkpoint_dependencies.append(new_reference) self._unconditional_dependency_names[name] = checkpointable self._handle_deferred_dependencies(name=name, checkpointable=checkpointable) return checkpointable def _handle_deferred_dependencies(self, name, checkpointable): """Pop and load any deferred checkpoint restores into `checkpointable`. This method does not add a new dependency on `checkpointable`, but it does check if any outstanding/deferred dependencies have been queued waiting for this dependency to be added (matched based on `name`). If so, `checkpointable` and its dependencies are restored. The restorations are considered fulfilled and so are deleted. `_track_checkpointable` is more appropriate for adding a normal/unconditional dependency, and includes handling for deferred restorations. This method allows objects such as `Optimizer` to use the same restoration logic while managing conditional dependencies themselves, by overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the object's dependencies based on the context it is saved/restored in (a single optimizer instance can have state associated with multiple graphs). Args: name: The name of the dependency within this object (`self`), used to match `checkpointable` with values saved in a checkpoint. checkpointable: The Checkpointable object to restore (inheriting from `CheckpointableBase`). """ self._maybe_initialize_checkpointable() deferred_dependencies_list = self._deferred_dependencies.pop(name, ()) for checkpoint_position in sorted( deferred_dependencies_list, key=lambda restore: restore.checkpoint.restore_uid, reverse=True): checkpoint_position.restore(checkpointable) def _restore_from_checkpoint_position(self, checkpoint_position): """Restore this object and its dependencies (may be deferred).""" # Attempt a breadth-first traversal, since presumably the user has more # control over shorter paths. If we don't have all of the dependencies at # this point, the end result is not breadth-first (since other deferred # traversals will happen later). visit_queue = collections.deque([checkpoint_position]) restore_ops = [] while visit_queue: current_position = visit_queue.popleft() restore_ops.extend(nest.flatten( current_position.checkpointable # pylint: disable=protected-access ._single_restoration_from_checkpoint_position( checkpoint_position=current_position, visit_queue=visit_queue))) return restore_ops def _single_restoration_from_checkpoint_position( self, checkpoint_position, visit_queue): """Restore this object, and either queue its dependencies or defer them.""" self._maybe_initialize_checkpointable() checkpoint = checkpoint_position.checkpoint # If the UID of this restore is lower than our current update UID, we don't # need to actually restore the object. However, we should pass the # restoration on to our dependencies. if checkpoint.restore_uid > self._update_uid: restore_ops = checkpoint_position.restore_ops() # TODO(allenl): Get a list of feeds for saving Python state self._update_uid = checkpoint.restore_uid else: restore_ops = () for child in checkpoint_position.object_proto.children: child_position = _CheckpointPosition( checkpoint=checkpoint, proto_id=child.node_id) local_object = self._lookup_dependency(child.local_name) if local_object is None: # We don't yet have a dependency registered with this name. Save it # in case we do. self._deferred_dependencies.setdefault(child.local_name, []).append( child_position) else: if child_position.bind_object(checkpointable=local_object): # This object's correspondence is new, so dependencies need to be # visited. Delay doing it so that we get a breadth-first dependency # resolution order (shallowest paths first). The caller is responsible # for emptying visit_queue. visit_queue.append(child_position) return restore_ops def _gather_saveables_for_checkpoint(self): """Returns a dictionary of values to checkpoint with this object. Keys in the returned dictionary are local to this object and in a separate namespace from dependencies. Values may either be `SaveableObject` factories or variables easily converted to `SaveableObject`s (as in `tf.train.Saver`'s `var_list` constructor argument). `SaveableObjects` have a name set, which Checkpointable needs to generate itself. So rather than returning `SaveableObjects` directly, this method should return a dictionary of callables which take `name` arguments and return `SaveableObjects` with that name. If this object may also be passed to the global-name-based `tf.train.Saver`, the returned callables should have a default value for their name argument (i.e. be callable with no arguments). Returned values must be saved only by this object; if any value may be shared, it should instead be a dependency. For example, variable objects save their own values with the key `VARIABLE_VALUE_KEY`, but objects which reference variables simply add a dependency. Returns: The dictionary mapping attribute names to `SaveableObject` factories described above. For example: {VARIABLE_VALUE_KEY: lambda name="global_name_for_this_object": SaveableObject(name=name, ...)} """ return {} class Checkpointable(CheckpointableBase): """Manages dependencies on other objects. `Checkpointable` objects may have dependencies: other `Checkpointable` objects which should be saved if the object declaring the dependency is saved. A correctly saveable program has a dependency graph such that if changing a global variable affects an object (e.g. changes the behavior of any of its methods) then there is a chain of dependencies from the influenced object to the variable. Dependency edges have names, and are created implicitly when a `Checkpointable` object is assigned to an attribute of another `Checkpointable` object. For example: ``` obj = Checkpointable() obj.v = ResourceVariable(0.) ``` The `Checkpointable` object `obj` now has a dependency named "v" on a variable. `Checkpointable` objects may specify `Tensor`s to be saved and restored directly (e.g. a `Variable` indicating how to save itself) rather than through dependencies on other objects. See `Checkpointable._gather_saveables_for_checkpoint` for details. """ def __setattr__(self, name, value): """Support self.foo = checkpointable syntax.""" # Perform the attribute assignment, and potentially call other __setattr__ # overrides such as that for tf.keras.Model. super(Checkpointable, self).__setattr__(name, value) if isinstance(value, CheckpointableBase): self._track_checkpointable( value, name=name, # Allow the user to switch the Checkpointable which is tracked by this # name, since assigning a new variable to an attribute has # historically been fine (e.g. Adam did this). # TODO(allenl): Should this be a warning once Checkpointable save/load # is usable? overwrite=True)
"""Representation of data arguments in QCalls in ELAPS:PlayMat.""" from __future__ import division from numbers import Number from PyQt4 import QtCore, QtGui from elaps import defines from elaps import signature class QDataArg(QtGui.QLineEdit): """Operand argument representation.""" def __init__(self, UI_call, *args, **kwargs): """Initialize the operand representation.""" QtGui.QLineEdit.__init__(self, *args, **kwargs) self.UI_call = UI_call self.playmat = UI_call.playmat self.offsetstr = None self.polygonmin = None self.linesminfront = None self.linesminback = None self.polygonmax = None self.linesmaxfront = None self.linesmaxback = None self.UI_init() @property def call(self): """Get the call.""" return self.UI_call.call def UI_init(self): """Initialize the GUI element.""" self.setAlignment(QtCore.Qt.AlignHCenter) self.setValidator(QtGui.QRegExpValidator( QtCore.QRegExp("[a-zA-Z][a-zA-Z0-9_]*"), self )) # style self.setStyleSheet(""" [invalid="true"] { background: #FFDDDD; } [invalid="false"]:!focus:!hover { background: transparent; border: none; } """) def paintEvent(self, event): """Paint the representation.""" if not self.linesminfront: # nothing to draw return QtGui.QLineEdit.paintEvent(self, event) brushes = self.playmat.brushes pens = self.playmat.pens painter = QtGui.QPainter(self) # max painter.setBrush(brushes["max"]) painter.setPen(pens[None]) painter.drawPolygon(self.polygonmax) painter.setPen(pens["maxback"]) painter.drawLines(self.linesmaxback) painter.setPen(pens["maxfront"]) painter.drawLines(self.linesmaxfront) # min painter.setBrush(brushes["min"]) painter.setPen(pens[None]) painter.drawPolygon(self.polygonmin) painter.setPen(pens["minback"]) painter.drawLines(self.linesminback) painter.setPen(pens["minfront"]) painter.drawLines(self.linesminfront) # offset if self.offsetstr: painter.drawText( QtCore.QRect(2, 2, self.width() - 4, self.height() - 4), QtCore.Qt.AlignBottom | QtCore.Qt.AlignRight, self.offsetstr ) # draw input on top painter.end() return QtGui.QLineEdit.paintEvent(self, event) # setters def setsize(self, height, width): """Set the size of the widget.""" sizehint = QtGui.QLineEdit().minimumSizeHint() fontmetrics = self.fontMetrics() minheight = sizehint.height() minwidth = sizehint.width() + fontmetrics.width(self.text()) minwidth = max(minwidth, minheight) if self.offsetstr: minheight += 3 * fontmetrics.height() + 8 minwidth = max(minwidth, fontmetrics.width(self.offsetstr) + 4) fixedwidth = max(width, minwidth) fixedheight = max(height, minheight) self.setFixedSize(fixedwidth, fixedheight) hoff = max(0, (minheight - height) // 2) woff = max(0, (minwidth - width) // 2) return hoff, woff def viz(self): """Visualization update.""" call = self.call value = call[self.argid] ex = self.playmat.experiment if value not in ex.operands: self.viz_none() return data = ex.get_operand(value) vary = ex.vary[value] dims = data["dims"] # vary self.offsetstr = None if vary["with"]: self.offsetstr = "" if len(dims) > 1: if vary["along"] < 3: self.offsetstr += u"\u2193\u2192\u2197"[vary["along"]] else: self.offsetstr += str(vary["along"]) self.offsetstr += ",".join(map(str, vary["with"])) if vary["offset"]: self.offsetstr += " + %s" % vary["offset"] # compute min and max from range dimmin = [] dimmax = [] for expr in dims: rangemin, rangemax = ex.ranges_eval_minmax(expr) if rangemin is None or rangemax is None: self.viz_none() return dimmin.append(rangemin) dimmax.append(rangemax) if float("inf") in dimmin or -float("inf") in dimmax: # something is not bounded self.viz_none() return if not all(isinstance(dim, Number) for dim in dimmin + dimmax): # something is not a number self.viz_none() return if ex.operands_maxdim() is None: # something with the range went wrong self.viz_none() return if isinstance(call.sig[self.argid], signature.Work): # maximum height for work maxdim = max(1, ex.operands_maxdim()) if dimmax[0] > maxdim: dims = [0, 0] dimmin = [maxdim, dimmin[0] // maxdim] dimmax = [maxdim, dimmax[0] // maxdim] if len(dims) == 1: self.viz_vector(dimmin, dimmax) elif len(dims) == 2: self.viz_matrix(dimmin, dimmax) elif len(dims) == 3: self.viz_tensor(dimmin, dimmax) def viz_none(self): """Empty visualization.""" self.setsize(0, 0) self.offsetstr = None self.polygonmax = None self.linesmaxfront = None self.linesmaxback = None self.polygonmin = None self.linesminfront = None self.linesminback = None def viz_vector(self, dimmin, dimmax): """Visualize a vector.""" self.viz_matrix(dimmin + [1], dimmax + [1]) def viz_matrix(self, dimmin, dimmax): """Visualize a matrix.""" ex = self.playmat.experiment scale = (self.playmat.viz_scale / max(1, ex.operands_maxdim())) dimmin = [int(round(scale * dim)) for dim in dimmin] dimmax = [int(round(scale * dim)) for dim in dimmax] call = ex.calls[self.UI_call.callid] properties = call.properties(self.argid) for prop in properties: if prop in ("lower", "upper"): self.viz_triangular(dimmin, dimmax, properties) return self.viz_tensor(dimmin + [1], dimmax + [1]) def viz_triangular(self, dimmin, dimmax, properties): """Visualize a triangular matrix.""" # compute total size and offsets h, w = dimmax hoff, woff = self.setsize(h + 1, w + 1) # maximum h, w = dimmax points = [[QtCore.QPoint(woff + x, hoff + y) for x in (0, w)] for y in (0, h)] if "lower" in properties: self.polygonmax = QtGui.QPolygon([ points[0][0], points[1][0], points[1][1], points[0][0], ]) self.linesmaxfront = [ QtCore.QLine(points[0][0], points[1][0]), # | QtCore.QLine(points[1][0], points[1][1]), # - QtCore.QLine(points[1][1], points[0][0]), # \ ] else: self.polygonmax = QtGui.QPolygon([ points[0][0], points[1][1], points[0][1], points[0][0], ]) self.linesmaxfront = [ QtCore.QLine(points[0][0], points[1][1]), # \ QtCore.QLine(points[1][1], points[0][1]), # | QtCore.QLine(points[0][1], points[0][0]), # - ] self.linesmaxback = [] if "symm" in properties or "herm" in properties: self.linesmaxback = [ QtCore.QLine(points[0][0], points[1][0]), # | QtCore.QLine(points[1][0], points[1][1]), # - QtCore.QLine(points[1][1], points[0][1]), # | QtCore.QLine(points[0][1], points[0][0]), # - ] # minimum h, w = dimmin points = [[QtCore.QPoint(woff + x, hoff + y) for x in (0, w)] for y in (0, h)] if "lower" in properties: self.polygonmin = QtGui.QPolygon([ points[0][0], points[1][0], points[1][1], points[0][0], ]) self.linesminfront = [ QtCore.QLine(points[0][0], points[1][0]), # | QtCore.QLine(points[1][0], points[1][1]), # - QtCore.QLine(points[1][1], points[0][0]), # \ ] else: self.polygonmin = QtGui.QPolygon([ points[0][0], points[1][1], points[0][1], points[0][0], ]) self.linesminfront = [ QtCore.QLine(points[0][0], points[1][1]), # \ QtCore.QLine(points[1][1], points[0][1]), # | QtCore.QLine(points[0][1], points[0][0]), # - ] self.linesminback = [] if "symm" in properties or "herm" in properties: self.linesminback = [ QtCore.QLine(points[0][0], points[1][0]), # | QtCore.QLine(points[1][0], points[1][1]), # - QtCore.QLine(points[1][1], points[0][1]), # | QtCore.QLine(points[0][1], points[0][0]), # - ] def viz_tensor(self, dimmin, dimmax): """Visualize a Tensor.""" # compute total size and offsets h, w, d = dimmax hoff, woff = self.setsize(h + d // 2 + 1, w + d // 2 + 1) # maximum h, w, d = dimmax points = [[[QtCore.QPoint(woff + x + z // 2, hoff + y + (d - z) // 2) for z in (0, d)] for x in (0, w)] for y in (0, h)] self.polygonmax = QtGui.QPolygon([ points[0][0][0], points[1][0][0], points[1][1][0], points[1][1][1], points[0][1][1], points[0][0][1], ]) self.linesmaxfront = [ QtCore.QLine(points[0][0][0], points[0][0][1]), # / QtCore.QLine(points[0][1][0], points[0][1][1]), # / QtCore.QLine(points[1][1][0], points[1][1][1]), # / QtCore.QLine(points[0][0][0], points[0][1][0]), # - QtCore.QLine(points[0][0][1], points[0][1][1]), # - QtCore.QLine(points[1][0][0], points[1][1][0]), # - QtCore.QLine(points[0][0][0], points[1][0][0]), # | QtCore.QLine(points[0][1][0], points[1][1][0]), # | QtCore.QLine(points[0][1][1], points[1][1][1]), # | ] self.linesmaxback = [ QtCore.QLine(points[1][0][0], points[1][0][1]), # / QtCore.QLine(points[1][0][1], points[1][1][1]), # - QtCore.QLine(points[0][0][1], points[1][0][1]), # | ] if d != 0: self.linesmaxback = [] # minimum h, w, d = dimmin points = [[[QtCore.QPoint(woff + x + z // 2, hoff + y + (d - z) // 2) for z in (0, d)] for x in (0, w)] for y in (0, h)] self.polygonmin = QtGui.QPolygon([ points[0][0][0], points[1][0][0], points[1][1][0], points[1][1][1], points[0][1][1], points[0][0][1], ]) self.linesminfront = [ QtCore.QLine(points[0][0][0], points[0][0][1]), # / QtCore.QLine(points[0][1][0], points[0][1][1]), # / QtCore.QLine(points[1][1][0], points[1][1][1]), # / QtCore.QLine(points[0][0][0], points[0][1][0]), # - QtCore.QLine(points[0][0][1], points[0][1][1]), # - QtCore.QLine(points[1][0][0], points[1][1][0]), # - QtCore.QLine(points[0][0][0], points[1][0][0]), # | QtCore.QLine(points[0][1][0], points[1][1][0]), # | QtCore.QLine(points[0][1][1], points[1][1][1]), # | ] self.linesminback = [ QtCore.QLine(points[1][0][0], points[1][0][1]), # / QtCore.QLine(points[1][0][1], points[1][1][1]), # - QtCore.QLine(points[0][0][1], points[1][0][1]), # | ]
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from collections import OrderedDict from .conditions import * from .schema import Schema import warnings import logging from .java_classes import JString def _dq(x): return "JString(\"" + x.replace("\"", "\\\"") + "\")" def _to_camel(x, first_upper=False): tokens = x.split('_') if first_upper: y = '' for t in tokens: y += t[0].upper() + t[1:] else: y = tokens[0] for t in tokens[1:]: y += t[0].upper() + t[1:] return y def _dict_to_jmap(d, JMap): jmap = JMap() for k, v in d.items(): jmap.put(k, v) return jmap class TransformProcess(object): def __init__(self, schema, inplace=True): self.schema = schema self.final_schema = schema.copy() self.steps = [] self.executors = {} self.inplace = inplace def add_step(self, step, *args): self.steps.append((step,) + args) def remove_column(self, *columns): if len(columns) == 1: columns = columns[0] if type(columns) in (list, tuple): self.add_step("removeColumns", *columns) for c in columns: del self.final_schema.columns[c] else: self.add_step("removeColumns", columns) del self.final_schema.columns[columns] else: self.add_step("removeColumns", *columns) for c in columns: del self.final_schema.columns[c] if not self.inplace: return self def remove_columns_except(self, *columns): if len(columns) == 1: columns = columns[0] if type(columns) in (list, tuple): self.add_step("removeAllColumnsExceptFor", *columns) to_del = [] for c in self.final_schema.columns: if c not in columns: to_del.append(c) for c in to_del: del self.final_schema.columns[c] else: self.add_step("removeAllColumnsExceptFor", columns) to_del = [] for c in self.final_schema.columns: if c != columns: to_del.append(c) for c in to_del: del self.final_schema.columns[c] else: self.add_step("removeAllColumnsExceptFor", *columns) to_del = [] for c in self.final_schema.columns: if c not in columns: to_del.append(c) for c in to_del: del self.final_schema.columns[c] if not self.inplace: return self def filter(self, condition): col_name = condition.column col_type = self.final_schema.get_column_type(col_name) col_type = col_type[0].upper() + col_type[1:] if condition.name in ("InSet", "NotInSet"): code = "filter(ConditionFilter({}ColumnCondition({}, ConditionOp.{}, HashSet(Arrays.asList({})))))" code = code.format(col_type, _dq(col_name), condition.name, ','.join( [_dq(x) for x in condition.set])) else: code = "filter(ConditionFilter({}ColumnCondition({}, ConditionOp.{}, {})" code = code.format(col_type, _dq(col_name), condition.name, condition.value) self.add_step("exec", code) if not self.inplace: return self def replace(self, column, value, condition): # there are 2 columns involved # the column whose content we are replacing # and the column against which the condition is written column1_type = self.final_schema.get_column_type(column) column1_type = column1_type[0].upper() + column1_type[1:] column2 = condition.column column2_type = self.final_schema.get_column_type(column2) column2_type = column2_type[0].upper() + column2_type[1:] if condition.name in ("InSet", "NotInSet"): code = "conditionalReplaceValueTransform({}, {}Writable({}), {}ColumnCondition({}, ConditionOp.{}, HashSet(Arrays.asList({}))))" code = code.format(_dq(column), column1_type, value, column2_type, _dq( column2), condition.name, ','.join([_dq(x) for x in condition.set])) else: code = "conditionalReplaceValueTransform({}, {}Writable({}), {}ColumnCondition({}, ConditionOp.{}, {}))" code = code.format(_dq(column), column1_type, value, column2_type, _dq( column2), condition.name, condition.value) self.add_step("exec", code) if not self.inplace: return self def rename_column(self, column, new_name): new_d = OrderedDict() old_d = self.final_schema.columns for k in old_d: if k == column: new_d[new_name] = old_d[k] else: new_d[k] = old_d[k] self.final_schema.columns = new_d self.add_step("renameColumn", JString(column), JString(new_name)) if not self.inplace: return self def string_to_time(self, column, format="YYY-MM-DD HH:mm:ss.SSS", time_zone="UTC"): self.final_schema.columns[column][0] = "DateTime" py_string = "stringToTimeTransform({}, {}, {})".format(_dq(column), _dq(format), "DateTimeZone." + time_zone) self.add_step("exec", py_string) if not self.inplace: return self def derive_column_from_time(self, source_column, new_column, field): code = 'transform(DeriveColumnsFromTimeTransformBuilder({}).addIntegerDerivedColumn({}, DateTimeFieldType.{}()).build())' code = code.format(_dq(source_column), _dq( new_column), _to_camel(field)) self.add_step("exec", code) self.final_schema.add_column("integer", new_column) if not self.inplace: return self def categorical_to_integer(self, column): if self.final_schema.columns[column][0] != 'categorical': raise Exception('Can not apply categorical_to_integer' ' transform on column \"{}\" because it is not a categorcal column.'.format(column)) self.final_schema.columns[column][0] = 'integer' self.add_step('categoricalToInteger', column) if not self.inplace: return self def append_string(self, column, string): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply append_string transform to column {} because it is not a string column'.format(column)) self.add_step('appendStringColumnTransform', JString(column), JString(string)) if not self.inplace: return self def lower(self, column): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply lower transform to column {} because it is not a string column'.format(column)) self.add_step( 'exec', 'transform(ChangeCaseStringTransform({}, ChangeCaseStringTransformCaseType.LOWER))'.format(_dq(column))) if not self.inplace: return self def upper(self, column): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply lower transform to column {} because it is not a string column'.format(column)) self.add_step( 'exec', 'transform(ChangeCaseStringTransform({}, ChangeCaseStringTransformCaseType.UPPER))'.format(_dq(column))) if not self.inplace: return self def concat(self, columns, new_column=None, delimiter=','): for column in columns: if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply concat transform to column {} because it is not a string column'.format(column)) if new_column is None: new_column = 'concat({})'.format(','.join(columns)) if new_column in self.final_schema.columns: raise Exception( 'Another column with name {} already exists.'.format(new_column)) columns = [_dq(c) for c in columns] self.final_schema.add_string_column(new_column) self.add_step('exec', 'transform(ConcatenateStringColumns({}, {}, Arrays.asList({})))'.format( _dq(new_column), _dq(delimiter), ', '.join(columns))) if not self.inplace: return self def remove_white_spaces(self, column): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply remove_white_spaces transform to column {} because it is not a string column'.format(column)) self.add_step( 'exec', 'transform(RemoveWhiteSpaceTransform({}))'.format(_dq(column))) if not self.inplace: return self def replace_empty_string(self, column, value): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply replace_empty_string transform to column {} because it is not a string column'.format(column)) self.add_step('exec', 'transform(ReplaceEmptyStringTransform({}, {}))'.format( _dq(column), _dq(value))) if not self.inplace: return self def replace_string(self, column, *args): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply replace_string transform to column {} because it is not a string column'.format(column)) if len(args) == 1: args = args[0] assert type( args) is dict, 'Invalid argument. Possible signatures are replace(str, str, str) and replace(str, dict)' elif len(args) == 2: assert type(args[0]) == str and type( args[1]) == str, 'Invalid argument. Possible signatures are replace(str, str, str) and replace(str, dict)' args = {args[0]: args[1]} else: raise Exception( 'Invalid argument. Possible signatures are replace(str, str, str) and replace(str, dict)') self.add_step('exec', 'transform(ReplaceStringTransform({}, _dict_to_jmap({}, JMap)))'.format( _dq(column), str(args))) if not self.inplace: return self def map_string(self, column, mapping): if self.final_schema.columns[column][0] != 'string': raise Exception( 'Can not apply replace_string transform to column {} because it is not a string column'.format(column)) self.add_step('exec', 'transform(StringMapTransform({}, _dict_to_jmap({}, JMap)))'.format( _dq(column), str(mapping))) if not self.inplace: return self def one_hot(self, column): if self.final_schema.columns[column][0] != 'categorical': raise Exception( 'Can not apply one_hot transform to column {} because it is not a categorical column'.format(column)) categories = self.final_schema.columns[column][2:] new_col_names = [column + '[{}]'.format(cat) for cat in categories] new_schema = OrderedDict() for k in self.final_schema.columns: if k == column: for c in new_col_names: new_schema[c] = ['integer'] else: new_schema[k] = self.final_schema.columns[k] self.final_schema.columns = new_schema self.add_step('categoricalToOneHot', column) if not self.inplace: return self def reduce(self, key, *args, **kwargs): # possible signatures: # tp.reduce(column_name, default_redcution) # example: tp.reduce('person', 'sum') # sums all columns # tp.reduce(column, {'amount' : 'sum', 'hours' : 'mean'}) # Explicit reduction for each columns # tp.reduce(column, 'sum', {'hours' : 'mean'}) # Explicit reduction for some columns, default reduction for others # tp.reduce(column, 'sum', 'hours'='mean') # kwargs instead of dict if type(key) is str: key = [key] else: key = list(key) non_key_columns = [ x for x in self.final_schema.columns if x not in key] col_2_reduction = {} if args: if type(args[0]) is dict: default = None col_2_reduction = args[0] else: default = args[0] if len(args) > 1: assert type(args[1]) == dict, 'Expected dict' col_2_reduction = args[1] else: col_2_reduction = kwargs else: default = None col_2_reduction = kwargs reductions = ['min', 'max', 'sum', 'prod', 'mean', 'std', 'uncorrected_std', 'var', 'pop_var', 'count', 'range', 'count_unique', 'first', 'last', 'append', 'prepend'] if default is None: for k in non_key_columns: assert k in col_2_reduction, "Reduction not specified for column {}.".format( k) else: assert default in reductions, "Invalid default reduction {}. Valid redcutions are {}.".format( default, reductions) for k, v in col_2_reduction.items(): assert v in reductions, "Invalid redcution {} specified for column {}. Valid reductions are {}.".format( v, k, reductions) reduction_to_function = {'std': 'stdevColumns', 'uncorrected_std': 'uncorrectedStdevColumns', 'var': 'variance', 'pop_var': 'populationVariance', 'first': 'takeFirstColumns', 'last': 'takeLastColumns', 'max': 'maxColumn'} if default is None: default = col_2_reduction[list(col_2_reduction.keys())[0]] reduction_to_op = {'std': 'Stdev', 'uncorrected_std': 'UncorrectedStdDev', 'var': 'Variance', 'pop_var': 'PopulationVariance', 'first': 'TakeFirst', 'last': 'TakeLast'} default_op = reduction_to_op.get(default, _to_camel(default, True)) col_2_function = {} for k, v in col_2_reduction.items(): f = reduction_to_function.get(v, _to_camel(v) + 'Columns') col_2_function[k] = f code = 'reduce(ReducerBuilder(ReduceOp.{}).keyColumns({})'.format( default_op, ','.join([_dq(k) for k in key])) for c, f in col_2_function.items(): code += ".{}({})".format(f, _dq(c)) code += '.build())' self.add_step('exec', code) reduction_to_type = {} for r in ['mean', 'std', 'var', 'pop_var', 'uncorrected_std']: reduction_to_type[r] = 'double' for r in ['append', 'prepend']: reduction_to_type[r] = 'string' for r in ['count', 'count_unique']: reduction_to_type[r] = 'long' new_schema = OrderedDict() for k, v in self.final_schema.columns.items(): if k in key: new_schema[k] = v else: reduction = col_2_reduction.get(k, default) old_type = v[0] op = reduction_to_op.get(reduction, _to_camel(default, True)) new_name = op.lower() + '(' + k + ')' new_type = reduction_to_type.get(reduction, old_type) new_schema[k] = [new_type, new_name] self.final_schema.columns = new_schema if not self.inplace: return self def serialize(self): config = {'steps': self.steps, 'schema': self.schema.serialize()} return config @classmethod def deserialize(cls, config): schema = Schema.deserialize(config['schema']) tp = cls(schema) tp.steps = config['steps'][:] return tp # TODO from_java is used in konduit a lot def to_java(self): from .java_classes import TransformProcessBuilder from .java_classes import ConditionOp from .java_classes import ConditionFilter from .java_classes import BooleanColumnCondition from .java_classes import CategoricalColumnCondition from .java_classes import DoubleColumnCondition #from .java_classes import FloatColumnCondition from .java_classes import StringColumnCondition from .java_classes import DateTimeZone from .java_classes import DeriveColumnsFromTimeTransformBuilder from .java_classes import Arrays, HashSet from .java_classes import BooleanWritable from .java_classes import IntegerWritable from .java_classes import LongWritable from .java_classes import FloatWritable from .java_classes import DoubleWritable from .java_classes import DateTimeFieldType from .java_classes import ChangeCaseStringTransform from .java_classes import ChangeCaseStringTransformCaseType from .java_classes import ConcatenateStringColumns from .java_classes import RemoveWhiteSpaceTransform from .java_classes import ReplaceEmptyStringTransform from .java_classes import ReplaceStringTransform from .java_classes import StringMapTransform from .java_classes import JMap from .java_classes import Arrays from .java_classes import ReducerBuilder from .java_classes import ReduceOp from .java_classes import JString jschema = self.schema.to_java() builder = TransformProcessBuilder(jschema) for step in self.steps: if step[0] == "exec": code = step[1] logging.info(code) exec("builder." + code) else: f = getattr(builder, step[0]) f(*step[1:]) return builder.build() def __call__(self, csv, executor='spark'): try: executor = self.executors[executor] except: if executor == 'spark': from .java_classes import spark_available if not spark_available: warnings.warn( 'Spark not available. Running local executor instead.') from .executors import LocalExecutor executor = LocalExecutor() self.executors['local'] = executor self.executors['spark'] = executor else: from .executors import SparkExecutor executor = SparkExecutor() self.executors['spark'] = executor if executor == 'local': from .executors import LocalExecutor executor = LocalExecutor() self.executors['local'] = executor return executor(self, csv)
# 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 keystonemiddleware import auth_token from oslo_log import log from keystone.common import authorization from keystone.common import context from keystone.common import dependency from keystone.common import tokenless_auth from keystone.common import wsgi import keystone.conf from keystone import exception from keystone.federation import constants as federation_constants from keystone.federation import utils from keystone.i18n import _, _LI, _LW from keystone.middleware import core from keystone.models import token_model from keystone.token.providers import common CONF = keystone.conf.CONF LOG = log.getLogger(__name__) __all__ = ('AuthContextMiddleware',) @dependency.requires('token_provider_api') class AuthContextMiddleware(auth_token.BaseAuthProtocol): """Build the authentication context from the request auth token.""" kwargs_to_fetch_token = True def __init__(self, app): bind = CONF.token.enforce_token_bind super(AuthContextMiddleware, self).__init__(app, log=LOG, enforce_token_bind=bind) def fetch_token(self, token, **kwargs): try: return self.token_provider_api.validate_token(token) except exception.TokenNotFound: raise auth_token.InvalidToken(_('Could not find token')) def _build_tokenless_auth_context(self, request): """Build the authentication context. The context is built from the attributes provided in the env, such as certificate and scope attributes. """ tokenless_helper = tokenless_auth.TokenlessAuthHelper(request.environ) (domain_id, project_id, trust_ref, unscoped) = ( tokenless_helper.get_scope()) user_ref = tokenless_helper.get_mapped_user( project_id, domain_id) # NOTE(gyee): if it is an ephemeral user, the # given X.509 SSL client cert does not need to map to # an existing user. if user_ref['type'] == utils.UserType.EPHEMERAL: auth_context = {} auth_context['group_ids'] = user_ref['group_ids'] auth_context[federation_constants.IDENTITY_PROVIDER] = ( user_ref[federation_constants.IDENTITY_PROVIDER]) auth_context[federation_constants.PROTOCOL] = ( user_ref[federation_constants.PROTOCOL]) if domain_id and project_id: msg = _('Scoping to both domain and project is not allowed') raise ValueError(msg) if domain_id: auth_context['domain_id'] = domain_id if project_id: auth_context['project_id'] = project_id auth_context['roles'] = user_ref['roles'] else: # it's the local user, so token data is needed. token_helper = common.V3TokenDataHelper() token_data = token_helper.get_token_data( user_id=user_ref['id'], method_names=[CONF.tokenless_auth.protocol], domain_id=domain_id, project_id=project_id) auth_context = {'user_id': user_ref['id']} auth_context['is_delegated_auth'] = False if domain_id: auth_context['domain_id'] = domain_id if project_id: auth_context['project_id'] = project_id auth_context['roles'] = [role['name'] for role in token_data['token']['roles']] return auth_context def _validate_trusted_issuer(self, request): """To further filter the certificates that are trusted. If the config option 'trusted_issuer' is absent or does not contain the trusted issuer DN, no certificates will be allowed in tokenless authorization. :param env: The env contains the client issuer's attributes :type env: dict :returns: True if client_issuer is trusted; otherwise False """ if not CONF.tokenless_auth.trusted_issuer: return False issuer = request.environ.get(CONF.tokenless_auth.issuer_attribute) if not issuer: msg = _LI('Cannot find client issuer in env by the ' 'issuer attribute - %s.') LOG.info(msg, CONF.tokenless_auth.issuer_attribute) return False if issuer in CONF.tokenless_auth.trusted_issuer: return True msg = _LI('The client issuer %(client_issuer)s does not match with ' 'the trusted issuer %(trusted_issuer)s') LOG.info( msg, {'client_issuer': issuer, 'trusted_issuer': CONF.tokenless_auth.trusted_issuer}) return False @wsgi.middleware_exceptions def process_request(self, request): context_env = request.environ.get(core.CONTEXT_ENV, {}) if not context_env.get('is_admin', False): resp = super(AuthContextMiddleware, self).process_request(request) if resp: return resp # NOTE(jamielennox): function is split so testing can check errors from # fill_context. There is no actual reason for fill_context to raise # errors rather than return a resp, simply that this is what happened # before refactoring and it was easier to port. This can be fixed up # and the middleware_exceptions helper removed. self.fill_context(request) def fill_context(self, request): # The request context stores itself in thread-local memory for logging. request_context = context.RequestContext( request_id=request.environ.get('openstack.request_id'), authenticated=False, overwrite=True) request.environ[context.REQUEST_CONTEXT_ENV] = request_context if authorization.AUTH_CONTEXT_ENV in request.environ: msg = _LW('Auth context already exists in the request ' 'environment; it will be used for authorization ' 'instead of creating a new one.') LOG.warning(msg) return # NOTE(gyee): token takes precedence over SSL client certificates. # This will preserve backward compatibility with the existing # behavior. Tokenless authorization with X.509 SSL client # certificate is effectively disabled if no trusted issuers are # provided. if request.environ.get(core.CONTEXT_ENV, {}).get('is_admin', False): request_context.is_admin = True auth_context = {} elif request.token_auth.has_user_token: request_context.auth_token = request.user_token ref = token_model.KeystoneToken(token_id=request.user_token, token_data=request.token_info) auth_context = authorization.token_to_auth_context(ref) elif self._validate_trusted_issuer(request): auth_context = self._build_tokenless_auth_context(request) else: LOG.debug('There is either no auth token in the request or ' 'the certificate issuer is not trusted. No auth ' 'context will be set.') return # set authenticated to flag to keystone that a token has been validated request_context.authenticated = True # The attributes of request_context are put into the logs. This is a # common pattern for all the OpenStack services. In all the other # projects these are IDs, so set the attributes to IDs here rather than # the name. request_context.user_id = auth_context.get('user_id') request_context.project_id = auth_context.get('project_id') request_context.domain_id = auth_context.get('domain_id') request_context.domain_name = auth_context.get('domain_name') request_context.user_domain_id = auth_context.get('user_domain_id') request_context.roles = auth_context.get('roles') is_admin_project = auth_context.get('is_admin_project', True) request_context.is_admin_project = is_admin_project project_domain_id = auth_context.get('project_domain_id') request_context.project_domain_id = project_domain_id is_delegated_auth = auth_context.get('is_delegated_auth', False) request_context.is_delegated_auth = is_delegated_auth request_context.trust_id = auth_context.get('trust_id') request_context.trustor_id = auth_context.get('trustor_id') request_context.trustee_id = auth_context.get('trustee_id') access_token_id = auth_context.get('access_token_id') request_context.oauth_consumer_id = auth_context.get('consumer_id') request_context.oauth_acess_token_id = access_token_id LOG.debug('RBAC: auth_context: %s', auth_context) request.environ[authorization.AUTH_CONTEXT_ENV] = auth_context @classmethod def factory(cls, global_config, **local_config): """Used for paste app factories in paste.deploy config files. Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs. A hypothetical configuration would look like: [filter:analytics] redis_host = 127.0.0.1 paste.filter_factory = keystone.analytics:Analytics.factory which would result in a call to the `Analytics` class as import keystone.analytics keystone.analytics.Analytics(app, redis_host='127.0.0.1') You could of course re-implement the `factory` method in subclasses, but using the kwarg passing it shouldn't be necessary. """ def _factory(app): conf = global_config.copy() conf.update(local_config) return cls(app, **local_config) return _factory
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=protected-access """Wrapper layers: layers that augment the functionality of another layer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import backend as K from tensorflow.python.keras.engine.base_layer import InputSpec from tensorflow.python.keras.engine.base_layer import Layer from tensorflow.python.keras.layers.recurrent import _standardize_args from tensorflow.python.keras.utils import generic_utils from tensorflow.python.keras.utils import tf_utils from tensorflow.python.ops import array_ops from tensorflow.python.util.tf_export import tf_export @tf_export('keras.layers.Wrapper') class Wrapper(Layer): """Abstract wrapper base class. Wrappers take another layer and augment it in various ways. Do not use this class as a layer, it is only an abstract base class. Two usable wrappers are the `TimeDistributed` and `Bidirectional` wrappers. Arguments: layer: The layer to be wrapped. """ def __init__(self, layer, **kwargs): assert isinstance(layer, Layer) self.layer = layer self._track_checkpointable(layer, name='layer') # Tracks mapping of Wrapper inputs to inner layer inputs. Useful when # the inner layer has update ops that depend on its inputs (as opposed # to the inputs to the Wrapper layer). self._input_map = {} super(Wrapper, self).__init__(**kwargs) def build(self, input_shape=None): self.built = True @property def activity_regularizer(self): if hasattr(self.layer, 'activity_regularizer'): return self.layer.activity_regularizer else: return None @property def trainable(self): return self.layer.trainable @trainable.setter def trainable(self, value): self.layer.trainable = value @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property def losses(self): return self.layer.losses + self._losses def get_weights(self): return self.layer.get_weights() def set_weights(self, weights): self.layer.set_weights(weights) def get_config(self): config = { 'layer': { 'class_name': self.layer.__class__.__name__, 'config': self.layer.get_config() } } base_config = super(Wrapper, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top layer = deserialize_layer( config.pop('layer'), custom_objects=custom_objects) return cls(layer, **config) @tf_export('keras.layers.TimeDistributed') class TimeDistributed(Wrapper): """This wrapper allows to apply a layer to every temporal slice of an input. The input should be at least 3D, and the dimension of index one will be considered to be the temporal dimension. Consider a batch of 32 samples, where each sample is a sequence of 10 vectors of 16 dimensions. The batch input shape of the layer is then `(32, 10, 16)`, and the `input_shape`, not including the samples dimension, is `(10, 16)`. You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10 timesteps, independently: ```python # as the first layer in a model model = Sequential() model.add(TimeDistributed(Dense(8), input_shape=(10, 16))) # now model.output_shape == (None, 10, 8) ``` The output will then have shape `(32, 10, 8)`. In subsequent layers, there is no need for the `input_shape`: ```python model.add(TimeDistributed(Dense(32))) # now model.output_shape == (None, 10, 32) ``` The output will then have shape `(32, 10, 32)`. `TimeDistributed` can be used with arbitrary layers, not just `Dense`, for instance with a `Conv2D` layer: ```python model = Sequential() model.add(TimeDistributed(Conv2D(64, (3, 3)), input_shape=(10, 299, 299, 3))) ``` Arguments: layer: a layer instance. Raises: ValueError: If not initialized with a `Layer` instance. """ def __init__(self, layer, **kwargs): if not isinstance(layer, Layer): raise ValueError( 'Please initialize `TimeDistributed` layer with a ' '`Layer` instance. You passed: {input}'.format(input=layer)) super(TimeDistributed, self).__init__(layer, **kwargs) self.supports_masking = True def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() assert len(input_shape) >= 3 self.input_spec = InputSpec(shape=input_shape) child_input_shape = [input_shape[0]] + input_shape[2:] if not self.layer.built: # The base layer class calls a conversion function on the input shape to # convert it to a TensorShape. The conversion function requires a # tuple which is why we cast the shape. self.layer.build(tuple(child_input_shape)) self.layer.built = True super(TimeDistributed, self).build() self.built = True def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() child_input_shape = tensor_shape.TensorShape([input_shape[0]] + input_shape[2:]) child_output_shape = self.layer.compute_output_shape( child_input_shape).as_list() timesteps = input_shape[1] return tensor_shape.TensorShape([child_output_shape[0], timesteps] + child_output_shape[1:]) def call(self, inputs, training=None, mask=None): kwargs = {} if generic_utils.has_arg(self.layer.call, 'training'): kwargs['training'] = training uses_learning_phase = False # pylint: disable=redefined-outer-name input_shape = K.int_shape(inputs) if input_shape[0]: # batch size matters, use rnn-based implementation def step(x, _): global uses_learning_phase # pylint: disable=global-variable-undefined output = self.layer.call(x, **kwargs) if hasattr(output, '_uses_learning_phase'): uses_learning_phase = (output._uses_learning_phase or uses_learning_phase) return output, [] _, outputs, _ = K.rnn( step, inputs, initial_states=[], input_length=input_shape[1], unroll=False) y = outputs else: # No batch size specified, therefore the layer will be able # to process batches of any size. # We can go with reshape-based implementation for performance. input_length = input_shape[1] if not input_length: input_length = array_ops.shape(inputs)[1] # Shape: (num_samples * timesteps, ...). And track the # transformation in self._input_map. input_uid = generic_utils.object_list_uid(inputs) inputs = array_ops.reshape(inputs, (-1,) + input_shape[2:]) self._input_map[input_uid] = inputs # (num_samples * timesteps, ...) y = self.layer.call(inputs, **kwargs) if hasattr(y, '_uses_learning_phase'): uses_learning_phase = y._uses_learning_phase # Shape: (num_samples, timesteps, ...) output_shape = self.compute_output_shape(input_shape).as_list() y = array_ops.reshape(y, (-1, input_length) + tuple(output_shape[2:])) # Apply activity regularizer if any: if (hasattr(self.layer, 'activity_regularizer') and self.layer.activity_regularizer is not None): regularization_loss = self.layer.activity_regularizer(y) self.add_loss(regularization_loss, inputs) if uses_learning_phase: y._uses_learning_phase = True return y @tf_export('keras.layers.Bidirectional') class Bidirectional(Wrapper): """Bidirectional wrapper for RNNs. Arguments: layer: `Recurrent` instance. merge_mode: Mode by which outputs of the forward and backward RNNs will be combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the outputs will not be combined, they will be returned as a list. Raises: ValueError: If not initialized with a `Layer` instance or In case of invalid `merge_mode` argument. Examples: ```python model = Sequential() model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10))) model.add(Bidirectional(LSTM(10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') ``` """ def __init__(self, layer, merge_mode='concat', weights=None, **kwargs): if not isinstance(layer, Layer): raise ValueError( 'Please initialize `Bidirectional` layer with a ' '`Layer` instance. You passed: {input}'.format(input=layer)) if merge_mode not in ['sum', 'mul', 'ave', 'concat', None]: raise ValueError('Invalid merge mode. ' 'Merge mode should be one of ' '{"sum", "mul", "ave", "concat", None}') self.forward_layer = copy.copy(layer) config = layer.get_config() config['go_backwards'] = not config['go_backwards'] self.backward_layer = layer.__class__.from_config(config) self.forward_layer._name = 'forward_' + self.forward_layer.name self.backward_layer._name = 'backward_' + self.backward_layer.name self.merge_mode = merge_mode if weights: nw = len(weights) self.forward_layer.initial_weights = weights[:nw // 2] self.backward_layer.initial_weights = weights[nw // 2:] self.stateful = layer.stateful self.return_sequences = layer.return_sequences self.return_state = layer.return_state self.supports_masking = True self._trainable = True self._num_constants = None super(Bidirectional, self).__init__(layer, **kwargs) self.input_spec = layer.input_spec @property def trainable(self): return self._trainable @trainable.setter def trainable(self, value): self._trainable = value self.forward_layer.trainable = value self.backward_layer.trainable = value def get_weights(self): return self.forward_layer.get_weights() + self.backward_layer.get_weights() def set_weights(self, weights): nw = len(weights) self.forward_layer.set_weights(weights[:nw // 2]) self.backward_layer.set_weights(weights[nw // 2:]) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): output_shape = tuple(self.forward_layer.compute_output_shape( input_shape).as_list()) if self.return_state: state_shape = output_shape[1:] output_shape = output_shape[0] if self.merge_mode == 'concat': output_shape = list(output_shape) output_shape[-1] *= 2 output_shape = tuple(output_shape) elif self.merge_mode is None: output_shape = [output_shape, copy.copy(output_shape)] if self.return_state: if self.merge_mode is None: return output_shape + state_shape + copy.copy(state_shape) return [output_shape] + state_shape + copy.copy(state_shape) return output_shape def __call__(self, inputs, initial_state=None, constants=None, **kwargs): """`Bidirectional.__call__` implements the same API as the wrapped `RNN`.""" inputs, initial_state, constants = _standardize_args( inputs, initial_state, constants, self._num_constants) if isinstance(inputs, list): if len(inputs) > 1: initial_state = inputs[1:] inputs = inputs[0] if initial_state is None and constants is None: return super(Bidirectional, self).__call__(inputs, **kwargs) # Applies the same workaround as in `RNN.__call__` additional_inputs = [] additional_specs = [] if initial_state is not None: # Check if `initial_state` can be splitted into half num_states = len(initial_state) if num_states % 2 > 0: raise ValueError( 'When passing `initial_state` to a Bidirectional RNN, ' 'the state should be a list containing the states of ' 'the underlying RNNs. ' 'Found: ' + str(initial_state)) kwargs['initial_state'] = initial_state additional_inputs += initial_state state_specs = [InputSpec(shape=K.int_shape(state)) for state in initial_state] self.forward_layer.state_spec = state_specs[:num_states // 2] self.backward_layer.state_spec = state_specs[num_states // 2:] additional_specs += state_specs if constants is not None: kwargs['constants'] = constants additional_inputs += constants constants_spec = [InputSpec(shape=K.int_shape(constant)) for constant in constants] self.forward_layer.constants_spec = constants_spec self.backward_layer.constants_spec = constants_spec additional_specs += constants_spec self._num_constants = len(constants) self.forward_layer._num_constants = self._num_constants self.backward_layer._num_constants = self._num_constants is_keras_tensor = K.is_keras_tensor(additional_inputs[0]) for tensor in additional_inputs: if K.is_keras_tensor(tensor) != is_keras_tensor: raise ValueError('The initial state of a Bidirectional' ' layer cannot be specified with a mix of' ' Keras tensors and non-Keras tensors' ' (a "Keras tensor" is a tensor that was' ' returned by a Keras layer, or by `Input`)') if is_keras_tensor: # Compute the full input spec, including state full_input = [inputs] + additional_inputs full_input_spec = self.input_spec + additional_specs # Perform the call with temporarily replaced input_spec original_input_spec = self.input_spec self.input_spec = full_input_spec output = super(Bidirectional, self).__call__(full_input, **kwargs) self.input_spec = original_input_spec return output else: return super(Bidirectional, self).__call__(inputs, **kwargs) def call(self, inputs, training=None, mask=None, initial_state=None, constants=None): """`Bidirectional.call` implements the same API as the wrapped `RNN`.""" kwargs = {} if generic_utils.has_arg(self.layer.call, 'training'): kwargs['training'] = training if generic_utils.has_arg(self.layer.call, 'mask'): kwargs['mask'] = mask if generic_utils.has_arg(self.layer.call, 'constants'): kwargs['constants'] = constants if initial_state is not None and generic_utils.has_arg( self.layer.call, 'initial_state'): forward_state = initial_state[:len(initial_state) // 2] backward_state = initial_state[len(initial_state) // 2:] y = self.forward_layer.call(inputs, initial_state=forward_state, **kwargs) y_rev = self.backward_layer.call( inputs, initial_state=backward_state, **kwargs) else: y = self.forward_layer.call(inputs, **kwargs) y_rev = self.backward_layer.call(inputs, **kwargs) if self.return_state: states = y[1:] + y_rev[1:] y = y[0] y_rev = y_rev[0] if self.return_sequences: y_rev = K.reverse(y_rev, 1) if self.merge_mode == 'concat': output = K.concatenate([y, y_rev]) elif self.merge_mode == 'sum': output = y + y_rev elif self.merge_mode == 'ave': output = (y + y_rev) / 2 elif self.merge_mode == 'mul': output = y * y_rev elif self.merge_mode is None: output = [y, y_rev] # Properly set learning phase if (getattr(y, '_uses_learning_phase', False) or getattr(y_rev, '_uses_learning_phase', False)): if self.merge_mode is None: for out in output: out._uses_learning_phase = True else: output._uses_learning_phase = True if self.return_state: if self.merge_mode is None: return output + states return [output] + states return output def reset_states(self): self.forward_layer.reset_states() self.backward_layer.reset_states() def build(self, input_shape): with K.name_scope(self.forward_layer.name): self.forward_layer.build(input_shape) with K.name_scope(self.backward_layer.name): self.backward_layer.build(input_shape) self.built = True def compute_mask(self, inputs, mask): if isinstance(mask, list): mask = mask[0] if self.return_sequences: if not self.merge_mode: output_mask = [mask, mask] else: output_mask = mask else: output_mask = [None, None] if not self.merge_mode else None if self.return_state: states = self.forward_layer.states state_mask = [None for _ in states] if isinstance(output_mask, list): return output_mask + state_mask * 2 return [output_mask] + state_mask * 2 return output_mask @property def trainable_weights(self): if hasattr(self.forward_layer, 'trainable_weights'): return (self.forward_layer.trainable_weights + self.backward_layer.trainable_weights) return [] @property def non_trainable_weights(self): if hasattr(self.forward_layer, 'non_trainable_weights'): return (self.forward_layer.non_trainable_weights + self.backward_layer.non_trainable_weights) return [] @property def updates(self): if hasattr(self.forward_layer, 'updates'): return self.forward_layer.updates + self.backward_layer.updates return [] @property def losses(self): if hasattr(self.forward_layer, 'losses'): return self.forward_layer.losses + self.backward_layer.losses return [] @property def constraints(self): constraints = {} if hasattr(self.forward_layer, 'constraints'): constraints.update(self.forward_layer.constraints) constraints.update(self.backward_layer.constraints) return constraints def get_config(self): config = {'merge_mode': self.merge_mode} if self._num_constants is not None: config['num_constants'] = self._num_constants base_config = super(Bidirectional, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): num_constants = config.pop('num_constants', None) layer = super(Bidirectional, cls).from_config(config, custom_objects=custom_objects) layer._num_constants = num_constants return layer
#!/usr/bin/env python3 import os, sys, re device = "u4k" pins = "2 3 4 6 9 10 11 12 13 14 15 16 17 18 19 20 21 23 25 26 27 28 31 32 34 35 36 37 38 42 43 44 45 46 47 48".split() #up5k # pins = "2 3 4 6 9 10 11 12 13 18 19 20 21 25 26 27 28 31 32 34 35 36 37 38 42 43 44 45 46 47 48".split() # This is the master IP reverse engineering script for three similar IPs: I2C, SPI ip_types = ["I2C", "SPI"] ip_locs = { } ip_locs["I2C"] = [(0, 21, 0), (25, 21, 0)] ip_locs["SPI"] = [(0, 0, 0), (25, 0, 1)] #spram_locs = [(0, 0, 1)] ip_data = { } #up5k # ip_types = ["I2C", "SPI", "LEDDA_IP"] # ip_locs = { } # ip_locs["I2C"] = [(0, 31, 0), (25, 31, 0)] # ip_locs["SPI"] = [(0, 0, 0), (25, 0, 1)] # ip_locs["LEDDA_IP"] = [(0, 31, 2)] # #spram_locs = [(0, 0, 1)] # ip_data = { } #signals[x][0] -> inputs, signals[x][1] ->outputs ip_signals = {} ip_signals["I2C"] = [["SBCLKI", "SBRWI", "SBSTBI", "SCLI", "SDAI"], ["SBACKO", "I2CIRQ", "I2CWKUP", "SCLO", "SCLOE", "SDAO", "SDAOE"]] ip_signals["SPI"] = [["SBCLKI", "SBRWI", "SBSTBI", "MI", "SI", "SCKI", "SCSNI"], ["SBACKO", "SPIIRQ", "SPIWKUP", "SO", "SOE", "MO", "MOE", "SCKO", "SCKOE"]] fixed_cbits = {} fixed_cbits[("I2C", (0, 21, 0))] = ["BUS_ADDR74_0", "I2C_SLAVE_INIT_ADDR_0"] fixed_cbits[("I2C", (25, 21, 0))] = ["BUS_ADDR74_0", "BUS_ADDR74_1", "I2C_SLAVE_INIT_ADDR_1"] fixed_cbits[("SPI", (0, 0, 0))] = [] fixed_cbits[("SPI", (25, 0, 1))] = ["BUS_ADDR74_1"] # WARNING: this is documented as BUS_ADDR74_0, but this is wrong and will cause icecube to fail. May be the same across devices #up5k # fixed_cbits[("I2C", (0, 31, 0))] = ["BUS_ADDR74_0", "I2C_SLAVE_INIT_ADDR_0"] # fixed_cbits[("I2C", (25, 31, 0))] = ["BUS_ADDR74_0", "BUS_ADDR74_1", "I2C_SLAVE_INIT_ADDR_1"] # fixed_cbits[("SPI", (0, 10, 0))] = [] # fixed_cbits[("SPI", (25, 10, 1))] = ["BUS_ADDR74_1"] # WARNING: this is documented as BUS_ADDR74_0, but this is wrong and will cause icecube to fail. May be the same across devices fuzz_cbits = {} fuzz_cbits["I2C"] = ["SDA_INPUT_DELAYED", "SDA_OUTPUT_DELAYED"] # Don't add slave address to the list, despite confusing primitive declaration, # it's only set in registers not the bitstream #for i in range(2, 10): #fuzz_cbits["I2C"].append("I2C_SLAVE_INIT_ADDR_%d" % i) for i in range(8): ip_signals["I2C"][0].append("SBADRI%d" % i) ip_signals["SPI"][0].append("SBADRI%d" % i) for i in range(8): ip_signals["I2C"][0].append("SBDATI%d" % i) ip_signals["SPI"][0].append("SBDATI%d" % i) for i in range(8): ip_signals["I2C"][1].append("SBDATO%d" % i) ip_signals["SPI"][1].append("SBDATO%d" % i) for i in range(4): ip_signals["SPI"][1].append("MCSNO%d" % i) ip_signals["SPI"][1].append("MCSNOE%d" % i) fuzz_net_options = {} fuzz_net_options["I2C"] = ["SBADRI", "SBDATI", "SBDATO"] fuzz_net_options["SPI"] = ["SBADRI", "SBDATI", "SBDATO", "MCSN"] available_cbits = {} available_cbits["I2C"] = [("BUS_ADDR74", 4), ("I2C_SLAVE_INIT_ADDR", 10)] available_cbits["SPI"] = [("BUS_ADDR74", 4)] # Return a param value in "Lattice style" def get_param_value(param_size, param_name, set_cbits): val = "\"0b" for i in range(param_size): if param_name + "_" + str((param_size - 1) - i) in set_cbits: val += "1" else: val += "0" val += "\"" return val # Build the output files for a given IP and config, returning # the pin2net map def make_ip(ip_type, ip_loc, fuzz_opt, set_cbits): used_inputs = [ ] used_outputs = [ ] for insig in ip_signals[ip_type][0]: ignore = False for o in fuzz_net_options[ip_type]: if o != fuzz_opt and insig.startswith(o): ignore = True if not ignore: used_inputs.append(insig) for outsig in ip_signals[ip_type][1]: ignore = False for o in fuzz_net_options[ip_type]: if o != fuzz_opt and outsig.startswith(o): ignore = True if not ignore: used_outputs.append(outsig) all_sigs = used_inputs + used_outputs all_cbits = set() all_cbits.update(set_cbits) if (ip_type, ip_loc) in fixed_cbits: all_cbits.update(fixed_cbits[(ip_type, ip_loc)]) with open("./work_ip/ip.v", "w") as f: print("module top(", file=f) for s in used_inputs: print("input %s," % s, file=f) for s in used_outputs[:-1]: print("output %s," % s, file=f) print("output %s);" % used_outputs[-1], file=f) print("SB_%s" % ip_type, file=f) if ip_type in available_cbits: print("\t#(", file=f) for p in available_cbits[ip_type]: name, width = p comma = "," if p != available_cbits[ip_type][-1] else "" print("\t\t.%s(%s)%s" % (name, get_param_value(width, name, all_cbits), comma), file=f) print("\t)", file=f) print("\tip_inst (",file=f) for sig in all_sigs[:-1]: print("\t\t.%s(%s)," % (sig, sig), file=f) print("\t\t.%s(%s)" % (all_sigs[-1], all_sigs[-1]), file=f) print("\t)", file=f) if "SDA_INPUT_DELAYED" in all_cbits: print("\t/* synthesis SDA_INPUT_DELAYED=1 */", file=f) else: print("\t/* synthesis SDA_INPUT_DELAYED=0 */", file=f) if "SDA_OUTPUT_DELAYED" in all_cbits: print("\t/* synthesis SDA_OUTPUT_DELAYED=1 */", file=f) else: print("\t/* synthesis SDA_OUTPUT_DELAYED=0 */", file=f) print(";", file=f) print("endmodule", file=f) pin2net = {} with open("./work_ip/ip.pcf","w") as f: temp_pins = list(pins) for sig in all_sigs: if len(temp_pins) == 0: sys.stderr.write("ERROR: no remaining pins to alloc") sys.exit(1) pin = temp_pins.pop() pin2net[pin] = sig print("set_io %s %s" % (sig, pin), file=f) print("set_location ip_inst %d %d %d" % ip_loc, file=f) return pin2net def check_for_pin_assignment(pin): out = None with open("./work_ip/ip.vlog", "r") as f: for l in f: if l.startswith("assign pin_{}".format(pin)): rhs = l.split("=") o_cen = rhs[1].split(" ")[1] out = rhs[1].split(" ")[3] return out #Parse the output of an icebox vlog file to determine connectivity def parse_vlog(f, pin2net, net_map): wires_to_check = dict() current_net = None for line in f: if line == "\n": current_net = None m = re.match(r"wire ([a-zA-Z0-9_]+);", line) if m: net = m.group(1) mp = re.match(r"pin_([a-zA-Z0-9]+)", net) if mp: pin = mp.group(1) if pin in pin2net: current_net = pin2net[pin] else: current_net = None #search for assignment data_input = check_for_pin_assignment(pin) if data_input: wires_to_check[data_input] = pin else: current_net = None elif current_net is not None: m = re.match(r"// \((\d+), (\d+), '([a-zA-Z0-9_/]+)'\)", line) if m: x = int(m.group(1)) y = int(m.group(2)) net = m.group(3) if not (net.startswith("sp") or net.startswith("glb") or net.startswith("neigh") or net.startswith("io") or net.startswith("local") or net.startswith("fabout")): net_map[current_net].add((x, y, net)) f.seek(0) for line in f: if line == "\n": current_net = None m = re.match(r"wire ([a-zA-Z0-9]+);", line) if m: net = m.group(1) if net in wires_to_check: pin = wires_to_check[net] if pin in pin2net: current_net = pin2net[pin] else: current_net = None else: current_net = None elif current_net is not None: m = re.match(r"// \((\d+), (\d+), '([a-zA-Z0-9_/]+)'\)", line) if m: x = int(m.group(1)) y = int(m.group(2)) net = m.group(3) if not (net.startswith("sp") or net.startswith("glb") or net.startswith("neigh") or net.startswith("io") or net.startswith("local") or net.startswith("fabout")): net_map[current_net].add((x, y, net)) def parse_exp(f): current_x = 0 current_y = 0 bits = set() for line in f: splitline = line.split(' ') if splitline[0].endswith("_tile"): current_x = int(splitline[1]) current_y = int(splitline[2]) elif splitline[0] == "IpConfig": bits.add((current_x, current_y, splitline[1].strip())) return bits if not os.path.exists("./work_ip"): os.mkdir("./work_ip") for ip in ip_types: ip_data[ip] = {} for loc in ip_locs[ip]: x, y, z = loc net_cbit_map = {} init_cbits = [] for sig in ip_signals[ip][0]: net_cbit_map[sig] = set() for sig in ip_signals[ip][1]: net_cbit_map[sig] = set() first = True for state in ["FUZZ_NETS", "FUZZ_CBITS"]: fuzz_options = None if state == "FUZZ_NETS": fuzz_options = fuzz_net_options[ip] else: if ip in fuzz_cbits: fuzz_options = fuzz_cbits[ip] else: fuzz_options = [] for n in fuzz_options: # if n != "SBDATO": # continue print("Fuzzing %s (%d, %d, %d) %s" % (ip, x, y, z, n)) fuzz_nets = fuzz_net_options[ip][0] if state == "FUZZ_NETS": fuzz_nets = n set_cbits = set() if state == "FUZZ_CBITS": set_cbits.add(n) pin2net = make_ip(ip, loc, fuzz_nets, set_cbits) retval = os.system("bash ../../icecube.sh -" + device + " ./work_ip/ip.v > ./work_ip/icecube.log 2>&1") if retval != 0: sys.stderr.write('ERROR: icecube returned non-zero error code\n') sys.exit(1) retval = os.system("../../../icebox/icebox_explain.py ./work_ip/ip.asc > ./work_ip/ip.exp") if retval != 0: sys.stderr.write('ERROR: icebox_explain returned non-zero error code\n') sys.exit(1) retval = os.system("../../../icebox/icebox_vlog.py -l ./work_ip/ip.asc > ./work_ip/ip.vlog") if retval != 0: sys.stderr.write('ERROR: icebox_vlog returned non-zero error code\n') sys.exit(1) with open("./work_ip/ip.vlog", "r") as f: parse_vlog(f, pin2net, net_cbit_map) bits = [] with open("./work_ip/ip.exp", "r") as f: bits = parse_exp(f) if first: idx = 0 for bit in bits: init_cbits.append(bit) if len(bits) == 1: net_cbit_map[ip + "_ENABLE"] = [bit] else: net_cbit_map[ip + "_ENABLE_" + str(idx)] = [bit] idx += 1 for bit in init_cbits: if bit not in bits: bx, by, bn = bit print('WARNING: while fuzzing %s (%d, %d, %d) bit (%d, %d, %s) has unknown function (not always set)' % (ip, x, y, z, bx, by, bn)) new_bits = [] for bit in bits: if bit not in init_cbits: new_bits.append(bit) if state == "FUZZ_NETS" and len(new_bits) != 0: for bit in new_bits: bx, by, bn = bit print('WARNING: while fuzzing %s (%d, %d, %d) bit (%d, %d, %s) has unknown function (not always set)' % (ip, x, y, z, bx, by, bn)) elif state == "FUZZ_CBITS": if len(new_bits) == 0: print('WARNING: while fuzzing %s (%d, %d, %d) param %s causes no change' % (ip, x, y, z, n)) else: idx = 0 for bit in new_bits: if len(new_bits) == 1: net_cbit_map[n] = [bit] else: net_cbit_map[n + "_" + str(idx)] = [bit] idx += 1 first = False # if n == "SBDATO": # exit() ip_data[ip][loc] = net_cbit_map with open(device + "_" + ip + "_data.txt", "w") as f: for loc in ip_data[ip]: x, y, z = loc print("\t(\"%s\", (%d, %d, %d)): {" % (ip, x, y, z), file=f) data = ip_data[ip][loc] for net in sorted(data): cnets = [] for cnet in data[net]: cnets.append("(%d, %d, \"%s\")" % cnet) print("\t\t%s %s, " % (("\"" + net.replace("[","_").replace("]","") + "\":").ljust(24), " ".join(cnets)), file=f) print("\t},", file=f)
""" Contains the primary optimization and contraction routines. """ from collections import namedtuple from decimal import Decimal from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple from . import backends, blas, helpers, parser, paths, sharing from .typing import ArrayIndexType, ArrayType, Collection, ContractionListType, PathType __all__ = [ "contract_path", "contract", "format_const_einsum_str", "ContractExpression", "shape_only", ] class PathInfo: """A printable object to contain information about a contraction path. **Attributes:** - **naive_cost** - *(int)* The estimate FLOP cost of a naive einsum contraction. - **opt_cost** - *(int)* The estimate FLOP cost of this optimized contraction path. - **largest_intermediate** - *(int)* The number of elements in the largest intermediate array that will be produced during the contraction. """ def __init__( self, contraction_list: ContractionListType, input_subscripts: str, output_subscript: str, indices: ArrayIndexType, path: PathType, scale_list: Sequence[int], naive_cost: int, opt_cost: int, size_list: Sequence[int], size_dict: Dict[str, int], ): self.contraction_list = contraction_list self.input_subscripts = input_subscripts self.output_subscript = output_subscript self.path = path self.indices = indices self.scale_list = scale_list self.naive_cost = Decimal(naive_cost) self.opt_cost = Decimal(opt_cost) self.speedup = self.naive_cost / self.opt_cost self.size_list = size_list self.size_dict = size_dict self.shapes = [tuple(size_dict[k] for k in ks) for ks in input_subscripts.split(",")] self.eq = "{}->{}".format(input_subscripts, output_subscript) self.largest_intermediate = Decimal(max(size_list)) def __repr__(self) -> str: # Return the path along with a nice string representation header = ("scaling", "BLAS", "current", "remaining") path_print = [ " Complete contraction: {}\n".format(self.eq), " Naive scaling: {}\n".format(len(self.indices)), " Optimized scaling: {}\n".format(max(self.scale_list)), " Naive FLOP count: {:.3e}\n".format(self.naive_cost), " Optimized FLOP count: {:.3e}\n".format(self.opt_cost), " Theoretical speedup: {:.3e}\n".format(self.speedup), " Largest intermediate: {:.3e} elements\n".format(self.largest_intermediate), "-" * 80 + "\n", "{:>6} {:>11} {:>22} {:>37}\n".format(*header), "-" * 80, ] for n, contraction in enumerate(self.contraction_list): inds, idx_rm, einsum_str, remaining, do_blas = contraction if remaining is not None: remaining_str = ",".join(remaining) + "->" + self.output_subscript else: remaining_str = "..." size_remaining = max(0, 56 - max(22, len(einsum_str))) path_run = ( self.scale_list[n], do_blas, einsum_str, remaining_str, size_remaining, ) path_print.append("\n{:>4} {:>14} {:>22} {:>{}}".format(*path_run)) return "".join(path_print) def _choose_memory_arg(memory_limit: int, size_list: List[int]) -> Optional[int]: if memory_limit == "max_input": return max(size_list) if memory_limit is None: return None if memory_limit < 1: if memory_limit == -1: return None else: raise ValueError("Memory limit must be larger than 0, or -1") return int(memory_limit) _VALID_CONTRACT_KWARGS = { "optimize", "path", "memory_limit", "einsum_call", "use_blas", "shapes", } def contract_path(*operands_: Any, **kwargs: Any) -> Tuple[PathType, PathInfo]: """ Find a contraction order `path`, without performing the contraction. **Parameters:** - **subscripts** - *(str)* Specifies the subscripts for summation. - **\\*operands** - *(list of array_like)* hese are the arrays for the operation. - **use_blas** - *(bool)* Do you use BLAS for valid operations, may use extra memory for more intermediates. - **optimize** - *(str, list or bool, optional (default: `auto`))* Choose the type of path. - if a list is given uses this as the path. - `'optimal'` An algorithm that explores all possible ways of contracting the listed tensors. Scales factorially with the number of terms in the contraction. - `'dp'` A faster (but essentially optimal) algorithm that uses dynamic programming to exhaustively search all contraction paths without outer-products. - `'greedy'` An cheap algorithm that heuristically chooses the best pairwise contraction at each step. Scales linearly in the number of terms in the contraction. - `'random-greedy'` Run a randomized version of the greedy algorithm 32 times and pick the best path. - `'random-greedy-128'` Run a randomized version of the greedy algorithm 128 times and pick the best path. - `'branch-all'` An algorithm like optimal but that restricts itself to searching 'likely' paths. Still scales factorially. - `'branch-2'` An even more restricted version of 'branch-all' that only searches the best two options at each step. Scales exponentially with the number of terms in the contraction. - `'auto'` Choose the best of the above algorithms whilst aiming to keep the path finding time below 1ms. - `'auto-hq'` Aim for a high quality contraction, choosing the best of the above algorithms whilst aiming to keep the path finding time below 1sec. - **memory_limit** - *({None, int, 'max_input'} (default: `None`))* - Give the upper bound of the largest intermediate tensor contract will build. - None or -1 means there is no limit - `max_input` means the limit is set as largest input tensor - a positive integer is taken as an explicit limit on the number of elements The default is None. Note that imposing a limit can make contractions exponentially slower to perform. - **shapes** - *(bool, optional)* Whether ``contract_path`` should assume arrays (the default) or array shapes have been supplied. **Returns:** - **path** - *(list of tuples)* The einsum path - **PathInfo** - *(str)* A printable object containing various information about the path found. **Notes:** The resulting path indicates which terms of the input contraction should be contracted first, the result of this contraction is then appended to the end of the contraction list. **Examples:** We can begin with a chain dot example. In this case, it is optimal to contract the b and c tensors represented by the first element of the path (1, 2). The resulting tensor is added to the end of the contraction and the remaining contraction, `(0, 1)`, is then executed. ```python a = np.random.rand(2, 2) b = np.random.rand(2, 5) c = np.random.rand(5, 2) path_info = opt_einsum.contract_path('ij,jk,kl->il', a, b, c) print(path_info[0]) #> [(1, 2), (0, 1)] print(path_info[1]) #> Complete contraction: ij,jk,kl->il #> Naive scaling: 4 #> Optimized scaling: 3 #> Naive FLOP count: 1.600e+02 #> Optimized FLOP count: 5.600e+01 #> Theoretical speedup: 2.857 #> Largest intermediate: 4.000e+00 elements #> ------------------------------------------------------------------------- #> scaling current remaining #> ------------------------------------------------------------------------- #> 3 kl,jk->jl ij,jl->il #> 3 jl,ij->il il->il ``` A more complex index transformation example. ```python I = np.random.rand(10, 10, 10, 10) C = np.random.rand(10, 10) path_info = oe.contract_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C) print(path_info[0]) #> [(0, 2), (0, 3), (0, 2), (0, 1)] print(path_info[1]) #> Complete contraction: ea,fb,abcd,gc,hd->efgh #> Naive scaling: 8 #> Optimized scaling: 5 #> Naive FLOP count: 8.000e+08 #> Optimized FLOP count: 8.000e+05 #> Theoretical speedup: 1000.000 #> Largest intermediate: 1.000e+04 elements #> -------------------------------------------------------------------------- #> scaling current remaining #> -------------------------------------------------------------------------- #> 5 abcd,ea->bcde fb,gc,hd,bcde->efgh #> 5 bcde,fb->cdef gc,hd,cdef->efgh #> 5 cdef,gc->defg hd,defg->efgh #> 5 defg,hd->efgh efgh->efgh ``` """ # Make sure all keywords are valid unknown_kwargs = set(kwargs) - _VALID_CONTRACT_KWARGS if len(unknown_kwargs): raise TypeError("einsum_path: Did not understand the following kwargs: {}".format(unknown_kwargs)) path_type = kwargs.pop("optimize", "auto") memory_limit = kwargs.pop("memory_limit", None) shapes = kwargs.pop("shapes", False) # Hidden option, only einsum should call this einsum_call_arg = kwargs.pop("einsum_call", False) use_blas = kwargs.pop("use_blas", True) # Python side parsing input_subscripts, output_subscript, operands = parser.parse_einsum_input(operands_) # Build a few useful list and sets input_list = input_subscripts.split(",") input_sets = [frozenset(x) for x in input_list] if shapes: input_shapes = operands else: input_shapes = [x.shape for x in operands] output_set = frozenset(output_subscript) indices = frozenset(input_subscripts.replace(",", "")) # Get length of each unique dimension and ensure all dimensions are correct size_dict: Dict[str, int] = {} for tnum, term in enumerate(input_list): sh = input_shapes[tnum] if len(sh) != len(term): raise ValueError( "Einstein sum subscript '{}' does not contain the " "correct number of indices for operand {}.".format(input_list[tnum], tnum) ) for cnum, char in enumerate(term): dim = int(sh[cnum]) if char in size_dict: # For broadcasting cases we always want the largest dim size if size_dict[char] == 1: size_dict[char] = dim elif dim not in (1, size_dict[char]): raise ValueError( "Size of label '{}' for operand {} ({}) does not match previous " "terms ({}).".format(char, tnum, size_dict[char], dim) ) else: size_dict[char] = dim # Compute size of each input array plus the output array size_list = [helpers.compute_size_by_dict(term, size_dict) for term in input_list + [output_subscript]] memory_arg = _choose_memory_arg(memory_limit, size_list) num_ops = len(input_list) # Compute naive cost # This is not quite right, need to look into exactly how einsum does this # indices_in_input = input_subscripts.replace(',', '') inner_product = (sum(len(x) for x in input_sets) - len(indices)) > 0 naive_cost = helpers.flop_count(indices, inner_product, num_ops, size_dict) # Compute the path if not isinstance(path_type, (str, paths.PathOptimizer)): # Custom path supplied path = path_type elif num_ops <= 2: # Nothing to be optimized path = [tuple(range(num_ops))] elif isinstance(path_type, paths.PathOptimizer): # Custom path optimizer supplied path = path_type(input_sets, output_set, size_dict, memory_arg) else: path_optimizer = paths.get_path_fn(path_type) path = path_optimizer(input_sets, output_set, size_dict, memory_arg) cost_list = [] scale_list = [] size_list = [] contraction_list = [] # Build contraction tuple (positions, gemm, einsum_str, remaining) for cnum, contract_inds in enumerate(path): # Make sure we remove inds from right to left contract_inds = tuple(sorted(list(contract_inds), reverse=True)) contract_tuple = helpers.find_contraction(contract_inds, input_sets, output_set) out_inds, input_sets, idx_removed, idx_contract = contract_tuple # Compute cost, scale, and size cost = helpers.flop_count(idx_contract, bool(idx_removed), len(contract_inds), size_dict) cost_list.append(cost) scale_list.append(len(idx_contract)) size_list.append(helpers.compute_size_by_dict(out_inds, size_dict)) tmp_inputs = [input_list.pop(x) for x in contract_inds] tmp_shapes = [input_shapes.pop(x) for x in contract_inds] if use_blas: do_blas = blas.can_blas(tmp_inputs, "".join(out_inds), idx_removed, tmp_shapes) else: do_blas = False # Last contraction if (cnum - len(path)) == -1: idx_result = output_subscript else: # use tensordot order to minimize transpositions all_input_inds = "".join(tmp_inputs) idx_result = "".join(sorted(out_inds, key=all_input_inds.find)) shp_result = parser.find_output_shape(tmp_inputs, tmp_shapes, idx_result) input_list.append(idx_result) input_shapes.append(shp_result) einsum_str = ",".join(tmp_inputs) + "->" + idx_result # for large expressions saving the remaining terms at each step can # incur a large memory footprint - and also be messy to print if len(input_list) <= 20: remaining: Optional[Tuple[str, ...]] = tuple(input_list) else: remaining = None contraction = (contract_inds, idx_removed, einsum_str, remaining, do_blas) contraction_list.append(contraction) opt_cost = sum(cost_list) if einsum_call_arg: return operands, contraction_list # type: ignore path_print = PathInfo( contraction_list, input_subscripts, output_subscript, indices, path, scale_list, naive_cost, opt_cost, size_list, size_dict, ) return path, path_print @sharing.einsum_cache_wrap def _einsum(*operands, **kwargs): """Base einsum, but with pre-parse for valid characters if a string is given.""" fn = backends.get_func("einsum", kwargs.pop("backend", "numpy")) if not isinstance(operands[0], str): return fn(*operands, **kwargs) einsum_str, operands = operands[0], operands[1:] # Do we need to temporarily map indices into [a-z,A-Z] range? if not parser.has_valid_einsum_chars_only(einsum_str): # Explicitly find output str first so as to maintain order if "->" not in einsum_str: einsum_str += "->" + parser.find_output_str(einsum_str) einsum_str = parser.convert_to_valid_einsum_chars(einsum_str) return fn(einsum_str, *operands, **kwargs) def _default_transpose(x: ArrayType, axes: Tuple[int, ...]) -> ArrayType: # most libraries implement a method version return x.transpose(axes) @sharing.transpose_cache_wrap def _transpose(x: ArrayType, axes: Tuple[int, ...], backend: str = "numpy") -> ArrayType: """Base transpose.""" fn = backends.get_func("transpose", backend, _default_transpose) return fn(x, axes) @sharing.tensordot_cache_wrap def _tensordot(x: ArrayType, y: ArrayType, axes: Tuple[int, ...], backend: str = "numpy") -> ArrayType: """Base tensordot.""" fn = backends.get_func("tensordot", backend) return fn(x, y, axes=axes) # Rewrite einsum to handle different cases def contract(*operands_: Any, **kwargs: Any) -> ArrayType: """ Evaluates the Einstein summation convention on the operands. A drop in replacement for NumPy's einsum function that optimizes the order of contraction to reduce overall scaling at the cost of several intermediate arrays. **Parameters:** - **subscripts** - *(str)* Specifies the subscripts for summation. - **\\*operands** - *(list of array_like)* hese are the arrays for the operation. - **out** - *(array_like)* A output array in which set the sresulting output. - **dtype** - *(str)* The dtype of the given contraction, see np.einsum. - **order** - *(str)* The order of the resulting contraction, see np.einsum. - **casting** - *(str)* The casting procedure for operations of different dtype, see np.einsum. - **use_blas** - *(bool)* Do you use BLAS for valid operations, may use extra memory for more intermediates. - **optimize** - *(str, list or bool, optional (default: ``auto``))* Choose the type of path. - if a list is given uses this as the path. - `'optimal'` An algorithm that explores all possible ways of contracting the listed tensors. Scales factorially with the number of terms in the contraction. - `'dp'` A faster (but essentially optimal) algorithm that uses dynamic programming to exhaustively search all contraction paths without outer-products. - `'greedy'` An cheap algorithm that heuristically chooses the best pairwise contraction at each step. Scales linearly in the number of terms in the contraction. - `'random-greedy'` Run a randomized version of the greedy algorithm 32 times and pick the best path. - `'random-greedy-128'` Run a randomized version of the greedy algorithm 128 times and pick the best path. - `'branch-all'` An algorithm like optimal but that restricts itself to searching 'likely' paths. Still scales factorially. - `'branch-2'` An even more restricted version of 'branch-all' that only searches the best two options at each step. Scales exponentially with the number of terms in the contraction. - `'auto'` Choose the best of the above algorithms whilst aiming to keep the path finding time below 1ms. - `'auto-hq'` Aim for a high quality contraction, choosing the best of the above algorithms whilst aiming to keep the path finding time below 1sec. - **memory_limit** - *({None, int, 'max_input'} (default: `None`))* - Give the upper bound of the largest intermediate tensor contract will build. - None or -1 means there is no limit - `max_input` means the limit is set as largest input tensor - a positive integer is taken as an explicit limit on the number of elements The default is None. Note that imposing a limit can make contractions exponentially slower to perform. - **backend** - *(str, optional (default: ``auto``))* Which library to use to perform the required ``tensordot``, ``transpose`` and ``einsum`` calls. Should match the types of arrays supplied, See :func:`contract_expression` for generating expressions which convert numpy arrays to and from the backend library automatically. **Returns:** - **out** - *(array_like)* The result of the einsum expression. **Notes:** This function should produce a result identical to that of NumPy's einsum function. The primary difference is ``contract`` will attempt to form intermediates which reduce the overall scaling of the given einsum contraction. By default the worst intermediate formed will be equal to that of the largest input array. For large einsum expressions with many input arrays this can provide arbitrarily large (1000 fold+) speed improvements. For contractions with just two tensors this function will attempt to use NumPy's built-in BLAS functionality to ensure that the given operation is performed optimally. When NumPy is linked to a threaded BLAS, potential speedups are on the order of 20-100 for a six core machine. """ optimize_arg = kwargs.pop("optimize", True) if optimize_arg is True: optimize_arg = "auto" valid_einsum_kwargs = ["out", "dtype", "order", "casting"] einsum_kwargs = {k: v for (k, v) in kwargs.items() if k in valid_einsum_kwargs} # If no optimization, run pure einsum if optimize_arg is False: return _einsum(*operands_, **einsum_kwargs) # Grab non-einsum kwargs use_blas = kwargs.pop("use_blas", True) memory_limit = kwargs.pop("memory_limit", None) backend = kwargs.pop("backend", "auto") gen_expression = kwargs.pop("_gen_expression", False) constants_dict = kwargs.pop("_constants_dict", {}) # Make sure remaining keywords are valid for einsum unknown_kwargs = [k for (k, v) in kwargs.items() if k not in valid_einsum_kwargs] if len(unknown_kwargs): raise TypeError("Did not understand the following kwargs: {}".format(unknown_kwargs)) if gen_expression: full_str = operands_[0] # Build the contraction list and operand operands: Sequence[ArrayType] contraction_list: ContractionListType operands, contraction_list = contract_path( # type: ignore *operands_, optimize=optimize_arg, memory_limit=memory_limit, einsum_call=True, use_blas=use_blas ) # check if performing contraction or just building expression if gen_expression: return ContractExpression(full_str, contraction_list, constants_dict, **einsum_kwargs) return _core_contract(operands, contraction_list, backend=backend, **einsum_kwargs) def infer_backend(x: Any) -> str: return x.__class__.__module__.split(".")[0] def parse_backend(arrays: Sequence[ArrayType], backend: str) -> str: """Find out what backend we should use, dipatching based on the first array if ``backend='auto'`` is specified. """ if backend != "auto": return backend backend = infer_backend(arrays[0]) # some arrays will be defined in modules that don't implement tensordot # etc. so instead default to numpy if not backends.has_tensordot(backend): return "numpy" return backend def _core_contract( operands_: Sequence[ArrayType], contraction_list: ContractionListType, backend: str = "auto", evaluate_constants: bool = False, **einsum_kwargs: Any, ) -> ArrayType: """Inner loop used to perform an actual contraction given the output from a ``contract_path(..., einsum_call=True)`` call. """ # Special handling if out is specified out_array = einsum_kwargs.pop("out", None) specified_out = out_array is not None operands = list(operands_) backend = parse_backend(operands, backend) # try and do as much as possible without einsum if not available no_einsum = not backends.has_einsum(backend) # Start contraction loop for num, contraction in enumerate(contraction_list): inds, idx_rm, einsum_str, _, blas_flag = contraction # check if we are performing the pre-pass of an expression with constants, # if so, break out upon finding first non-constant (None) operand if evaluate_constants and any(operands[x] is None for x in inds): return operands, contraction_list[num:] tmp_operands = [operands.pop(x) for x in inds] # Do we need to deal with the output? handle_out = specified_out and ((num + 1) == len(contraction_list)) # Call tensordot (check if should prefer einsum, but only if available) if blas_flag and ("EINSUM" not in blas_flag or no_einsum): # type: ignore # Checks have already been handled input_str, results_index = einsum_str.split("->") input_left, input_right = input_str.split(",") tensor_result = "".join(s for s in input_left + input_right if s not in idx_rm) if idx_rm: # Find indices to contract over left_pos, right_pos = [], [] for s in idx_rm: left_pos.append(input_left.find(s)) right_pos.append(input_right.find(s)) # Construct the axes tuples in a canonical order axes = tuple(zip(*sorted(zip(left_pos, right_pos)))) else: # Ensure axes is always pair of tuples axes = ((), ()) # Contract! new_view = _tensordot(*tmp_operands, axes=axes, backend=backend) # Build a new view if needed if (tensor_result != results_index) or handle_out: transpose = tuple(map(tensor_result.index, results_index)) new_view = _transpose(new_view, axes=transpose, backend=backend) if handle_out: out_array[:] = new_view # Call einsum else: # If out was specified if handle_out: einsum_kwargs["out"] = out_array # Do the contraction new_view = _einsum(einsum_str, *tmp_operands, backend=backend, **einsum_kwargs) # Append new items and dereference what we can operands.append(new_view) del tmp_operands, new_view if specified_out: return out_array else: return operands[0] def format_const_einsum_str(einsum_str: str, constants: Iterable[int]) -> str: """Add brackets to the constant terms in ``einsum_str``. For example: >>> format_const_einsum_str('ab,bc,cd->ad', [0, 2]) 'bc,[ab,cd]->ad' No-op if there are no constants. """ if not constants: return einsum_str if "->" in einsum_str: lhs, rhs = einsum_str.split("->") arrow = "->" else: lhs, rhs, arrow = einsum_str, "", "" wrapped_terms = ["[{}]".format(t) if i in constants else t for i, t in enumerate(lhs.split(","))] formatted_einsum_str = "{}{}{}".format(",".join(wrapped_terms), arrow, rhs) # merge adjacent constants formatted_einsum_str = formatted_einsum_str.replace("],[", ",") return formatted_einsum_str class ContractExpression: """Helper class for storing an explicit ``contraction_list`` which can then be repeatedly called solely with the array arguments. """ def __init__( self, contraction: str, contraction_list: ContractionListType, constants_dict: Dict[int, ArrayType], **einsum_kwargs: Any, ): self.contraction_list = contraction_list self.einsum_kwargs = einsum_kwargs self.contraction = format_const_einsum_str(contraction, constants_dict.keys()) # need to know _full_num_args to parse constants with, and num_args to call with self._full_num_args = contraction.count(",") + 1 self.num_args = self._full_num_args - len(constants_dict) # likewise need to know full contraction list self._full_contraction_list = contraction_list self._constants_dict = constants_dict self._evaluated_constants: Dict[str, Any] = {} self._backend_expressions: Dict[str, Any] = {} def evaluate_constants(self, backend: str = "auto") -> None: """Convert any constant operands to the correct backend form, and perform as many contractions as possible to create a new list of operands, stored in ``self._evaluated_constants[backend]``. This also makes sure ``self.contraction_list`` only contains the remaining, non-const operations. """ # prepare a list of operands, with `None` for non-consts tmp_const_ops = [self._constants_dict.get(i, None) for i in range(self._full_num_args)] backend = parse_backend(tmp_const_ops, backend) # get the new list of operands with constant operations performed, and remaining contractions try: new_ops, new_contraction_list = backends.evaluate_constants(backend, tmp_const_ops, self) except KeyError: new_ops, new_contraction_list = self(*tmp_const_ops, backend=backend, evaluate_constants=True) self._evaluated_constants[backend] = new_ops self.contraction_list = new_contraction_list def _get_evaluated_constants(self, backend: str) -> List[Optional[ArrayType]]: """Retrieve or generate the cached list of constant operators (mixed in with None representing non-consts) and the remaining contraction list. """ try: return self._evaluated_constants[backend] except KeyError: self.evaluate_constants(backend) return self._evaluated_constants[backend] def _get_backend_expression(self, arrays: Sequence[ArrayType], backend: str) -> Any: try: return self._backend_expressions[backend] except KeyError: fn = backends.build_expression(backend, arrays, self) self._backend_expressions[backend] = fn return fn def _contract( self, arrays: Sequence[ArrayType], out: Optional[ArrayType] = None, backend: str = "auto", evaluate_constants: bool = False, ) -> ArrayType: """The normal, core contraction.""" contraction_list = self._full_contraction_list if evaluate_constants else self.contraction_list return _core_contract( list(arrays), contraction_list, out=out, backend=backend, evaluate_constants=evaluate_constants, **self.einsum_kwargs, ) def _contract_with_conversion( self, arrays: Sequence[ArrayType], out: Optional[ArrayType], backend: str, evaluate_constants: bool = False, ) -> ArrayType: """Special contraction, i.e., contraction with a different backend but converting to and from that backend. Retrieves or generates a cached expression using ``arrays`` as templates, then calls it with ``arrays``. If ``evaluate_constants=True``, perform a partial contraction that prepares the constant tensors and operations with the right backend. """ # convert consts to correct type & find reduced contraction list if evaluate_constants: return backends.evaluate_constants(backend, arrays, self) result = self._get_backend_expression(arrays, backend)(*arrays) if out is not None: out[()] = result return out return result def __call__(self, *arrays: ArrayType, **kwargs: Any) -> ArrayType: """Evaluate this expression with a set of arrays. Parameters ---------- arrays : seq of array The arrays to supply as input to the expression. out : array, optional (default: ``None``) If specified, output the result into this array. backend : str, optional (default: ``numpy``) Perform the contraction with this backend library. If numpy arrays are supplied then try to convert them to and from the correct backend array type. """ out = kwargs.pop("out", None) backend = parse_backend(arrays, kwargs.pop("backend", "auto")) evaluate_constants = kwargs.pop("evaluate_constants", False) if kwargs: raise ValueError( "The only valid keyword arguments to a `ContractExpression` " "call are `out=` or `backend=`. Got: {}.".format(kwargs) ) correct_num_args = self._full_num_args if evaluate_constants else self.num_args if len(arrays) != correct_num_args: raise ValueError( "This `ContractExpression` takes exactly {} array arguments " "but received {}.".format(self.num_args, len(arrays)) ) if self._constants_dict and not evaluate_constants: # fill in the missing non-constant terms with newly supplied arrays ops_var, ops_const = iter(arrays), self._get_evaluated_constants(backend) ops: Sequence[ArrayType] = [next(ops_var) if op is None else op for op in ops_const] else: ops = arrays try: # Check if the backend requires special preparation / calling # but also ignore non-numpy arrays -> assume user wants same type back if backends.has_backend(backend) and all(infer_backend(x) == "numpy" for x in arrays): return self._contract_with_conversion(ops, out, backend, evaluate_constants=evaluate_constants) return self._contract(ops, out, backend, evaluate_constants=evaluate_constants) except ValueError as err: original_msg = str(err.args) if err.args else "" msg = ( "Internal error while evaluating `ContractExpression`. Note that few checks are performed" " - the number and rank of the array arguments must match the original expression. " "The internal error was: '{}'".format(original_msg), ) err.args = msg raise def __repr__(self) -> str: if self._constants_dict: constants_repr = ", constants={}".format(sorted(self._constants_dict)) else: constants_repr = "" return "<ContractExpression('{}'{})>".format(self.contraction, constants_repr) def __str__(self) -> str: s = [self.__repr__()] for i, c in enumerate(self.contraction_list): s.append("\n {}. ".format(i + 1)) s.append("'{}'".format(c[2]) + (" [{}]".format(c[-1]) if c[-1] else "")) if self.einsum_kwargs: s.append("\neinsum_kwargs={}".format(self.einsum_kwargs)) return "".join(s) Shaped = namedtuple("Shaped", ["shape"]) def shape_only(shape: Collection[Tuple[int, ...]]) -> Shaped: """Dummy ``numpy.ndarray`` which has a shape only - for generating contract expressions. """ return Shaped(shape) def contract_expression(subscripts: str, *shapes: PathType, **kwargs: Any) -> Any: """Generate a reusable expression for a given contraction with specific shapes, which can, for example, be cached. **Parameters:** - **subscripts** - *(str)* Specifies the subscripts for summation. - **shapes** - *(sequence of integer tuples)* Shapes of the arrays to optimize the contraction for. - **constants** - *(sequence of int, optional)* The indices of any constant arguments in `shapes`, in which case the actual array should be supplied at that position rather than just a shape. If these are specified, then constant parts of the contraction between calls will be reused. Additionally, if a GPU-enabled backend is used for example, then the constant tensors will be kept on the GPU, minimizing transfers. - **kwargs** - Passed on to `contract_path` or `einsum`. See `contract`. **Returns:** - **expr** - *(ContractExpression)* Callable with signature `expr(*arrays, out=None, backend='numpy')` where the array's shapes should match `shapes`. **Notes:** - The `out` keyword argument should be supplied to the generated expression rather than this function. - The `backend` keyword argument should also be supplied to the generated expression. If numpy arrays are supplied, if possible they will be converted to and back from the correct backend array type. - The generated expression will work with any arrays which have the same rank (number of dimensions) as the original shapes, however, if the actual sizes are different, the expression may no longer be optimal. - Constant operations will be computed upon the first call with a particular backend, then subsequently reused. **Examples:** Basic usage: ```python expr = contract_expression("ab,bc->ac", (3, 4), (4, 5)) a, b = np.random.rand(3, 4), np.random.rand(4, 5) c = expr(a, b) np.allclose(c, a @ b) #> True ``` Supply `a` as a constant: ```python expr = contract_expression("ab,bc->ac", a, (4, 5), constants=[0]) expr #> <ContractExpression('[ab],bc->ac', constants=[0])> c = expr(b) np.allclose(c, a @ b) #> True ``` """ if not kwargs.get("optimize", True): raise ValueError("Can only generate expressions for optimized contractions.") for arg in ("out", "backend"): if kwargs.get(arg, None) is not None: raise ValueError( "'{}' should only be specified when calling a " "`ContractExpression`, not when building it.".format(arg) ) if not isinstance(subscripts, str): subscripts, shapes = parser.convert_interleaved_input((subscripts,) + shapes) kwargs["_gen_expression"] = True # build dict of constant indices mapped to arrays constants = kwargs.pop("constants", ()) constants_dict = {i: shapes[i] for i in constants} kwargs["_constants_dict"] = constants_dict # apart from constant arguments, make dummy arrays dummy_arrays = [s if i in constants else shape_only(s) for i, s in enumerate(shapes)] return contract(subscripts, *dummy_arrays, **kwargs)
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import unittest from contextlib import contextmanager from pathlib import Path from textwrap import dedent from typing import Iterator from pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest class GraphIntegrationTest(PantsRunIntegrationTest): @classmethod def use_pantsd_env_var(cls): """Some of the tests here expect to read the standard error after an intentional failure. However, when pantsd is enabled, these errors are logged to logs/exceptions.<pid>.log So stderr appears empty. (see #7320) """ return False _NO_BUILD_FILE_TARGET_BASE = "testprojects/src/python/no_build_file" _SOURCES_TARGET_BASE = "testprojects/src/python/sources" _BUNDLE_TARGET_BASE = "testprojects/src/java/org/pantsbuild/testproject/bundle" _ERR_TARGETS = { "testprojects/src/python/sources:some-missing-some-not": [ "['*.txt', '*.rs']", "Snapshot(PathGlobs(globs=('testprojects/src/python/sources/*.txt', 'testprojects/src/python/sources/*.rs'), glob_match_error_behavior<Exactly(GlobMatchErrorBehavior)>=GlobMatchErrorBehavior(value=error), conjunction<Exactly(GlobExpansionConjunction)>=GlobExpansionConjunction(value=all_match)))", 'Unmatched glob from testprojects/src/python/sources:some-missing-some-not\'s `sources` field: "testprojects/src/python/sources/*.rs"', ], "testprojects/src/python/sources:missing-sources": [ "*.scala", "Snapshot(PathGlobs(globs=('testprojects/src/python/sources/*.scala', '!testprojects/src/python/sources/*Test.scala', '!testprojects/src/python/sources/*Spec.scala'), glob_match_error_behavior<Exactly(GlobMatchErrorBehavior)>=GlobMatchErrorBehavior(value=error), conjunction<Exactly(GlobExpansionConjunction)>=GlobExpansionConjunction(value=any_match)))", 'Unmatched glob from testprojects/src/python/sources:missing-sources\'s `sources` field:: "testprojects/src/python/sources/*.scala", excludes: ["testprojects/src/python/sources/*Test.scala", "testprojects/src/python/sources/*Spec.scala"]', ], "testprojects/src/java/org/pantsbuild/testproject/bundle:missing-bundle-fileset": [ "['a/b/file1.txt']", "['*.aaaa', '*.bbbb']", "['*.aaaa']", "['**/*.abab']", "['file1.aaaa', 'file2.aaaa']", "Snapshot(PathGlobs(globs=('testprojects/src/java/org/pantsbuild/testproject/bundle/*.aaaa',), glob_match_error_behavior<Exactly(GlobMatchErrorBehavior)>=GlobMatchErrorBehavior(value=error), conjunction<Exactly(GlobExpansionConjunction)>=GlobExpansionConjunction(value=all_match)))", 'Unmatched glob from testprojects/src/java/org/pantsbuild/testproject/bundle:missing-bundle-fileset\'s `bundles` field:: "testprojects/src/java/org/pantsbuild/testproject/bundle/*.aaaa"', ], } @contextmanager def setup_sources_targets(self) -> Iterator[None]: build_path = Path(self._SOURCES_TARGET_BASE, "BUILD") original_content = build_path.read_text() new_content = dedent( """\ scala_library( name='missing-sources', ) resources( name='missing-literal-files', sources=[ 'nonexistent_test_file.txt', 'another_nonexistent_file.txt', ], ) resources( name='missing-globs', sources=['*.a'], ) resources( name='missing-rglobs', sources=['**/*.a'], ) resources( name='some-missing-some-not', sources=['*.txt', '*.rs'], ) resources( name='overlapping-globs', sources=['sources.txt', '*.txt'], ) """ ) with self.with_overwritten_file_content(build_path, f"{original_content}\n{new_content}"): yield @contextmanager def setup_bundle_target(self) -> Iterator[None]: build_path = Path(self._BUNDLE_TARGET_BASE, "BUILD") original_content = build_path.read_text() new_content = dedent( """\ jvm_app( name='missing-bundle-fileset', binary=':bundle-bin', bundles=[ bundle(fileset=['a/b/file1.txt']), bundle(fileset=['**/*.aaaa', '**/*.bbbb']), bundle(fileset=['*.aaaa']), bundle(fileset=['**/*.abab']), bundle(fileset=['file1.aaaa', 'file2.aaaa']), ], ) """ ) with self.with_overwritten_file_content(build_path, f"{original_content}\n{new_content}"): yield def test_missing_sources_warnings(self): target_to_unmatched_globs = { "missing-globs": ["*.a"], "missing-rglobs": ["**/*.a"], "missing-literal-files": ["another_nonexistent_file.txt", "nonexistent_test_file.txt"], } with self.setup_sources_targets(): for target in target_to_unmatched_globs: target_full = f"{self._SOURCES_TARGET_BASE}:{target}" pants_run = self.run_pants( ["filedeps", target_full], config={GLOBAL_SCOPE_CONFIG_SECTION: {"files_not_found_behavior": "warn"}}, ) self.assert_success(pants_run) unmatched_globs = target_to_unmatched_globs[target] formatted_globs = ", ".join( f'"{os.path.join(self._SOURCES_TARGET_BASE, glob)}"' for glob in unmatched_globs ) error_origin = f"from {self._SOURCES_TARGET_BASE}:{target}'s `sources` field" if len(unmatched_globs) == 1: assert ( f"[WARN] Unmatched glob {error_origin}: {formatted_globs}" in pants_run.stderr_data ) else: assert ( f"[WARN] Unmatched globs {error_origin}: [{formatted_globs}]" in pants_run.stderr_data ) def test_existing_sources(self): target_full = f"{self._SOURCES_TARGET_BASE}:text" pants_run = self.run_pants( ["filedeps", target_full], config={GLOBAL_SCOPE_CONFIG_SECTION: {"files_not_found_behavior": "warn"}}, ) self.assert_success(pants_run) assert "[WARN] Unmatched glob" not in pants_run.stderr_data def test_missing_bundles_warnings(self): target_full = f"{self._BUNDLE_TARGET_BASE}:missing-bundle-fileset" error_origin = f"from {target_full}'s `bundles` field" with self.setup_bundle_target(): pants_run = self.run_pants( ["filedeps", target_full], config={GLOBAL_SCOPE_CONFIG_SECTION: {"files_not_found_behavior": "warn"}}, ) self.assert_success(pants_run) unmatched_glob = ["*.aaaa", "**/*.abab"] unmatched_globs = [["**/*.aaaa", "**/*.bbbb"], ["file1.aaaa", "file2.aaaa"]] for glob in unmatched_glob: formatted_glob = f'"{os.path.join(self._BUNDLE_TARGET_BASE, glob)}"' assert ( f"[WARN] Unmatched glob {error_origin}: {formatted_glob}" in pants_run.stderr_data ) for globs in unmatched_globs: formatted_globs = ", ".join( f'"{os.path.join(self._BUNDLE_TARGET_BASE, glob)}"' for glob in globs ) assert ( f"[WARN] Unmatched globs {error_origin}: [{formatted_globs}]" in pants_run.stderr_data ) def test_existing_bundles(self): target_full = f"{self._BUNDLE_TARGET_BASE}:mapper" pants_run = self.run_pants( ["filedeps", target_full], config={GLOBAL_SCOPE_CONFIG_SECTION: {"files_not_found_behavior": "warn"}}, ) self.assert_success(pants_run) self.assertNotIn("[WARN] Unmatched glob", pants_run.stderr_data) def test_existing_directory_with_no_build_files_fails(self): pants_run = self.run_pants(["list", f"{self._NO_BUILD_FILE_TARGET_BASE}::"]) self.assert_failure(pants_run) self.assertIn("does not match any targets.", pants_run.stderr_data) @unittest.skip("Flaky: https://github.com/pantsbuild/pants/issues/6787") def test_error_message(self): with self.setup_bundle_target(), self.setup_sources_targets(): for target in self._ERR_TARGETS: expected_excerpts = self._ERR_TARGETS[target] pants_run = self.run_pants( ["filedeps", target], config={GLOBAL_SCOPE_CONFIG_SECTION: {"files_not_found_behavior": "error"}}, ) self.assert_failure(pants_run) for excerpt in expected_excerpts: self.assertIn(excerpt, pants_run.stderr_data)
## # Copyright (c) 2005-2014 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## import sys from hashlib import md5 from twisted.cred import error from twisted.internet import address from twisted.internet.defer import inlineCallbacks, returnValue from twisted.python import failure from txweb2.auth import digest from txweb2.auth.wrapper import UnauthorizedResponse from txweb2.test.test_server import SimpleRequest from twistedcaldav.directory.digest import QopDigestCredentialFactory from twistedcaldav.test.util import TestCase from twistedcaldav.config import config from txweb2.auth.digest import DigestCredentialFactory from txweb2.test.test_httpauth import makeDigestDeterministic from txweb2.test.test_httpauth import FAKE_STATIC_NONCE class FakeDigestCredentialFactory(QopDigestCredentialFactory): """ A Fake Digest Credential Factory that generates a predictable nonce and opaque """ def __init__(self, *args, **kwargs): super(FakeDigestCredentialFactory, self).__init__(*args, **kwargs) makeDigestDeterministic(self._real) clientAddress = address.IPv4Address('TCP', '127.0.0.1', 80) challengeOpaque = ('75c4bd95b96b7b7341c646c6502f0833-MTc4Mjg4NzU' '4NzE2MTIyMzkyODgxMjU0NzcwNjg1LHJlbW90ZWhvc3Q' 'sMA==') challengeNonce = '178288758716122392881254770685' challengeResponse = ('digest', {'nonce': challengeNonce, 'qop': 'auth', 'realm': 'test realm', 'algorithm': 'md5', }) cnonce = "29fc54aa1641c6fa0e151419361c8f23" authRequest1 = (('username="username", realm="test realm", nonce="%s", ' 'uri="/write/", response="%s", algorithm="md5", ' 'cnonce="29fc54aa1641c6fa0e151419361c8f23", nc=00000001, ' 'qop="auth"'), ('username="username", realm="test realm", nonce="%s", ' 'uri="/write/", response="%s", algorithm="md5"')) authRequest2 = (('username="username", realm="test realm", nonce="%s", ' 'uri="/write/", response="%s", algorithm="md5", ' 'cnonce="29fc54aa1641c6fa0e151419361c8f23", nc=00000002, ' 'qop="auth"'), ('username="username", realm="test realm", nonce="%s", ' 'uri="/write/", response="%s", algorithm="md5"')) authRequest3 = ('username="username", realm="test realm", nonce="%s", ' 'uri="/write/", response="%s", algorithm="md5"') authRequestComma = (('username="user,name", realm="test realm", nonce="%s", ' 'uri="/write/1,2.txt", response="%s", algorithm="md5", ' 'cnonce="29fc54aa1641c6fa0e151419361c8f23", nc=00000001, ' 'qop="auth"'), ('username="user,name", realm="test realm", nonce="%s", ' 'uri="/write/1,2.txt", response="%s", algorithm="md5"')) namelessAuthRequest = 'realm="test realm",nonce="doesn\'t matter"' emtpyAttributeAuthRequest = 'realm="",nonce="doesn\'t matter"' class DigestAuthTestCase(TestCase): """ Test the behavior of DigestCredentialFactory """ def setUp(self): """ Create a DigestCredentialFactory for testing """ TestCase.setUp(self) config.ProcessType = "Single" self.namespace1 = "DIGEST1" self.namespace2 = "DIGEST2" self.credentialFactories = (QopDigestCredentialFactory( 'md5', 'auth', 'test realm', self.namespace1 ), QopDigestCredentialFactory( 'md5', '', 'test realm', self.namespace2 )) def getDigestResponse(self, challenge, ncount): """ Calculate the response for the given challenge """ nonce = challenge.get('nonce') algo = challenge.get('algorithm').lower() qop = challenge.get('qop') if qop: expected = digest.calcResponse( digest.calcHA1(algo, "username", "test realm", "password", nonce, cnonce), algo, nonce, ncount, cnonce, qop, "GET", "/write/", None ) else: expected = digest.calcResponse( digest.calcHA1(algo, "username", "test realm", "password", nonce, cnonce), algo, nonce, None, None, None, "GET", "/write/", None ) return expected def getDigestResponseComma(self, challenge, ncount): """ Calculate the response for the given challenge """ nonce = challenge.get('nonce') algo = challenge.get('algorithm').lower() qop = challenge.get('qop') if qop: expected = digest.calcResponse( digest.calcHA1(algo, "user,name", "test realm", "password", nonce, cnonce), algo, nonce, ncount, cnonce, qop, "GET", "/write/1,2.txt", None ) else: expected = digest.calcResponse( digest.calcHA1(algo, "user,name", "test realm", "password", nonce, cnonce), algo, nonce, None, None, None, "GET", "/write/1,2.txt", None ) return expected @inlineCallbacks def assertRaisesDeferred(self, exception, f, *args, **kwargs): try: result = (yield f(*args, **kwargs)) except exception, inst: returnValue(inst) except: raise self.failureException('%s raised instead of %s:\n %s' % (sys.exc_info()[0], exception.__name__, failure.Failure().getTraceback())) else: raise self.failureException('%s not raised (%r returned)' % (exception.__name__, result)) @inlineCallbacks def test_getChallenge(self): """ Test that all the required fields exist in the challenge, and that the information matches what we put into our DigestCredentialFactory """ challenge = (yield self.credentialFactories[0].getChallenge(clientAddress)) self.assertEquals(challenge['qop'], 'auth') self.assertEquals(challenge['realm'], 'test realm') self.assertEquals(challenge['algorithm'], 'md5') self.assertTrue("nonce" in challenge) challenge = (yield self.credentialFactories[1].getChallenge(clientAddress)) self.assertFalse('qop' in challenge) self.assertEquals(challenge['realm'], 'test realm') self.assertEquals(challenge['algorithm'], 'md5') self.assertTrue("nonce" in challenge) @inlineCallbacks def test_response(self): """ Test that we can decode a valid response to our challenge """ for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkPassword('password')) @inlineCallbacks def test_multiResponse(self): """ Test that multiple responses to to a single challenge are handled successfully. """ for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkPassword('password')) clientResponse = authRequest2[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000002"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkPassword('password')) @inlineCallbacks def test_failsWithDifferentMethod(self): """ Test that the response fails if made for a different request method than it is being issued for. """ for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, SimpleRequest(None, 'POST', '/'))) self.failIf(creds.checkPassword('password')) @inlineCallbacks def test_noUsername(self): """ Test that login fails when our response does not contain a username, or the username field is empty. """ # Check for no username for factory in self.credentialFactories: e = (yield self.assertRaisesDeferred(error.LoginFailed, factory.decode, namelessAuthRequest, _trivial_GET())) self.assertEquals(str(e), "Invalid response, no username given.") # Check for an empty username e = (yield self.assertRaisesDeferred(error.LoginFailed, factory.decode, namelessAuthRequest + ',username=""', _trivial_GET())) self.assertEquals(str(e), "Invalid response, no username given.") @inlineCallbacks def test_noNonce(self): """ Test that login fails when our response does not contain a nonce """ for factory in self.credentialFactories: e = (yield self.assertRaisesDeferred(error.LoginFailed, factory.decode, 'realm="Test",username="Foo",opaque="bar"', _trivial_GET())) self.assertEquals(str(e), "Invalid response, no nonce given.") @inlineCallbacks def test_emptyAttribute(self): """ Test that login fails when our response contains an attribute with no value, """ # Check for no username for factory in self.credentialFactories: e = (yield self.assertRaisesDeferred(error.LoginFailed, factory.decode, emtpyAttributeAuthRequest, _trivial_GET())) self.assertEquals(str(e), "Invalid response, no username given.") @inlineCallbacks def test_checkHash(self): """ Check that given a hash of the form 'username:realm:password' we can verify the digest challenge """ for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkHash( md5('username:test realm:password').hexdigest())) self.failIf(creds.checkHash( md5('username:test realm:bogus').hexdigest())) @inlineCallbacks def test_invalidNonceCount(self): """ Test that login fails when the nonce-count is repeated. """ credentialFactories = ( FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.namespace1), FakeDigestCredentialFactory('md5', '', 'test realm', self.namespace2) ) for ctr, factory in enumerate(credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse1 = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) clientResponse2 = authRequest2[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000002"), ) yield factory.decode(clientResponse1, _trivial_GET()) yield factory.decode(clientResponse2, _trivial_GET()) if challenge.get('qop') is not None: yield self.assertRaisesDeferred( error.LoginFailed, factory.decode, clientResponse2, _trivial_GET() ) challenge = (yield factory.getChallenge(clientAddress)) clientResponse1 = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) del challenge['qop'] clientResponse3 = authRequest3 % ( challenge['nonce'], self.getDigestResponse(challenge, "00000002"), ) yield factory.decode(clientResponse1, _trivial_GET()) yield self.assertRaisesDeferred( error.LoginFailed, factory.decode, clientResponse3, _trivial_GET() ) @inlineCallbacks def test_invalidNonce(self): """ Test that login fails when the given nonce from the response, does not match the nonce encoded in the opaque. """ credentialFactories = ( FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.namespace1), FakeDigestCredentialFactory('md5', '', 'test realm', self.namespace2) ) for ctr, factory in enumerate(credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) challenge['nonce'] = "noNoncense" clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) request = _trivial_GET() yield self.assertRaisesDeferred( error.LoginFailed, factory.decode, clientResponse, request ) factory._invalidate(FAKE_STATIC_NONCE) response = (yield UnauthorizedResponse.makeResponse( {"Digest": factory}, request.remoteAddr )) response.headers.getHeader("www-authenticate")[0][1] @inlineCallbacks def test_oldNonce(self): """ Test that the login fails when the given opaque is older than DigestCredentialFactory.CHALLENGE_LIFETIME_SECS """ credentialFactories = ( FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.namespace1), FakeDigestCredentialFactory('md5', '', 'test realm', self.namespace2) ) for ctr, factory in enumerate(credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) nonce_count, timestamp = (yield factory.db.get(challenge['nonce'])) factory.db.set(challenge['nonce'], (nonce_count, timestamp - 2 * digest.DigestCredentialFactory.CHALLENGE_LIFETIME_SECS)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) request = _trivial_GET() yield self.assertRaisesDeferred( error.LoginFailed, factory.decode, clientResponse, request ) response = (yield UnauthorizedResponse.makeResponse( {"Digest": factory}, request.remoteAddr, )) wwwhdrs = response.headers.getHeader("www-authenticate")[0][1] self.assertTrue('stale' in wwwhdrs, msg="No stale parameter in Digest WWW-Authenticate headers: %s" % (wwwhdrs,)) self.assertEquals(wwwhdrs['stale'], 'true', msg="stale parameter not set to true in Digest WWW-Authenticate headers: %s" % (wwwhdrs,)) def test_incompatibleCalcHA1Options(self): """ Test that the appropriate error is raised when any of the pszUsername, pszRealm, or pszPassword arguments are specified with the preHA1 keyword argument. """ arguments = ( ("user", "realm", "password", "preHA1"), (None, "realm", None, "preHA1"), (None, None, "password", "preHA1"), ) for pszUsername, pszRealm, pszPassword, preHA1 in arguments: self.assertRaises( TypeError, digest.calcHA1, "md5", pszUsername, pszRealm, pszPassword, "nonce", "cnonce", preHA1=preHA1 ) @inlineCallbacks def test_commaURI(self): """ Check that commas in valued are parsed out properly. """ for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequestComma[ctr] % ( challenge['nonce'], self.getDigestResponseComma(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkPassword('password')) @inlineCallbacks def test_stale_response(self): """ Test that we can decode a valid response to our challenge """ theTime = 0 class newtime(object): def time(self): return theTime from twistedcaldav.directory import digest as ddigest self.patch(ddigest, "time", newtime()) for ctr, factory in enumerate(self.credentialFactories): challenge = (yield factory.getChallenge(clientAddress)) clientResponse = authRequest1[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000001"), ) creds = (yield factory.decode(clientResponse, _trivial_GET())) self.failUnless(creds.checkPassword('password')) theTime += DigestCredentialFactory.CHALLENGE_LIFETIME_SECS + 1 request = _trivial_GET() try: clientResponse = authRequest2[ctr] % ( challenge['nonce'], self.getDigestResponse(challenge, "00000002"), ) creds = (yield factory.decode(clientResponse, request)) self.fail("Nonce should have timed out") except error.LoginFailed: self.assertTrue(hasattr(request.remoteAddr, "stale")) except Exception, e: self.fail("Invalid exception from nonce timeout: %s" % e) challenge = (yield factory.getChallenge(request.remoteAddr)) self.assertTrue(challenge.get("stale") == "true") def _trivial_GET(): return SimpleRequest(None, 'GET', '/')
"""Test the Enphase Envoy config flow.""" from unittest.mock import MagicMock, patch import httpx from homeassistant import config_entries from homeassistant.components import zeroconf from homeassistant.components.enphase_envoy.const import DOMAIN from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_form(hass: HomeAssistant) -> None: """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ), patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.get_full_serial_number", return_value="1234", ), patch( "homeassistant.components.enphase_envoy.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Envoy 1234" assert result2["data"] == { "host": "1.1.1.1", "name": "Envoy 1234", "username": "test-username", "password": "test-password", } assert len(mock_setup_entry.mock_calls) == 1 async def test_user_no_serial_number(hass: HomeAssistant) -> None: """Test user setup without a serial number.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ), patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.get_full_serial_number", return_value=None, ), patch( "homeassistant.components.enphase_envoy.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Envoy" assert result2["data"] == { "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", } assert len(mock_setup_entry.mock_calls) == 1 async def test_user_fetching_serial_fails(hass: HomeAssistant) -> None: """Test user setup without a serial number.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ), patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.get_full_serial_number", side_effect=httpx.HTTPStatusError( "any", request=MagicMock(), response=MagicMock() ), ), patch( "homeassistant.components.enphase_envoy.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Envoy" assert result2["data"] == { "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", } assert len(mock_setup_entry.mock_calls) == 1 async def test_form_invalid_auth(hass: HomeAssistant) -> None: """Test we handle invalid auth.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", side_effect=httpx.HTTPStatusError( "any", request=MagicMock(), response=MagicMock() ), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "invalid_auth"} async def test_form_cannot_connect(hass: HomeAssistant) -> None: """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", side_effect=httpx.HTTPError("any"), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"} async def test_form_unknown_error(hass: HomeAssistant) -> None: """Test we handle unknown error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", side_effect=ValueError, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "unknown"} async def test_zeroconf(hass: HomeAssistant) -> None: """Test we can setup from zeroconf.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=zeroconf.ZeroconfServiceInfo( host="1.1.1.1", addresses=["1.1.1.1"], hostname="mock_hostname", name="mock_name", port=None, properties={"serialnum": "1234"}, type="mock_type", ), ) await hass.async_block_till_done() assert result["type"] == "form" assert result["step_id"] == "user" with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ), patch( "homeassistant.components.enphase_envoy.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Envoy 1234" assert result2["result"].unique_id == "1234" assert result2["data"] == { "host": "1.1.1.1", "name": "Envoy 1234", "username": "test-username", "password": "test-password", } assert len(mock_setup_entry.mock_calls) == 1 async def test_form_host_already_exists(hass: HomeAssistant) -> None: """Test host already exists.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", }, title="Envoy", ) config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) await hass.async_block_till_done() assert result2["type"] == "abort" assert result2["reason"] == "already_configured" async def test_zeroconf_serial_already_exists(hass: HomeAssistant) -> None: """Test serial number already exists from zeroconf.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", }, unique_id="1234", title="Envoy", ) config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=zeroconf.ZeroconfServiceInfo( host="1.1.1.1", addresses=["1.1.1.1"], hostname="mock_hostname", name="mock_name", port=None, properties={"serialnum": "1234"}, type="mock_type", ), ) assert result["type"] == "abort" assert result["reason"] == "already_configured" async def test_zeroconf_host_already_exists(hass: HomeAssistant) -> None: """Test hosts already exists from zeroconf.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", }, title="Envoy", ) config_entry.add_to_hass(hass) with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ), patch( "homeassistant.components.enphase_envoy.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=zeroconf.ZeroconfServiceInfo( host="1.1.1.1", addresses=["1.1.1.1"], hostname="mock_hostname", name="mock_name", port=None, properties={"serialnum": "1234"}, type="mock_type", ), ) await hass.async_block_till_done() assert result["type"] == "abort" assert result["reason"] == "already_configured" assert config_entry.unique_id == "1234" assert config_entry.title == "Envoy 1234" assert len(mock_setup_entry.mock_calls) == 1 async def test_reauth(hass: HomeAssistant) -> None: """Test we reauth auth.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ "host": "1.1.1.1", "name": "Envoy", "username": "test-username", "password": "test-password", }, title="Envoy", ) config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={ "source": config_entries.SOURCE_REAUTH, "unique_id": config_entry.unique_id, "entry_id": config_entry.entry_id, }, ) with patch( "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", return_value=True, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "test-username", "password": "test-password", }, ) assert result2["type"] == "abort" assert result2["reason"] == "reauth_successful"
import numpy as np from nrrd.errors import NRRDError def parse_vector(x, dtype=None): """Parse NRRD vector from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int vector` and :ref:`user-guide:double vector` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD vector dtype : data-type, optional Datatype to use for the resulting Numpy array. Datatype can be :class:`float`, :class:`int` or :obj:`None`. If :obj:`dtype` is :obj:`None`, then it will be automatically determined by checking any of the vector elements for fractional numbers. If found, then the vector will be converted to :class:`float`, otherwise :class:`int`. Default is to automatically determine datatype. Returns ------- vector : (N,) :class:`numpy.ndarray` Vector that is parsed from the :obj:`x` string """ if x[0] != '(' or x[-1] != ')': raise NRRDError('Vector should be enclosed by parentheses.') # Always convert to float and then truncate to integer if desired # The reason why is parsing a floating point string to int will fail (i.e. int('25.1') will fail) vector = np.array([float(x) for x in x[1:-1].split(',')]) # If using automatic datatype detection, then start by converting to float and determining if the number is whole # Truncate to integer if dtype is int also if dtype is None: vector_trunc = vector.astype(int) if np.all((vector - vector_trunc) == 0): vector = vector_trunc elif dtype == int: vector = vector.astype(int) elif dtype != float: raise NRRDError('dtype should be None for automatic type detection, float or int') return vector def parse_optional_vector(x, dtype=None): """Parse optional NRRD vector from string into (N,) :class:`numpy.ndarray` or :obj:`None`. Function parses optional NRRD vector from string into an (N,) :class:`numpy.ndarray`. This function works the same as :meth:`parse_vector` except if :obj:`x` is 'none', :obj:`vector` will be :obj:`None` See :ref:`user-guide:int vector` and :ref:`user-guide:double vector` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD vector or 'none' dtype : data-type, optional Datatype to use for the resulting Numpy array. Datatype can be :class:`float`, :class:`int` or :obj:`None`. If :obj:`dtype` is :obj:`None`, then it will be automatically determined by checking any of the vector elements for fractional numbers. If found, then the vector will be converted to :class:`float`, otherwise :class:`int`. Default is to automatically determine datatype. Returns ------- vector : (N,) :class:`numpy.ndarray` or :obj:`None` Vector that is parsed from the :obj:`x` string or :obj:`None` if :obj:`x` is 'none' """ if x == 'none': return None else: return parse_vector(x, dtype) def parse_matrix(x, dtype=None): """Parse NRRD matrix from string into (M,N) :class:`numpy.ndarray`. See :ref:`user-guide:int matrix` and :ref:`user-guide:double matrix` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD matrix dtype : data-type, optional Datatype to use for the resulting Numpy array. Datatype can be :class:`float`, :class:`int` or :obj:`None`. If :obj:`dtype` is :obj:`None`, then it will be automatically determined by checking any of the elements for fractional numbers. If found, then the matrix will be converted to :class:`float`, otherwise :class:`int`. Default is to automatically determine datatype. Returns ------- matrix : (M,N) :class:`numpy.ndarray` Matrix that is parsed from the :obj:`x` string """ # Split input by spaces, convert each row into a vector and stack them vertically to get a matrix matrix = [parse_vector(x, dtype=float) for x in x.split()] # Get the size of each row vector and then remove duplicate sizes # There should be exactly one value in the matrix because all row sizes need to be the same if len(np.unique([len(x) for x in matrix])) != 1: raise NRRDError('Matrix should have same number of elements in each row') matrix = np.vstack(matrix) # If using automatic datatype detection, then start by converting to float and determining if the number is whole # Truncate to integer if dtype is int also if dtype is None: matrix_trunc = matrix.astype(int) if np.all((matrix - matrix_trunc) == 0): matrix = matrix_trunc elif dtype == int: matrix = matrix.astype(int) elif dtype != float: raise NRRDError('dtype should be None for automatic type detection, float or int') return matrix def parse_optional_matrix(x): """Parse optional NRRD matrix from string into (M,N) :class:`numpy.ndarray` of :class:`float`. Function parses optional NRRD matrix from string into an (M,N) :class:`numpy.ndarray` of :class:`float`. This function works the same as :meth:`parse_matrix` except if a row vector in the matrix is none, the resulting row in the returned matrix will be all NaNs. See :ref:`user-guide:double matrix` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD matrix Returns ------- matrix : (M,N) :class:`numpy.ndarray` of :class:`float` Matrix that is parsed from the :obj:`x` string """ # Split input by spaces to get each row and convert into a vector. The row can be 'none', in which case it will # return None matrix = [parse_optional_vector(x, dtype=float) for x in x.split()] # Get the size of each row vector, 0 if None sizes = np.array([0 if x is None else len(x) for x in matrix]) # Get sizes of each row vector removing duplicate sizes # Since each row vector should be same size, the unique sizes should return one value for the row size or it may # return a second one (0) if there are None vectors unique_sizes = np.unique(sizes) if len(unique_sizes) != 1 and (len(unique_sizes) != 2 or unique_sizes.min() != 0): raise NRRDError('Matrix should have same number of elements in each row') # Create a vector row of NaN's that matches same size of remaining vector rows # Stack the vector rows together to create matrix nan_row = np.full((unique_sizes.max()), np.nan) matrix = np.vstack([nan_row if x is None else x for x in matrix]) return matrix def parse_number_list(x, dtype=None): """Parse NRRD number list from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int list` and :ref:`user-guide:double list` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD number list dtype : data-type, optional Datatype to use for the resulting Numpy array. Datatype can be :class:`float`, :class:`int` or :obj:`None`. If :obj:`dtype` is :obj:`None`, then it will be automatically determined by checking for fractional numbers. If found, then the string will be converted to :class:`float`, otherwise :class:`int`. Default is to automatically determine datatype. Returns ------- vector : (N,) :class:`numpy.ndarray` Vector that is parsed from the :obj:`x` string """ # Always convert to float and then perform truncation to integer if necessary number_list = np.array([float(x) for x in x.split()]) if dtype is None: number_list_trunc = number_list.astype(int) # If there is no difference between the truncated number list and the number list, then that means that the # number list was all integers and we can just return that if np.all((number_list - number_list_trunc) == 0): number_list = number_list_trunc elif dtype == int: number_list = number_list.astype(int) elif dtype != float: raise NRRDError('dtype should be None for automatic type detection, float or int') return number_list def parse_number_auto_dtype(x): """Parse number from string with automatic type detection. Parses input string and converts to a number using automatic type detection. If the number contains any fractional parts, then the number will be converted to float, otherwise the number will be converted to an int. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. Parameters ---------- x : :class:`str` String representation of number Returns ------- result : :class:`int` or :class:`float` Number parsed from :obj:`x` string """ value = float(x) if value.is_integer(): value = int(value) return value
# new tests should be added to test_cli.py, not here from __future__ import absolute_import import copy import hashlib import os import shlex import shutil import subprocess import sys import tempfile import unittest class TerrariumTester(unittest.TestCase): def setUp(self): _, requirements = tempfile.mkstemp(prefix='test_terrarium_req-') target = tempfile.mkdtemp(prefix='test_terrarium_target-') self.initial_config = { 'target': target, 'storage_dir': tempfile.mkdtemp(prefix='test_terrarium_storage-'), 'python': os.path.join(target, 'bin', 'python'), 'terrarium': 'terrarium', 'requirements': requirements, 'environ': {}, 'opts': '', } self.configs = [] self.config_push(initial=True) @property def config(self): return self.configs[0] @property def target(self): return self.config['target'] @property def storage_dir(self): return self.config['storage_dir'] @property def python(self): return self.config['python'] @property def terrarium(self): return self.config['terrarium'] @property def environ(self): return self.config['environ'] @property def requirements(self): return self.config['requirements'] @property def opts(self): return self.config['opts'] def config_pop(self): return self.configs.pop() def config_push(self, initial=True): if initial: config = copy.deepcopy(self.initial_config) else: config = copy.deepcopy(self.configs[0]) self.configs.insert(0, config) return config def tearDown(self): for config in self.configs: if os.path.exists(config['target']): shutil.rmtree(config['target']) if os.path.exists('%s.bak' % config['target']): shutil.rmtree('%s.bak' % config['target']) if os.path.exists(config['storage_dir']): shutil.rmtree(config['storage_dir']) if os.path.exists(config['requirements']): os.unlink(config['requirements']) def _run(self, command, **kwargs): defaults = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, } defaults.update(kwargs) env = {} if self.environ: env.update(os.environ) env.update(self.environ) defaults['env'] = env kwargs = defaults sys.stdout.write('Executing "%s"\n' % command) params = shlex.split(command) result = subprocess.Popen(params, **kwargs) stdout, stderr = result.communicate() return (stdout, stderr), result.returncode def _get_path(self, *paths): paths = list(paths) paths.insert( 0, os.path.dirname( os.path.abspath(__file__) ), ) return os.path.abspath( os.path.join(*paths) ) def _get_path_terrarium(self): return self._get_path('..') def _python(self, command='', **kwargs): output, return_code = self._run( '%s %s' % ( self.python, command, ) ) return output, return_code def _terrarium(self, command='', call_using_python=False, **kwargs): options = [] for key, value in kwargs.items(): options.append('--%s' % key.replace('_', '-')) if value is not None and value is not True: options.append(value) command = ' '.join([ self.terrarium, ' '.join(options), self.opts, command, ]) if call_using_python: output, return_code = self._python(command) else: output, return_code = self._run( command, ) return output, return_code def _install(self, call_using_python=False, **kwargs): command = 'install %s' % ( self.requirements, ) output, return_code = self._terrarium( command, target=self.target, call_using_python=call_using_python, **kwargs ) return output, return_code def _key(self, **kwargs): command = 'key %s' % ( self.requirements, ) (stdout, stderr), return_code = self._terrarium(command) self.assertEqual(return_code, 0) self.assertEqual(stderr, '') requirements_key = stdout.strip() return requirements_key def _add_requirements(self, *requirements): with open(self.requirements, 'a') as f: f.writelines('\n'.join(requirements)) f.write('\n') def _add_test_requirement(self): test_requirement = self._get_path('fixtures', 'test_requirement') self._add_requirements(test_requirement) def _add_terrarium_requirement(self): import virtualenv self._add_requirements( os.environ['TOX_PACKAGE'], 'virtualenv==%s' % virtualenv.virtualenv_version ) def _clear_requirements(self, *requirements): with open(self.requirements, 'w'): pass def _can_import_requirements(self, *requirements): imported = [] for r in requirements: output, return_code = self._python( '-c "import %s"' % r ) if return_code == 0: imported.append(r) return imported def assertInstall(self, *args, **kwargs): expected_return_code = kwargs.pop('return_code', 0) (stdout, stderr), return_code = self._install(*args, **kwargs) # Print output so it is displayed in the event of an error sys.stdout.write('\n---------- stdout ----------\n') sys.stdout.write(stdout) sys.stdout.write('\n---------- stderr ----------\n') sys.stdout.write(stderr) sys.stdout.write('\n---------- ------ ----------\n') self.assertEqual(return_code, expected_return_code) return stdout, stderr def assertExists(self, path): self.assertTrue(os.path.exists(path)) def assertNotExists(self, path): self.assertFalse(os.path.exists(path)) class TestTerrarium(TerrariumTester): def test_install_requirements_with_dependency(self): # This test involves a requirements file with two items, # test_requirement and foo_requirement. foo_requirement has # test_requirement as a dependency. We check that, if test_requirement # comes first in the requirements, the install of foo_requirement will # be successful. self._add_requirements( self._get_path('fixtures', 'test_requirement'), self._get_path('fixtures', 'foo_requirement'), ) self.assertInstall() actual = self._can_import_requirements( 'test_requirement', 'foo_requirement', ) expected = ['test_requirement', 'foo_requirement'] self.assertEqual(actual, expected) def test_install_with_requirement_comments(self): # Verify that a requirement file with comment lines can be used. self._add_requirements( self._get_path('fixtures', 'test_requirement'), '# This is a comment line in the requirements file.', ) self.assertInstall() actual = self._can_import_requirements( 'test_requirement', ) expected = ['test_requirement'] self.assertEqual(actual, expected) def test_install_editable_with_hash_egg_name(self): # Verify that a requirement file with a hash egg name can be used and # is not confused with a comment # If the #egg=foobar is removed, pip will fail self._add_requirements( '-e git+git://github.com/PolicyStat/terrarium.git#egg=foobar', ) self.assertInstall() actual = self._can_import_requirements( 'terrarium', ) expected = ['terrarium'] self.assertEqual(actual, expected) def test_hash_default_empty_requirements(self): # Verify that the hash of an empty requirements file is predictable command = 'hash %s' % ( self.requirements, ) (stdout, stderr), return_code = self._terrarium(command) expected_digest = hashlib.md5('').hexdigest() self.assertEqual(return_code, 0) self.assertEqual(stdout.strip(), expected_digest) self.assertEqual(stderr, '') def test_install_old_backup_symlink(self): # Create a scenario where the backup (from a previous install) is # actually a symlink instead of a directory os.symlink(self.target, '%s.bak' % self.target) self.assertInstall() self.assertInstall() def test_install_replace_activate_virtualenv_path(self): # Verify that when replacing an existing virtualenv, the VIRTUAL_ENV # path in the activate script matches the original path of the # replaced environment self.assertInstall() self.assertInstall() activate = os.path.join(self.target, 'bin', 'activate') with open(activate) as f: contents = f.read() self.assertTrue( 'VIRTUAL_ENV="%s"' % self.target in contents ) def test_install_storage_dir_archive(self): # Verify that the --storage-dir option causes terrarium create an # archive for the given requirement set self.assertInstall(storage_dir=self.storage_dir) requirements_key = self._key() archive = os.path.join(self.storage_dir, requirements_key) self.assertExists(archive) # Verify that the environment is returned to a usable state activate = os.path.join(self.target, 'bin', 'activate') with open(activate) as f: contents = f.read() self.assertTrue( 'VIRTUAL_ENV="%s"' % self.target in contents ) def test_install_storage_dir_archive_by_environ(self): # Verify that the --storage-dir option causes terrarium create an # archive for the given requirement set self.environ['TERRARIUM_STORAGE_DIR'] = self.storage_dir self.assertInstall() requirements_key = self._key() archive = os.path.join(self.storage_dir, requirements_key) self.assertExists(archive) # Verify that the environment is returned to a usable state activate = os.path.join(self.target, 'bin', 'activate') with open(activate) as f: contents = f.read() self.assertTrue( 'VIRTUAL_ENV="%s"' % self.target in contents ) def test_install_storage_dir_no_archive(self): # Verify that the --no-upload option causes terrarium to not create an # archive for the given requirement set self.assertInstall( storage_dir=self.storage_dir, no_upload=True, ) requirements_key = self._key() archive = os.path.join(self.storage_dir, requirements_key) self.assertNotExists(archive) def test_install_storage_dir_archive_extracted(self): # Verify that an archived terrarium can be later extracted and used # Build an archive self._add_test_requirement() self.assertInstall(storage_dir=self.storage_dir) requirements_key = self._key() archive = os.path.join(self.storage_dir, requirements_key) self.assertExists(archive) # Just install a blank environment self._clear_requirements() # Replace the environment with something else self.assertInstall(no_backup=True) actual = self._can_import_requirements( 'test_requirement', # Should not exist in the replacement ) expected = [] self.assertEqual(actual, expected) # Now attempt to install from the archive self._add_test_requirement() stdout, stderr = self.assertInstall( no_backup=True, storage_dir=self.storage_dir, verbose=True, ) self.assertNotEqual(stdout, '') self.assertEqual(stderr, '') actual = self._can_import_requirements( 'test_requirement', # Should exist now ) expected = ['test_requirement'] self.assertEqual(actual, expected) def test_install_with_terrarium_in_environment(self): # Verify that terrarium can replace an existing environment, the one # that terrarium executes from self._add_test_requirement() self._add_terrarium_requirement() self.assertInstall() actual = self._can_import_requirements( 'test_requirement', 'terrarium', ) expected = [ 'test_requirement', 'terrarium', ] self.assertEqual(actual, expected) # Use terrarium contained in the new environment config = self.config_push() config['terrarium'] = os.path.join( self.target, 'bin', 'terrarium', ) output = self.assertInstall( no_backup=True, call_using_python=True, ) self.assertFalse('Requirement already satisfied' in output[0]) actual = self._can_import_requirements( 'test_requirement', 'terrarium', ) expected = [ 'test_requirement', 'terrarium', ] self.assertEqual(actual, expected) def test_extract_with_terrarium_in_environment(self): # Verify that terrarium can install after being extracted from an # archive that was previously installed self._add_terrarium_requirement() self.assertInstall(storage_dir=self.storage_dir) # Use terrarium contained in the new environment config = self.config_push() config['terrarium'] = os.path.join( self.target, 'bin', 'terrarium', ) config['opts'] = '-VV' self.assertInstall( no_backup=True, storage_dir=self.storage_dir, ) self.assertExists(self.python) def test_logging_output_default(self): self._add_test_requirement() self._add_terrarium_requirement() stdout, stderr = self.assertInstall() self.assertEqual('', stdout) self.assertEqual('', stderr) def test_logging_output_verbose(self): self._add_test_requirement() self._add_terrarium_requirement() stdout, stderr = self.assertInstall(verbose=True) self.assertNotEqual('', stdout) self.assertEqual('', stderr) def test_sensitive_arguments_are_sensitive(self): command = 'hash %s' % ( self.requirements, ) self.config['opts'] = '-VV' (stdout, stderr), return_code = self._terrarium( command, s3_secret_key='should_not_appear', s3_access_key='do_not_show_me', ) self.assertEqual('', stderr) self.assertEqual(return_code, 0) self.assertTrue( stdout.startswith('[DEBUG] Initialized with Namespace') ) self.assertTrue('s3_secret_key' in stdout) self.assertTrue('s3_access_key' in stdout) self.assertTrue('should_not_appear' not in stdout) self.assertTrue('do_not_show_me' not in stdout) def test_restore_previously_backed_up_environment(self): output, return_code = self._terrarium( 'revert', target=self.target, ) self.assertEqual(return_code, 1) self._add_test_requirement() self.assertInstall() with open(os.path.join(self.target, 'foo'), 'w') as f: f.write('bar') self.assertInstall() with open(os.path.join(self.target, 'moo'), 'w') as f: f.write('cow') self.assertExists('%s.bak' % self.target) output, return_code = self._terrarium( 'revert', target=self.target, ) self.assertEqual(return_code, 0) self.assertNotExists('%s.bak' % self.target) self.assertExists(os.path.join(self.target, 'foo')) self.assertNotExists(os.path.join(self.target, 'moo'))
#!/usr/bin/env python3 import json, pprint, os, time, queue, sys import argparse from collections import defaultdict, Counter from classes.color import Color from classes.cache import Cache from classes.results import Results from classes.fingerprints import Fingerprints from classes.discovery import * from classes.headers import ExtractHeaders from classes.matcher import Match from classes.printer import Printer from classes.output import Output from classes.request2 import Requester, UnknownHostName class Wig(object): def __init__(self, args): self.options = { 'url': args.url, 'prefix': '', 'user_agent': args.user_agent, 'proxy': args.proxy, 'verbosity': args.verbosity, 'threads': 10, 'batch_size': 20, 'run_all': args.run_all, 'match_all': args.match_all, 'stop_after': args.stop_after, 'no_cache_load': args.no_cache_load, 'no_cache_save': args.no_cache_save, } self.data = { 'cache': Cache(), 'results': Results(self.options), 'fingerprints': Fingerprints(), 'matcher': Match(), 'colorizer': Color(), 'printer': Printer(args.verbosity, Color()), 'detected_cms': set(), 'error_pages': set(), 'requested': queue.Queue() } self.data['results'].printer = self.data['printer'] self.data['requester'] = Requester(self.options, self.data) def run(self): """ --- DETECT REDIRECTION ------------- """ try: is_redirected, new_url = self.data['requester'].detect_redirect() except UnknownHostName as e: error = self.data['colorizer'].format(e, 'red', False) print(error) sys.exit(1) if is_redirected: hilight_host = self.data['colorizer'].format(new_url, 'red', False) choice = input("Redirected to %s. Continue? [Y|n]:" % (hilight_host,)) # if not, exit if choice in ['n', 'N']: sys.exit(1) # else update the host else: self.options['url'] = new_url self.data['requester'].url = new_url """ ------------------------------------ """ # load cache if this is not disabled self.data['cache'].set_host(self.options['url']) if not self.options['no_cache_load']: self.data['cache'].load() # timer started after the user interaction self.data['timer'] = time.time() """ --- GET SITE INFO ------------------ """ # get the title title = DiscoverTitle(self.options, self.data).run() self.data['results'].site_info['title'] = title # get the IP of the domain ip = DiscoverIP(self.options['url']).run() self.data['results'].site_info['ip'] = ip """ ------------------------------------ """ """ --- DETECT ERROR PAGES ------------- """ # find error pages self.data['error_pages'] = DiscoverErrorPage(self.options, self.data).run() # set matcher error pages self.data['matcher'].error_pages = self.data['error_pages'] """ ------------------------------------ """ """ --- VERSION DETECTION -------------- """ # Search for the first CMS cms_finder = DiscoverCMS(self.options, self.data).run() # find Platform platform_finder = DiscoverPlatform(self.options, self.data).run() """ ------------------------------------ """ """ --- GET MORE DATA FROM THE SITE ---- """ # find interesting files DiscoverInteresting(self.options, self.data).run() # find and request links to static files on the pages DiscoverMore(self.options, self.data).run() """ ------------------------------------ """ """ --- SEARCH FOR JAVASCRIPT LIBS ----- """ # do this after 'DiscoverMore' has been run, to detect JS libs # located in places not covered by the fingerprints DiscoverJavaScript(self.options, self.data).run() """ ------------------------------------ """ """ --- SEARCH THE CACHE --------------- """ # some fingerprints do not have urls - search the cache # for matches DiscoverUrlLess(self.options, self.data).run() # search for cookies DiscoverCookies(self.data).run() # search the cache for headers ExtractHeaders(self.data).run() # search for indications of the used operating system DiscoverOS(self.options, self.data).run() # search for all CMS if specified by the user if self.options['match_all']: DiscoverAllCMS(self.data).run() """ ------------------------------------ """ """ --- SEARCH FOR VULNERABILITIES ----- """ # search the vulnerability fingerprints for matches DiscoverVulnerabilities(self.data).run() """ ------------------------------------ """ """ --- SAVE THE CACHE ----------------- """ if not self.options['no_cache_save']: self.data['cache'].save() """ ------------------------------------ """ """ --- PRINT RESULTS ------------------ """ # calc an set run time self.data['runtime'] = time.time() - self.data['timer'] # update the URL count self.data['url_count'] = self.data['cache'].get_num_urls() # Create outputter and get results outputter = Output(self.options, self.data) title, data = outputter.get_results() # quick, ugly hack for issue 5 (https://github.com/jekyc/wig/issues/5) try: # this will fail, if the title contains unprintable chars print(title) except: pass print(data) """ ------------------------------------ """ if __name__ == '__main__': parser = argparse.ArgumentParser(description='WebApp Information Gatherer') parser.add_argument('url', type=str, help='The url to scan e.g. http://example.com') parser.add_argument('-n', type=int, default=1, dest="stop_after", help='Stop after this amount of CMSs have been detected. Default: 1') parser.add_argument('-a', action='store_true', dest='run_all', default=False, help='Do not stop after the first CMS is detected') parser.add_argument('-m', action='store_true', dest='match_all', default=False, help='Try harder to find a match without making more requests') parser.add_argument('-u', action='store_true', dest='user_agent', default='Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36', help='User-agent to use in the requests') parser.add_argument('--no_cache_load', action='store_true', default=False, help='Do not load cached responses') parser.add_argument('--no_cache_save', action='store_true', default=False, help='Do not save the cache for later use') parser.add_argument('-N', action='store_true', dest='no_cache', default=False, help='Shortcut for --no_cache_load and --no_cache_save') parser.add_argument('--verbosity', '-v', action='count', default=0, help='Increase verbosity. Use multiple times for more info') parser.add_argument('--proxy', dest='proxy', default=None, help='Tunnel through a proxy (format: localhost:8080)') args = parser.parse_args() if '://' not in args.url: args.url = 'http://' + args.url if args.no_cache: args.no_cache_load = True args.no_cache_save = True try: title = """ dP dP dP dP .88888. 88 88 88 88 d8' `88 88 .8P .8P 88 88 88 d8' d8' 88 88 YP88 88.d8P8.d8P 88 Y8. .88 8888' Y88' dP `88888' WebApp Information Gatherer """ print(title) wig = Wig(args) wig.run() except KeyboardInterrupt: # detect ctrl+c for w in wig.workers: w.kill = True raise
############################################################################# # # 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. # ############################################################################# # # Project Name : IEEE 802.11 Timeline Tool # # Author : Alex Ashley # ############################################################################# from ballot.models import Ballot, DenormalizedBallot from project.models import InProgress, Published, Withdrawn from util.cache import CacheControl from util.forms import DateModelForm from util.io import export_html from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse from django import forms,http from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_page from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from util.db import bulk_delete import sys, logging #@login_required class BallotDelete(DeleteView): model = Ballot success_url = reverse_lazy('ballot.views.main_page') class BallotForm(DateModelForm): curstat = forms.IntegerField(widget=forms.HiddenInput) curpk = forms.IntegerField(widget=forms.HiddenInput, required=False) def __init__(self, *args, **kwargs): super(BallotForm, self).__init__(*args, **kwargs) ordered_fields = ['number','project','draft'] self.fields.keyOrder = ordered_fields + [ i for i in self.fields if i not in ordered_fields ] class Meta: model = Ballot @login_required @cache_page(60 * 15) def main_page(request): next_page=reverse('ballot.views.main_page') if request.GET.get('refresh'): for b in Ballot.objects.all(): DenormalizedBallot.request_update(ballot_pk=b.number) return http.HttpResponseRedirect(next_page) needs_update = not DenormalizedBallot.backlog_poll().idle return render_to_response('ballot/index.html', locals(), context_instance=RequestContext(request)) @login_required def wg_page(request, export=None): if request.GET.get('refresh'): for b in Ballot.objects.filter(ballot_type=Ballot.WGInitial.code): DenormalizedBallot.request_update(ballot_pk=b.number) for b in Ballot.objects.filter(ballot_type=Ballot.WGRecirc.code): DenormalizedBallot.request_update(ballot_pk=b.number) return http.HttpResponseRedirect(reverse('ballot.views.wg_page')) next_page = reverse('ballot.views.wg_page') if request.GET.get('redraw',None) is not None: try: redraw = int(request.GET.get('redraw',0)) except ValueError: redraw = 0 cc = CacheControl() if redraw==0: cc.open_ver = cc.open_ver + 1 elif redraw==1: cc.closed_ver = cc.closed_ver + 1 return http.HttpResponseRedirect(next_page) ballots = list(DenormalizedBallot.objects.filter(ballot_type=DenormalizedBallot.WGInitial.code))+list(DenormalizedBallot.objects.filter(ballot_type=DenormalizedBallot.WGRecirc.code))+list(DenormalizedBallot.objects.filter(ballot_type=DenormalizedBallot.Procedural.code)) return ballot_page(request,ballots,export, sponsor=False, next=next_page, export_page='LetterBallots') @login_required def sponsor_page(request, export=None): if request.GET.get('refresh'): for b in Ballot.objects.filter(ballot_type=Ballot.SBInitial.code): DenormalizedBallot.request_update(ballot_pk=b.number) for b in Ballot.objects.filter(ballot_type=Ballot.SBRecirc.code): DenormalizedBallot.request_update(ballot_pk=b.number) return http.HttpResponseRedirect(reverse('ballot.views.sponsor_page')) next_page=reverse('ballot.views.sponsor_page') if request.GET.get('redraw',None) is not None: try: redraw = int(request.GET.get('redraw',0)) except ValueError: redraw = 0 cc = CacheControl() if redraw==0: cc.open_ver = cc.open_ver + 1 elif redraw==1: cc.closed_ver = cc.closed_ver + 1 return http.HttpResponseRedirect(next_page) ballots = list(DenormalizedBallot.objects.filter(ballot_type=DenormalizedBallot.SBInitial.code))+list(DenormalizedBallot.objects.filter(ballot_type=DenormalizedBallot.SBRecirc.code)) return ballot_page(request,ballots,export, sponsor=True, next=next_page, export_page='SponsorBallots') @login_required def add_ballot(request): return edit_ballot(request,bal=None) @login_required def edit_ballot(request,bal): context = {} context.update(csrf(request)) next_page = request.GET.get('next','/') if bal is None: lbnum = Ballot.FIRST_SPONSOR_LBNUM for b in Ballot.objects.all(): lbnum = max(lbnum,b.number+1) ballot = Ballot(number=lbnum) else: ballot = get_object_or_404(Ballot,pk=bal) if request.method == 'POST': if request.POST.has_key('cancel'): return http.HttpResponseRedirect(next_page) if request.POST.has_key('delete'): return http.HttpResponseRedirect(reverse('del_ballot',args=[bal])) form = BallotForm(request.POST, request.FILES, instance=ballot) if form.is_valid(): data = form.cleaned_data ballot = form.save() if data['curpk'] and data['curpk']!=ballot.pk: try: Ballot.objects.get(pk=data['curpk']).delete() except Ballot.DoesNotExist: pass cc = CacheControl() if data['curstat'] != ballot.project.status.id: if InProgress.id==data['curstat']: cc.in_progress_ver = cc.in_progress_ver+1 if Published.id==data['curstat']: cc.published_ver = cc.published_ver+1 if Withdrawn.id==data['curstat']: cc.withdrawn_ver = cc.withdrawn_ver+1 return http.HttpResponseRedirect(next_page) else: initial={'curstat':ballot.project.status.id, 'curpk':ballot.pk} if bal is not None else {'curstat':0} form = BallotForm(instance=ballot, initial=initial) context['form'] = form context['object'] = ballot context['no_delete'] = bal is None return render_to_response('edit-object.html',context, context_instance=RequestContext(request)) #@login_required #def del_ballot(request,bal): # next_page = request.GET.get('next','/') # return create_update.delete_object(request, model=Ballot, object_id=bal, # post_delete_redirect=next_page) def ballot_page(request, ballots, export, sponsor, next, export_page): closed_ballots = [] open_ballots = [] needs_update = not DenormalizedBallot.backlog_poll().idle for b in ballots: if b.is_open: open_ballots.append(b) else: closed_ballots.append(b) if sponsor: open_ballots.sort(key=lambda x: x.closed, reverse=True) closed_ballots.sort(key=lambda x: x.closed, reverse=True) else: open_ballots.sort(key=lambda x: x.number, reverse=True) closed_ballots.sort(key=lambda x: x.number, reverse=True) context = dict(has_open=len(open_ballots)>0, open=open_ballots, \ closed=closed_ballots, next_page=next, export=export, \ sponsor=sponsor, needs_update=needs_update, \ export_page=reverse('ballot.views.main_page')+export_page) context_instance=RequestContext(request) context_instance['cache'].export = export if export: return export_html('ballot/ballots.html', context, context_instance=context_instance, filename='%s.%s'%(export_page,export)) return render_to_response('ballot/ballots.html', context, context_instance=context_instance) #class BallotBacklogPoll(BacklogPoll): # backlog = BallotBacklog # denormalized = DenormalizedBallot # check_backlog = check_ballot_backlog @login_required def backlog_poll(request): stats = DenormalizedBallot.backlog_poll() return HttpResponse(content='{"backlog":%d, "count":%d}'%(stats.waiting+stats.active,DenormalizedBallot.objects.count()), mimetype='application/json') #return BallotBacklogPoll().poll(request) @csrf_exempt def backlog_worker(request): try: dn = DenormalizedBallot.denormalize(ballot_pk=request.POST['ballot'], commit=True) return HttpResponse(content='DenormalizedBallot %s'%(dn.task_group), mimetype='text/plain') except DenormalizedBallot.DoesNotExist: return HttpResponse(content='DenormalizedBallot %s does not exist'%str(request.POST['ballot']), mimetype='text/plain') # done=[] # try: # for backlog in BallotBacklog.objects.all(): # done.append(backlog.number) # try: # DenormalizedBallot.denormalize(backlog) # except Ballot.DoesNotExist: # sys.stderr.write('Unable to find ballot %d\n'%backlog.number) # pass # message='Timeline backlog complete' # return render_to_response('done.html',locals(),context_instance=RequestContext(request)) # except: # raise # finally: # bulk_delete(BallotBacklog,BallotBacklog.objects.filter(pk__in=done)) @receiver(post_save, sender=DenormalizedBallot) def update_cache(sender, instance, **kwargs): # instance is a DenormalizedBallot object cc = CacheControl() if instance.is_open: cc.open_ver = cc.open_ver+1 else: cc.closed_ver = cc.closed_ver+1 @receiver(pre_delete, sender=DenormalizedBallot) def update_cache2(sender, instance, **kwargs): cc = CacheControl() if instance.is_open: cc.open_ver = cc.open_ver+1 else: cc.closed_ver = cc.closed_ver+1