gt
stringclasses
1 value
context
stringlengths
2.49k
119k
<<<<<<< HEAD <<<<<<< HEAD '''Test the functions and main class method of textView.py. Since all methods and functions create (or destroy) a TextViewer, which is a widget containing multiple widgets, all tests must be gui tests. Using mock Text would not change this. Other mocks are used to retrieve information about calls. The coverage is essentially 100%. ''' from test.support import requires requires('gui') import unittest import os from tkinter import Tk from idlelib import textView as tv from idlelib.idle_test.mock_idle import Func from idlelib.idle_test.mock_tk import Mbox def setUpModule(): global root root = Tk() def tearDownModule(): global root root.destroy() # pyflakes falsely sees root as undefined del root class TV(tv.TextViewer): # used by TextViewTest transient = Func() grab_set = Func() wait_window = Func() class TextViewTest(unittest.TestCase): def setUp(self): TV.transient.__init__() TV.grab_set.__init__() TV.wait_window.__init__() def test_init_modal(self): view = TV(root, 'Title', 'test text') self.assertTrue(TV.transient.called) self.assertTrue(TV.grab_set.called) self.assertTrue(TV.wait_window.called) view.Ok() def test_init_nonmodal(self): view = TV(root, 'Title', 'test text', modal=False) self.assertFalse(TV.transient.called) self.assertFalse(TV.grab_set.called) self.assertFalse(TV.wait_window.called) view.Ok() def test_ok(self): view = TV(root, 'Title', 'test text', modal=False) view.destroy = Func() view.Ok() self.assertTrue(view.destroy.called) del view.destroy # unmask real function view.destroy class textviewTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.orig_mbox = tv.tkMessageBox tv.tkMessageBox = Mbox @classmethod def tearDownClass(cls): tv.tkMessageBox = cls.orig_mbox del cls.orig_mbox def test_view_text(self): # If modal True, tkinter will error with 'can't invoke "event" command' view = tv.view_text(root, 'Title', 'test text', modal=False) self.assertIsInstance(view, tv.TextViewer) def test_view_file(self): test_dir = os.path.dirname(__file__) testfile = os.path.join(test_dir, 'test_textview.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsInstance(view, tv.TextViewer) self.assertIn('Test', view.textView.get('1.0', '1.end')) view.Ok() # Mock messagebox will be used and view_file will not return anything testfile = os.path.join(test_dir, '../notthere.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsNone(view) if __name__ == '__main__': unittest.main(verbosity=2) ======= '''Test the functions and main class method of textView.py. Since all methods and functions create (or destroy) a TextViewer, which is a widget containing multiple widgets, all tests must be gui tests. Using mock Text would not change this. Other mocks are used to retrieve information about calls. The coverage is essentially 100%. ''' from test.support import requires requires('gui') import unittest import os from tkinter import Tk from idlelib import textView as tv from idlelib.idle_test.mock_idle import Func from idlelib.idle_test.mock_tk import Mbox def setUpModule(): global root root = Tk() def tearDownModule(): global root root.destroy() # pyflakes falsely sees root as undefined del root class TV(tv.TextViewer): # used by TextViewTest transient = Func() grab_set = Func() wait_window = Func() class TextViewTest(unittest.TestCase): def setUp(self): TV.transient.__init__() TV.grab_set.__init__() TV.wait_window.__init__() def test_init_modal(self): view = TV(root, 'Title', 'test text') self.assertTrue(TV.transient.called) self.assertTrue(TV.grab_set.called) self.assertTrue(TV.wait_window.called) view.Ok() def test_init_nonmodal(self): view = TV(root, 'Title', 'test text', modal=False) self.assertFalse(TV.transient.called) self.assertFalse(TV.grab_set.called) self.assertFalse(TV.wait_window.called) view.Ok() def test_ok(self): view = TV(root, 'Title', 'test text', modal=False) view.destroy = Func() view.Ok() self.assertTrue(view.destroy.called) del view.destroy # unmask real function view.destroy class textviewTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.orig_mbox = tv.tkMessageBox tv.tkMessageBox = Mbox @classmethod def tearDownClass(cls): tv.tkMessageBox = cls.orig_mbox del cls.orig_mbox def test_view_text(self): # If modal True, tkinter will error with 'can't invoke "event" command' view = tv.view_text(root, 'Title', 'test text', modal=False) self.assertIsInstance(view, tv.TextViewer) def test_view_file(self): test_dir = os.path.dirname(__file__) testfile = os.path.join(test_dir, 'test_textview.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsInstance(view, tv.TextViewer) self.assertIn('Test', view.textView.get('1.0', '1.end')) view.Ok() # Mock messagebox will be used and view_file will not return anything testfile = os.path.join(test_dir, '../notthere.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsNone(view) if __name__ == '__main__': unittest.main(verbosity=2) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= '''Test the functions and main class method of textView.py. Since all methods and functions create (or destroy) a TextViewer, which is a widget containing multiple widgets, all tests must be gui tests. Using mock Text would not change this. Other mocks are used to retrieve information about calls. The coverage is essentially 100%. ''' from test.support import requires requires('gui') import unittest import os from tkinter import Tk from idlelib import textView as tv from idlelib.idle_test.mock_idle import Func from idlelib.idle_test.mock_tk import Mbox def setUpModule(): global root root = Tk() def tearDownModule(): global root root.destroy() # pyflakes falsely sees root as undefined del root class TV(tv.TextViewer): # used by TextViewTest transient = Func() grab_set = Func() wait_window = Func() class TextViewTest(unittest.TestCase): def setUp(self): TV.transient.__init__() TV.grab_set.__init__() TV.wait_window.__init__() def test_init_modal(self): view = TV(root, 'Title', 'test text') self.assertTrue(TV.transient.called) self.assertTrue(TV.grab_set.called) self.assertTrue(TV.wait_window.called) view.Ok() def test_init_nonmodal(self): view = TV(root, 'Title', 'test text', modal=False) self.assertFalse(TV.transient.called) self.assertFalse(TV.grab_set.called) self.assertFalse(TV.wait_window.called) view.Ok() def test_ok(self): view = TV(root, 'Title', 'test text', modal=False) view.destroy = Func() view.Ok() self.assertTrue(view.destroy.called) del view.destroy # unmask real function view.destroy class textviewTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.orig_mbox = tv.tkMessageBox tv.tkMessageBox = Mbox @classmethod def tearDownClass(cls): tv.tkMessageBox = cls.orig_mbox del cls.orig_mbox def test_view_text(self): # If modal True, tkinter will error with 'can't invoke "event" command' view = tv.view_text(root, 'Title', 'test text', modal=False) self.assertIsInstance(view, tv.TextViewer) def test_view_file(self): test_dir = os.path.dirname(__file__) testfile = os.path.join(test_dir, 'test_textview.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsInstance(view, tv.TextViewer) self.assertIn('Test', view.textView.get('1.0', '1.end')) view.Ok() # Mock messagebox will be used and view_file will not return anything testfile = os.path.join(test_dir, '../notthere.py') view = tv.view_file(root, 'Title', testfile, modal=False) self.assertIsNone(view) if __name__ == '__main__': unittest.main(verbosity=2) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### import sys from generate import generate MAX_ARGS = 16 def make_params(nargs, *prefix): params = ["object arg%d" % i for i in range(nargs)] return ", ".join(list(prefix) + params) def make_params1(nargs, prefix=("CodeContext context",)): params = ["object arg%d" % i for i in range(nargs)] return ", ".join(list(prefix) + params) def make_args(nargs, *prefix): params = ["arg%d" % i for i in range(nargs)] return ", ".join(list(prefix) + params) def make_args1(nargs, prefix, start=0): args = ["arg%d" % i for i in range(start, nargs)] return ", ".join(list(prefix) + args) def make_calltarget_type_args(nargs): return ', '.join(['PythonFunction'] + ['object'] * (nargs + 1)) def gen_args_comma(nparams, comma): args = "" for i in xrange(nparams): args = args + comma + ("object arg%d" % i) comma = ", " return args def gen_args(nparams): return gen_args_comma(nparams, "") def gen_args_call(nparams, *prefix): args = "" comma = "" for i in xrange(nparams): args = args + comma +("arg%d" % i) comma = ", " if prefix: if args: args = prefix[0] + ', ' + args else: args = prefix[0] return args def gen_args_array(nparams): args = gen_args_call(nparams) if args: return "{ " + args + " }" else: return "{ }" def gen_callargs(nparams): args = "" comma = "" for i in xrange(nparams): args = args + comma + ("callArgs[%d]" % i) comma = "," return args def gen_args_paramscall(nparams): args = "" comma = "" for i in xrange(nparams): args = args + comma + ("args[%d]" % i) comma = "," return args method_caller_template = """ class MethodBinding<%(typeParams)s> : BaseMethodBinding { private CallSite<Func<CallSite, CodeContext, object, object, %(typeParams)s, object>> _site; public MethodBinding(PythonInvokeBinder binder) { _site = CallSite<Func<CallSite, CodeContext, object, object, %(typeParams)s, object>>.Create(binder); } public object SelfTarget(CallSite site, CodeContext context, object target, %(callParams)s) { Method self = target as Method; if (self != null && self._inst != null) { return _site.Target(_site, context, self._func, self._inst, %(callArgs)s); } return ((CallSite<Func<CallSite, CodeContext, object, %(typeParams)s, object>>)site).Update(site, context, target, %(callArgs)s); } public object SelflessTarget(CallSite site, CodeContext context, object target, object arg0, %(callParamsSelfless)s) { Method self = target as Method; if (self != null && self._inst == null) { return _site.Target(_site, context, self._func, PythonOps.MethodCheckSelf(context, self, arg0), %(callArgsSelfless)s); } return ((CallSite<Func<CallSite, CodeContext, object, object, %(typeParams)s, object>>)site).Update(site, context, target, arg0, %(callArgsSelfless)s); } public override Delegate GetSelfTarget() { return new Func<CallSite, CodeContext, object, %(typeParams)s, object>(SelfTarget); } public override Delegate GetSelflessTarget() { return new Func<CallSite, CodeContext, object, object, %(typeParams)s, object>(SelflessTarget); } }""" def method_callers(cw): for nparams in range(1, MAX_ARGS-3): cw.write(method_caller_template % { 'typeParams' : ', '.join(('T%d' % d for d in xrange(nparams))), 'callParams': ', '.join(('T%d arg%d' % (d,d) for d in xrange(nparams))), 'callParamsSelfless': ', '.join(('T%d arg%d' % (d,d+1) for d in xrange(nparams))), 'callArgsSelfless' : ', '.join(('arg%d' % (d+1) for d in xrange(nparams))), 'argCount' : nparams, 'callArgs': ', '.join(('arg%d' % d for d in xrange(nparams))), 'genFuncArgs' : make_calltarget_type_args(nparams), }) def selfless_method_caller_switch(cw): cw.enter_block('switch (typeArgs.Length)') for i in range(1, MAX_ARGS-3): cw.write('case %d: binding = (BaseMethodBinding)Activator.CreateInstance(typeof(MethodBinding<%s>).MakeGenericType(typeArgs), binder); break;' % (i, ',' * (i-1))) cw.exit_block() function_caller_template = """ public sealed class FunctionCaller<%(typeParams)s> : FunctionCaller { public FunctionCaller(int compat) : base(compat) { } public object Call%(argCount)d(CallSite site, CodeContext context, object func, %(callParams)s) { PythonFunction pyfunc = func as PythonFunction; if (pyfunc != null && pyfunc._compat == _compat) { return ((Func<%(genFuncArgs)s>)pyfunc.func_code.Target)(pyfunc, %(callArgs)s); } return ((CallSite<Func<CallSite, CodeContext, object, %(typeParams)s, object>>)site).Update(site, context, func, %(callArgs)s); }""" defaults_template = """ public object Default%(defaultCount)dCall%(argCount)d(CallSite site, CodeContext context, object func, %(callParams)s) { PythonFunction pyfunc = func as PythonFunction; if (pyfunc != null && pyfunc._compat == _compat) { int defaultIndex = pyfunc.Defaults.Length - pyfunc.NormalArgumentCount + %(argCount)d; return ((Func<%(genFuncArgs)s>)pyfunc.func_code.Target)(pyfunc, %(callArgs)s, %(defaultArgs)s); } return ((CallSite<Func<CallSite, CodeContext, object, %(typeParams)s, object>>)site).Update(site, context, func, %(callArgs)s); }""" defaults_template_0 = """ public object Default%(argCount)dCall0(CallSite site, CodeContext context, object func) { PythonFunction pyfunc = func as PythonFunction; if (pyfunc != null && pyfunc._compat == _compat) { int defaultIndex = pyfunc.Defaults.Length - pyfunc.NormalArgumentCount; return ((Func<%(genFuncArgs)s>)pyfunc.func_code.Target)(pyfunc, %(defaultArgs)s); } return ((CallSite<Func<CallSite, CodeContext, object, object>>)site).Update(site, context, func); }""" def function_callers(cw): cw.write('''class FunctionCallerProperties { internal const int MaxGeneratedFunctionArgs = %d; }''' % (MAX_ARGS-2)) cw.write('') for nparams in range(1, MAX_ARGS-2): cw.write(function_caller_template % { 'typeParams' : ', '.join(('T%d' % d for d in xrange(nparams))), 'callParams': ', '.join(('T%d arg%d' % (d,d) for d in xrange(nparams))), 'argCount' : nparams, 'callArgs': ', '.join(('arg%d' % d for d in xrange(nparams))), 'genFuncArgs' : make_calltarget_type_args(nparams), }) for i in xrange(nparams + 1, MAX_ARGS - 2): cw.write(defaults_template % { 'typeParams' : ', '.join(('T%d' % d for d in xrange(nparams))), 'callParams': ', '.join(('T%d arg%d' % (d,d) for d in xrange(nparams))), 'argCount' : nparams, 'totalParamCount' : i, 'callArgs': ', '.join(('arg%d' % d for d in xrange(nparams))), 'defaultCount' : i - nparams, 'defaultArgs' : ', '.join(('pyfunc.Defaults[defaultIndex + %d]' % curDefault for curDefault in xrange(i - nparams))), 'genFuncArgs' : make_calltarget_type_args(i), }) cw.write('}') def function_callers_0(cw): for i in xrange(1, MAX_ARGS - 2): cw.write(defaults_template_0 % { 'argCount' : i, 'defaultArgs' : ', '.join(('pyfunc.Defaults[defaultIndex + %d]' % curDefault for curDefault in xrange(i))), 'genFuncArgs' : make_calltarget_type_args(i), }) function_caller_switch_template = """case %(argCount)d: callerType = typeof(FunctionCaller<%(arity)s>).MakeGenericType(typeParams); mi = callerType.GetMethod(baseName + "Call%(argCount)d"); Debug.Assert(mi != null); fc = GetFunctionCaller(callerType, funcCompat); funcType = typeof(Func<,,,,%(arity)s>).MakeGenericType(allParams); return new Binding.FastBindResult<T>((T)(object)mi.CreateDelegate(funcType, fc), true);""" def function_caller_switch(cw): for nparams in range(1, MAX_ARGS-2): cw.write(function_caller_switch_template % { 'arity' : ',' * (nparams - 1), 'argCount' : nparams, }) def gen_lazy_call_targets(cw): for nparams in range(MAX_ARGS): cw.enter_block("public static object OriginalCallTarget%d(%s)" % (nparams, make_params(nparams, "PythonFunction function"))) cw.write("function.func_code.LazyCompileFirstTarget(function);") cw.write("return ((Func<%s>)function.func_code.Target)(%s);" % (make_calltarget_type_args(nparams), gen_args_call(nparams, 'function'))) cw.exit_block() cw.write('') def gen_recursion_checks(cw): for nparams in range(MAX_ARGS): cw.enter_block("internal class PythonFunctionRecursionCheck%d" % (nparams, )) cw.write("private readonly Func<%s> _target;" % (make_calltarget_type_args(nparams), )) cw.write('') cw.enter_block('public PythonFunctionRecursionCheck%d(Func<%s> target)' % (nparams, make_calltarget_type_args(nparams))) cw.write('_target = target;') cw.exit_block() cw.write('') cw.enter_block('public object CallTarget(%s)' % (make_params(nparams, "PythonFunction/*!*/ function"), )) cw.write('PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);') cw.enter_block('try') cw.write('return _target(%s);' % (gen_args_call(nparams, 'function'), )) cw.finally_block() cw.write('PythonOps.FunctionPopFrame();') cw.exit_block() cw.exit_block() cw.exit_block() cw.write('') def gen_recursion_delegate_switch(cw): for nparams in range(MAX_ARGS): cw.case_label('case %d:' % nparams) cw.write('finalTarget = new Func<%s>(new PythonFunctionRecursionCheck%d((Func<%s>)finalTarget).CallTarget);' % (make_calltarget_type_args(nparams), nparams, make_calltarget_type_args(nparams))) cw.write('break;') cw.dedent() def get_call_type(postfix): if postfix == "": return "CallType.None" else: return "CallType.ImplicitInstance" def make_call_to_target(cw, index, postfix, extraArg): cw.enter_block("public override object Call%(postfix)s(%(params)s)", postfix=postfix, params=make_params1(index)) cw.write("if (target%(index)d != null) return target%(index)d(%(args)s);", index=index, args = make_args1(index, extraArg)) cw.write("throw BadArgumentError(%(callType)s, %(nargs)d);", callType=get_call_type(postfix), nargs=index) cw.exit_block() def make_call_to_targetX(cw, index, postfix, extraArg): cw.enter_block("public override object Call%(postfix)s(%(params)s)", postfix=postfix, params=make_params1(index)) cw.write("return target%(index)d(%(args)s);", index=index, args = make_args1(index, extraArg)) cw.exit_block() def make_error_calls(cw, index): cw.enter_block("public override object Call(%(params)s)", params=make_params1(index)) cw.write("throw BadArgumentError(CallType.None, %(nargs)d);", nargs=index) cw.exit_block() if index > 0: cw.enter_block("public override object CallInstance(%(params)s)", params=make_params1(index)) cw.write("throw BadArgumentError(CallType.ImplicitInstance, %(nargs)d);", nargs=index) cw.exit_block() def gen_call(nargs, nparams, cw, extra=[]): args = extra + ["arg%d" % i for i in range(nargs)] cw.enter_block("public override object Call(%s)" % make_params1(nargs)) # first emit error checking... ndefaults = nparams-nargs if nargs != nparams: cw.write("if (Defaults.Length < %d) throw BadArgumentError(%d);" % (ndefaults,nargs)) # emit the common case of no recursion check if (nargs == nparams): cw.write("if (!EnforceRecursion) return target(%s);" % ", ".join(args)) else: dargs = args + ["Defaults[Defaults.Length - %d]" % i for i in range(ndefaults, 0, -1)] cw.write("if (!EnforceRecursion) return target(%s);" % ", ".join(dargs)) # emit non-common case of recursion check cw.write("PushFrame();") cw.enter_block("try") # make function body if (nargs == nparams): cw.write("return target(%s);" % ", ".join(args)) else: dargs = args + ["Defaults[Defaults.Length - %d]" % i for i in range(ndefaults, 0, -1)] cw.write("return target(%s);" % ", ".join(dargs)) cw.finally_block() cw.write("PopFrame();") cw.exit_block() cw.exit_block() def gen_params_callN(cw, any): cw.enter_block("public override object Call(CodeContext context, params object[] args)") cw.write("if (!IsContextAware) return Call(args);") cw.write("") cw.enter_block("if (Instance == null)") cw.write("object[] newArgs = new object[args.Length + 1];") cw.write("newArgs[0] = context;") cw.write("Array.Copy(args, 0, newArgs, 1, args.Length);") cw.write("return Call(newArgs);") cw.else_block() # need to call w/ Context, Instance, *args if any: cw.enter_block("switch (args.Length)") for i in xrange(MAX_ARGS-1): if i == 0: cw.write(("case %d: if(target2 != null) return target2(context, Instance); break;") % (i)) else: cw.write(("case %d: if(target%d != null) return target%d(context, Instance, " + gen_args_paramscall(i) + "); break;") % (i, i+2, i+2)) cw.exit_block() cw.enter_block("if (targetN != null)") cw.write("object [] newArgs = new object[args.Length+2];") cw.write("newArgs[0] = context;") cw.write("newArgs[1] = Instance;") cw.write("Array.Copy(args, 0, newArgs, 2, args.Length);") cw.write("return targetN(newArgs);") cw.exit_block() cw.write("throw BadArgumentError(args.Length);") cw.exit_block() else: cw.write("object [] newArgs = new object[args.Length+2];") cw.write("newArgs[0] = context;") cw.write("newArgs[1] = Instance;") cw.write("Array.Copy(args, 0, newArgs, 2, args.Length);") cw.write("return target(newArgs);") cw.exit_block() cw.exit_block() cw.write("") CODE = """ public static object Call(%(params)s) { FastCallable fc = func as FastCallable; if (fc != null) return fc.Call(%(args)s); return PythonCalls.Call(func, %(argsArray)s); }""" def gen_python_switch(cw): for nparams in range(MAX_ARGS): genArgs = make_calltarget_type_args(nparams) cw.write("""case %d: originalTarget = (Func<%s>)OriginalCallTarget%d; return typeof(Func<%s>);""" % (nparams, genArgs, nparams, genArgs)) fast_type_call_template = """ class FastBindingBuilder<%(typeParams)s> : FastBindingBuilderBase { public FastBindingBuilder(CodeContext context, PythonType type, PythonInvokeBinder binder, Type siteType, Type[] genTypeArgs) : base(context, type, binder, siteType, genTypeArgs) { } protected override Delegate GetNewSiteDelegate(PythonInvokeBinder binder, object func) { return new Func<%(newInitDlgParams)s>(new NewSite<%(typeParams)s>(binder, func).Call); } protected override Delegate MakeDelegate(int version, Delegate newDlg, LateBoundInitBinder initBinder) { return new Func<%(funcParams)s>( new FastTypeSite<%(typeParams)s>( version, (Func<%(newInitDlgParams)s>)newDlg, initBinder ).CallTarget ); } } class FastTypeSite<%(typeParams)s> { private readonly int _version; private readonly Func<%(newInitDlgParams)s> _new; private readonly CallSite<Func<%(nestedSlowSiteParams)s>> _initSite; public FastTypeSite(int version, Func<%(newInitDlgParams)s> @new, LateBoundInitBinder initBinder) { _version = version; _new = @new; _initSite = CallSite<Func<%(nestedSlowSiteParams)s>>.Create(initBinder); } public object CallTarget(CallSite site, CodeContext context, object type, %(callTargetArgs)s) { PythonType pt = type as PythonType; if (pt != null && pt.Version == _version) { object res = _new(context, type, %(callTargetPassedArgs)s); _initSite.Target(_initSite, context, res, %(callTargetPassedArgs)s); return res; } return ((CallSite<Func<%(funcParams)s>>)site).Update(site, context, type, %(callTargetPassedArgs)s); } } class NewSite<%(typeParams)s> { private readonly CallSite<Func<%(nestedSiteParams)s>> _site; private readonly object _target; public NewSite(PythonInvokeBinder binder, object target) { _site = CallSite<Func<%(nestedSiteParams)s>>.Create(binder); _target = target; } public object Call(CodeContext context, object typeOrInstance, %(callTargetArgs)s) { return _site.Target(_site, context, _target, typeOrInstance, %(callTargetPassedArgs)s); } } """ def gen_fast_type_callers(cw): for nparams in range(1, 6): funcParams = 'CallSite, CodeContext, object, ' + ', '.join(('T%d' % d for d in xrange(nparams))) + ', object' newInitDlgParams = 'CodeContext, object, ' + ', '.join(('T%d' % d for d in xrange(nparams))) + ', object' callTargetArgs = ', '.join(('T%d arg%d' % (d, d) for d in xrange(nparams))) callTargetPassedArgs = ', '.join(('arg%d' % (d, ) for d in xrange(nparams))) nestedSiteParams = 'CallSite, CodeContext, object, object, ' + ', '.join(('T%d' % d for d in xrange(nparams))) + ', object' nestedSlowSiteParams = 'CallSite, CodeContext, object, ' + ', '.join(('T%d' % d for d in xrange(nparams))) + ', object' cw.write(fast_type_call_template % { 'typeParams' : ', '.join(('T%d' % d for d in xrange(nparams))), 'funcParams' : funcParams, 'newInitDlgParams' : newInitDlgParams, 'callTargetArgs' : callTargetArgs, 'callTargetPassedArgs': callTargetPassedArgs, 'nestedSiteParams' : nestedSiteParams, 'nestedSlowSiteParams' : nestedSlowSiteParams, }) def gen_fast_type_caller_switch(cw): for nparams in range(1, 6): cw.write('case %d: baseType = typeof(FastBindingBuilder<%s>); break;' % (nparams, (',' * (nparams - 1)))) fast_init_template = """ class FastInitSite<%(typeParams)s> { private readonly int _version; private readonly PythonFunction _slot; private readonly CallSite<Func<CallSite, CodeContext, PythonFunction, object, %(typeParams)s, object>> _initSite; public FastInitSite(int version, PythonInvokeBinder binder, PythonFunction target) { _version = version; _slot = target; _initSite = CallSite<Func<CallSite, CodeContext, PythonFunction, object, %(typeParams)s, object>>.Create(binder); } public object CallTarget(CallSite site, CodeContext context, object inst, %(callParams)s) { IPythonObject pyObj = inst as IPythonObject; if (pyObj != null && pyObj.PythonType.Version == _version) { _initSite.Target(_initSite, context, _slot, inst, %(callArgs)s); return inst; } return ((CallSite<Func<CallSite, CodeContext, object, %(typeParams)s, object>>)site).Update(site, context, inst, %(callArgs)s); } public object EmptyCallTarget(CallSite site, CodeContext context, object inst, %(callParams)s) { IPythonObject pyObj = inst as IPythonObject; if ((pyObj != null && pyObj.PythonType.Version == _version) || DynamicHelpers.GetPythonType(inst).Version == _version) { return inst; } return ((CallSite<Func<CallSite, CodeContext, object, %(typeParams)s, object>>)site).Update(site, context, inst, %(callArgs)s); } } """ MAX_FAST_INIT_ARGS = 6 def gen_fast_init_callers(cw): for nparams in range(1, MAX_FAST_INIT_ARGS): callParams = ', '.join(('T%d arg%d' % (d, d) for d in xrange(nparams))) callArgs = ', '.join(('arg%d' % (d, ) for d in xrange(nparams))) cw.write(fast_init_template % { 'typeParams' : ', '.join(('T%d' % d for d in xrange(nparams))), 'callParams' : callParams, 'callArgs': callArgs, }) def gen_fast_init_switch(cw): for nparams in range(1, MAX_FAST_INIT_ARGS): cw.write("case %d: initSiteType = typeof(FastInitSite<%s>); break;" % (nparams, ',' * (nparams-1), )) def gen_fast_init_max_args(cw): cw.write("public const int MaxFastLateBoundInitArgs = %d;" % MAX_FAST_INIT_ARGS) MAX_INSTRUCTION_PROVIDED_CALLS = 7 def gen_call_expression_instruction_switch(cw): for i in xrange(MAX_INSTRUCTION_PROVIDED_CALLS): cw.case_label('case %d:' % i) cw.write('compiler.Compile(Parent.LocalContext);') cw.write('compiler.Compile(_target);') for j in xrange(i): cw.write('compiler.Compile(_args[%d].Expression);' % j) cw.write('compiler.Instructions.Emit(new Invoke%dInstruction(Parent.PyContext));' % i) cw.write('return;') cw.dedent() def gen_call_expression_instructions(cw): for i in xrange(MAX_INSTRUCTION_PROVIDED_CALLS): siteargs = 'object, ' * (i + 1) argfetch = '\n'.join([' var arg%d = frame.Pop();' % (j-1) for j in xrange(i, 0, -1)]) callargs = ', '.join(['target'] + ['arg%d' % j for j in xrange(i)]) cw.write(""" class Invoke%(argcount)dInstruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, %(siteargs)sobject>> _site; public Invoke%(argcount)dInstruction(PythonContext context) { _site = context.CallSite%(argcount)d; } public override int ConsumedStack { get { return %(consumedCount)d; } } public override int Run(InterpretedFrame frame) { %(argfetch)s var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), %(callargs)s)); return +1; } }""" % {'siteargs': siteargs, 'argfetch' : argfetch, 'callargs' : callargs, 'argcount' : i, 'consumedCount' : i + 2 }) def gen_shared_call_sites_storage(cw): for i in xrange(MAX_INSTRUCTION_PROVIDED_CALLS): siteargs = 'object, ' * (i + 1) cw.writeline('private CallSite<Func<CallSite, CodeContext, %sobject>> _callSite%d;' % (siteargs, i)) def gen_shared_call_sites_properties(cw): for i in xrange(MAX_INSTRUCTION_PROVIDED_CALLS): siteargs = 'object, ' * (i + 1) cw.enter_block('internal CallSite<Func<CallSite, CodeContext, %sobject>> CallSite%d' % (siteargs, i)) cw.enter_block('get') cw.writeline('EnsureCall%dSite();' % i) cw.writeline('return _callSite%d;' % i) cw.exit_block() cw.exit_block() cw.writeline('') cw.enter_block('private void EnsureCall%dSite()' % i) cw.enter_block('if (_callSite%d == null)' % i) cw.writeline('Interlocked.CompareExchange(') cw.indent() cw.writeline('ref _callSite%d,' % i) cw.writeline('CallSite<Func<CallSite, CodeContext, %sobject>>.Create(Invoke(new CallSignature(%d))),' % (siteargs, i)) cw.writeline('null') cw.dedent() cw.writeline(');') cw.exit_block() cw.exit_block() cw.writeline('') def main(): return generate( ("Python Selfless Method Caller Switch", selfless_method_caller_switch), ("Python Method Callers", method_callers), ("Python Shared Call Sites Properties", gen_shared_call_sites_properties), ("Python Shared Call Sites Storage", gen_shared_call_sites_storage), ("Python Call Expression Instructions", gen_call_expression_instructions), ("Python Call Expression Instruction Switch", gen_call_expression_instruction_switch), ("Python Fast Init Max Args", gen_fast_init_max_args), ("Python Fast Init Switch", gen_fast_init_switch), ("Python Fast Init Callers", gen_fast_init_callers), ("Python Fast Type Caller Switch", gen_fast_type_caller_switch), ("Python Fast Type Callers", gen_fast_type_callers), ("Python Recursion Enforcement", gen_recursion_checks), ("Python Recursion Delegate Switch", gen_recursion_delegate_switch), ("Python Lazy Call Targets", gen_lazy_call_targets), ("Python Zero Arg Function Callers", function_callers_0), ("Python Function Callers", function_callers), ("Python Function Caller Switch", function_caller_switch), ("Python Call Target Switch", gen_python_switch), ) if __name__ == "__main__": main()
import re import time import json import datetime from datetime import timedelta from django.utils.timesince import timesince import base64, pickle from django import template register = template.Library() from django.contrib.auth.models import User from userprofile.models import Profile from django.conf import settings import pymongo from pymongo import MongoClient from pymongo import ASCENDING, DESCENDING client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) if settings.MONGO_USER: client.cloudly.authenticate(settings.MONGO_USER, settings.MONGO_PASSWORD) mongo = client.cloudly from vms.models import Cache def _seconds_since_epoch(d): date_time = d.isoformat().split('.')[0].replace('T',' ') pattern = '%Y-%m-%d %H:%M:%S' seconds_since_epoch = int(time.mktime(time.strptime(date_time, pattern))) return seconds_since_epoch @register.filter(name='dict_get') def dict_get(h, key): try: return h[key] except: pass return None @register.filter(name='get_notification_age') def get_notification_age(value): now = datetime.datetime.now() try: difference = now - value except: return value if difference <= timedelta(minutes=1): return 'just now' return '%(time)s ago' % {'time': timesince(value).split(', ')[0]} @register.filter(name="get_historical_events") def get_historical_events(server_id): historical_service_statuses = mongo.historical_service_statuses historical_service_statuses = historical_service_statuses.find({'server_id':server_id,'type':'status',}) historical_service_statuses = historical_service_statuses.sort("_id",pymongo.DESCENDING) historical_service_statuses = historical_service_statuses.limit(50) return historical_service_statuses @register.filter(name="get_server_status") def get_server_status(server): if((datetime.datetime.now()-server['last_seen']).total_seconds()>300): return "offline" if((datetime.datetime.now()-server['last_seen']).total_seconds()>20): return "stopped" return "online" @register.filter(name='get_offline_seconds') def get_offline_seconds(server): return int((datetime.datetime.now()-server['last_seen']).total_seconds()) @register.filter(name='get_server_id_from_name') def get_server_id_from_name(name, secret): servers = mongo.servers server = servers.find_one({'name':name,'secret':secret,}) return server['uuid'] @register.filter(name='manual_notifs_count_unfortunately') def manual_notifs_count_unfortunately(notifs): return notifs.count() @register.filter(name='convert_disk_name') def convert_disk_name(x): try: return x.replace('/','slash') except: pass return None @register.filter(name="count_list") def count_list(x): return len(x) @register.filter(name="times_hundred") def times_hundred(x): try: return float(x)*100 except: return "error" @register.filter(name="times_hundred_rounded") def times_hundred_rounded(x): try: return int(float(x)*100) except: return "error" @register.filter(name='clear_filename') def clear_filename(f): try: return str(f)[20:] except: return f @register.filter(name='shorten_key') def shorten_key(key): return key[:11]+'..' @register.filter(name='shorten_string') def shorten_string(x,shorten): return x[:shorten] @register.filter(name='get_file_extension') def get_file_extension(f): return str(f).split('.')[-1:][0] @register.filter(name='replace_dots') def replace_dots(text): return text.replace(':','-') @register.filter(name='replace_dot') def replace_dot(text): return text.replace('.','-') @register.filter(name='replace_underscope') def replace_underscope(text): return text.replace('_',' ') @register.filter(name='replace_warning') def replace_warning(text): return text.replace("Warning - ", "") @register.filter(name='make_float') def make_float(value): return float(value) @register.filter(name='make_json') def make_json(json_): try: return json.loads(json_) except: return {} @register.filter(name='get_service_unity') def get_service_unity(service): unity = "" if service == 'SYSTEM_CPU': unity = '%' return unity @register.filter(name='make_json_sorted') def make_json_sorted(json_): json_ = json.loads(json_) json_.sort(key=lambda json_: json_['Timestamp']) return json_ @register.filter(name='get_tags') def get_tags(package): return Tags.objects.filter(package=package) @register.filter(name='to_mb') def to_mb(x): return long(x)/1024/1000 @register.filter(name='capitalize') def capitalize(s): return s.upper() @register.filter(name="clean_ps_command") def clean_ps_command(command): if(command[-1:]==":"): command = command[:-1] if(command[0]=="-"): command = command[1:] if(command[0]==" "): command = command[1:] command = command.replace('[','') command = command.replace(']','') command = command.replace('/usr/local/bin/','') command = command.replace('/usr/local/sbin/','') command = command.replace('/usr/bin/','') command = command.replace('/usr/sbin/','') command = command.replace('/bin/','') command = command.replace('/sbin/','') command = command.split(' ')[0] command = re.sub("([a-z|0-9]*)([A-Z][a-zA-Z]*)", "\\1 \\2", command) if(command[0]==" "): command = command[1:] command = command.split(' ')[0] return command @register.filter(name="work_single_ps_command") def work_single_ps_command(cmd): command = "" for i in cmd: command += i + " " command = command[:-1] return command @register.filter(name='format_datetime_special') def format_datetime_special(date): year = date.split('-')[0] month = date.split('-')[1] day = date.split('-')[2].split('T')[0] hour = date.split('-')[2].split('T')[1].split(':')[0] minute = date.split('-')[2].split('T')[1].split(':')[1] second = date.split('-')[2].split('T')[1].split(':')[2] return {'year':year, 'month':month, 'day':day, 'hour':hour, 'minute':minute, 'second':second} @register.filter(name='count_user_servers') def count_user_servers(user): try: vms_cache = Cache.objects.get(user=user) vms_response = vms_cache.vms_response vms_response = base64.b64decode(vms_response) vms_response = pickle.loads(vms_response) vms_cached_response = vms_response except: vms_cached_response = [] return len(vms_cached_response) @register.filter(name='count_user_files') def count_user_files(user): #users_files_count = Uploaded_Files.objects.filter(user=user).count() users_files_count = 0 return users_files_count @register.filter(name='count_user_files_size') def count_user_files_size(user): total_size = 0 #for user_file in Uploaded_Files.objects.filter(user=user): # total_size += user_file.size return total_size @register.filter(name='get_server_activities') def get_server_activities(server_uuid): activities = mongo.activity.find({'uuid':server_uuid,}).sort('_id',-1) return activities @register.filter(name='substract_one') def substract_one(x): x = int(x) return x-1 @register.filter(name='clean_percentage') def clean_percentage(x): return str(x).replace('%','')
# Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/ # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import base64 import datetime from hashlib import sha256 from hashlib import sha1 import hmac import logging from email.utils import formatdate from operator import itemgetter import functools import time import calendar import json from botocore.exceptions import NoCredentialsError from botocore.utils import normalize_url_path, percent_encode_sequence from botocore.compat import HTTPHeaders from botocore.compat import quote, unquote, urlsplit, parse_qs from botocore.compat import urlunsplit from botocore.compat import encodebytes from botocore.compat import six from botocore.compat import json from botocore.compat import MD5_AVAILABLE from botocore.compat import ensure_unicode logger = logging.getLogger(__name__) EMPTY_SHA256_HASH = ( 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') # This is the buffer size used when calculating sha256 checksums. # Experimenting with various buffer sizes showed that this value generally # gave the best result (in terms of performance). PAYLOAD_BUFFER = 1024 * 1024 ISO8601 = '%Y-%m-%dT%H:%M:%SZ' SIGV4_TIMESTAMP = '%Y%m%dT%H%M%SZ' SIGNED_HEADERS_BLACKLIST = [ 'expect', 'user-agent', 'x-amzn-trace-id', ] UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD' class BaseSigner(object): REQUIRES_REGION = False def add_auth(self, request): raise NotImplementedError("add_auth") class SigV2Auth(BaseSigner): """ Sign a request with Signature V2. """ def __init__(self, credentials): self.credentials = credentials def calc_signature(self, request, params): logger.debug("Calculating signature using v2 auth.") split = urlsplit(request.url) path = split.path if len(path) == 0: path = '/' string_to_sign = '%s\n%s\n%s\n' % (request.method, split.netloc, path) lhmac = hmac.new(self.credentials.secret_key.encode('utf-8'), digestmod=sha256) pairs = [] for key in sorted(params): # Any previous signature should not be a part of this # one, so we skip that particular key. This prevents # issues during retries. if key == 'Signature': continue value = six.text_type(params[key]) pairs.append(quote(key.encode('utf-8'), safe='') + '=' + quote(value.encode('utf-8'), safe='-_~')) qs = '&'.join(pairs) string_to_sign += qs logger.debug('String to sign: %s', string_to_sign) lhmac.update(string_to_sign.encode('utf-8')) b64 = base64.b64encode(lhmac.digest()).strip().decode('utf-8') return (qs, b64) def add_auth(self, request): # The auth handler is the last thing called in the # preparation phase of a prepared request. # Because of this we have to parse the query params # from the request body so we can update them with # the sigv2 auth params. if self.credentials is None: raise NoCredentialsError if request.data: # POST params = request.data else: # GET params = request.params params['AWSAccessKeyId'] = self.credentials.access_key params['SignatureVersion'] = '2' params['SignatureMethod'] = 'HmacSHA256' params['Timestamp'] = time.strftime(ISO8601, time.gmtime()) if self.credentials.token: params['SecurityToken'] = self.credentials.token qs, signature = self.calc_signature(request, params) params['Signature'] = signature return request class SigV3Auth(BaseSigner): def __init__(self, credentials): self.credentials = credentials def add_auth(self, request): if self.credentials is None: raise NoCredentialsError if 'Date' in request.headers: del request.headers['Date'] request.headers['Date'] = formatdate(usegmt=True) if self.credentials.token: if 'X-Amz-Security-Token' in request.headers: del request.headers['X-Amz-Security-Token'] request.headers['X-Amz-Security-Token'] = self.credentials.token new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'), digestmod=sha256) new_hmac.update(request.headers['Date'].encode('utf-8')) encoded_signature = encodebytes(new_hmac.digest()).strip() signature = ('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=%s,Signature=%s' % (self.credentials.access_key, 'HmacSHA256', encoded_signature.decode('utf-8'))) if 'X-Amzn-Authorization' in request.headers: del request.headers['X-Amzn-Authorization'] request.headers['X-Amzn-Authorization'] = signature class SigV4Auth(BaseSigner): """ Sign a request with Signature V4. """ REQUIRES_REGION = True def __init__(self, credentials, service_name, region_name): self.credentials = credentials # We initialize these value here so the unit tests can have # valid values. But these will get overriden in ``add_auth`` # later for real requests. self._region_name = region_name self._service_name = service_name def _sign(self, key, msg, hex=False): if hex: sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest() else: sig = hmac.new(key, msg.encode('utf-8'), sha256).digest() return sig def headers_to_sign(self, request): """ Select the headers from the request that need to be included in the StringToSign. """ header_map = HTTPHeaders() for name, value in request.headers.items(): lname = name.lower() if lname not in SIGNED_HEADERS_BLACKLIST: header_map[lname] = value if 'host' not in header_map: # Ensure we sign the lowercased version of the host, as that # is what will ultimately be sent on the wire. # TODO: We should set the host ourselves, instead of relying on our # HTTP client to set it for us. header_map['host'] = self._canonical_host(request.url).lower() return header_map def _canonical_host(self, url): url_parts = urlsplit(url) default_ports = { 'http': 80, 'https': 443 } if any(url_parts.scheme == scheme and url_parts.port == port for scheme, port in default_ports.items()): # No need to include the port if it's the default port. return url_parts.hostname # Strip out auth if it's present in the netloc. return url_parts.netloc.rsplit('@', 1)[-1] def canonical_query_string(self, request): # The query string can come from two parts. One is the # params attribute of the request. The other is from the request # url (in which case we have to re-split the url into its components # and parse out the query string component). if request.params: return self._canonical_query_string_params(request.params) else: return self._canonical_query_string_url(urlsplit(request.url)) def _canonical_query_string_params(self, params): l = [] for param in sorted(params): value = str(params[param]) l.append('%s=%s' % (quote(param, safe='-_.~'), quote(value, safe='-_.~'))) cqs = '&'.join(l) return cqs def _canonical_query_string_url(self, parts): canonical_query_string = '' if parts.query: # [(key, value), (key2, value2)] key_val_pairs = [] for pair in parts.query.split('&'): key, _, value = pair.partition('=') key_val_pairs.append((key, value)) sorted_key_vals = [] # Sort by the key names, and in the case of # repeated keys, then sort by the value. for key, value in sorted(key_val_pairs): sorted_key_vals.append('%s=%s' % (key, value)) canonical_query_string = '&'.join(sorted_key_vals) return canonical_query_string def canonical_headers(self, headers_to_sign): """ Return the headers that need to be included in the StringToSign in their canonical form by converting all header keys to lower case, sorting them in alphabetical order and then joining them into a string, separated by newlines. """ headers = [] sorted_header_names = sorted(set(headers_to_sign)) for key in sorted_header_names: value = ','.join(self._header_value(v) for v in sorted(headers_to_sign.get_all(key))) headers.append('%s:%s' % (key, ensure_unicode(value))) return '\n'.join(headers) def _header_value(self, value): # From the sigv4 docs: # Lowercase(HeaderName) + ':' + Trimall(HeaderValue) # # The Trimall function removes excess white space before and after # values, and converts sequential spaces to a single space. return ' '.join(value.split()) def signed_headers(self, headers_to_sign): l = ['%s' % n.lower().strip() for n in set(headers_to_sign)] l = sorted(l) return ';'.join(l) def payload(self, request): if not self._should_sha256_sign_payload(request): # When payload signing is disabled, we use this static string in # place of the payload checksum. return UNSIGNED_PAYLOAD request_body = request.body if request_body and hasattr(request_body, 'seek'): position = request_body.tell() read_chunksize = functools.partial(request_body.read, PAYLOAD_BUFFER) checksum = sha256() for chunk in iter(read_chunksize, b''): checksum.update(chunk) hex_checksum = checksum.hexdigest() request_body.seek(position) return hex_checksum elif request_body: # The request serialization has ensured that # request.body is a bytes() type. return sha256(request_body).hexdigest() else: return EMPTY_SHA256_HASH def _should_sha256_sign_payload(self, request): # Payloads will always be signed over insecure connections. if not request.url.startswith('https'): return True # Certain operations may have payload signing disabled by default. # Since we don't have access to the operation model, we pass in this # bit of metadata through the request context. return request.context.get('payload_signing_enabled', True) def canonical_request(self, request): cr = [request.method.upper()] path = self._normalize_url_path(urlsplit(request.url).path) cr.append(path) cr.append(self.canonical_query_string(request)) headers_to_sign = self.headers_to_sign(request) cr.append(self.canonical_headers(headers_to_sign) + '\n') cr.append(self.signed_headers(headers_to_sign)) if 'X-Amz-Content-SHA256' in request.headers: body_checksum = request.headers['X-Amz-Content-SHA256'] else: body_checksum = self.payload(request) cr.append(body_checksum) return '\n'.join(cr) def _normalize_url_path(self, path): normalized_path = quote(normalize_url_path(path), safe='/~') return normalized_path def scope(self, request): scope = [self.credentials.access_key] scope.append(request.context['timestamp'][0:8]) scope.append(self._region_name) scope.append(self._service_name) scope.append('aws4_request') return '/'.join(scope) def credential_scope(self, request): scope = [] scope.append(request.context['timestamp'][0:8]) scope.append(self._region_name) scope.append(self._service_name) scope.append('aws4_request') return '/'.join(scope) def string_to_sign(self, request, canonical_request): """ Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign. """ sts = ['AWS4-HMAC-SHA256'] sts.append(request.context['timestamp']) sts.append(self.credential_scope(request)) sts.append(sha256(canonical_request.encode('utf-8')).hexdigest()) return '\n'.join(sts) def signature(self, string_to_sign, request): key = self.credentials.secret_key k_date = self._sign(('AWS4' + key).encode('utf-8'), request.context['timestamp'][0:8]) k_region = self._sign(k_date, self._region_name) k_service = self._sign(k_region, self._service_name) k_signing = self._sign(k_service, 'aws4_request') return self._sign(k_signing, string_to_sign, hex=True) def add_auth(self, request): if self.credentials is None: raise NoCredentialsError datetime_now = datetime.datetime.utcnow() request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP) # This could be a retry. Make sure the previous # authorization header is removed first. self._modify_request_before_signing(request) canonical_request = self.canonical_request(request) logger.debug("Calculating signature using v4 auth.") logger.debug('CanonicalRequest:\n%s', canonical_request) string_to_sign = self.string_to_sign(request, canonical_request) logger.debug('StringToSign:\n%s', string_to_sign) signature = self.signature(string_to_sign, request) logger.debug('Signature:\n%s', signature) self._inject_signature_to_request(request, signature) def _inject_signature_to_request(self, request, signature): l = ['AWS4-HMAC-SHA256 Credential=%s' % self.scope(request)] headers_to_sign = self.headers_to_sign(request) l.append('SignedHeaders=%s' % self.signed_headers(headers_to_sign)) l.append('Signature=%s' % signature) request.headers['Authorization'] = ', '.join(l) return request def _modify_request_before_signing(self, request): if 'Authorization' in request.headers: del request.headers['Authorization'] self._set_necessary_date_headers(request) if self.credentials.token: if 'X-Amz-Security-Token' in request.headers: del request.headers['X-Amz-Security-Token'] request.headers['X-Amz-Security-Token'] = self.credentials.token if not request.context.get('payload_signing_enabled', True): if 'X-Amz-Content-SHA256' in request.headers: del request.headers['X-Amz-Content-SHA256'] request.headers['X-Amz-Content-SHA256'] = UNSIGNED_PAYLOAD def _set_necessary_date_headers(self, request): # The spec allows for either the Date _or_ the X-Amz-Date value to be # used so we check both. If there's a Date header, we use the date # header. Otherwise we use the X-Amz-Date header. if 'Date' in request.headers: del request.headers['Date'] datetime_timestamp = datetime.datetime.strptime( request.context['timestamp'], SIGV4_TIMESTAMP) request.headers['Date'] = formatdate( int(calendar.timegm(datetime_timestamp.timetuple()))) if 'X-Amz-Date' in request.headers: del request.headers['X-Amz-Date'] else: if 'X-Amz-Date' in request.headers: del request.headers['X-Amz-Date'] request.headers['X-Amz-Date'] = request.context['timestamp'] class S3SigV4Auth(SigV4Auth): def _modify_request_before_signing(self, request): super(S3SigV4Auth, self)._modify_request_before_signing(request) if 'X-Amz-Content-SHA256' in request.headers: del request.headers['X-Amz-Content-SHA256'] request.headers['X-Amz-Content-SHA256'] = self.payload(request) def _should_sha256_sign_payload(self, request): # S3 allows optional body signing, so to minimize the performance # impact, we opt to not SHA256 sign the body on streaming uploads, # provided that we're on https. client_config = request.context.get('client_config') s3_config = getattr(client_config, 's3', None) # The config could be None if it isn't set, or if the customer sets it # to None. if s3_config is None: s3_config = {} # The explicit configuration takes precedence over any implicit # configuration. sign_payload = s3_config.get('payload_signing_enabled', None) if sign_payload is not None: return sign_payload # We require that both content-md5 be present and https be enabled # to implicitly disable body signing. The combination of TLS and # content-md5 is sufficiently secure and durable for us to be # confident in the request without body signing. if not request.url.startswith('https') or \ 'Content-MD5' not in request.headers: return True # If the input is streaming we disable body signing by default. if request.context.get('has_streaming_input', False): return False # If the S3-specific checks had no results, delegate to the generic # checks. return super(S3SigV4Auth, self)._should_sha256_sign_payload(request) def _normalize_url_path(self, path): # For S3, we do not normalize the path. return path class SigV4QueryAuth(SigV4Auth): DEFAULT_EXPIRES = 3600 def __init__(self, credentials, service_name, region_name, expires=DEFAULT_EXPIRES): super(SigV4QueryAuth, self).__init__(credentials, service_name, region_name) self._expires = expires def _modify_request_before_signing(self, request): # We automatically set this header, so if it's the auto-set value we # want to get rid of it since it doesn't make sense for presigned urls. content_type = request.headers.get('content-type') blacklisted_content_type = ( 'application/x-www-form-urlencoded; charset=utf-8' ) if content_type == blacklisted_content_type: del request.headers['content-type'] # Note that we're not including X-Amz-Signature. # From the docs: "The Canonical Query String must include all the query # parameters from the preceding table except for X-Amz-Signature. signed_headers = self.signed_headers(self.headers_to_sign(request)) auth_params = { 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256', 'X-Amz-Credential': self.scope(request), 'X-Amz-Date': request.context['timestamp'], 'X-Amz-Expires': self._expires, 'X-Amz-SignedHeaders': signed_headers, } if self.credentials.token is not None: auth_params['X-Amz-Security-Token'] = self.credentials.token # Now parse the original query string to a dict, inject our new query # params, and serialize back to a query string. url_parts = urlsplit(request.url) # parse_qs makes each value a list, but in our case we know we won't # have repeated keys so we know we have single element lists which we # can convert back to scalar values. query_dict = dict( [(k, v[0]) for k, v in parse_qs(url_parts.query, keep_blank_values=True).items()]) # The spec is particular about this. It *has* to be: # https://<endpoint>?<operation params>&<auth params> # You can't mix the two types of params together, i.e just keep doing # new_query_params.update(op_params) # new_query_params.update(auth_params) # percent_encode_sequence(new_query_params) operation_params = '' if request.data: # We also need to move the body params into the query string. To # do this, we first have to convert it to a dict. query_dict.update(self._get_body_as_dict(request)) request.data = '' if query_dict: operation_params = percent_encode_sequence(query_dict) + '&' new_query_string = (operation_params + percent_encode_sequence(auth_params)) # url_parts is a tuple (and therefore immutable) so we need to create # a new url_parts with the new query string. # <part> - <index> # scheme - 0 # netloc - 1 # path - 2 # query - 3 <-- we're replacing this. # fragment - 4 p = url_parts new_url_parts = (p[0], p[1], p[2], new_query_string, p[4]) request.url = urlunsplit(new_url_parts) def _get_body_as_dict(self, request): # For query services, request.data is form-encoded and is already a # dict, but for other services such as rest-json it could be a json # string or bytes. In those cases we attempt to load the data as a # dict. data = request.data if isinstance(data, six.binary_type): data = json.loads(data.decode('utf-8')) elif isinstance(data, six.string_types): data = json.loads(data) return data def _inject_signature_to_request(self, request, signature): # Rather than calculating an "Authorization" header, for the query # param quth, we just append an 'X-Amz-Signature' param to the end # of the query string. request.url += '&X-Amz-Signature=%s' % signature class S3SigV4QueryAuth(SigV4QueryAuth): """S3 SigV4 auth using query parameters. This signer will sign a request using query parameters and signature version 4, i.e a "presigned url" signer. Based off of: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html """ def _normalize_url_path(self, path): # For S3, we do not normalize the path. return path def payload(self, request): # From the doc link above: # "You don't include a payload hash in the Canonical Request, because # when you create a presigned URL, you don't know anything about the # payload. Instead, you use a constant string "UNSIGNED-PAYLOAD". return UNSIGNED_PAYLOAD class S3SigV4PostAuth(SigV4Auth): """ Presigns a s3 post Implementation doc here: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-UsingHTTPPOST.html """ def add_auth(self, request): datetime_now = datetime.datetime.utcnow() request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP) fields = {} if request.context.get('s3-presign-post-fields', None) is not None: fields = request.context['s3-presign-post-fields'] policy = {} conditions = [] if request.context.get('s3-presign-post-policy', None) is not None: policy = request.context['s3-presign-post-policy'] if policy.get('conditions', None) is not None: conditions = policy['conditions'] policy['conditions'] = conditions fields['x-amz-algorithm'] = 'AWS4-HMAC-SHA256' fields['x-amz-credential'] = self.scope(request) fields['x-amz-date'] = request.context['timestamp'] conditions.append({'x-amz-algorithm': 'AWS4-HMAC-SHA256'}) conditions.append({'x-amz-credential': self.scope(request)}) conditions.append({'x-amz-date': request.context['timestamp']}) if self.credentials.token is not None: fields['x-amz-security-token'] = self.credentials.token conditions.append({'x-amz-security-token': self.credentials.token}) # Dump the base64 encoded policy into the fields dictionary. fields['policy'] = base64.b64encode( json.dumps(policy).encode('utf-8')).decode('utf-8') fields['x-amz-signature'] = self.signature(fields['policy'], request) request.context['s3-presign-post-fields'] = fields request.context['s3-presign-post-policy'] = policy class HmacV1Auth(BaseSigner): # List of Query String Arguments of Interest QSAOfInterest = ['accelerate', 'acl', 'cors', 'defaultObjectAcl', 'location', 'logging', 'partNumber', 'policy', 'requestPayment', 'torrent', 'versioning', 'versionId', 'versions', 'website', 'uploads', 'uploadId', 'response-content-type', 'response-content-language', 'response-expires', 'response-cache-control', 'response-content-disposition', 'response-content-encoding', 'delete', 'lifecycle', 'tagging', 'restore', 'storageClass', 'notification', 'replication', 'requestPayment', 'analytics', 'metrics', 'inventory', 'select', 'select-type'] def __init__(self, credentials, service_name=None, region_name=None): self.credentials = credentials def sign_string(self, string_to_sign): new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'), digestmod=sha1) new_hmac.update(string_to_sign.encode('utf-8')) return encodebytes(new_hmac.digest()).strip().decode('utf-8') def canonical_standard_headers(self, headers): interesting_headers = ['content-md5', 'content-type', 'date'] hoi = [] if 'Date' in headers: del headers['Date'] headers['Date'] = self._get_date() for ih in interesting_headers: found = False for key in headers: lk = key.lower() if headers[key] is not None and lk == ih: hoi.append(headers[key].strip()) found = True if not found: hoi.append('') return '\n'.join(hoi) def canonical_custom_headers(self, headers): hoi = [] custom_headers = {} for key in headers: lk = key.lower() if headers[key] is not None: if lk.startswith('x-amz-'): custom_headers[lk] = ','.join(v.strip() for v in headers.get_all(key)) sorted_header_keys = sorted(custom_headers.keys()) for key in sorted_header_keys: hoi.append("%s:%s" % (key, custom_headers[key])) return '\n'.join(hoi) def unquote_v(self, nv): """ TODO: Do we need this? """ if len(nv) == 1: return nv else: return (nv[0], unquote(nv[1])) def canonical_resource(self, split, auth_path=None): # don't include anything after the first ? in the resource... # unless it is one of the QSA of interest, defined above # NOTE: # The path in the canonical resource should always be the # full path including the bucket name, even for virtual-hosting # style addressing. The ``auth_path`` keeps track of the full # path for the canonical resource and would be passed in if # the client was using virtual-hosting style. if auth_path is not None: buf = auth_path else: buf = split.path if split.query: qsa = split.query.split('&') qsa = [a.split('=', 1) for a in qsa] qsa = [self.unquote_v(a) for a in qsa if a[0] in self.QSAOfInterest] if len(qsa) > 0: qsa.sort(key=itemgetter(0)) qsa = ['='.join(a) for a in qsa] buf += '?' buf += '&'.join(qsa) return buf def canonical_string(self, method, split, headers, expires=None, auth_path=None): cs = method.upper() + '\n' cs += self.canonical_standard_headers(headers) + '\n' custom_headers = self.canonical_custom_headers(headers) if custom_headers: cs += custom_headers + '\n' cs += self.canonical_resource(split, auth_path=auth_path) return cs def get_signature(self, method, split, headers, expires=None, auth_path=None): if self.credentials.token: del headers['x-amz-security-token'] headers['x-amz-security-token'] = self.credentials.token string_to_sign = self.canonical_string(method, split, headers, auth_path=auth_path) logger.debug('StringToSign:\n%s', string_to_sign) return self.sign_string(string_to_sign) def add_auth(self, request): if self.credentials is None: raise NoCredentialsError logger.debug("Calculating signature using hmacv1 auth.") split = urlsplit(request.url) logger.debug('HTTP request method: %s', request.method) signature = self.get_signature(request.method, split, request.headers, auth_path=request.auth_path) self._inject_signature(request, signature) def _get_date(self): return formatdate(usegmt=True) def _inject_signature(self, request, signature): if 'Authorization' in request.headers: # We have to do this because request.headers is not # normal dictionary. It has the (unintuitive) behavior # of aggregating repeated setattr calls for the same # key value. For example: # headers['foo'] = 'a'; headers['foo'] = 'b' # list(headers) will print ['foo', 'foo']. del request.headers['Authorization'] request.headers['Authorization'] = ( "AWS %s:%s" % (self.credentials.access_key, signature)) class HmacV1QueryAuth(HmacV1Auth): """ Generates a presigned request for s3. Spec from this document: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html #RESTAuthenticationQueryStringAuth """ DEFAULT_EXPIRES = 3600 def __init__(self, credentials, expires=DEFAULT_EXPIRES): self.credentials = credentials self._expires = expires def _get_date(self): return str(int(time.time() + int(self._expires))) def _inject_signature(self, request, signature): query_dict = {} query_dict['AWSAccessKeyId'] = self.credentials.access_key query_dict['Signature'] = signature for header_key in request.headers: lk = header_key.lower() # For query string requests, Expires is used instead of the # Date header. if header_key == 'Date': query_dict['Expires'] = request.headers['Date'] # We only want to include relevant headers in the query string. # These can be anything that starts with x-amz, is Content-MD5, # or is Content-Type. elif lk.startswith('x-amz-') or lk in ['content-md5', 'content-type']: query_dict[lk] = request.headers[lk] # Combine all of the identified headers into an encoded # query string new_query_string = percent_encode_sequence(query_dict) # Create a new url with the presigned url. p = urlsplit(request.url) if p[3]: # If there was a pre-existing query string, we should # add that back before injecting the new query string. new_query_string = '%s&%s' % (p[3], new_query_string) new_url_parts = (p[0], p[1], p[2], new_query_string, p[4]) request.url = urlunsplit(new_url_parts) class HmacV1PostAuth(HmacV1Auth): """ Generates a presigned post for s3. Spec from this document: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingHTTPPOST.html """ def add_auth(self, request): fields = {} if request.context.get('s3-presign-post-fields', None) is not None: fields = request.context['s3-presign-post-fields'] policy = {} conditions = [] if request.context.get('s3-presign-post-policy', None) is not None: policy = request.context['s3-presign-post-policy'] if policy.get('conditions', None) is not None: conditions = policy['conditions'] policy['conditions'] = conditions fields['AWSAccessKeyId'] = self.credentials.access_key if self.credentials.token is not None: fields['x-amz-security-token'] = self.credentials.token conditions.append({'x-amz-security-token': self.credentials.token}) # Dump the base64 encoded policy into the fields dictionary. fields['policy'] = base64.b64encode( json.dumps(policy).encode('utf-8')).decode('utf-8') fields['signature'] = self.sign_string(fields['policy']) request.context['s3-presign-post-fields'] = fields request.context['s3-presign-post-policy'] = policy # Defined at the bottom instead of the top of the module because the Auth # classes weren't defined yet. AUTH_TYPE_MAPS = { 'v2': SigV2Auth, 'v4': SigV4Auth, 'v4-query': SigV4QueryAuth, 'v3': SigV3Auth, 'v3https': SigV3Auth, 's3': HmacV1Auth, 's3-query': HmacV1QueryAuth, 's3-presign-post': HmacV1PostAuth, 's3v4': S3SigV4Auth, 's3v4-query': S3SigV4QueryAuth, 's3v4-presign-post': S3SigV4PostAuth, }
from copy import copy import io import re import inspect from sondra.exceptions import ParseError from sondra import help from functools import wraps from copy import deepcopy def expose_method(method): method.exposed = True method.slug = method.__name__.replace('_','-') return method # TODO validate input against schema. # TODO Add document processors and invoke method with properly dereferenced documents instead of keys def invoke_method(request, method): pass # TODO validate output against schema. # TODO Fix formatter to handle referencing or dereferencing documents as requested. def method_return(request, method): pass # TODO indicate that the API request should be passed as a parameter and what its name is, by default _request def accepts_request(): pass def ignore_request(): pass # TODO indicate that this method should ignore the _user parameter, even if it is authenticated. def ignore_user(): pass # TODO indicate that this method accepts a user parameter and what its name is, by default _user def accepts_user(): pass def expose_method_explicit(request_schema=None, response_schema=None, side_effects=False, title=None, description=None): request_schema = request_schema or {'type': 'null'} response_schema = response_schema or {'type': 'null'} def expose_method_decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): return func(*args, **kwargs) func_wrapper.exposed = True func_wrapper.slug = func.__name__.replace('_', '-') # auto-fill request schema items based on metadata if they were not explicitly provided. req_schema = deepcopy(request_schema) if 'title' not in req_schema: req_schema['title'] = title or func.__name__ if 'description' not in req_schema: req_schema['description'] = req_schema.get('description', description or func.__doc__ or '*No description provided*') req_schema['side_effects'] = side_effects rsp_schema = deepcopy(response_schema) if 'title' not in rsp_schema: rsp_schema['title'] = title or func.__name__ if 'description' not in rsp_schema: rsp_schema['description'] = rsp_schema.get('description', description or func.__doc__ or '*No description provided*') func_wrapper.title = title or func.__name__ func_wrapper.request_schema = req_schema func_wrapper.response_schema = rsp_schema @wraps(func) def invoke(*args, request=None): func(*args, **request) func_wrapper.invoke = invoke return func_wrapper return expose_method_decorator def method_url(instance, method): return instance.url + '.' + method.slug if instance is not None else method.slug def method_schema(instance, method): id = method.slug if instance is not None: if instance: id = instance.url else: id = "*" + method.slug return { "id": id, "title": getattr(method, 'title', method.__name__), "description": method.__doc__ or "*No description provided*", "oneOf": [{"$ref": "#/definitions/method_request"}, {"$ref": "#/definitions/method_response"}], "definitions": { "method_request": method_request_schema(instance, method), "method_response": method_response_schema(instance, method) } } def method_response_schema(instance, method): if hasattr(method, 'response_schema'): return method.response_schema # parse the return schema metadata = inspect.signature(method) if metadata.return_annotation is not metadata.empty: argtype = _parse_arg(instance, metadata.return_annotation) if 'type' in argtype: if argtype['type'] in {'list', 'object'}: return argtype else: return { "type": "object", "properties": { "_": argtype } } elif "$ref" in argtype: return argtype else: return { "type": "object", "properties": { "_": argtype } } else: return {"type": "object", "description": "no return value."} def method_request_schema(instance, method): if hasattr(method, 'request_schema'): return method.request_schema required_args = [] metadata = inspect.signature(method) properties = {} for i, (name, param) in enumerate(metadata.parameters.items()): if name.startswith('_'): continue # skips parameters filled in by decorators # if i == 0: # skip the first arg. # continue schema = _parse_arg(instance, param.annotation) if param.default is not metadata.empty: schema['default'] = param.default else: required_args.append(name) properties[name] = schema ret = { "type": "object", "properties": properties } if required_args: ret['required'] = required_args return ret def _parse_arg(instance, arg): from sondra.document import Document from sondra.collection import Collection if isinstance(arg, tuple): arg, description = arg else: description = None if arg is None: return {"type": "null"} if isinstance(arg, str): arg = {"type": "string", "foreignKey": arg} elif arg is str: arg = {"type": "string"} elif arg is bytes: arg = {"type": "string", "formatters": "attachment"} elif arg is int: arg = {"type": "integer"} elif arg is float: arg = {"type": "number"} elif arg is bool: arg = {"type": "boolean"} elif arg is list: arg = {"type": "array"} elif arg is dict: arg = {"type": "object"} elif isinstance(arg, re._pattern_type): arg = {"type": "string", "pattern": arg.pattern} elif isinstance(arg, list): arg = {"type": "array", "items": _parse_arg(instance, arg[0])} elif isinstance(arg, dict): arg = {"type": "object", "properties": {k: _parse_arg(instance, v) for k, v in arg.items()}} elif issubclass(arg, Collection): arg = {"$ref": (instance.application[arg.slug].url if instance is not None else "<application>") + ";schema"} elif issubclass(arg, Document): arg = copy(arg.schema) else: arg = {"type": ['string','boolean','integer','number','array','object'], "description": "Unspecified type arg."} if description: arg['description'] = description return arg def method_help(instance, method, out=None, initial_heading_level=0): out = out or io.StringIO() builder = help.SchemaHelpBuilder( method_schema(instance, method), out=out, initial_heading_level=0 ) builder.build() builder.line() return out.getvalue()
""" SQL functions reference lists: https://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html """ from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import ( BaseSpatialOperations, ) from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.operations import DatabaseOperations from django.utils.functional import cached_property from django.utils.version import get_version_tuple class SpatialiteNullCheckOperator(SpatialOperator): def as_sql(self, connection, lookup, template_params, sql_params): sql, params = super().as_sql(connection, lookup, template_params, sql_params) return '%s > 0' % sql, params class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): name = 'spatialite' spatialite = True Adapter = SpatiaLiteAdapter collect = 'Collect' extent = 'Extent' makeline = 'MakeLine' unionagg = 'GUnion' from_text = 'GeomFromText' gis_operators = { # Binary predicates 'equals': SpatialiteNullCheckOperator(func='Equals'), 'disjoint': SpatialiteNullCheckOperator(func='Disjoint'), 'touches': SpatialiteNullCheckOperator(func='Touches'), 'crosses': SpatialiteNullCheckOperator(func='Crosses'), 'within': SpatialiteNullCheckOperator(func='Within'), 'overlaps': SpatialiteNullCheckOperator(func='Overlaps'), 'contains': SpatialiteNullCheckOperator(func='Contains'), 'intersects': SpatialiteNullCheckOperator(func='Intersects'), 'relate': SpatialiteNullCheckOperator(func='Relate'), 'coveredby': SpatialiteNullCheckOperator(func='CoveredBy'), 'covers': SpatialiteNullCheckOperator(func='Covers'), # Returns true if B's bounding box completely contains A's bounding box. 'contained': SpatialOperator(func='MbrWithin'), # Returns true if A's bounding box completely contains B's bounding box. 'bbcontains': SpatialOperator(func='MbrContains'), # Returns true if A's bounding box overlaps B's bounding box. 'bboverlaps': SpatialOperator(func='MbrOverlaps'), # These are implemented here as synonyms for Equals 'same_as': SpatialiteNullCheckOperator(func='Equals'), 'exact': SpatialiteNullCheckOperator(func='Equals'), # Distance predicates 'dwithin': SpatialOperator(func='PtDistWithin'), } disallowed_aggregates = (models.Extent3D,) select = 'CAST (AsEWKB(%s) AS BLOB)' function_names = { 'AsWKB': 'St_AsBinary', 'ForcePolygonCW': 'ST_ForceLHR', 'Length': 'ST_Length', 'LineLocatePoint': 'ST_Line_Locate_Point', 'NumPoints': 'ST_NPoints', 'Reverse': 'ST_Reverse', 'Scale': 'ScaleCoords', 'Translate': 'ST_Translate', 'Union': 'ST_Union', } @cached_property def unsupported_functions(self): unsupported = {'BoundingCircle', 'GeometryDistance', 'MemSize'} if not self.lwgeom_version(): unsupported |= {'Azimuth', 'GeoHash', 'IsValid', 'MakeValid'} return unsupported @cached_property def spatial_version(self): """Determine the version of the SpatiaLite library.""" try: version = self.spatialite_version_tuple()[1:] except Exception as exc: raise ImproperlyConfigured( 'Cannot determine the SpatiaLite version for the "%s" database. ' 'Was the SpatiaLite initialization SQL loaded on this database?' % ( self.connection.settings_dict['NAME'], ) ) from exc if version < (4, 3, 0): raise ImproperlyConfigured('GeoDjango supports SpatiaLite 4.3.0 and above.') return version def convert_extent(self, box): """ Convert the polygon data received from SpatiaLite to min/max values. """ if box is None: return None shell = GEOSGeometry(box).shell xmin, ymin = shell[0][:2] xmax, ymax = shell[2][:2] return (xmin, ymin, xmax, ymax) def geo_db_type(self, f): """ Return None because geometry columns are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None def get_distance(self, f, value, lookup_type): """ Return the distance parameters for the given geometry field, lookup value, and lookup type. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): if lookup_type == 'dwithin': raise ValueError( 'Only numeric values of degree units are allowed on ' 'geographic DWithin queries.' ) dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value return [dist_param] def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller. """ cursor = self.connection._cursor() try: cursor.execute('SELECT %s' % func) row = cursor.fetchone() finally: cursor.close() return row[0] def geos_version(self): "Return the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func('geos_version()') def proj4_version(self): "Return the version of the PROJ.4 library used by SpatiaLite." return self._get_spatialite_func('proj4_version()') def lwgeom_version(self): """Return the version of LWGEOM library used by SpatiaLite.""" return self._get_spatialite_func('lwgeom_version()') def spatialite_version(self): "Return the SpatiaLite library version as a string." return self._get_spatialite_func('spatialite_version()') def spatialite_version_tuple(self): """ Return the SpatiaLite version as a tuple (version string, major, minor, subminor). """ version = self.spatialite_version() return (version,) + get_version_tuple(version) def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = 'unionagg' if agg_name.lower() == 'union' else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteGeometryColumns return SpatialiteGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys return SpatialiteSpatialRefSys def get_geometry_converter(self, expression): geom_class = expression.output_field.geom_class read = wkb_r().read def converter(value, expression, connection): return None if value is None else GEOSGeometryBase(read(value), geom_class) return converter
import logging import copy import datetime import pytz import re from collections import defaultdict from helpers.match_manipulator import MatchManipulator from models.match import Match class MatchHelper(object): @classmethod def add_match_times(cls, event, matches): """ Calculates and adds match times given an event and match time strings (from USFIRST) Assumes the last match is played on the last day of comeptition and works backwards from there. """ if event.timezone_id is None: # Can only calculate match times if event timezone is known logging.warning('Cannot compute match time for event with no timezone_id: {}'.format(event.key_name)) return matches_reversed = cls.play_order_sort_matches(matches, reverse=True) tz = pytz.timezone(event.timezone_id) last_match_time = None cur_date = event.end_date + datetime.timedelta(hours=23, minutes=59, seconds=59) # end_date is specified at midnight of the last day for match in matches_reversed: r = re.match(r'(\d+):(\d+) (am|pm)', match.time_string.lower()) hour = int(r.group(1)) minute = int(r.group(2)) if hour == 12: hour = 0 if r.group(3) == 'pm': hour += 12 match_time = datetime.datetime(cur_date.year, cur_date.month, cur_date.day, hour, minute) if last_match_time is not None and last_match_time + datetime.timedelta(hours=6) < match_time: cur_date = cur_date - datetime.timedelta(days=1) match_time = datetime.datetime(cur_date.year, cur_date.month, cur_date.day, hour, minute) last_match_time = match_time match.time = match_time - tz.utcoffset(match_time) """ Helper to put matches into sub-dictionaries for the way we render match tables """ # Allows us to sort matches by key name. # Note: Matches within a comp_level (qual, qf, sf, f, etc.) will be in order, # but the comp levels themselves may not be in order. Doesn't matter because # XXX_match_table.html checks for comp_level when rendering the page @classmethod def natural_sort_matches(self, matches): import re convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda match: [convert(c) for c in re.split('([0-9]+)', str(match.key_name))] return sorted(matches, key=alphanum_key) @classmethod def play_order_sort_matches(self, matches, reverse=False): sort_key = lambda match: match.play_order return sorted(matches, key=sort_key, reverse=reverse) @classmethod def organizeMatches(self, match_list): match_list = MatchHelper.natural_sort_matches(match_list) matches = dict([(comp_level, list()) for comp_level in Match.COMP_LEVELS]) matches["num"] = len(match_list) while len(match_list) > 0: match = match_list.pop(0) matches[match.comp_level].append(match) return matches @classmethod def recentMatches(self, matches, num=3): matches = filter(lambda x: x.has_been_played, matches) matches = self.play_order_sort_matches(matches) return matches[-num:] @classmethod def upcomingMatches(self, matches, num=3): matches = self.play_order_sort_matches(matches) last_played_match_index = None for i, match in enumerate(reversed(matches)): if match.has_been_played: last_played_match_index = len(matches) - i break upcoming_matches = [] for i, match in enumerate(matches[last_played_match_index:]): if i == num: break if not match.has_been_played: upcoming_matches.append(match) return upcoming_matches @classmethod def deleteInvalidMatches(self, match_list): """ A match is invalid iff it is an elim match where the match number is 3 and the same alliance won in match numbers 1 and 2 of the same set. """ matches_by_key = {} for match in match_list: matches_by_key[match.key_name] = match return_list = [] for match in match_list: if match.comp_level in Match.ELIM_LEVELS and match.match_number == 3 and (not match.has_been_played): match_1 = matches_by_key.get(Match.renderKeyName(match.event.id(), match.comp_level, match.set_number, 1)) match_2 = matches_by_key.get(Match.renderKeyName(match.event.id(), match.comp_level, match.set_number, 2)) if match_1 is not None and match_2 is not None and\ match_1.has_been_played and match_2.has_been_played and\ match_1.winning_alliance == match_2.winning_alliance: try: MatchManipulator.delete(match) logging.warning("Deleting invalid match: %s" % match.key_name) except: logging.warning("Tried to delete invalid match, but failed: %s" % match.key_name) continue return_list.append(match) return return_list @classmethod def generateBracket(cls, matches, alliance_selections=None): complete_alliances = [] bracket_table = defaultdict(lambda: defaultdict(dict)) for comp_level in ['qf', 'sf', 'f']: for match in matches[comp_level]: set_number = match.set_number if set_number not in bracket_table[comp_level]: bracket_table[comp_level][set_number] = { 'red_alliance': [], 'blue_alliance': [], 'winning_alliance': None, 'red_wins': 0, 'blue_wins': 0, } for color in ['red', 'blue']: alliance = copy.copy(match.alliances[color]['teams']) for i, complete_alliance in enumerate(complete_alliances): # search for alliance. could be more efficient if len(set(alliance).intersection(set(complete_alliance))) >= 2: # if >= 2 teams are the same, then the alliance is the same backups = list(set(alliance).difference(set(complete_alliance))) complete_alliances[i] += backups # ensures that backup robots are listed last for team_num in cls.getOrderedAlliance(complete_alliances[i], alliance_selections): if team_num not in bracket_table[comp_level][set_number]['{}_alliance'.format(color)]: bracket_table[comp_level][set_number]['{}_alliance'.format(color)].append(team_num) break else: complete_alliances.append(alliance) winner = match.winning_alliance if not winner or winner == '': # if the match is a tie continue bracket_table[comp_level][set_number]['{}_wins'.format(winner)] = \ bracket_table[comp_level][set_number]['{}_wins'.format(winner)] + 1 if bracket_table[comp_level][set_number]['red_wins'] == 2: bracket_table[comp_level][set_number]['winning_alliance'] = 'red' if bracket_table[comp_level][set_number]['blue_wins'] == 2: bracket_table[comp_level][set_number]['winning_alliance'] = 'blue' return bracket_table @classmethod def generatePlayoffAdvancement2015(cls, matches, alliance_selections=None): complete_alliances = [] advancement = defaultdict(list) # key: comp level; value: list of [complete_alliance, [scores], average_score] for comp_level in ['ef', 'qf', 'sf']: for match in matches.get(comp_level, []): if not match.has_been_played: continue for color in ['red', 'blue']: alliance = cls.getOrderedAlliance(match.alliances[color]['teams'], alliance_selections) for i, complete_alliance in enumerate(complete_alliances): # search for alliance. could be more efficient if len(set(alliance).intersection(set(complete_alliance))) >= 2: # if >= 2 teams are the same, then the alliance is the same backups = list(set(alliance).difference(set(complete_alliance))) complete_alliances[i] += backups # ensures that backup robots are listed last break else: i = None complete_alliances.append(alliance) is_new = False if i is not None: for j, (complete_alliance, scores, _) in enumerate(advancement[comp_level]): # search for alliance. could be more efficient if len(set(complete_alliances[i]).intersection(set(complete_alliance))) >= 2: # if >= 2 teams are the same, then the alliance is the same complete_alliance = complete_alliances[i] scores.append(match.alliances[color]['score']) advancement[comp_level][j][2] = float(sum(scores)) / len(scores) break else: is_new = True score = match.alliances[color]['score'] if i is None: advancement[comp_level].append([alliance, [score], score]) elif is_new: advancement[comp_level].append([complete_alliances[i], [score], score]) advancement[comp_level] = sorted(advancement[comp_level], key=lambda x: -x[2]) # sort by descending average score return advancement @classmethod def getOrderedAlliance(cls, team_keys, alliance_selections): if alliance_selections: for alliance_selection in alliance_selections: # search for alliance. could be more efficient picks = alliance_selection['picks'] if len(set(picks).intersection(set(team_keys))) >= 2: # if >= 2 teams are the same, then the alliance is the same backups = list(set(team_keys).difference(set(picks))) team_keys = picks + backups break team_nums = [] for team in team_keys: # Strip the "frc" prefix team_nums.append(team[3:]) return team_nums """ Valid breakdowns are those used for seeding. Varies by year. For 2014, seeding outlined in Section 5.3.4 in the 2014 manual. """ VALID_BREAKDOWNS = { 2014: set(['auto', 'assist', 'truss+catch', 'teleop_goal+foul']), 2015: set(['coopertition_points', 'auto_points', 'container_points', 'tote_points', 'litter_points', 'foul_points']), } @classmethod def is_valid_score_breakdown_key(cls, key, year): """ If valid, returns True. Otherwise, returns the set of valid breakdowns. """ valid_breakdowns = cls.VALID_BREAKDOWNS.get(year, set()) if key in valid_breakdowns: return True else: return valid_breakdowns @classmethod def tiebreak_winner(cls, match): """ Compute elim winner using tiebreakers """ if match.comp_level not in match.ELIM_LEVELS or not match.score_breakdown or \ 'red' not in match.score_breakdown or 'blue' not in match.score_breakdown: return '' red_breakdown = match.score_breakdown['red'] blue_breakdown = match.score_breakdown['blue'] tiebreakers = [] # Tuples of (red_tiebreaker, blue_tiebreaker) or None. Higher value wins. if match.year == 2016: # Greater number of FOUL points awarded (i.e. the ALLIANCE that played the cleaner MATCH) if 'foulPoints' in red_breakdown and 'foulPoints' in blue_breakdown: tiebreakers.append((red_breakdown['foulPoints'], blue_breakdown['foulPoints'])) else: tiebreakers.append(None) # Cumulative sum of BREACH and CAPTURE points if 'breachPoints' in red_breakdown and 'breachPoints' in blue_breakdown and \ 'capturePoints' in red_breakdown and 'capturePoints' in blue_breakdown: red_breach_capture = red_breakdown['breachPoints'] + red_breakdown['capturePoints'] blue_breach_capture = blue_breakdown['breachPoints'] + blue_breakdown['capturePoints'] tiebreakers.append((red_breach_capture, blue_breach_capture)) else: tiebreakers.append(None) # Cumulative sum of scored AUTO points if 'autoPoints' in red_breakdown and 'autoPoints' in blue_breakdown: tiebreakers.append((red_breakdown['autoPoints'], blue_breakdown['autoPoints'])) else: tiebreakers.append(None) # Cumulative sum of scored SCALE and CHALLENGE points if 'teleopScalePoints' in red_breakdown and 'teleopScalePoints' in blue_breakdown and \ 'teleopChallengePoints' in red_breakdown and 'teleopChallengePoints' in blue_breakdown: red_scale_challenge = red_breakdown['teleopScalePoints'] + red_breakdown['teleopChallengePoints'] blue_scale_challenge = blue_breakdown['teleopScalePoints'] + blue_breakdown['teleopChallengePoints'] tiebreakers.append((red_scale_challenge, blue_scale_challenge)) else: tiebreakers.append(None) # Cumulative sum of scored TOWER GOAL points (High and Low goals from AUTO and TELEOP) if 'autoBoulderPoints' in red_breakdown and 'autoBoulderPoints' in blue_breakdown and \ 'teleopBoulderPoints' in red_breakdown and 'teleopBoulderPoints' in blue_breakdown: red_boulder = red_breakdown['autoBoulderPoints'] + red_breakdown['teleopBoulderPoints'] blue_boulder = blue_breakdown['autoBoulderPoints'] + blue_breakdown['teleopBoulderPoints'] tiebreakers.append((red_boulder, blue_boulder)) else: tiebreakers.append(None) # Cumulative sum of CROSSED UNDAMAGED DEFENSE points (AUTO and TELEOP) if 'autoCrossingPoints' in red_breakdown and 'autoCrossingPoints' in blue_breakdown and \ 'teleopCrossingPoints' in red_breakdown and 'teleopCrossingPoints' in blue_breakdown: red_crossing = red_breakdown['autoCrossingPoints'] + red_breakdown['teleopCrossingPoints'] blue_crossing = blue_breakdown['autoCrossingPoints'] + blue_breakdown['teleopCrossingPoints'] tiebreakers.append((red_crossing, blue_crossing)) else: tiebreakers.append(None) for tiebreaker in tiebreakers: if tiebreaker is None: return '' elif tiebreaker[0] > tiebreaker[1]: return 'red' elif tiebreaker[1] > tiebreaker[0]: return 'blue' return ''
""" <Program> lockserver_daemon.py <Started> 30 June 2009 <Author> Justin Samuel <Purpose> This is the XML-RPC Backend that is used by various components of SeattleGeni. XML-RPC Interface: TODO: describe the interface """ import datetime import sys import time import traceback import thread # These are used to build a single-threaded XMLRPC server. import SocketServer import SimpleXMLRPCServer import xmlrpclib # To send the admins emails when there's an unhandled exception. import django.core.mail # We use django.db.reset_queries() to prevent memory "leaks" due to query # logging when settings.DEBUG is True. import django.db # The config module contains the authcode that is required for performing # privileged operations. import seattlegeni.backend.config from seattlegeni.common.api import keydb from seattlegeni.common.api import keygen # The lockserver is needed by the vessel cleanup thread. from seattlegeni.common.api import lockserver from seattlegeni.common.api import maindb from seattlegeni.common.api import nodemanager from seattlegeni.common.exceptions import * from seattlegeni.common.util import log from seattlegeni.common.util import parallel from seattlegeni.common.util.assertions import * from seattlegeni.common.util.decorators import log_function_call from seattlegeni.common.util.decorators import log_function_call_without_first_argument from seattlegeni.website import settings # The port that we'll listen on. LISTENPORT = 8020 class ThreadedXMLRPCServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer): """This is a threaded XMLRPC Server. """ def _get_node_handle_from_nodeid(nodeid, owner_pubkey=None): # Raises DoesNotExistError if no such node exists. node = maindb.get_node(nodeid) # If a specific owner key wasn't provided, use the one that is set in the # database for this node. if owner_pubkey is None: owner_pubkey = node.owner_pubkey # Raises DoesNotExistError if no such key exists. owner_privkey = keydb.get_private_key(owner_pubkey) return nodemanager.get_node_handle(nodeid, node.last_known_ip, node.last_known_port, owner_pubkey, owner_privkey) def _assert_number_of_arguments(functionname, args, exact_number): """ <Purpose> Ensure that an args tuple which one of the public xmlrpc functions was called with has an expected number of arguments. <Arguments> functionname: The name of the function whose number of arguments are being checked. This is just for logging in the case that the arguments don't match. args: A tuple of arguments (received by the other function through *args). exact_number: The exact number of arguments that must be in the args tuple. <Exceptions> Raises InvalidRequestError if args does not contain exact_number items. <Side Effects> None. <Returns> None. """ if len(args) != exact_number: message = "Invalid number of arguments to function " + functionname + ". " message += "Expected " + str(exact_number) + ", received " + str(len(args)) + "." raise InvalidRequestError(message) def _assert_valid_authcode(authcode): if authcode != seattlegeni.backend.config.authcode: raise InvalidRequestError("The provided authcode (" + authcode + ") is invalid.") class BackendPublicFunctions(object): """ All public functions of this class are automatically exposed as part of the xmlrpc interface. """ def _dispatch(self, method, args): """ We provide a _dispatch function (which SimpleXMLRPCServer looks for and uses) so that we can log exceptions due to our programming errors within the backend as well to detect incorrect usage by clients. """ try: # Get the requested function (making sure it exists). try: func = getattr(self, method) except AttributeError: raise InvalidRequestError("The requested method '" + method + "' doesn't exist.") # Call the requested function. return func(*args) except NodemanagerCommunicationError, e: raise xmlrpclib.Fault(100, "Node communication failure: " + str(e)) except (DoesNotExistError, InvalidRequestError, AssertionError): log.error("The backend was used incorrectly: " + traceback.format_exc()) raise except: # We assume all other exceptions are bugs in the backend. Unlike the # lockserver where it might result in broader data corruption, here in # the backend we allow the backend to continue serving other requests. # That is, we don't go through steps to try to shutdown the backend. message = "The backend had an internal error: " + traceback.format_exc() log.critical(message) # Send an email to the addresses listed in settings.ADMINS if not settings.DEBUG: subject = "Critical SeattleGeni backend error" django.core.mail.mail_admins(subject, message) raise # Using @staticmethod makes it so that 'self' doesn't get passed in as the first arg. @staticmethod @log_function_call def GenerateKey(*args): """ This is a public function of the XMLRPC server. See the module comments at the top of the file for a description of how it is used. """ _assert_number_of_arguments('GenerateKey', args, 1) keydescription = args[0] assert_str(keydescription) # Generate a new keypair. (pubkey, privkey) = keygen.generate_keypair() # Store the private key in the keydb. keydb.set_private_key(pubkey, privkey, keydescription) # Return the public key as a string. return pubkey # Using @staticmethod makes it so that 'self' doesn't get passed in as the first arg. @staticmethod @log_function_call def SetVesselUsers(*args): """ This is a public function of the XMLRPC server. See the module comments at the top of the file for a description of how it is used. """ _assert_number_of_arguments('SetVesselUsers', args, 3) (nodeid, vesselname, userkeylist) = args assert_str(nodeid) assert_str(vesselname) assert_list(userkeylist) for userkey in userkeylist: assert_str(userkey) # Note: The nodemanager checks whether each key is a valid key and will # raise an exception if it is not. # Raises a DoesNotExistError if there is no node with this nodeid. nodehandle = _get_node_handle_from_nodeid(nodeid) # Raises NodemanagerCommunicationError if it fails. nodemanager.change_users(nodehandle, vesselname, userkeylist) # Using @staticmethod makes it so that 'self' doesn't get passed in as the first arg. @staticmethod @log_function_call_without_first_argument def SetVesselOwner(*args): """ This is a public function of the XMLRPC server. See the module comments at the top of the file for a description of how it is used. """ _assert_number_of_arguments('SetVesselOwner', args, 5) (authcode, nodeid, vesselname, old_ownerkey, new_ownerkey) = args assert_str(authcode) assert_str(nodeid) assert_str(vesselname) assert_str(old_ownerkey) assert_str(new_ownerkey) _assert_valid_authcode(authcode) # Note: The nodemanager checks whether the owner key is a valid key and # will raise an exception if it is not. # Raises a DoesNotExistError if there is no node with this nodeid. nodehandle = _get_node_handle_from_nodeid(nodeid, owner_pubkey=old_ownerkey) # Raises NodemanagerCommunicationError if it fails. nodemanager.change_owner(nodehandle, vesselname, new_ownerkey) # Using @staticmethod makes it so that 'self' doesn't get passed in as the first arg. @staticmethod @log_function_call_without_first_argument def SplitVessel(*args): """ This is a public function of the XMLRPC server. See the module comments at the top of the file for a description of how it is used. """ _assert_number_of_arguments('SplitVessels', args, 4) (authcode, nodeid, vesselname, desiredresourcedata) = args assert_str(authcode) assert_str(nodeid) assert_str(vesselname) assert_str(desiredresourcedata) _assert_valid_authcode(authcode) # Raises a DoesNotExistError if there is no node with this nodeid. nodehandle = _get_node_handle_from_nodeid(nodeid) # Raises NodemanagerCommunicationError if it fails. return nodemanager.split_vessel(nodehandle, vesselname, desiredresourcedata) # Using @staticmethod makes it so that 'self' doesn't get passed in as the first arg. @staticmethod @log_function_call_without_first_argument def JoinVessels(*args): """ This is a public function of the XMLRPC server. See the module comments at the top of the file for a description of how it is used. """ _assert_number_of_arguments('JoinVessels', args, 4) (authcode, nodeid, firstvesselname, secondvesselname) = args assert_str(authcode) assert_str(nodeid) assert_str(firstvesselname) assert_str(secondvesselname) _assert_valid_authcode(authcode) # Raises a DoesNotExistError if there is no node with this nodeid. nodehandle = _get_node_handle_from_nodeid(nodeid) # Raises NodemanagerCommunicationError if it fails. return nodemanager.join_vessels(nodehandle, firstvesselname, secondvesselname) def cleanup_vessels(): """ This function is started as separate thread. It continually checks whether there are vessels needing to be cleaned up and initiates cleanup as needed. """ log.info("[cleanup_vessels] cleanup thread started.") # Start a transaction management. django.db.transaction.enter_transaction_management() # Run forever. while True: try: # Sleep a few seconds for those times where we don't have any vessels to clean up. time.sleep(5) # We shouldn't be running the backend in production with # settings.DEBUG = True. Just in case, though, tell django to reset its # list of saved queries each time through the loop. Note that this is not # specific to the cleanup thread as other parts of the backend are using # the maindb, as well, so we're overloading the purpose of the cleanup # thread by doing this here. This is just a convenient place to do it. # See http://docs.djangoproject.com/en/dev/faq/models/#why-is-django-leaking-memory # for more info. if settings.DEBUG: django.db.reset_queries() # First, make it so that expired vessels are seen as dirty. We aren't # holding a lock on the nodes when we do this. It's possible that we do # this while someone else has a lock on the node. What would result? # I believe the worst result is that a user has their vessel marked as # dirty after they renewed in the case where they are renewing it just # as it expires (with some exceptionally bad timing involved). And, # that's not really very bad as if the user is trying to renew at the # exact moment it expires, their trying their luck with how fast their # request gets processed, anyways. In short, I don't think it's important # enough to either obtain locks to do this or to rewrite the code to # avoid any need for separately marking expired vessels as dirty rather # than just trying to process expired vessels directly in the code below. date_started=datetime.datetime.now() expired_list = maindb.mark_expired_vessels_as_dirty() if len(expired_list) > 0: log.info("[cleanup_vessels] " + str(len(expired_list)) + " expired vessels have been marked as dirty: " + str(expired_list)) maindb.create_action_log_event("mark_expired_vessels_as_dirty", user=None, second_arg=None, third_arg=None, was_successful=True, message=None, date_started=date_started, vessel_list=expired_list) # Get a list of vessels to clean up. This doesn't include nodes known to # be inactive as we would just continue failing to communicate with nodes # that are down. cleanupvessellist = maindb.get_vessels_needing_cleanup() if len(cleanupvessellist) == 0: continue log.info("[cleanup_vessels] " + str(len(cleanupvessellist)) + " vessels to clean up: " + str(cleanupvessellist)) parallel_results = parallel.run_parallelized(cleanupvessellist, _cleanup_single_vessel) if len(parallel_results["exception"]) > 0: for vessel, exception_message in parallel_results["exception"]: log_message = "Unhandled exception during parallelized vessel cleanup: " + exception_message log.critical(log_message) # Raise the last exceptions so that the admin gets an email. raise InternalError(log_message) except: message = "[cleanup_vessels] Something very bad happened: " + traceback.format_exc() log.critical(message) # Send an email to the addresses listed in settings.ADMINS if not settings.DEBUG: subject = "Critical SeattleGeni backend error" django.core.mail.mail_admins(subject, message) # Sleep for ten minutes to make sure we don't flood the admins with error # report emails. time.sleep(600) finally: # Manually commit the transaction to prevent caching. django.db.transaction.commit() def _cleanup_single_vessel(vessel): """ This function is passed by cleanup_vessels() as the function argument to run_parallelized(). """ # This does seem wasteful of lockserver communication to require four # round-trips with the lockserver (get handle, lock, unlock, release handle), # but if we really want to fix that then I think the best thing to do would # be to allow obtaining a lockhandle and releasing a lockhandle to be done # in the same calls as lock acquisition and release. node_id = maindb.get_node_identifier_from_vessel(vessel) lockserver_handle = lockserver.create_lockserver_handle() # Lock the node that the vessels is on. lockserver.lock_node(lockserver_handle, node_id) try: # Get a new vessel object from the db in case it was modified in the db # before the lock was obtained. vessel = maindb.get_vessel(node_id, vessel.name) # Now that we have a lock on the node that this vessel is on, find out # if we should still clean up this vessel (e.g. maybe a node state # transition script moved the node to a new state and this vessel was # removed). needscleanup, reasonwhynot = maindb.does_vessel_need_cleanup(vessel) if not needscleanup: log.info("[_cleanup_single_vessel] Vessel " + str(vessel) + " no longer needs cleanup: " + reasonwhynot) return nodeid = maindb.get_node_identifier_from_vessel(vessel) nodehandle = _get_node_handle_from_nodeid(nodeid) try: log.info("[_cleanup_single_vessel] About to ChangeUsers on vessel " + str(vessel)) nodemanager.change_users(nodehandle, vessel.name, ['']) log.info("[_cleanup_single_vessel] About to ResetVessel on vessel " + str(vessel)) nodemanager.reset_vessel(nodehandle, vessel.name) except NodemanagerCommunicationError: # We don't pass this exception up. Maybe the node is offline now. At some # point, it will be marked in the database as offline (should we be doing # that here?). At that time, the dirty vessels on that node will not be # in the cleanup list anymore. log.info("[_cleanup_single_vessel] Failed to cleanup vessel " + str(vessel) + ". " + traceback.format_exc()) return # We only mark it as clean if no exception was raised when trying to # perform the above nodemanager operations. maindb.mark_vessel_as_clean(vessel) log.info("[_cleanup_single_vessel] Successfully cleaned up vessel " + str(vessel)) finally: # Unlock the node. lockserver.unlock_node(lockserver_handle, node_id) lockserver.destroy_lockserver_handle(lockserver_handle) def sync_user_keys_of_vessels(): """ This function is started as separate thread. It continually checks whether there are vessels needing their user keys sync'd and initiates the user key sync as needed. """ log.info("[sync_user_keys_of_vessels] thread started.") # Run forever. while True: try: # Sleep a few seconds for those times where we don't have any vessels to clean up. time.sleep(5) # We shouldn't be running the backend in production with # settings.DEBUG = True. Just in case, though, tell django to reset its # list of saved queries each time through the loop. if settings.DEBUG: django.db.reset_queries() # Get a list of vessels that need to have user keys sync'd. This doesn't # include nodes known to be inactive as we would just continue failing to # communicate with nodes that are down. vessellist = maindb.get_vessels_needing_user_key_sync() if len(vessellist) == 0: continue log.info("[sync_user_keys_of_vessels] " + str(len(vessellist)) + " vessels to have user keys sync'd: " + str(vessellist)) parallel_results = parallel.run_parallelized(vessellist, _sync_user_keys_of_single_vessel) if len(parallel_results["exception"]) > 0: for vessel, exception_message in parallel_results["exception"]: log_message = "Unhandled exception during parallelized vessel user key sync: " + exception_message log.critical(log_message) # Raise the last exceptions so that the admin gets an email. raise InternalError(log_message) except: message = "[sync_user_keys_of_vessels] Something very bad happened: " + traceback.format_exc() log.critical(message) # Send an email to the addresses listed in settings.ADMINS if not settings.DEBUG: subject = "Critical SeattleGeni backend error" django.core.mail.mail_admins(subject, message) # Sleep for ten minutes to make sure we don't flood the admins with error # report emails. time.sleep(600) def _sync_user_keys_of_single_vessel(vessel): """ This function is passed by sync_user_keys_of_vessels() as the function argument to run_parallelized(). """ # This does seem wasteful of lockserver communication to require four # round-trips with the lockserver (get handle, lock, unlock, release handle), # but if we really want to fix that then I think the best thing to do would # be to allow obtaining a lockhandle and releasing a lockhandle to be done # in the same calls as lock acquisition and release. node_id = maindb.get_node_identifier_from_vessel(vessel) lockserver_handle = lockserver.create_lockserver_handle() # Lock the node that the vessels is on. lockserver.lock_node(lockserver_handle, node_id) try: # Get a new vessel object from the db in case it was modified in the db # before the lock was obtained. vessel = maindb.get_vessel(node_id, vessel.name) # Now that we have a lock on the node that this vessel is on, find out # if we should still sync user keys on this vessel (e.g. maybe a node state # transition script moved the node to a new state and this vessel was # removed). needssync, reasonwhynot = maindb.does_vessel_need_user_key_sync(vessel) if not needssync: log.info("[_sync_user_keys_of_single_vessel] Vessel " + str(vessel) + " no longer needs user key sync: " + reasonwhynot) return nodeid = maindb.get_node_identifier_from_vessel(vessel) nodehandle = _get_node_handle_from_nodeid(nodeid) # The list returned from get_users_with_access_to_vessel includes the key of # the user who has acquired the vessel along with any other users they have # given access to. user_list = maindb.get_users_with_access_to_vessel(vessel) key_list = [] for user in user_list: key_list.append(user.user_pubkey) if len(key_list) == 0: raise InternalError("InternalError: Empty user key list for vessel " + str(vessel)) try: log.info("[_sync_user_keys_of_single_vessel] About to ChangeUsers on vessel " + str(vessel)) nodemanager.change_users(nodehandle, vessel.name, key_list) except NodemanagerCommunicationError: # We don't pass this exception up. Maybe the node is offline now. At some # point, it will be marked in the database as offline and won't show up in # our list of vessels to sync user keys of anymore. log.info("[_sync_user_keys_of_single_vessel] Failed to sync user keys of vessel " + str(vessel) + ". " + traceback.format_exc()) return # We only mark it as sync'd if no exception was raised when trying to perform # the above nodemanager operations. maindb.mark_vessel_as_not_needing_user_key_sync(vessel) log.info("[_sync_user_keys_of_single_vessel] Successfully sync'd user keys of vessel " + str(vessel)) finally: # Unlock the node. lockserver.unlock_node(lockserver_handle, node_id) lockserver.destroy_lockserver_handle(lockserver_handle) def main(): # Initialize the main database. maindb.init_maindb() # Initialize the key database. keydb.init_keydb() # Initialize the nodemanager. nodemanager.init_nodemanager() # Start the background thread that does vessel cleanup. thread.start_new_thread(cleanup_vessels, ()) # Start the background thread that does vessel user key synchronization. thread.start_new_thread(sync_user_keys_of_vessels, ()) # Register the XMLRPCServer. Use allow_none to allow allow the python None value. server = ThreadedXMLRPCServer(("127.0.0.1", LISTENPORT), allow_none=True) log.info("Backend listening on port " + str(LISTENPORT) + ".") server.register_instance(BackendPublicFunctions()) while True: server.handle_request() if __name__ == '__main__': try: main() except KeyboardInterrupt: log.info("Exiting on KeyboardInterrupt.") sys.exit(0)
#!/usr/bin/python import sys import subprocess import os import logging import getopt import time import tempfile from datetime import datetime from NagiosCheck import NagiosCheck, NagiosTimeout class NagiosCheckApp(NagiosCheck): """ This module checks proper working of applications instanced through Science Gateways. Both application and SG are defined by the specified JMX file, which is passed as input to jMeter, which actually performs the application run on the SG. Application instance is double checked with a query to the User tracking DB """ def __init__(self, warnThr, critThres, outFil, jmxDF, jmxLF, testSz, utdbCParFile, utdbCClassPre, logLev=logging.DEBUG): # initialize father NagiosCheck.__init__(self, warnThr, critThres, outFil, logLev) ## get check specific input self.jmxDescFile = jmxDF self.jmxLogFile = jmxLF self.jobDescriptions = [] self.testSize = testSz self.UTDbClParamFile = utdbCParFile self.UTDbCLClassPrefix = utdbCClassPre @classmethod def getInputParameters(self, argV=sys.argv): """ implements the abstract method for the input retrieval Thresholds are converted in percents """ inputDict = {} filename = argV[0] helpMessage = ("%s -c <critical_threshold_rate> " "-w <warning_threshold_rate> " "-o <output_file> -j <jmx_properties_file> " "-l <jmx_log_file> -n <number of jobs>" "-p <user tracking db connection parameters> " "-t <utdb-classes-prefix>" % (filename)) try: opts, args = getopt.getopt(argV[1:], "hc:w:o:j:l:n:p:t:", ["--help", "--critical", "--warning", "--outfile", "--jmx", "--jmx-log", "--number-of-jobs", "--utdb-param", "--utdb-classes-prefix"]) except getopt.GetoptError: print helpMessage sys.exit(NagiosCheck.UNKNOWN) for opt, arg in opts: if opt == '-h': print helpMessage sys.exit(NagiosCheck.UNKNOWN) elif opt in ("-c", "--critical"): inputDict['criticalThreshold'] = float(arg) / 100.0 elif opt in ("-w", "--warning"): inputDict['warningThreshold'] = float(arg) / 100.0 elif opt in ("-o", "--outfile"): inputDict['logFile'] = arg elif opt in ("-j", "--jmx"): inputDict['jmxF'] = arg elif opt in ("-l", "--jmx-log"): inputDict['jmxL'] = arg elif opt in ("-n", "--number-of-jobs"): inputDict['testSize'] = int(arg) elif opt in ("-p", "--utdb-param"): inputDict['utdbClParam'] = arg elif opt in ("-t", "--utdb-classes-prefix"): inputDict['utdbClClassPre'] = arg return inputDict def runJMeter(self, jMeterPrefix="/usr/local/apache-jmeter-2.9/bin"): """ perform a single jmeter run """ jMeterOutcome = 0 jobDesc = ("SG-MonCheck-JM_%s" % (datetime.now().strftime("%Y%m%d-%H%M%S"))) mytmp = tempfile.TemporaryFile(mode='w+b', dir='/tmp', suffix='jmeterDEBUG') #shutup=os.open('/tmp/jmeterdebug.txt','w') os.chdir('/tmp') jMeterCmd = ("%s/jmeter -n -t %s -l %s -JjobDes=%s" % (jMeterPrefix, self.jmxDescFile, self.jmxLogFile, jobDesc)) # sembra che a nagios dia fastidio la verbosita' ### self.logger.debug(jMeterCmd.split()) self.logger.debug("Starting jMeter with command: %s " % (jMeterCmd)) # subprocess wants a list, 1st element is command name # others are optional arguments try: jMeterOutcome = subprocess.call(jMeterCmd.split(), stdout=mytmp, stderr=mytmp) self.logger.debug("jMeter executed for %s" % (jobDesc)) except subprocess.CalledProcessError as e: self.logger.error("%s : could not call jmeter" % (str(e))) return 1 except Exception as e: self.logger.error("%s : could not call jmeter" % (str(e))) return 1 if (jMeterOutcome != ""): self.logger.info("job %s submitted: job description is %s" % (self.jmxDescFile, jobDesc)) # job description list will contain only submitted jobs descriptors self.jobDescriptions.append(jobDesc) return 0 else: self.logger.error("Some error occurred during %s submission" % (self.jmxDescFile)) return 1 def setUTDBJavaContext(self): log4jJar = "log4j-1.2-1.2.16.jar" jSagaJar = "jsaga-job-management-1.5.8.jar" mysqlJar = "mysql.jar" # user tracking db class prefixes - needs to be repeated for all jars ? javapath = ("%s/%s:%s/%s:%s/%s:%s" % (self.UTDbCLClassPrefix, log4jJar, self.UTDbCLClassPrefix, jSagaJar, self.UTDbCLClassPrefix, mysqlJar, self.UTDbCLClassPrefix)) os.environ['CLASSPATH'] = javapath def checkJobOutcome(self, jobDescr): # run UTDB Client """ Users tracking DB Client returns integers. This tuple maps back the job status code with the corresponding label """ jobStatus = ("DONE", "NEW", "SUBMITTED", "RUNNING", "SUSPENDED", "FAILED", "CANCELED", "Not Found", "Unknown") self.logger.debug("Querying User Tracking Database about %s" % (jobDescr)) utdbResponse = subprocess.call(["java", "UsersTrackingDBClient", self.UTDbClParamFile, jobDescr]) if (utdbResponse < 7): self.logger.info("%s found in User Tracking DB with status: %s" % (jobDescr, jobStatus[utdbResponse])) return 0 else: self.logger.info("%s not found in User Tracking DB" % (jobDescr)) return 1 def runCheck(self): # runJmeter gives 0 on success, 1 on failure submitted = 0 missed = 0 failures = 0 testResults = {} """ call runJMeter """ for c in range(0, self.testSize): self.logger.debug("Calling jmeter for job %d" % (c)) missed += self.runJMeter() submitted = self.testSize - missed # if there are no jobs submitted there's nothing to check further if submitted <= 0: testResults['score'] = 1 return pause = 6 * submitted # take a break - allow the Grid Engine to register the job self.logger.debug("Sleeping a bit, giving some time to Grid Engine " "for jobs registration (6 second for each job)") time.sleep(pause) self.setUTDBJavaContext() for jD in self.jobDescriptions: failures += self.checkJobOutcome(jD) # allows check.testSize = 0 just for debug, in this case score is 100% # if testSize is zero, then return failure code score = float(failures) / float(check.testSize) testResults['score'] = score testResults['failures'] = failures testResults['submitted'] = submitted return testResults def analyzeScore(self, checkScore, failures, submitted): if checkScore >= self.criticalThreshold: self.outMsg = ("CRITICAL: failed to retrieve status for " "%d jobs out of %d submitted (%.2f %% failed)" % (failures, submitted, checkScore * 100)) self.result = NagiosCheck.CRITICAL elif checkScore >= self.warningThreshold: self.outMsg = ("WARNING: failed to retrieve status for " "%d jobs out of %d submitted (%.2f %% failed)" % (failures, submitted, checkScore * 100)) self.result = NagiosCheck.WARNING elif checkScore >= 0.0: self.outMsg = ("OK: status retrieved for " "%d jobs out of %d submitted (%.2f %% failed)" % (submitted - failures, submitted, checkScore * 100)) self.result = NagiosCheck.OK else: self.outMsg = "UNKNOWN: Unable to check on service's health" self.result = NagiosCheck.UNKNOWN self.logger.info(self.outMsg) if (__name__ == "__main__"): failures = 0 inputDict = NagiosCheckApp.getInputParameters() check = NagiosCheckApp(inputDict['warningThreshold'], inputDict['criticalThreshold'], inputDict['logFile'], inputDict['jmxF'], inputDict['jmxL'], inputDict['testSize'], inputDict['utdbClParam'], inputDict['utdbClClassPre'] ) check.verifyThresholds() check.logger.info("*" * 80) check.logger.info(("Input parameters taken, starting check with %d jobs." "Critical Threshold %.2f Warning Threshold %.2f" % (check.testSize, check.criticalThreshold, check.warningThreshold))) testResults = check.runCheck() check.analyzeScore(testResults['score'], testResults['failures'], testResults['submitted']) print check.outMsg sys.exit(check.result)
import io import json import os import pickle import tempfile import uuid from django.core.management import call_command from django.test import TestCase from django.test import TransactionTestCase from mock import call from mock import MagicMock from mock import Mock from mock import patch from sqlalchemy import create_engine from .sqlalchemytesting import django_connection_engine from .test_content_app import ContentNodeTestBase from kolibri.core.content import models as content from kolibri.core.content.models import AssessmentMetaData from kolibri.core.content.models import ChannelMetadata from kolibri.core.content.models import CONTENT_SCHEMA_VERSION from kolibri.core.content.models import ContentNode from kolibri.core.content.models import File from kolibri.core.content.models import LocalFile from kolibri.core.content.models import NO_VERSION from kolibri.core.content.models import V020BETA1 from kolibri.core.content.models import V040BETA3 from kolibri.core.content.models import VERSION_1 from kolibri.core.content.utils.annotation import recurse_availability_up_tree from kolibri.core.content.utils.annotation import set_leaf_node_availability_from_local_file_availability from kolibri.core.content.utils.channel_import import ChannelImport from kolibri.core.content.utils.channel_import import import_channel_from_local_db from kolibri.core.content.utils.channels import read_channel_metadata_from_db_file from kolibri.core.content.utils.paths import get_content_database_file_path from kolibri.core.content.utils.sqlalchemybridge import get_default_db_string @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.find_unique_tree_id') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassConstructorTestCase(TestCase): """ Testcase for the base channel import class constructor """ def test_channel_id(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') self.assertEqual(channel_import.channel_id, 'test') @patch('kolibri.core.content.utils.channel_import.get_content_database_file_path') def test_two_bridges(self, db_path_mock, apps_mock, tree_id_mock, BridgeMock): db_path_mock.return_value = 'test' ChannelImport('test') BridgeMock.assert_has_calls([call(sqlite_file_path='test'), call(app_name='content')]) @patch('kolibri.core.content.utils.channel_import.get_content_database_file_path') def test_get_config(self, db_path_mock, apps_mock, tree_id_mock, BridgeMock): ChannelImport('test') apps_mock.assert_has_calls([call.get_app_config('content'), call.get_app_config().get_models(include_auto_created=True)]) def test_tree_id(self, apps_mock, tree_id_mock, BridgeMock): ChannelImport('test') tree_id_mock.assert_called_once_with() @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.get_all_destination_tree_ids') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassMethodUniqueTreeIdTestCase(TestCase): """ Testcase for the base channel import class unique tree id generator """ def test_empty(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 1) def test_one_one(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 2) def test_one_two(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [2] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 1) def test_two_one_two(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 2] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 3) def test_two_one_three(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 3] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 2) def test_three_one_two_three(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 2, 3] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 4) def test_three_one_two_four(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 2, 4] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 3) def test_three_one_three_four(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 3, 4] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 2) def test_three_one_three_five(self, apps_mock, tree_ids_mock, BridgeMock): tree_ids_mock.return_value = [1, 3, 5] channel_import = ChannelImport('test') self.assertEqual(channel_import.find_unique_tree_id(), 2) @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.find_unique_tree_id') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassGenRowMapperTestCase(TestCase): """ Testcase for the base channel import class row mapper generator """ def test_base_mapper(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') mapper = channel_import.generate_row_mapper() record = MagicMock() record.test_attr = 'test_val' self.assertEqual(mapper(record, 'test_attr'), 'test_val') def test_column_name_mapping(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') mappings = { 'test_attr': 'test_attr_mapped' } mapper = channel_import.generate_row_mapper(mappings=mappings) record = MagicMock() record.test_attr_mapped = 'test_val' self.assertEqual(mapper(record, 'test_attr'), 'test_val') def test_method_mapping(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') mappings = { 'test_attr': 'test_map_method' } mapper = channel_import.generate_row_mapper(mappings=mappings) record = {} test_map_method = Mock() test_map_method.return_value = 'test_val' channel_import.test_map_method = test_map_method self.assertEqual(mapper(record, 'test_attr'), 'test_val') def test_no_column_mapping(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') mappings = { 'test_attr': 'test_attr_mapped' } mapper = channel_import.generate_row_mapper(mappings=mappings) record = Mock(spec=['test_attr']) with self.assertRaises(AttributeError): mapper(record, 'test_attr') @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.find_unique_tree_id') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassGenTableMapperTestCase(TestCase): """ Testcase for the base channel import class table mapper generator """ def test_base_mapper(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') mapper = channel_import.generate_table_mapper() self.assertEqual(mapper, channel_import.base_table_mapper) def test_method_mapping(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') table_map = 'test_map_method' test_map_method = Mock() channel_import.test_map_method = test_map_method mapper = channel_import.generate_table_mapper(table_map=table_map) self.assertEqual(mapper, test_map_method) def test_no_column_mapping(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') table_map = 'test_map_method' with self.assertRaises(AttributeError): channel_import.generate_table_mapper(table_map=table_map) @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.find_unique_tree_id') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassTableImportTestCase(TestCase): """ Testcase for the base channel import class table import method """ def test_no_models_unflushed_rows_passed_through(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') record_mock = MagicMock(spec=['__table__']) channel_import.destination.get_class.return_value = record_mock self.assertEqual(0, channel_import.table_import(MagicMock(), lambda x, y: None, lambda x: [], 0)) def test_no_merge_records_bulk_insert_no_flush(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') record_mock = MagicMock(spec=['__table__']) record_mock.__table__.columns.items.return_value = [('test_attr', MagicMock())] channel_import.destination.get_class.return_value = record_mock channel_import.table_import(MagicMock(), lambda x, y: 'test_val', lambda x: [{}] * 100, 0) channel_import.destination.session.flush.assert_not_called() def test_no_merge_records_bulk_insert_flush(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') record_mock = MagicMock(spec=['__table__']) record_mock.__table__.columns.items.return_value = [('test_attr', MagicMock())] channel_import.destination.get_class.return_value = record_mock channel_import.table_import(MagicMock(), lambda x, y: 'test_val', lambda x: [{}] * 10000, 0) channel_import.destination.session.flush.assert_called_once_with() @patch('kolibri.core.content.utils.channel_import.merge_models', new=[]) def test_merge_records_merge_no_flush(self, apps_mock, tree_id_mock, BridgeMock): from kolibri.core.content.utils.channel_import import merge_models channel_import = ChannelImport('test') record_mock = MagicMock(spec=['__table__']) record_mock.__table__.columns.items.return_value = [('test_attr', MagicMock())] channel_import.destination.get_class.return_value = record_mock model_mock = MagicMock() model_mock._meta.pk.name = 'test_attr' merge_models.append(model_mock) channel_import.merge_record = Mock() channel_import.table_import(model_mock, lambda x, y: 'test_val', lambda x: [{}] * 100, 0) channel_import.destination.session.flush.assert_not_called() @patch('kolibri.core.content.utils.channel_import.merge_models', new=[]) def test_merge_records_merge_flush(self, apps_mock, tree_id_mock, BridgeMock): from kolibri.core.content.utils.channel_import import merge_models channel_import = ChannelImport('test') record_mock = Mock(spec=['__table__']) record_mock.__table__.columns.items.return_value = [('test_attr', MagicMock())] channel_import.destination.get_class.return_value = record_mock model_mock = Mock() model_mock._meta.pk.name = 'test_attr' merge_models.append(model_mock) channel_import.merge_record = Mock() channel_import.table_import(model_mock, lambda x, y: 'test_val', lambda x: [{}] * 10000, 0) channel_import.destination.session.flush.assert_called_once_with() @patch('kolibri.core.content.utils.channel_import.Bridge') @patch('kolibri.core.content.utils.channel_import.ChannelImport.find_unique_tree_id') @patch('kolibri.core.content.utils.channel_import.apps') class BaseChannelImportClassOtherMethodsTestCase(TestCase): """ Testcase for the base channel import class remaining methods """ def test_import_channel_methods_called(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') model_mock = Mock(spec=['__name__']) channel_import.content_models = [model_mock] mapping_mock = Mock() channel_import.schema_mapping = { model_mock: mapping_mock } with patch.object(channel_import, 'generate_row_mapper'),\ patch.object(channel_import, 'generate_table_mapper'),\ patch.object(channel_import, 'table_import'),\ patch.object(channel_import, 'check_and_delete_existing_channel'): channel_import.import_channel_data() channel_import.generate_row_mapper.assert_called_once_with(mapping_mock.get('per_row')) channel_import.generate_table_mapper.assert_called_once_with(mapping_mock.get('per_table')) channel_import.table_import.assert_called_once() channel_import.check_and_delete_existing_channel.assert_called_once() channel_import.destination.session.commit.assert_called_once_with() def test_end(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') channel_import.end() channel_import.destination.end.assert_has_calls([call(), call()]) def test_destination_tree_ids(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') class_mock = Mock() channel_import.destination.get_class.return_value = class_mock channel_import.get_all_destination_tree_ids() channel_import.destination.assert_has_calls([ call.session.query(class_mock.tree_id), call.session.query().distinct(), call.session.query().distinct().all() ]) def test_base_table_mapper(self, apps_mock, tree_id_mock, BridgeMock): channel_import = ChannelImport('test') class_mock = Mock() [record for record in channel_import.base_table_mapper(class_mock)] channel_import.destination.assert_has_calls([ call.session.query(class_mock), call.session.query().all() ]) class MaliciousDatabaseTestCase(TestCase): @patch('kolibri.core.content.utils.channel_import.set_leaf_node_availability_from_local_file_availability') @patch('kolibri.core.content.utils.channel_import.recurse_availability_up_tree') @patch('kolibri.core.content.utils.channel_import.initialize_import_manager') def test_non_existent_root_node(self, initialize_manager_mock, recurse_mock, leaf_mock): import_mock = MagicMock() initialize_manager_mock.return_value = import_mock channel_id = '6199dde695db4ee4ab392222d5af1e5c' def create_channel(): ChannelMetadata.objects.create( id=channel_id, name='test', min_schema_version='1', root_id=channel_id, ) import_mock.import_channel_data.side_effect = create_channel import_channel_from_local_db(channel_id) try: channel = ChannelMetadata.objects.get(id=channel_id) assert channel.root except ContentNode.DoesNotExist: self.fail('Channel imported without a valid root node') SCHEMA_PATH_TEMPLATE = os.path.join(os.path.dirname(__file__), '../fixtures/{name}_content_schema') DATA_PATH_TEMPLATE = os.path.join(os.path.dirname(__file__), '../fixtures/{name}_content_data.json') class ContentImportTestBase(TransactionTestCase): """This is run using a TransactionTestCase, as by default, Django runs each test inside an atomic context in order to easily roll back any changes to the DB. However, as we are setting things in the Django DB using SQLAlchemy these changes are not caught by this atomic context, and data will persist across tests. In order to deal with this, we call an explicit db flush at the end of every test case, both this flush and the SQLAlchemy insertions can cause issues with the atomic context used by Django.""" @property def schema_name(self): return self.legacy_schema or self.name @property def data_name(self): return self.legacy_schema or self.name def setUp(self): try: self.set_content_fixture() except (IOError, EOFError): print('No content schema and/or data for {name}'.format(name=self.schema_name)) super(ContentImportTestBase, self).setUp() @patch('kolibri.core.content.utils.channel_import.get_content_database_file_path') def set_content_fixture(self, db_path_mock): _, self.content_db_path = tempfile.mkstemp(suffix='.sqlite3') db_path_mock.return_value = self.content_db_path self.content_engine = create_engine('sqlite:///' + self.content_db_path, convert_unicode=True) with open(SCHEMA_PATH_TEMPLATE.format(name=self.schema_name), 'rb') as f: metadata = pickle.load(f) data_path = DATA_PATH_TEMPLATE.format(name=self.data_name) with io.open(data_path, mode='r', encoding='utf-8') as f: data = json.load(f) metadata.bind = self.content_engine metadata.create_all() conn = self.content_engine.connect() # Write data for each fixture into the table for table in metadata.sorted_tables: if data[table.name]: conn.execute(table.insert(), data[table.name]) conn.close() with patch('kolibri.core.content.utils.sqlalchemybridge.get_engine', new=self.get_engine): channel_metadata = read_channel_metadata_from_db_file(get_content_database_file_path('6199dde695db4ee4ab392222d5af1e5c')) # Double check that we have actually created a valid content db that is recognized as having that schema assert channel_metadata.inferred_schema_version == self.schema_name import_channel_from_local_db('6199dde695db4ee4ab392222d5af1e5c') def get_engine(self, connection_string): if connection_string == get_default_db_string(): return django_connection_engine() return self.content_engine def tearDown(self): call_command('flush', interactive=False) super(ContentImportTestBase, self).tearDown() @classmethod def tearDownClass(cls): django_connection_engine().dispose() super(ContentImportTestBase, cls).tearDownClass() class NaiveImportTestCase(ContentNodeTestBase, ContentImportTestBase): """ Integration test for naive import """ # When incrementing content schema versions, this should be incremented to the new version # A new TestCase for importing for this old version should then be subclassed from this TestCase # See 'NoVersionImportTestCase' below for an example name = CONTENT_SCHEMA_VERSION legacy_schema = None def test_no_update_old_version(self): channel = ChannelMetadata.objects.first() channel.version += 1 channel_version = channel.version channel.save() self.set_content_fixture() channel.refresh_from_db() self.assertEqual(channel.version, channel_version) def test_localfile_available_remain_after_import(self): local_file = LocalFile.objects.get(pk='9f9438fe6b0d42dd8e913d7d04cfb2b2') local_file.available = True local_file.save() self.set_content_fixture() local_file.refresh_from_db() self.assertTrue(local_file.available) def residual_object_deleted(self, Model): # Checks that objects previously associated with a channel are deleted on channel upgrade obj = Model.objects.first() # older databases may not import data for all models so if this is None, ignore if obj is not None: # Set id to a new UUID so that it does an insert at save obj.id = uuid.uuid4().hex obj.save() obj_id = obj.id channel = ChannelMetadata.objects.first() # Decrement current channel version to ensure reimport channel.version -= 1 channel.save() self.set_content_fixture() with self.assertRaises(Model.DoesNotExist): assert Model.objects.get(pk=obj_id) def test_residual_file_deleted_after_reimport(self): self.residual_object_deleted(File) def test_residual_assessmentmetadata_deleted_after_reimport(self): self.residual_object_deleted(AssessmentMetaData) def test_residual_contentnode_deleted_after_reimport(self): root_node = ChannelMetadata.objects.first().root obj = ContentNode.objects.create( title='test', id=uuid.uuid4().hex, parent=root_node, content_id=uuid.uuid4().hex, channel_id=root_node.channel_id, ) obj_id = obj.id channel = ChannelMetadata.objects.first() # Decrement current channel version to ensure reimport channel.version -= 1 channel.save() self.set_content_fixture() with self.assertRaises(ContentNode.DoesNotExist): assert ContentNode.objects.get(pk=obj_id) def test_existing_localfiles_are_not_overwritten(self): with patch('kolibri.core.content.utils.sqlalchemybridge.get_engine', new=self.get_engine): channel_id = '6199dde695db4ee4ab392222d5af1e5c' channel = ChannelMetadata.objects.get(id=channel_id) # mark LocalFile objects as available for f in channel.root.children.first().files.all(): f.local_file.available = True f.local_file.save() # channel's not yet available, as we haven't done the annotation assert not channel.root.available # propagate availability up the tree set_leaf_node_availability_from_local_file_availability(channel_id) recurse_availability_up_tree(channel_id=channel_id) # after reloading, channel should now be available channel.root.refresh_from_db() assert channel.root.available # set the channel version to a low number to ensure we trigger a re-import of metadata ChannelMetadata.objects.filter(id=channel_id).update(version=-1) # reimport the metadata self.set_content_fixture() # after reloading, the files and their ancestor ContentNodes should all still be available channel.root.refresh_from_db() assert channel.root.available assert channel.root.children.first().available assert channel.root.children.first().files.all()[0].available assert channel.root.children.first().files.all()[0].local_file.available class ImportLongDescriptionsTestCase(ContentImportTestBase, TransactionTestCase): """ When using Postgres, char limits on fields are enforced strictly. This was causing errors importing as described in: https://github.com/learningequality/kolibri/issues/3600 """ name = CONTENT_SCHEMA_VERSION legacy_schema = None data_name = "longdescriptions" longdescription = "soverylong" * 45 def test_long_descriptions(self): self.assertEqual(ContentNode.objects.get(id="32a941fb77c2576e8f6b294cde4c3b0c").license_description, self.longdescription) self.assertEqual(ContentNode.objects.get(id="2e8bac07947855369fe2d77642dfc870").description, self.longdescription) class Version1ImportTestCase(NaiveImportTestCase): """ Integration test for import from no version import """ name = VERSION_1 @classmethod def tearDownClass(cls): super(Version1ImportTestCase, cls).tearDownClass() @classmethod def setUpClass(cls): super(Version1ImportTestCase, cls).setUpClass() class NoVersionImportTestCase(NaiveImportTestCase): """ Integration test for import from no version import """ name = NO_VERSION @classmethod def tearDownClass(cls): super(NoVersionImportTestCase, cls).tearDownClass() @classmethod def setUpClass(cls): super(NoVersionImportTestCase, cls).setUpClass() class NoVersionv020ImportTestCase(NoVersionImportTestCase): """ Integration test for import from no version import for legacy schema 0.2.0beta1 """ legacy_schema = V020BETA1 def test_lang_str(self): # test for Language __str__ p = content.Language.objects.get(lang_code="en") self.assertEqual(str(p), '') @classmethod def tearDownClass(cls): super(NoVersionv020ImportTestCase, cls).tearDownClass() @classmethod def setUpClass(cls): super(NoVersionv020ImportTestCase, cls).setUpClass() class NoVersionv040ImportTestCase(NoVersionv020ImportTestCase): """ Integration test for import from no version import for legacy schema 0.4.0beta3 """ legacy_schema = V040BETA3 @classmethod def tearDownClass(cls): super(NoVersionv020ImportTestCase, cls).tearDownClass() @classmethod def setUpClass(cls): super(NoVersionv040ImportTestCase, cls).setUpClass()
import datetime import pytz from moto.packages.boto.ec2.elb.policies import Policies, OtherPolicy from collections import OrderedDict from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.core.utils import BackendDict from moto.ec2.models import ec2_backends from .exceptions import ( BadHealthCheckDefinition, DuplicateLoadBalancerName, DuplicateListenerError, EmptyListenersError, InvalidSecurityGroupError, LoadBalancerNotFoundError, TooManyTagsError, CertificateNotFoundException, ) class FakeHealthCheck(BaseModel): def __init__( self, timeout, healthy_threshold, unhealthy_threshold, interval, target ): self.timeout = timeout self.healthy_threshold = healthy_threshold self.unhealthy_threshold = unhealthy_threshold self.interval = interval self.target = target if not target.startswith(("HTTP", "TCP", "HTTPS", "SSL")): raise BadHealthCheckDefinition class FakeListener(BaseModel): def __init__(self, load_balancer_port, instance_port, protocol, ssl_certificate_id): self.load_balancer_port = load_balancer_port self.instance_port = instance_port self.protocol = protocol.upper() self.ssl_certificate_id = ssl_certificate_id self.policy_names = [] def __repr__(self): return "FakeListener(lbp: %s, inp: %s, pro: %s, cid: %s, policies: %s)" % ( self.load_balancer_port, self.instance_port, self.protocol, self.ssl_certificate_id, self.policy_names, ) class FakeBackend(BaseModel): def __init__(self, instance_port): self.instance_port = instance_port self.policy_names = [] def __repr__(self): return "FakeBackend(inp: %s, policies: %s)" % ( self.instance_port, self.policy_names, ) class FakeLoadBalancer(CloudFormationModel): def __init__( self, name, zones, ports, scheme=None, vpc_id=None, subnets=None, security_groups=None, elb_backend=None, ): self.name = name self.health_check = None self.instance_sparse_ids = [] self.instance_autoscaling_ids = [] self.zones = zones self.listeners = [] self.backends = [] self.created_time = datetime.datetime.now(pytz.utc) self.scheme = scheme or "internet-facing" self.attributes = FakeLoadBalancer.get_default_attributes() self.policies = Policies() self.policies.other_policies = [] self.policies.app_cookie_stickiness_policies = [] self.policies.lb_cookie_stickiness_policies = [] self.security_groups = security_groups or [] self.subnets = subnets or [] self.vpc_id = vpc_id or "vpc-56e10e3d" self.tags = {} self.dns_name = "%s.us-east-1.elb.amazonaws.com" % (name) for port in ports: listener = FakeListener( protocol=(port.get("protocol") or port["Protocol"]), load_balancer_port=( port.get("load_balancer_port") or port["LoadBalancerPort"] ), instance_port=(port.get("instance_port") or port["InstancePort"]), ssl_certificate_id=port.get( "ssl_certificate_id", port.get("SSLCertificateId") ), ) if listener.ssl_certificate_id: elb_backend._register_certificate( listener.ssl_certificate_id, self.dns_name ) self.listeners.append(listener) # it is unclear per the AWS documentation as to when or how backend # information gets set, so let's guess and set it here *shrug* backend = FakeBackend( instance_port=(port.get("instance_port") or port["InstancePort"]) ) self.backends.append(backend) @property def instance_ids(self): """Return all the instances attached to the ELB""" return self.instance_sparse_ids + self.instance_autoscaling_ids @staticmethod def cloudformation_name_type(): return "LoadBalancerName" @staticmethod def cloudformation_type(): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancing-loadbalancer.html return "AWS::ElasticLoadBalancing::LoadBalancer" @classmethod def create_from_cloudformation_json( cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json["Properties"] elb_backend = elb_backends[region_name] new_elb = elb_backend.create_load_balancer( name=properties.get("LoadBalancerName", resource_name), zones=properties.get("AvailabilityZones", []), ports=properties["Listeners"], scheme=properties.get("Scheme", "internet-facing"), ) instance_ids = properties.get("Instances", []) for instance_id in instance_ids: elb_backend.register_instances(new_elb.name, [instance_id]) policies = properties.get("Policies", []) port_policies = {} for policy in policies: policy_name = policy["PolicyName"] other_policy = OtherPolicy() other_policy.policy_name = policy_name elb_backend.create_lb_other_policy(new_elb.name, other_policy) for port in policy.get("InstancePorts", []): policies_for_port = port_policies.get(port, set()) policies_for_port.add(policy_name) port_policies[port] = policies_for_port for port, policies in port_policies.items(): elb_backend.set_load_balancer_policies_of_backend_server( new_elb.name, port, list(policies) ) health_check = properties.get("HealthCheck") if health_check: elb_backend.configure_health_check( load_balancer_name=new_elb.name, timeout=health_check["Timeout"], healthy_threshold=health_check["HealthyThreshold"], unhealthy_threshold=health_check["UnhealthyThreshold"], interval=health_check["Interval"], target=health_check["Target"], ) return new_elb @classmethod def update_from_cloudformation_json( cls, original_resource, new_resource_name, cloudformation_json, region_name ): cls.delete_from_cloudformation_json( original_resource.name, cloudformation_json, region_name ) return cls.create_from_cloudformation_json( new_resource_name, cloudformation_json, region_name ) @classmethod def delete_from_cloudformation_json( cls, resource_name, cloudformation_json, region_name ): elb_backend = elb_backends[region_name] try: elb_backend.delete_load_balancer(resource_name) except KeyError: pass @property def physical_resource_id(self): return self.name @classmethod def has_cfn_attr(cls, attribute): return attribute in [ "CanonicalHostedZoneName", "CanonicalHostedZoneNameID", "DNSName", "SourceSecurityGroup.GroupName", "SourceSecurityGroup.OwnerAlias", ] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException if attribute_name == "CanonicalHostedZoneName": raise NotImplementedError( '"Fn::GetAtt" : [ "{0}" , "CanonicalHostedZoneName" ]"' ) elif attribute_name == "CanonicalHostedZoneNameID": raise NotImplementedError( '"Fn::GetAtt" : [ "{0}" , "CanonicalHostedZoneNameID" ]"' ) elif attribute_name == "DNSName": return self.dns_name elif attribute_name == "SourceSecurityGroup.GroupName": raise NotImplementedError( '"Fn::GetAtt" : [ "{0}" , "SourceSecurityGroup.GroupName" ]"' ) elif attribute_name == "SourceSecurityGroup.OwnerAlias": raise NotImplementedError( '"Fn::GetAtt" : [ "{0}" , "SourceSecurityGroup.OwnerAlias" ]"' ) raise UnformattedGetAttTemplateException() @classmethod def get_default_attributes(cls): attributes = dict() attributes["cross_zone_load_balancing"] = {"enabled": False} attributes["connection_draining"] = {"enabled": False} attributes["access_log"] = {"enabled": False} attributes["connection_settings"] = {"idle_timeout": 60} return attributes def add_tag(self, key, value): if len(self.tags) >= 10 and key not in self.tags: raise TooManyTagsError() self.tags[key] = value def list_tags(self): return self.tags def remove_tag(self, key): if key in self.tags: del self.tags[key] def delete(self, region): """Not exposed as part of the ELB API - used for CloudFormation.""" elb_backends[region].delete_load_balancer(self.name) class ELBBackend(BaseBackend): def __init__(self, region_name=None): self.region_name = region_name self.load_balancers = OrderedDict() def reset(self): region_name = self.region_name self.__dict__ = {} self.__init__(region_name) def create_load_balancer( self, name, zones, ports, scheme="internet-facing", subnets=None, security_groups=None, ): vpc_id = None ec2_backend = ec2_backends[self.region_name] if subnets: subnet = ec2_backend.get_subnet(subnets[0]) vpc_id = subnet.vpc_id if name in self.load_balancers: raise DuplicateLoadBalancerName(name) if not ports: raise EmptyListenersError() if not security_groups: security_groups = [] for security_group in security_groups: if ec2_backend.get_security_group_from_id(security_group) is None: raise InvalidSecurityGroupError() new_load_balancer = FakeLoadBalancer( name=name, zones=zones, ports=ports, scheme=scheme, subnets=subnets, security_groups=security_groups, vpc_id=vpc_id, elb_backend=self, ) self.load_balancers[name] = new_load_balancer return new_load_balancer def create_load_balancer_listeners(self, name, ports): balancer = self.load_balancers.get(name, None) if balancer: for port in ports: protocol = port["protocol"] instance_port = port["instance_port"] lb_port = port["load_balancer_port"] ssl_certificate_id = port.get("ssl_certificate_id") for listener in balancer.listeners: if lb_port == listener.load_balancer_port: if protocol != listener.protocol: raise DuplicateListenerError(name, lb_port) if instance_port != listener.instance_port: raise DuplicateListenerError(name, lb_port) if ssl_certificate_id != listener.ssl_certificate_id: raise DuplicateListenerError(name, lb_port) break else: if ssl_certificate_id: self._register_certificate( ssl_certificate_id, balancer.dns_name ) balancer.listeners.append( FakeListener( lb_port, instance_port, protocol, ssl_certificate_id ) ) return balancer def describe_load_balancers(self, names): balancers = self.load_balancers.values() if names: matched_balancers = [ balancer for balancer in balancers if balancer.name in names ] if len(names) != len(matched_balancers): missing_elb = list(set(names) - set(matched_balancers))[0] raise LoadBalancerNotFoundError(missing_elb) return matched_balancers else: return balancers def delete_load_balancer_listeners(self, name, ports): balancer = self.load_balancers.get(name, None) listeners = [] if balancer: for lb_port in ports: for listener in balancer.listeners: if int(lb_port) == int(listener.load_balancer_port): continue else: listeners.append(listener) balancer.listeners = listeners return balancer def delete_load_balancer(self, load_balancer_name): self.load_balancers.pop(load_balancer_name, None) def get_load_balancer(self, load_balancer_name): return self.load_balancers.get(load_balancer_name) def apply_security_groups_to_load_balancer( self, load_balancer_name, security_group_ids ): load_balancer = self.load_balancers.get(load_balancer_name) ec2_backend = ec2_backends[self.region_name] for security_group_id in security_group_ids: if ec2_backend.get_security_group_from_id(security_group_id) is None: raise InvalidSecurityGroupError() load_balancer.security_groups = security_group_ids def configure_health_check( self, load_balancer_name, timeout, healthy_threshold, unhealthy_threshold, interval, target, ): check = FakeHealthCheck( timeout, healthy_threshold, unhealthy_threshold, interval, target ) load_balancer = self.get_load_balancer(load_balancer_name) load_balancer.health_check = check return check def set_load_balancer_listener_ssl_certificate( self, name, lb_port, ssl_certificate_id ): balancer = self.load_balancers.get(name, None) if balancer: for idx, listener in enumerate(balancer.listeners): if lb_port == listener.load_balancer_port: balancer.listeners[idx].ssl_certificate_id = ssl_certificate_id if ssl_certificate_id: self._register_certificate( ssl_certificate_id, balancer.dns_name ) return balancer def register_instances( self, load_balancer_name, instance_ids, from_autoscaling=False ): load_balancer = self.get_load_balancer(load_balancer_name) attr_name = ( "instance_sparse_ids" if not from_autoscaling else "instance_autoscaling_ids" ) actual_instance_ids = getattr(load_balancer, attr_name) actual_instance_ids.extend(instance_ids) return load_balancer def deregister_instances( self, load_balancer_name, instance_ids, from_autoscaling=False ): load_balancer = self.get_load_balancer(load_balancer_name) attr_name = ( "instance_sparse_ids" if not from_autoscaling else "instance_autoscaling_ids" ) actual_instance_ids = getattr(load_balancer, attr_name) new_instance_ids = [ instance_id for instance_id in actual_instance_ids if instance_id not in instance_ids ] setattr(load_balancer, attr_name, new_instance_ids) return load_balancer def modify_load_balancer_attributes( self, load_balancer_name, cross_zone=None, connection_settings=None, connection_draining=None, access_log=None, ): load_balancer = self.get_load_balancer(load_balancer_name) if cross_zone: load_balancer.attributes["cross_zone_load_balancing"] = cross_zone if connection_settings: load_balancer.attributes["connection_settings"] = connection_settings if connection_draining: load_balancer.attributes["connection_draining"] = connection_draining if "timeout" not in connection_draining: load_balancer.attributes["connection_draining"][ "timeout" ] = 300 # default if access_log: load_balancer.attributes["access_log"] = access_log def create_lb_other_policy(self, load_balancer_name, other_policy): load_balancer = self.get_load_balancer(load_balancer_name) if other_policy.policy_name not in [ p.policy_name for p in load_balancer.policies.other_policies ]: load_balancer.policies.other_policies.append(other_policy) return load_balancer def create_app_cookie_stickiness_policy(self, load_balancer_name, policy): load_balancer = self.get_load_balancer(load_balancer_name) load_balancer.policies.app_cookie_stickiness_policies.append(policy) return load_balancer def create_lb_cookie_stickiness_policy(self, load_balancer_name, policy): load_balancer = self.get_load_balancer(load_balancer_name) load_balancer.policies.lb_cookie_stickiness_policies.append(policy) return load_balancer def set_load_balancer_policies_of_backend_server( self, load_balancer_name, instance_port, policies ): load_balancer = self.get_load_balancer(load_balancer_name) backend = [ b for b in load_balancer.backends if int(b.instance_port) == instance_port ][0] backend_idx = load_balancer.backends.index(backend) backend.policy_names = policies load_balancer.backends[backend_idx] = backend return load_balancer def set_load_balancer_policies_of_listener( self, load_balancer_name, load_balancer_port, policies ): load_balancer = self.get_load_balancer(load_balancer_name) listener = [ l_listener for l_listener in load_balancer.listeners if int(l_listener.load_balancer_port) == load_balancer_port ][0] listener_idx = load_balancer.listeners.index(listener) listener.policy_names = policies load_balancer.listeners[listener_idx] = listener return load_balancer def _register_certificate(self, ssl_certificate_id, dns_name): from moto.acm.models import acm_backends, AWSResourceNotFoundException acm_backend = acm_backends[self.region_name] try: acm_backend.set_certificate_in_use_by(ssl_certificate_id, dns_name) except AWSResourceNotFoundException: raise CertificateNotFoundException() # Use the same regions as EC2 elb_backends = BackendDict(ELBBackend, "ec2")
import json import os import random import re import shutil import tempfile from datetime import datetime import pandas from cognitiveatlas.api import get_concept, get_task from django.db.models import Min from expfactory.experiment import get_experiments from expfactory.survey import export_questions from expfactory.utils import copy_directory from expfactory.vm import custom_battery_download from git import Repo from numpy.random import choice from expdj.apps.experiments.models import (CognitiveAtlasConcept, CognitiveAtlasTask, Experiment, ExperimentBooleanVariable, ExperimentNumericVariable, ExperimentStringVariable, ExperimentTemplate, ExperimentVariable) from expdj.apps.turk.models import Result from expdj.settings import BASE_DIR, MEDIA_ROOT, STATIC_ROOT, EXP_REPO media_dir = os.path.join(BASE_DIR, MEDIA_ROOT) # EXPERIMENT FACTORY PYTHON FUNCTIONS #################################### def get_experiment_selection(repo_type="experiments"): # tmpdir = custom_battery_download(repos=[repo_type]) tmpdir = os.path.join(EXP_REPO, 'expfactory-{}'.format(repo_type)) experiments = get_experiments( tmpdir, load=True, warning=False, repo_type=repo_type) experiments = [x[0] for x in experiments] # shutil.rmtree(tmpdir) return experiments def get_experiment_type(experiment): '''get_experiment_type returns the installation folder (eg, games, surveys, experiments) based on the template specified in the config.json :param experiment: the ExperimentTemplate object ''' if experiment.template in ["jspsych"]: return "experiments" elif experiment.template in ["survey"]: return "surveys" elif experiment.template in ["phaser"]: return "games" def parse_experiment_variable(variable): experiment_variable = None if isinstance(variable, dict): try: description = variable["description"] if "description" in variable.keys( ) else None if "name" in variable.keys(): name = variable["name"] if "datatype" in variable.keys(): if variable["datatype"].lower() == "numeric": variable_min = variable["range"][0] if "range" in variable.keys( ) else None variable_max = variable["range"][1] if "range" in variable.keys( ) else None experiment_variable, _ = ExperimentNumericVariable.objects.update_or_create( name=name, description=description, variable_min=variable_min, variable_max=variable_max) elif variable["datatype"].lower() == "string": experiment_variable, _ = ExperimentStringVariable.objects.update_or_create( name=name, description=description, variable_options=variable_options) elif variable["datatype"].lower() == "boolean": experiment_variable, _ = ExperimentBooleanVariable.objects.update_or_create( name=name, description=description) experiment_variable.save() except BaseException: pass return experiment_variable def install_experiments(experiment_tags=None, repo_type="experiments"): # We will return list of experiments that did not install successfully errored_experiments = [] # tmpdir = custom_battery_download(repos=[repo_type, "battery"]) tmpdir = os.path.join(EXP_REPO, 'expfactory-{}'.format(repo_type)) # could catch non existant repos with git.exc.InvalidGitRepositoryError # repo = Repo("%s/%s" % (tmpdir, repo_type)) repo = Repo(tmpdir) # The git commit is saved with the experiment as the "version" commit = repo.commit('master').__str__() experiments = get_experiments(tmpdir, load=True, warning=False) if experiment_tags is not None: experiments = [e for e in experiments if e[0] ["exp_id"] in experiment_tags] for experiment in experiments: try: performance_variable = None rejection_variable = None if "experiment_variables" in experiment[0]: if isinstance(experiment[0]["experiment_variables"], list): for var in experiment[0]["experiment_variables"]: if var["type"].lower().strip() == "bonus": performance_variable = parse_experiment_variable( var) elif var["type"].lower().strip() == "credit": rejection_variable = parse_experiment_variable(var) else: parse_experiment_variable(var) # adds to database if isinstance(experiment[0]["reference"], list): reference = experiment[0]["reference"][0] else: reference = experiment[0]["reference"] cognitive_atlas_task = get_cognitiveatlas_task( experiment[0]["cognitive_atlas_task_id"]) new_experiment, _ = ExperimentTemplate.objects.update_or_create( exp_id=experiment[0]["exp_id"], defaults={ "name": experiment[0]["name"], "cognitive_atlas_task": cognitive_atlas_task, "publish": bool(experiment[0]["publish"]), "time": experiment[0]["time"], "reference": reference, "version": commit, "template": experiment[0]["template"], "performance_variable": performance_variable, "rejection_variable": rejection_variable } ) new_experiment.save() experiment_folder = "%s/%s" % (tmpdir, experiment[0]["exp_id"]) output_folder = "%s/%s/%s" % (media_dir, repo_type, experiment[0]["exp_id"]) if os.path.exists(output_folder): shutil.rmtree(output_folder) copy_directory(experiment_folder, output_folder) except BaseException: errored_experiments.append(experiment[0]["exp_id"]) # shutil.rmtree(tmpdir) return errored_experiments # EXPERIMENTS AND BATTERIES ############################################## def make_experiment_lookup(tags, battery=None): '''Generate lookup based on exp_id''' experiment_lookup = dict() for tag in tags: experiment = None try: if battery is not None: # First try retrieving from battery experiment = battery.experiments.filter( template__exp_id=tag)[0] if isinstance(experiment, Experiment): tmp = {"include_bonus": experiment.include_bonus, "include_catch": experiment.include_catch, "experiment": experiment.template} else: experiment = None if experiment is None: experiment = ExperimentTemplate.objects.filter(exp_id=tag)[0] tmp = {"include_bonus": "Unknown", "include_catch": "Unknown", "experiment": experiment} experiment_lookup[tag] = tmp except BaseException: pass return experiment_lookup def get_battery_results(battery, exp_id=None, clean=False): '''get_battery_results filters down to a battery, and optionally, an experiment of interest :param battery: expdj.models.Battery :param expid: an ExperimentTemplate.tag variable, eg "test_task" :param clean: remove battery info, subject info, and identifying information ''' args = {"battery": battery} if exp_id is not None: args["experiment__exp_id"] = exp_id results = Result.objects.filter(**args) df = make_results_df(battery, results) if clean: columns_to_remove = [ x for x in df.columns.tolist() if re.search( "worker_|^battery_", x)] columns_to_remove = columns_to_remove + [ "experiment_include_bonus", "experiment_include_catch", "result_id", "result_view_history", "result_time_elapsed", "result_timing_post_trial", "result_stim_duration", "result_internal_node_id", "result_trial_index", "result_trial_type", "result_stimulus", "experiment_reference", "experiment_cognitive_atlas_task_id", "result_dateTime", "result_exp_id", "result_page_num"] df.drop(columns_to_remove, axis=1, inplace=True, errors="ignore") df.columns = [x.replace("result_", "") for x in df.columns.tolist()] df.index = range(0, df.shape[0]) return df def make_results_df(battery, results): variables = get_unique_variables(results) tags = get_unique_experiments(results) lookup = make_experiment_lookup(tags, battery) header = ['worker_id', 'worker_platform', 'worker_browser', 'battery_name', 'battery_owner', 'battery_owner_email', 'experiment_completed', 'experiment_include_bonus', 'experiment_include_catch', 'experiment_exp_id', 'experiment_name', 'experiment_reference', 'experiment_cognitive_atlas_task_id'] column_names = header + variables df = pandas.DataFrame(columns=column_names) for result in results: try: if result.completed: worker_id = result.worker_id for t in range(len(result.taskdata)): row_id = "%s_%s_%s" % ( result.experiment.exp_id, worker_id, t) trial = result.taskdata[t] # Add worker and battery information df.loc[row_id, ["worker_id", "worker_platform", "worker_browser", "battery_name", "battery_owner", "battery_owner_email"]] = [worker_id, result.platform, result.browser, battery.name, battery.owner.username, battery.owner.email] # Look up the experiment exp = lookup[result.experiment.exp_id] df.loc[row_id, ["experiment_completed", "experiment_include_bonus", "experiment_include_catch", "experiment_exp_id", "experiment_name", "experiment_reference", "experiment_cognitive_atlas_task_id"]] = [result.completed, exp["include_bonus"], exp["include_catch"], exp["experiment"].exp_id, exp["experiment"].name, exp["experiment"].reference, exp["experiment"].cognitive_atlas_task_id] # Parse data for key in trial.keys(): if key != "trialdata": df.loc[row_id, key] = trial[key] for key in trial["trialdata"].keys(): df.loc[row_id, key] = trial["trialdata"][key] except BaseException: pass # Change all names that don't start with experiment or worker or # experiment to be result result_variables = [x for x in column_names if x not in header] for result_variable in result_variables: df = df.rename( columns={ result_variable: "result_%s" % result_variable}) final_names = ["result_%s" % x for x in variables] # rename uniqueid to result id if "result_uniqueid" in df.columns: df = df.rename(columns={'result_uniqueid': 'result_id'}) return df # COGNITIVE ATLAS FUNCTIONS ############################################## def get_cognitiveatlas_task(task_id): '''get_cognitiveatlas_task return the database entry for CognitiveAtlasTask if it exists, and update concepts for that task. If not, create it. :param task_id: the unique id for the cognitive atlas task ''' try: task = get_task(id=task_id).json[0] cogatlas_task, _ = CognitiveAtlasTask.objects.update_or_create( cog_atlas_id=task["id"], defaults={"name": task["name"]}) concept_list = [] if "concepts" in task.keys(): for concept in task["concepts"]: cogatlas_concept = get_concept( id=concept["concept_id"]).json[0] cogatlas_concept, _ = CognitiveAtlasConcept.objects.update_or_create( cog_atlas_id=cogatlas_concept["id"], defaults={ "name": cogatlas_concept["name"]}, definition=cogatlas_concept["definition_text"]) cogatlas_concept.save() concept_list.append(cogatlas_concept) cogatlas_task.concepts = concept_list cogatlas_task.save() return cogatlas_task except BaseException: # Any error with API, etc, return None return None # BONUS AND REJECTION CREDIT ############################################# def update_credits(experiment, cid): # Turn off credit conditions if no variables exist is_bonus = True if experiment.template.performance_variable.id == cid else False is_rejection = True if experiment.template.rejection_variable.id == cid else False # This only works given each experiment has one bonus or rejection criteria if is_bonus and len(experiment.credit_conditions) == 0: experiment.include_bonus = False if is_rejection and len(experiment.credit_conditions) == 0: experiment.include_catch = False experiment.save() # EXPERIMENT SELECTION ################################################### def select_random_n(experiments, N): '''select_experiments_N a selection algorithm that selects a random N experiments from list :param experiments: list of experiment.Experiment objects, with time variable specified in minutes :param N: the number of experiments to select ''' if N > len(experiments): N = len(experiments) return choice(experiments, N).tolist() def select_ordered(experiments, selection_number=1): '''select_ordered will return a list of the next "selection_number" of experiments. Lower numbers are returned first, and if multiple numbers are specified for orders, these will be selected from randomly. :param experiments: the list of Experiment objects to select from :param selection_number: the number of experiments to choose (default 1) ''' next_value = experiments.aggregate(Min('order'))["order__min"] experiment_choices = [e for e in experiments if e.order == next_value] return select_random_n(experiment_choices, selection_number) def select_experiments(battery, uncompleted_experiments, selection_number=1): '''select_experiments selects experiments based on the presentation_order variable defined in the battery (random or specific) :param battery: the battery object :param uncompleted_experiments: a list of Experiment objects to select from :param selection_number: the number of experiments to select ''' if battery.presentation_order == "random": task_list = select_random_n(uncompleted_experiments, selection_number) elif battery.presentation_order == "specified": task_list = select_ordered( uncompleted_experiments, selection_number=selection_number) return task_list def select_experiments_time(maximum_time_allowed, experiments): '''select_experiments_time a selection algorithm that selects experiments from list based on not exceeding some max time this function is not implemented anywhere, as the battery length is determined by experiments added to battery. :param maximum_time_allowed: the maximum time allowed, in seconds :param experiments: list of experiment.Experiment objects, with time variable specified in minutes ''' # Add tasks with random selection until we reach the time limit task_list = [] total_time = 0 exps = experiments[:] while (total_time < maximum_time_allowed) and len(exps) > 0: # Randomly select an experiment experiment = exps.pop(choice(range(len(exps)))) if (total_time + experiment.template.time * 60.0) <= maximum_time_allowed: task_list.append(experiment) return task_list # GENERAL UTILS ########################################################## def remove_keys(dictionary, keys): '''remove_key deletes a key from a dictionary''' if isinstance(keys, str): keys = [keys] new_dict = dict(dictionary) # in case Query dict for key in keys: if key in new_dict: del new_dict[key] return new_dict def complete_survey_result(exp_id, taskdata): '''complete_survey_result parses the form names (question ids) and matches to a lookup table generated by expfactory-python survey module that has complete question / option information. :param experiment: the survey unique id, expected to be :param taskdata: the taskdata from the server, typically an ordered dict ''' taskdata = dict(taskdata) experiment = [{"exp_id": exp_id}] experiment_folder = "%s/%s/%s" % (media_dir, "surveys", exp_id) question_lookup = export_questions(experiment, experiment_folder) final_data = {} for queskey, quesval in taskdata.iteritems(): if queskey in question_lookup: complete_question = question_lookup[queskey] complete_question["response"] = quesval[0] else: complete_question = {"response": quesval[0]} final_data[queskey] = complete_question return final_data
import characterquests from characterutil import * def sz_01_10_Wandering_Isle(count,datatree,openfile): characterquests.charquestheader(count,"01-10: Wandering Isle",openfile) def z_80_90_Jade_Forest(count,datatree,openfile): characterquests.charquestheader(count,"80-90: Jade Forest",openfile) characterquests.charquestprintfaction(count,datatree,openfile,29552,"Critical Condition","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29553,"The Missing Admiral","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29555,"The White Pawn","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29556,"Hozen Aren't Your Friends, Hozen Are Your Enemies","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29558,"The Path of War","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29559,"Freeing Our Brothers","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29560,"Ancient Power","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29562,"Jailbreak","alliance") characterquests.charquestprint(count,datatree,openfile,29576,"An Air of Worry") characterquests.charquestprint(count,datatree,openfile,29578,"Defiance") characterquests.charquestprint(count,datatree,openfile,29579,"Rally the Survivors") characterquests.charquestprint(count,datatree,openfile,29580,"Orchard-Supplied Hardware") characterquests.charquestprint(count,datatree,openfile,29585,"Spitfire") characterquests.charquestprint(count,datatree,openfile,29586,"The Splintered Path") characterquests.charquestprint(count,datatree,openfile,29587,"Unbound") characterquests.charquestprint(count,datatree,openfile,29617,"Tian Monastery") characterquests.charquestprint(count,datatree,openfile,29618,"The High Elder") characterquests.charquestprint(count,datatree,openfile,29619,"A Courteous Guest") characterquests.charquestprint(count,datatree,openfile,29620,"The Great Banquet") characterquests.charquestprint(count,datatree,openfile,29622,"Your Training Starts Now") characterquests.charquestprint(count,datatree,openfile,29623,"Perfection") characterquests.charquestprint(count,datatree,openfile,29624,"Attention") characterquests.charquestprint(count,datatree,openfile,29626,"Groundskeeper Wu") characterquests.charquestprint(count,datatree,openfile,29627,"A Proper Weapon") characterquests.charquestprint(count,datatree,openfile,29628,"A Strong Back") characterquests.charquestprint(count,datatree,openfile,29629,"A Steady Hand") characterquests.charquestprint(count,datatree,openfile,29630,"And a Heavy Fist") characterquests.charquestprint(count,datatree,openfile,29631,"Burning Bright") characterquests.charquestprint(count,datatree,openfile,29632,"Becoming Battle-Ready") characterquests.charquestprint(count,datatree,openfile,29633,"Zhi-Zhi, the Dextrous") characterquests.charquestprint(count,datatree,openfile,29634,"Husshun, the Wizened") characterquests.charquestprint(count,datatree,openfile,29635,"Xiao, the Eater") characterquests.charquestprint(count,datatree,openfile,29636,"A Test of Endurance") characterquests.charquestprint(count,datatree,openfile,29637,"The Rumpus") characterquests.charquestprint(count,datatree,openfile,29639,"Flying Colors") characterquests.charquestprint(count,datatree,openfile,29646,"Flying Colors") characterquests.charquestprint(count,datatree,openfile,29647,"Flying Colors") characterquests.charquestprint(count,datatree,openfile,29670,"Maul Gormal") characterquests.charquestprintfaction(count,datatree,openfile,29694,"Regroup!","horde") characterquests.charquestprint(count,datatree,openfile,29716,"The Double Hozen Dare") characterquests.charquestprint(count,datatree,openfile,29717,"Down Kitty!") characterquests.charquestprint(count,datatree,openfile,29723,"The Jade Witch") characterquests.charquestprintfaction(count,datatree,openfile,29725,"SI:7 Report: Fire From the Sky","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29726,"SI:7 Report: Hostile Natives","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29727,"SI:7 Report: Take No Prisoners","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29730,"Scouting Report: Hostile Natives","horde") characterquests.charquestprintfaction(count,datatree,openfile,29731,"Scouting Report: On the Right Track","horde") characterquests.charquestprintfaction(count,datatree,openfile,29733,"SI:7 Report: Lost in the Woods","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29743,"Monstrosity","horde") characterquests.charquestprint(count,datatree,openfile,29745,"The Sprites' Plight") characterquests.charquestprint(count,datatree,openfile,29747,"Break the Cycle") characterquests.charquestprint(count,datatree,openfile,29748,"Simulacrumble") characterquests.charquestprint(count,datatree,openfile,29749,"An Urgent Plea") characterquests.charquestprint(count,datatree,openfile,29750,"Vessels of the Spirit") characterquests.charquestprint(count,datatree,openfile,29751,"Ritual Artifacts") characterquests.charquestprint(count,datatree,openfile,29752,"The Wayward Dead") characterquests.charquestprint(count,datatree,openfile,29753,"Back to Nature") characterquests.charquestprint(count,datatree,openfile,29754,"To Bridge Earth and Sky") characterquests.charquestprint(count,datatree,openfile,29755,"Pei-Back") characterquests.charquestprint(count,datatree,openfile,29756,"A Humble Offering") characterquests.charquestprintfaction(count,datatree,openfile,29759,"Kung Din","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29762,"Family Heirlooms","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29765,"Cryin' My Eyes Out","horde") characterquests.charquestprintfaction(count,datatree,openfile,29804,"Seein' Red","horde") characterquests.charquestprintfaction(count,datatree,openfile,29815,"Forensic Science","horde") characterquests.charquestprintfaction(count,datatree,openfile,29821,"Missed Me By... That Much!","horde") characterquests.charquestprintfaction(count,datatree,openfile,29822,"Lay of the Land","horde") characterquests.charquestprintfaction(count,datatree,openfile,29823,"Scouting Report: The Friend of My Enemy","horde") characterquests.charquestprintfaction(count,datatree,openfile,29824,"Scouting Report: Like Jinyu in a Barrel","horde") characterquests.charquestprintfaction(count,datatree,openfile,29827,"Acid Rain","horde") characterquests.charquestprint(count,datatree,openfile,29865,"The Silkwood Road") characterquests.charquestprint(count,datatree,openfile,29866,"The Threads that Stick") characterquests.charquestprintfaction(count,datatree,openfile,29879,"Swallowed Whole","horde") characterquests.charquestprint(count,datatree,openfile,29881,"The Perfect Color") characterquests.charquestprint(count,datatree,openfile,29882,"Quill of Stingers") characterquests.charquestprintfaction(count,datatree,openfile,29883,"The Pearlfin Situation","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29885,"Road Rations","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29887,"The Elder's Instruments","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29888,"Seek Out the Lorewalker","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29889,"Borrowed Brew","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29890,"Finding Your Center","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29891,"Potency","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29892,"Body","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29893,"Hue","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29894,"Spirits of the Water","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29898,"Sacred Waters","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29899,"Rest in Peace","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29900,"An Ancient Legend","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29901,"Anduin's Decision","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29903,"A Perfect Match","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29904,"Bigger Fish to Fry","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29905,"Let Them Burn","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29906,"Carp Diem","alliance") characterquests.charquestprint(count,datatree,openfile,29920,"Getting Permission") characterquests.charquestprintfaction(count,datatree,openfile,29922,"In Search of Wisdom","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29924,"Kill Kher Shan","horde") characterquests.charquestprint(count,datatree,openfile,29925,"All We Can Spare") characterquests.charquestprint(count,datatree,openfile,29926,"Calamity Jade") characterquests.charquestprint(count,datatree,openfile,29927,"Mann's Man") characterquests.charquestprint(count,datatree,openfile,29928,"I Have No Jade And I Must Scream") characterquests.charquestprint(count,datatree,openfile,29929,"Trapped!") characterquests.charquestprint(count,datatree,openfile,29930,"What's Mined Is Yours") characterquests.charquestprint(count,datatree,openfile,29931,"The Serpent's Heart") characterquests.charquestprint(count,datatree,openfile,29932,"The Temple of the Jade Serpent") characterquests.charquestprintfaction(count,datatree,openfile,29933,"The Bees' Knees","horde") characterquests.charquestprintfaction(count,datatree,openfile,29935,"Orders are Orders","horde") characterquests.charquestprintfaction(count,datatree,openfile,29936,"Instant Messaging","horde") characterquests.charquestprintfaction(count,datatree,openfile,29937,"Furious Fowl","horde") characterquests.charquestprintfaction(count,datatree,openfile,29939,"Boom Bait","horde") characterquests.charquestprintfaction(count,datatree,openfile,29941,"Beyond the Horizon","horde") characterquests.charquestprintfaction(count,datatree,openfile,29942,"Silly Wikket, Slickies are for Hozen","horde") characterquests.charquestprintfaction(count,datatree,openfile,29943,"Guerrillas in our Midst","horde") characterquests.charquestprintfaction(count,datatree,openfile,29966,"Burning Down the House","horde") characterquests.charquestprintfaction(count,datatree,openfile,29967,"Boom Goes the Doonamite!","horde") characterquests.charquestprintfaction(count,datatree,openfile,29968,"Green-ish Energy","horde") characterquests.charquestprintfaction(count,datatree,openfile,29971,"The Scouts Return","horde") characterquests.charquestprint(count,datatree,openfile,29993,"Find the Boy") characterquests.charquestprint(count,datatree,openfile,29995,"Shrine of the Dawn") characterquests.charquestprint(count,datatree,openfile,29997,"The Scryer's Dilemma") characterquests.charquestprint(count,datatree,openfile,29998,"The Librarian's Quandary") characterquests.charquestprint(count,datatree,openfile,29999,"The Rider's Bind") characterquests.charquestprint(count,datatree,openfile,30000,"The Jade Serpent") characterquests.charquestprint(count,datatree,openfile,30001,"Moth-Ridden") characterquests.charquestprint(count,datatree,openfile,30002,"Pages of History") characterquests.charquestprint(count,datatree,openfile,30004,"Everything In Its Place") characterquests.charquestprint(count,datatree,openfile,30005,"Lighting Up the Sky") characterquests.charquestprint(count,datatree,openfile,30006,"The Darkness Around Us") characterquests.charquestprint(count,datatree,openfile,30011,"A New Vision") characterquests.charquestprintfaction(count,datatree,openfile,30015,"Dawn's Blossom","horde") characterquests.charquestprint(count,datatree,openfile,30063,"Behind the Masks") characterquests.charquestprint(count,datatree,openfile,30064,"Saving the Sutras") characterquests.charquestprint(count,datatree,openfile,30065,"Arrows of Fortune") characterquests.charquestprint(count,datatree,openfile,30066,"Hidden Power") characterquests.charquestprint(count,datatree,openfile,30067,"The Shadow of Doubt") characterquests.charquestprint(count,datatree,openfile,30068,"Flames of the Void") characterquests.charquestprintfaction(count,datatree,openfile,30069,"No Plan Survives Contact with the Enemy","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30070,"The Fall of Ga'trul","alliance") characterquests.charquestprint(count,datatree,openfile,30134,"Wild Things") characterquests.charquestprint(count,datatree,openfile,30135,"Beating the Odds") characterquests.charquestprint(count,datatree,openfile,30136,"Empty Nests") characterquests.charquestprint(count,datatree,openfile,30137,"Egg Collection") characterquests.charquestprint(count,datatree,openfile,30138,"Choosing the One") characterquests.charquestprint(count,datatree,openfile,30139,"The Rider's Journey") characterquests.charquestprint(count,datatree,openfile,30140,"The Rider's Journey") characterquests.charquestprint(count,datatree,openfile,30141,"The Rider's Journey") characterquests.charquestprint(count,datatree,openfile,30142,"It's A...") characterquests.charquestprint(count,datatree,openfile,30143,"They Grow Like Weeds") characterquests.charquestprint(count,datatree,openfile,30144,"Flight Training: Ring Round-Up") characterquests.charquestprint(count,datatree,openfile,30145,"Flight Training: Full Speed Ahead") characterquests.charquestprint(count,datatree,openfile,30146,"Snack Time") characterquests.charquestprint(count,datatree,openfile,30147,"Fragments of the Past") characterquests.charquestprint(count,datatree,openfile,30148,"Just a Flesh Wound") characterquests.charquestprint(count,datatree,openfile,30149,"A Feast for the Senses") characterquests.charquestprint(count,datatree,openfile,30150,"Sweet as Honey") characterquests.charquestprint(count,datatree,openfile,30151,"Catch!") characterquests.charquestprint(count,datatree,openfile,30152,"The Sky Race") characterquests.charquestprint(count,datatree,openfile,30154,"The Easiest Way To A Serpent's Heart") characterquests.charquestprint(count,datatree,openfile,30155,"Restoring the Balance") characterquests.charquestprint(count,datatree,openfile,30156,"Feeding Time") characterquests.charquestprint(count,datatree,openfile,30157,"Emptier Nests") characterquests.charquestprint(count,datatree,openfile,30158,"Disarming the Enemy") characterquests.charquestprint(count,datatree,openfile,30159,"Preservation") characterquests.charquestprint(count,datatree,openfile,30187,"Flight Training: In Due Course") characterquests.charquestprint(count,datatree,openfile,30188,"Riding the Skies") characterquests.charquestprintfaction(count,datatree,openfile,30466,"Sufficient Motivation","horde") characterquests.charquestprintfaction(count,datatree,openfile,30484,"Gauging Our Progress","horde") characterquests.charquestprintfaction(count,datatree,openfile,30485,"Last Piece of the Puzzle","horde") characterquests.charquestprint(count,datatree,openfile,30495,"Love's Labor") characterquests.charquestprintfaction(count,datatree,openfile,30498,"Get Back Here!","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30499,"Get Back Here!","horde") characterquests.charquestprint(count,datatree,openfile,30500,"Residual Fallout") characterquests.charquestprint(count,datatree,openfile,30502,"Jaded Heart") characterquests.charquestprintfaction(count,datatree,openfile,30504,"Emergency Response","horde") characterquests.charquestprintfaction(count,datatree,openfile,30565,"An Unexpected Advantage","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30568,"Helping the Cause","alliance") characterquests.charquestprint(count,datatree,openfile,30648,"Moving On") characterquests.charquestprintfaction(count,datatree,openfile,31112,"They're So Thorny!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31121,"Stay a While, and Listen","horde") characterquests.charquestprintfaction(count,datatree,openfile,31130,"A Visit with Lorewalker Cho","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31132,"A Mile in My Shoes","horde") characterquests.charquestprintfaction(count,datatree,openfile,31134,"If These Stones Could Speak","horde") characterquests.charquestprintfaction(count,datatree,openfile,31152,"Peering Into the Past","horde") characterquests.charquestprintfaction(count,datatree,openfile,31167,"Family Tree","horde") characterquests.charquestprint(count,datatree,openfile,31194,"Slitherscale Suppression") characterquests.charquestprint(count,datatree,openfile,31230,"Welcome to Dawn's Blossom") characterquests.charquestprintfaction(count,datatree,openfile,31239,"What's in a Name Name?","horde") characterquests.charquestprintfaction(count,datatree,openfile,31241,"Wicked Wikkets","horde") characterquests.charquestprintfaction(count,datatree,openfile,31261,"Captain Jack's Dead","horde") characterquests.charquestprint(count,datatree,openfile,31303,"The Seal is Broken") characterquests.charquestprint(count,datatree,openfile,31307,"FLAG - Jade Infused Blade") characterquests.charquestprintfaction(count,datatree,openfile,31319,"Emergency Response","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31362,"Last Piece of the Puzzle","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31373,"The Order of the Cloud Serpent","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31375,"The Order of the Cloud Serpent","horde") characterquests.charquestprintfaction(count,datatree,openfile,31732,"Unleash Hell","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31733,"Touching Ground","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31734,"Welcome Wagons","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31735,"The Right Tool For The Job","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31736,"Envoy of the Alliance","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31737,"The Cost of War","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31738,"Pillaging Peons","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31739,"Priorities!","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31740,"Koukou's Rampage","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31741,"Twinspire Keep","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31742,"Fractured Forces","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31743,"Smoke Before Fire","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31744,"Unfair Trade","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31745,"Onward and Inward","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31765,"Paint it Red!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31766,"Touching Ground","horde") characterquests.charquestprintfaction(count,datatree,openfile,31767,"Finish Them!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31768,"Fire Is Always the Answer","horde") characterquests.charquestprintfaction(count,datatree,openfile,31769,"The Final Blow!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31770,"You're Either With Us Or...","horde") characterquests.charquestprintfaction(count,datatree,openfile,31771,"Face to Face With Consequence","horde") characterquests.charquestprintfaction(count,datatree,openfile,31772,"Priorities!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31773,"Prowler Problems","horde") characterquests.charquestprintfaction(count,datatree,openfile,31774,"Seeking Zin'jun","horde") characterquests.charquestprintfaction(count,datatree,openfile,31775,"Assault on the Airstrip","horde") characterquests.charquestprintfaction(count,datatree,openfile,31776,"Strongarm Tactics","horde") characterquests.charquestprintfaction(count,datatree,openfile,31777,"Choppertunity","horde") characterquests.charquestprintfaction(count,datatree,openfile,31778,"Unreliable Allies","horde") characterquests.charquestprintfaction(count,datatree,openfile,31779,"The Darkness Within","horde") characterquests.charquestprint(count,datatree,openfile,31784,"Onyx To Goodness") characterquests.charquestprint(count,datatree,openfile,31810,"Riding the Skies") characterquests.charquestprint(count,datatree,openfile,31811,"Riding the Skies") characterquests.charquestprintfaction(count,datatree,openfile,31978,"Priorities!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31999,"Nazgrim's Command","horde") characterquests.charquestprint(count,datatree,openfile,33250,"A Time-Lost Treasure") characterquests.charquestprintfaction(count,datatree,openfile,49538,"Warchief's Command: Jade Forest!","horde") characterquests.charquestprintfaction(count,datatree,openfile,49556,"Hero's Call: Jade Forest!","alliance") def z_81_90_Valley_of_the_Four_Winds(count,datatree,openfile): characterquests.charquestheader(count,"81-90: Valley of the Four Winds",openfile) characterquests.charquestprint(count,datatree,openfile,29577,"Ashyo's Vision") characterquests.charquestprint(count,datatree,openfile,29581,"The Golden Dream") characterquests.charquestprint(count,datatree,openfile,29600,"Snap Judgment") characterquests.charquestprint(count,datatree,openfile,29757,"Bottletoads") characterquests.charquestprint(count,datatree,openfile,29758,"Guess Whose Back") characterquests.charquestprint(count,datatree,openfile,29871,"Clever Ashyo") characterquests.charquestprint(count,datatree,openfile,29872,"Lin Tenderpaw") characterquests.charquestprint(count,datatree,openfile,29877,"A Poor Grasp of the Basics") characterquests.charquestprint(count,datatree,openfile,29907,"Chen and Li Li") characterquests.charquestprint(count,datatree,openfile,29908,"A Seemingly Endless Nuisance") characterquests.charquestprint(count,datatree,openfile,29909,"Low Turnip Turnout") characterquests.charquestprint(count,datatree,openfile,29910,"Rampaging Rodents") characterquests.charquestprint(count,datatree,openfile,29911,"Practically Perfect Produce") characterquests.charquestprint(count,datatree,openfile,29912,"The Fabulous Miss Fanny") characterquests.charquestprint(count,datatree,openfile,29913,"The Meat They'll Eat") characterquests.charquestprint(count,datatree,openfile,29914,"Back to the Sty") characterquests.charquestprint(count,datatree,openfile,29915,"A Neighbor's Duty") characterquests.charquestprint(count,datatree,openfile,29916,"Piercing Talons and Slavering Jaws") characterquests.charquestprint(count,datatree,openfile,29917,"Lupello") characterquests.charquestprint(count,datatree,openfile,29918,"A Lesson in Bravery") characterquests.charquestprint(count,datatree,openfile,29919,"Great Minds Drink Alike") characterquests.charquestprint(count,datatree,openfile,29940,"Taking a Crop") characterquests.charquestprint(count,datatree,openfile,29944,"Leaders Among Breeders") characterquests.charquestprint(count,datatree,openfile,29945,"Yellow and Red Make Orange") characterquests.charquestprint(count,datatree,openfile,29946,"The Warren-Mother") characterquests.charquestprint(count,datatree,openfile,29947,"Crouching Carrot, Hidden Turnip") characterquests.charquestprint(count,datatree,openfile,29948,"Thieves to the Core") characterquests.charquestprint(count,datatree,openfile,29949,"Legacy") characterquests.charquestprint(count,datatree,openfile,29950,"Li Li's Day Off") characterquests.charquestprint(count,datatree,openfile,29951,"Muddy Water") characterquests.charquestprint(count,datatree,openfile,29952,"Broken Dreams") characterquests.charquestprint(count,datatree,openfile,29981,"Stemming the Swarm") characterquests.charquestprint(count,datatree,openfile,29982,"Evacuation Orders") characterquests.charquestprint(count,datatree,openfile,29983,"The Hidden Master") characterquests.charquestprint(count,datatree,openfile,29984,"Unyielding Fists: Trial of Bamboo") characterquests.charquestprint(count,datatree,openfile,29985,"They Will Be Mist") characterquests.charquestprint(count,datatree,openfile,29986,"Fog Wards") characterquests.charquestprint(count,datatree,openfile,29987,"Unyielding Fists: Trial of Wood") characterquests.charquestprint(count,datatree,openfile,29988,"A Taste For Eggs") characterquests.charquestprint(count,datatree,openfile,29989,"Unyielding Fists: Trial of Stone") characterquests.charquestprint(count,datatree,openfile,29990,"Training and Discipline") characterquests.charquestprint(count,datatree,openfile,29992,"Tenderpaw By Name, Tender Paw By Reputation") characterquests.charquestprint(count,datatree,openfile,30028,"Grain Recovery") characterquests.charquestprint(count,datatree,openfile,30029,"Wee Little Shenanigans") characterquests.charquestprint(count,datatree,openfile,30030,"Out of Sprite") characterquests.charquestprint(count,datatree,openfile,30031,"Taste Test") characterquests.charquestprint(count,datatree,openfile,30032,"The Quest for Better Barley") characterquests.charquestprint(count,datatree,openfile,30046,"Chen's Resolution") characterquests.charquestprint(count,datatree,openfile,30047,"The Chen Taste Test") characterquests.charquestprint(count,datatree,openfile,30048,"Li Li and the Grain") characterquests.charquestprint(count,datatree,openfile,30049,"Doesn't Hold Water") characterquests.charquestprint(count,datatree,openfile,30050,"Gardener Fran and the Watering Can") characterquests.charquestprint(count,datatree,openfile,30051,"The Great Water Hunt") characterquests.charquestprint(count,datatree,openfile,30052,"Weed War") characterquests.charquestprint(count,datatree,openfile,30053,"Hop Hunting") characterquests.charquestprint(count,datatree,openfile,30054,"Enough is Ookin' Enough") characterquests.charquestprint(count,datatree,openfile,30055,"Stormstout's Hops") characterquests.charquestprint(count,datatree,openfile,30056,"The Farmer's Daughter") characterquests.charquestprint(count,datatree,openfile,30057,"Seeing Orange") characterquests.charquestprint(count,datatree,openfile,30058,"Mothallus!") characterquests.charquestprint(count,datatree,openfile,30059,"The Moth Rebellion") characterquests.charquestprint(count,datatree,openfile,30072,"Where Silk Comes From") characterquests.charquestprint(count,datatree,openfile,30073,"The Emperor") characterquests.charquestprint(count,datatree,openfile,30074,"Knocking on the Door") characterquests.charquestprint(count,datatree,openfile,30075,"Clear the Way") characterquests.charquestprint(count,datatree,openfile,30076,"The Fanciest Water") characterquests.charquestprint(count,datatree,openfile,30077,"Barrels, Man") characterquests.charquestprint(count,datatree,openfile,30078,"Cleaning House") characterquests.charquestprint(count,datatree,openfile,30086,"The Search for the Hidden Master") characterquests.charquestprint(count,datatree,openfile,30117,"Stoneplow Thirsts") characterquests.charquestprint(count,datatree,openfile,30172,"Barreling Along") characterquests.charquestprint(count,datatree,openfile,30181,"Mushan Mastery") characterquests.charquestprint(count,datatree,openfile,30182,"Fox Mastery") characterquests.charquestprint(count,datatree,openfile,30183,"Stalker Mastery") characterquests.charquestprint(count,datatree,openfile,30184,"Mushan Mastery: Darkhide") characterquests.charquestprint(count,datatree,openfile,30185,"Tortoise Mastery") characterquests.charquestprint(count,datatree,openfile,30186,"Parental Mastery") characterquests.charquestprintfaction(count,datatree,openfile,30241,"Warn Stoneplow","horde") characterquests.charquestprint(count,datatree,openfile,30252,"A Helping Hand") characterquests.charquestprint(count,datatree,openfile,30254,"Learn and Grow II: Tilling and Planting") characterquests.charquestprint(count,datatree,openfile,30255,"Learn and Grow III: Tending Crops") characterquests.charquestprint(count,datatree,openfile,30256,"Learn and Grow IV: Harvesting") characterquests.charquestprint(count,datatree,openfile,30257,"Learn and Grow V: Halfhill Market") characterquests.charquestprint(count,datatree,openfile,30258,"Mung-Mung's Vote I: A Hozen's Problem") characterquests.charquestprint(count,datatree,openfile,30259,"Mung-Mung's Vote II: Rotten to the Core") characterquests.charquestprint(count,datatree,openfile,30260,"Growing the Farm I: The Weeds") characterquests.charquestprint(count,datatree,openfile,30267,"Watery Woes") characterquests.charquestprint(count,datatree,openfile,30275,"A Crocolisk Tale") characterquests.charquestprint(count,datatree,openfile,30325,"Where It Counts") characterquests.charquestprint(count,datatree,openfile,30326,"The Kunzen Legend-Chief") characterquests.charquestprint(count,datatree,openfile,30334,"Stealing is Bad... Re-Stealing is OK") characterquests.charquestprintfaction(count,datatree,openfile,30360,"Warn Stoneplow","alliance") characterquests.charquestprint(count,datatree,openfile,30376,"Hope Springs Eternal") characterquests.charquestprint(count,datatree,openfile,30516,"Growing the Farm I: A Little Problem") characterquests.charquestprint(count,datatree,openfile,30517,"Farmer Fung's Vote I: Yak Attack") characterquests.charquestprint(count,datatree,openfile,30518,"Farmer Fung's Vote II: On the Loose") characterquests.charquestprint(count,datatree,openfile,30519,"Nana's Vote I: Nana's Secret Recipe") characterquests.charquestprint(count,datatree,openfile,30521,"Haohan's Vote I: Bungalow Break-In") characterquests.charquestprint(count,datatree,openfile,30522,"Haohan's Vote II: The Real Culprits") characterquests.charquestprint(count,datatree,openfile,30523,"Growing the Farm II: The Broken Wagon") characterquests.charquestprint(count,datatree,openfile,30524,"Growing the Farm II: Knock on Wood") characterquests.charquestprint(count,datatree,openfile,30525,"Haohan's Vote III: Pure Poison") characterquests.charquestprint(count,datatree,openfile,30526,"Lost and Lonely") characterquests.charquestprint(count,datatree,openfile,30527,"Haohan's Vote IV: Melons For Felons") characterquests.charquestprint(count,datatree,openfile,30528,"Haohan's Vote V: Chief Yip-Yip") characterquests.charquestprint(count,datatree,openfile,30529,"Growing the Farm III: The Mossy Boulder") characterquests.charquestprint(count,datatree,openfile,30534,"A Second Hand") characterquests.charquestprint(count,datatree,openfile,30535,"Learn and Grow I: Seeds") characterquests.charquestprint(count,datatree,openfile,30622,"The Swarm Begins") characterquests.charquestprint(count,datatree,openfile,30623,"The Mantidote") characterquests.charquestprintfaction(count,datatree,openfile,30624,"It Does You No Good In The Keg","alliance") characterquests.charquestprint(count,datatree,openfile,30625,"Students No More") characterquests.charquestprint(count,datatree,openfile,30626,"Retreat!") characterquests.charquestprint(count,datatree,openfile,30627,"The Savior of Stoneplow") characterquests.charquestprint(count,datatree,openfile,30628,"The Gratitude of Stoneplow") characterquests.charquestprintfaction(count,datatree,openfile,30653,"It Does You No Good In The Keg","horde") characterquests.charquestprint(count,datatree,openfile,31312,"The Old Map") characterquests.charquestprint(count,datatree,openfile,31313,"Just A Folk Story") characterquests.charquestprint(count,datatree,openfile,31314,"Old Man Thistle's Treasure") characterquests.charquestprint(count,datatree,openfile,31315,"The Heartland Legacy") characterquests.charquestprint(count,datatree,openfile,31320,"Buy A Fish A Drink?") characterquests.charquestprint(count,datatree,openfile,31321,"Buy A Fish A Round?") characterquests.charquestprint(count,datatree,openfile,31322,"Buy A Fish A Keg?") characterquests.charquestprint(count,datatree,openfile,31323,"Buy A Fish A Brewery?") characterquests.charquestprint(count,datatree,openfile,31325,"A Very Nice Necklace") characterquests.charquestprint(count,datatree,openfile,31326,"Tina's Tasteful Tiara") characterquests.charquestprint(count,datatree,openfile,31328,"An Exquisite Earring") characterquests.charquestprint(count,datatree,openfile,31329,"A Beautiful Brooch") characterquests.charquestprint(count,datatree,openfile,31338,"Lost Sheepie") characterquests.charquestprint(count,datatree,openfile,31339,"Lost Sheepie... Again") characterquests.charquestprint(count,datatree,openfile,31340,"Oh Sheepie...") characterquests.charquestprint(count,datatree,openfile,31341,"A Wolf In Sheep's Clothing") characterquests.charquestprintfaction(count,datatree,openfile,31372,"The Tillers","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31374,"The Tillers","horde") characterquests.charquestprint(count,datatree,openfile,31529,"Mission: Culling The Vermin") characterquests.charquestprint(count,datatree,openfile,31530,"Mission: The Hozen Dozen") characterquests.charquestprint(count,datatree,openfile,31531,"Mission: Aerial Threat") characterquests.charquestprint(count,datatree,openfile,31532,"Mission: Predator of the Cliffs") characterquests.charquestprint(count,datatree,openfile,31534,"The Beginner's Brew") characterquests.charquestprint(count,datatree,openfile,31537,"Ella's Taste Test") characterquests.charquestprint(count,datatree,openfile,31538,"A Worthy Brew") characterquests.charquestprint(count,datatree,openfile,31671,"Why Not Scallions?") characterquests.charquestprint(count,datatree,openfile,31936,"The \\\"Jinyu Princess\\\" Irrigation System") characterquests.charquestprint(count,datatree,openfile,31937,"Thunder King Pest Repellers") characterquests.charquestprint(count,datatree,openfile,31938,"The \\\"Earth-Slasher\\\" Master Plow") characterquests.charquestprint(count,datatree,openfile,31945,"Learn and Grow VI: Gina's Vote") characterquests.charquestprint(count,datatree,openfile,31946,"Mung-Mung's Vote III: The Great Carrot Caper") characterquests.charquestprint(count,datatree,openfile,31947,"Farmer Fung's Vote III: Crazy For Cabbage") characterquests.charquestprint(count,datatree,openfile,31948,"Nana's Vote II: The Sacred Springs") characterquests.charquestprint(count,datatree,openfile,31949,"Nana's Vote III: Witchberry Julep") characterquests.charquestprint(count,datatree,openfile,32018,"His Name Was... Stormstout") characterquests.charquestprint(count,datatree,openfile,32019,"They Call Him... Stormstout") characterquests.charquestprint(count,datatree,openfile,32035,"Got Silk?") characterquests.charquestprint(count,datatree,openfile,32038,"Stag Mastery") characterquests.charquestprint(count,datatree,openfile,32045,"Children of the Water") characterquests.charquestprint(count,datatree,openfile,32189,"A Shabby New Face") characterquests.charquestprint(count,datatree,openfile,32198,"One Magical, Flying Kingdom's Trash...") characterquests.charquestprint(count,datatree,openfile,32682,"Inherit the Earth") characterquests.charquestprint(count,datatree,openfile,38935,"His Name Was... Stormstout") characterquests.charquestprintfaction(count,datatree,openfile,49539,"Warchief's Command: Valley of the Four Winds!","horde") characterquests.charquestprintfaction(count,datatree,openfile,49557,"Hero's Call: Valley of the Four Winds!","alliance") def z_81_90_Krasarang_Wilds(count,datatree,openfile): characterquests.charquestheader(count,"81-90: Krasarang Wilds",openfile) characterquests.charquestprint(count,datatree,openfile,29873,"Ken-Ken") characterquests.charquestprintfaction(count,datatree,openfile,29874,"Kang Bramblestaff","alliance") characterquests.charquestprintfaction(count,datatree,openfile,29875,"Kang Bramblestaff","horde") characterquests.charquestprint(count,datatree,openfile,30079,"What's Eating Zhu's Watch?") characterquests.charquestprint(count,datatree,openfile,30080,"Finding Yi-Mo") characterquests.charquestprint(count,datatree,openfile,30081,"Materia Medica") characterquests.charquestprint(count,datatree,openfile,30082,"Cheer Up, Yi-Mo") characterquests.charquestprint(count,datatree,openfile,30083,"Securing the Province") characterquests.charquestprint(count,datatree,openfile,30084,"Borderlands") characterquests.charquestprint(count,datatree,openfile,30088,"Why So Serious?") characterquests.charquestprint(count,datatree,openfile,30089,"Apply Directly to the Forehead") characterquests.charquestprint(count,datatree,openfile,30090,"Zhu's Despair") characterquests.charquestprint(count,datatree,openfile,30091,"Tears of Pandaria") characterquests.charquestprintfaction(count,datatree,openfile,30121,"Search Party","horde") characterquests.charquestprintfaction(count,datatree,openfile,30123,"Skitterer Stew","horde") characterquests.charquestprintfaction(count,datatree,openfile,30124,"Blind Them!","horde") characterquests.charquestprintfaction(count,datatree,openfile,30127,"Threat from Dojan","horde") characterquests.charquestprintfaction(count,datatree,openfile,30128,"The Pools of Youth","horde") characterquests.charquestprintfaction(count,datatree,openfile,30129,"The Mogu Agenda","horde") characterquests.charquestprintfaction(count,datatree,openfile,30130,"Herbal Remedies","horde") characterquests.charquestprintfaction(count,datatree,openfile,30131,"Life","horde") characterquests.charquestprintfaction(count,datatree,openfile,30132,"Going West","horde") characterquests.charquestprintfaction(count,datatree,openfile,30133,"Into the Wilds","horde") characterquests.charquestprintfaction(count,datatree,openfile,30163,"For the Tribe","horde") characterquests.charquestprintfaction(count,datatree,openfile,30164,"The Stoneplow Convoy","horde") characterquests.charquestprint(count,datatree,openfile,30168,"Thieving Raiders") characterquests.charquestprint(count,datatree,openfile,30169,"Raid Leader Slovan") characterquests.charquestprintfaction(count,datatree,openfile,30174,"For Family","horde") characterquests.charquestprintfaction(count,datatree,openfile,30175,"The Mantid","horde") characterquests.charquestprintfaction(count,datatree,openfile,30178,"Into the Wilds","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30179,"Poisoned!","horde") characterquests.charquestprintfaction(count,datatree,openfile,30229,"The Greater Danger","horde") characterquests.charquestprintfaction(count,datatree,openfile,30230,"Re-Reclaim","horde") characterquests.charquestprint(count,datatree,openfile,30268,"The Murksweats") characterquests.charquestprint(count,datatree,openfile,30269,"Unsafe Passage") characterquests.charquestprint(count,datatree,openfile,30270,"Blinding the Riverblades") characterquests.charquestprint(count,datatree,openfile,30271,"Sha Can Awe") characterquests.charquestprint(count,datatree,openfile,30272,"Striking the Rain") characterquests.charquestprint(count,datatree,openfile,30273,"In the House of the Red Crane") characterquests.charquestprint(count,datatree,openfile,30274,"The Arcanic Oubliette") characterquests.charquestprintfaction(count,datatree,openfile,30344,"The Lost Dynasty","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30346,"Where are the Pools","alliance") characterquests.charquestprint(count,datatree,openfile,30347,"The Pools of Youth") characterquests.charquestprintfaction(count,datatree,openfile,30348,"Immortality?","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30349,"Threat from Dojan","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30350,"Squirmy Delight","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30351,"Lotus Tea","alliance") characterquests.charquestprint(count,datatree,openfile,30352,"Crane Mastery") characterquests.charquestprint(count,datatree,openfile,30353,"Profit Mastery") characterquests.charquestprintfaction(count,datatree,openfile,30354,"No Sister Left Behind","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30355,"Re-Reclaim","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30356,"Sever Their Supply Line","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30357,"The Stoneplow Convoy","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30359,"The Lord Reclaimer","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30361,"The Mantid","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30363,"Going on the Offensive","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30384,"Blind Them!","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30445,"The Waters of Youth","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30461,"Into the Wilds","horde") characterquests.charquestprintfaction(count,datatree,openfile,30462,"Into the Wilds","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30464,"Going West","horde") characterquests.charquestprintfaction(count,datatree,openfile,30465,"Going on the Offensive","alliance") characterquests.charquestprint(count,datatree,openfile,30666,"Sudden, Unexpected Crocolisk Aggression") characterquests.charquestprint(count,datatree,openfile,30667,"Particular Plumage") characterquests.charquestprint(count,datatree,openfile,30668,"Build Your Own Raft") characterquests.charquestprint(count,datatree,openfile,30669,"The Lorewalker on the Lake") characterquests.charquestprint(count,datatree,openfile,30671,"Wisdom Has A Price") characterquests.charquestprint(count,datatree,openfile,30672,"Balance") characterquests.charquestprint(count,datatree,openfile,30674,"Balance Without Violence") characterquests.charquestprint(count,datatree,openfile,30675,"Buried Hozen Treasure") characterquests.charquestprint(count,datatree,openfile,30691,"Misery") characterquests.charquestprint(count,datatree,openfile,30694,"Tread Lightly") characterquests.charquestprint(count,datatree,openfile,30695,"Ahead on the Way") characterquests.charquestprint(count,datatree,openfile,31260,"Profit Mastery: Chasheen") characterquests.charquestprint(count,datatree,openfile,31262,"Crane Mastery: Needlebeak") characterquests.charquestprintfaction(count,datatree,openfile,31369,"The Anglers","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31370,"The Anglers","horde") characterquests.charquestprintfaction(count,datatree,openfile,49540,"Warchief's Command: Krasarang Wilds!","horde") characterquests.charquestprintfaction(count,datatree,openfile,49558,"Hero's Call: Krasarang Wilds!","alliance") def z_82_90_KunLai_Summit(count,datatree,openfile): characterquests.charquestheader(count,"82-90: KunLai Summit",openfile) characterquests.charquestprint(count,datatree,openfile,30457,"Call Out Their Leader") characterquests.charquestprint(count,datatree,openfile,30459,"All of the Arrows") characterquests.charquestprint(count,datatree,openfile,30460,"Hit Medicine") characterquests.charquestprint(count,datatree,openfile,30467,"My Son...") characterquests.charquestprint(count,datatree,openfile,30468,"Enraged Vengeance") characterquests.charquestprint(count,datatree,openfile,30469,"Repossession") characterquests.charquestprint(count,datatree,openfile,30480,"The Ritual") characterquests.charquestprint(count,datatree,openfile,30487,"Comin' Round the Mountain") characterquests.charquestprint(count,datatree,openfile,30488,"The Missing Muskpaw") characterquests.charquestprint(count,datatree,openfile,30489,"Fresh Needle Scent") characterquests.charquestprint(count,datatree,openfile,30490,"Yakity Yak") characterquests.charquestprint(count,datatree,openfile,30491,"At the Yak Wash") characterquests.charquestprint(count,datatree,openfile,30492,"Back in Yak") characterquests.charquestprint(count,datatree,openfile,30496,"The Waterspeaker's Staff") characterquests.charquestprintfaction(count,datatree,openfile,30506,"Admiral Taylor has Awakened","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30507,"Admiral Taylor has Awakened","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30508,"Admiral Taylor has Awakened","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30509,"General Nazgrim has Awakened","horde") characterquests.charquestprintfaction(count,datatree,openfile,30510,"General Nazgrim has Awakened","horde") characterquests.charquestprintfaction(count,datatree,openfile,30511,"General Nazgrim has Awakened","horde") characterquests.charquestprintfaction(count,datatree,openfile,30512,"Westwind Rest","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30513,"Eastwind Rest","horde") characterquests.charquestprintfaction(count,datatree,openfile,30514,"Challenge Accepted","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30515,"Challenge Accepted","horde") characterquests.charquestprintfaction(count,datatree,openfile,30569,"Trouble on the Farmstead","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30570,"Trouble on the Farmstead","horde") characterquests.charquestprint(count,datatree,openfile,30571,"Farmhand Freedom") characterquests.charquestprintfaction(count,datatree,openfile,30575,"Round 'Em Up","alliance") characterquests.charquestprint(count,datatree,openfile,30581,"... and the Pot, Too!") characterquests.charquestprint(count,datatree,openfile,30582,"The Late Mrs. Muskpaw") characterquests.charquestprintfaction(count,datatree,openfile,30583,"Blue Dwarf Needs Food Badly","alliance") characterquests.charquestprint(count,datatree,openfile,30587,"Yakity Yak") characterquests.charquestprint(count,datatree,openfile,30592,"The Burlap Trail: To Burlap Waystation") characterquests.charquestprintfaction(count,datatree,openfile,30593,"Deanimate the Reanimated","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30594,"Deanimate the Reanimated","horde") characterquests.charquestprint(count,datatree,openfile,30595,"Profiting off of the Past") characterquests.charquestprint(count,datatree,openfile,30596,"A Zandalari Troll?") characterquests.charquestprint(count,datatree,openfile,30599,"A Monkey Idol") characterquests.charquestprint(count,datatree,openfile,30600,"No Pack Left Behind") characterquests.charquestprint(count,datatree,openfile,30601,"Instant Courage") characterquests.charquestprint(count,datatree,openfile,30602,"The Rabbitsfoot") characterquests.charquestprint(count,datatree,openfile,30603,"The Broketooth Ravage") characterquests.charquestprint(count,datatree,openfile,30604,"Breaking Broketooth") characterquests.charquestprint(count,datatree,openfile,30605,"Bros Before Hozen") characterquests.charquestprint(count,datatree,openfile,30606,"Thumping Knucklethump") characterquests.charquestprint(count,datatree,openfile,30607,"Hozen Love Their Keys") characterquests.charquestprint(count,datatree,openfile,30608,"The Snackrifice") characterquests.charquestprint(count,datatree,openfile,30610,"Grummle! Grummle! Grummle!") characterquests.charquestprint(count,datatree,openfile,30611,"Unleash The Yeti!") characterquests.charquestprint(count,datatree,openfile,30612,"The Leader Hozen") characterquests.charquestprint(count,datatree,openfile,30614,"Oil Stop") characterquests.charquestprint(count,datatree,openfile,30615,"A Zandalari Troll?") characterquests.charquestprint(count,datatree,openfile,30616,"Traffic Issues") characterquests.charquestprint(count,datatree,openfile,30617,"Roadside Assistance") characterquests.charquestprint(count,datatree,openfile,30618,"Resupplying One Keg") characterquests.charquestprintfaction(count,datatree,openfile,30619,"Mogu?! Oh No-gu!","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30620,"Mogu?! Oh No-gu!","horde") characterquests.charquestprint(count,datatree,openfile,30621,"They Stole My Luck!") characterquests.charquestprintfaction(count,datatree,openfile,30650,"Pandaren Prisoners","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30651,"Barrels of Fun","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30652,"In Tents Channeling","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30655,"Pandaren Prisoners","horde") characterquests.charquestprintfaction(count,datatree,openfile,30656,"Barrels of Fun","horde") characterquests.charquestprintfaction(count,datatree,openfile,30657,"In Tents Channeling","horde") characterquests.charquestprint(count,datatree,openfile,30660,"The Ordo Warbringer") characterquests.charquestprint(count,datatree,openfile,30661,"The Ordo Warbringer") characterquests.charquestprintfaction(count,datatree,openfile,30662,"The Ordo Warbringer","alliance") characterquests.charquestprintfaction(count,datatree,openfile,30663,"The Ordo Warbringer","horde") characterquests.charquestprint(count,datatree,openfile,30665,"The Defense of Shado-Pan Fallback") characterquests.charquestprint(count,datatree,openfile,30670,"Turnabout") characterquests.charquestprint(count,datatree,openfile,30673,"Holed Up") characterquests.charquestprint(count,datatree,openfile,30680,"Holed Up") characterquests.charquestprint(count,datatree,openfile,30681,"Holed Up") characterquests.charquestprint(count,datatree,openfile,30682,"Holed Up") characterquests.charquestprint(count,datatree,openfile,30683,"One Traveler's Misfortune") characterquests.charquestprint(count,datatree,openfile,30684,"Seeker's Folly") characterquests.charquestprint(count,datatree,openfile,30690,"Unmasking the Yaungol") characterquests.charquestprint(count,datatree,openfile,30692,"The Burlap Trail: To Kota Basecamp") characterquests.charquestprint(count,datatree,openfile,30699,"To Winter's Blossom") characterquests.charquestprint(count,datatree,openfile,30710,"Provoking the Trolls") characterquests.charquestprint(count,datatree,openfile,30715,"A Line Unbroken") characterquests.charquestprint(count,datatree,openfile,30723,"Honor, Even in Death") characterquests.charquestprint(count,datatree,openfile,30724,"To the Wall!") characterquests.charquestprint(count,datatree,openfile,30742,"Shut it Down") characterquests.charquestprint(count,datatree,openfile,30743,"Gourmet Kafa") characterquests.charquestprint(count,datatree,openfile,30744,"Kota Blend") characterquests.charquestprint(count,datatree,openfile,30745,"Trouble Brewing") characterquests.charquestprint(count,datatree,openfile,30746,"A Fair Trade") characterquests.charquestprint(count,datatree,openfile,30747,"The Burlap Grind") characterquests.charquestprint(count,datatree,openfile,30750,"Off the Wall!") characterquests.charquestprint(count,datatree,openfile,30751,"A Terrible Sacrifice") characterquests.charquestprint(count,datatree,openfile,30752,"Unbelievable!") characterquests.charquestprint(count,datatree,openfile,30765,"Regaining Honor") characterquests.charquestprint(count,datatree,openfile,30766,"Profiting off of the Past") characterquests.charquestprint(count,datatree,openfile,30794,"Emergency Care") characterquests.charquestprint(count,datatree,openfile,30795,"Staying Connected") characterquests.charquestprint(count,datatree,openfile,30796,"An End to Everything") characterquests.charquestprint(count,datatree,openfile,30797,"It Was Almost Alive") characterquests.charquestprint(count,datatree,openfile,30798,"Breaking the Emperor's Shield") characterquests.charquestprint(count,datatree,openfile,30799,"The Tomb of Shadows") characterquests.charquestprint(count,datatree,openfile,30800,"Stealing Their Thunder King") characterquests.charquestprint(count,datatree,openfile,30801,"Lessons from History") characterquests.charquestprint(count,datatree,openfile,30802,"Chasing the Storm") characterquests.charquestprint(count,datatree,openfile,30804,"The Fearmaster") characterquests.charquestprint(count,datatree,openfile,30805,"Justice") characterquests.charquestprint(count,datatree,openfile,30806,"The Scent of Life") characterquests.charquestprint(count,datatree,openfile,30807,"By the Falls, For the Fallen") characterquests.charquestprint(count,datatree,openfile,30808,"A Grummle's Luck") characterquests.charquestprint(count,datatree,openfile,30816,"Checking In") characterquests.charquestprint(count,datatree,openfile,30819,"Preparing the Remains") characterquests.charquestprint(count,datatree,openfile,30820,"A Funeral") characterquests.charquestprint(count,datatree,openfile,30821,"The Burlap Grind") characterquests.charquestprint(count,datatree,openfile,30823,"Shut it Down") characterquests.charquestprint(count,datatree,openfile,30824,"Gourmet Kafa") characterquests.charquestprint(count,datatree,openfile,30825,"Kota Blend") characterquests.charquestprint(count,datatree,openfile,30826,"Trouble Brewing") characterquests.charquestprint(count,datatree,openfile,30828,"Cleansing the Mere") characterquests.charquestprint(count,datatree,openfile,30829,"The Tongue of Ba-Shon") characterquests.charquestprint(count,datatree,openfile,30834,"Father and Child Reunion") characterquests.charquestprint(count,datatree,openfile,30855,"The Fall of Shai Hu") characterquests.charquestprint(count,datatree,openfile,30879,"Round 1: Brewmaster Chani") characterquests.charquestprint(count,datatree,openfile,30880,"Round 1: The Streetfighter") characterquests.charquestprint(count,datatree,openfile,30881,"Round 2: Clever Ashyo &amp; Ken-Ken") characterquests.charquestprint(count,datatree,openfile,30882,"Round 2: Kang Bramblestaff") characterquests.charquestprint(count,datatree,openfile,30883,"Round 3: The Wrestler") characterquests.charquestprint(count,datatree,openfile,30885,"Round 3: Master Boom Boom") characterquests.charquestprint(count,datatree,openfile,30902,"Round 4: Master Windfur") characterquests.charquestprint(count,datatree,openfile,30907,"Round 4: The P.U.G.") characterquests.charquestprint(count,datatree,openfile,30935,"Fisherman's Tale") characterquests.charquestprint(count,datatree,openfile,30942,"Make A Fighter Out of Me") characterquests.charquestprint(count,datatree,openfile,30943,"Handle With Care") characterquests.charquestprint(count,datatree,openfile,30944,"It Takes A Village") characterquests.charquestprint(count,datatree,openfile,30945,"What's Yours Is Mine") characterquests.charquestprint(count,datatree,openfile,30946,"Revelations") characterquests.charquestprint(count,datatree,openfile,30967,"Free the Dissenters") characterquests.charquestprint(count,datatree,openfile,30991,"Do a Barrel Roll!") characterquests.charquestprint(count,datatree,openfile,30992,"Finish This!") characterquests.charquestprint(count,datatree,openfile,30993,"Where are My Reinforcements?") characterquests.charquestprint(count,datatree,openfile,30994,"Lao-Chin's Gambit") characterquests.charquestprint(count,datatree,openfile,30999,"Path Less Traveled") characterquests.charquestprint(count,datatree,openfile,31011,"Enemies At Our Door") characterquests.charquestprint(count,datatree,openfile,31207,"The Arena of Annihilation") characterquests.charquestprint(count,datatree,openfile,31228,"Prophet Khar'zul") characterquests.charquestprintfaction(count,datatree,openfile,31251,"Best Meals Anywhere!","horde") characterquests.charquestprintfaction(count,datatree,openfile,31252,"Back to Westwind Rest","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31253,"Back to Eastwind Rest","horde") characterquests.charquestprintfaction(count,datatree,openfile,31254,"The Road to Kun-Lai","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31255,"The Road to Kun-Lai","horde") characterquests.charquestprintfaction(count,datatree,openfile,31256,"Round 'Em Up","horde") characterquests.charquestprint(count,datatree,openfile,31285,"The Spring Drifter") characterquests.charquestprint(count,datatree,openfile,31286,"Robbing Robbers of Robbers") characterquests.charquestprint(count,datatree,openfile,31287,"Educating Saurok") characterquests.charquestprint(count,datatree,openfile,31306,"Seeker's Folly") characterquests.charquestprint(count,datatree,openfile,31380,"Trial At The Temple of the White Tiger") characterquests.charquestprint(count,datatree,openfile,31381,"Trial At The Temple of the White Tiger") characterquests.charquestprintfaction(count,datatree,openfile,31392,"Temple of the White Tiger","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31393,"Temple of the White Tiger","horde") characterquests.charquestprintfaction(count,datatree,openfile,31394,"A Celestial Experience","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31395,"A Celestial Experience","horde") characterquests.charquestprintfaction(count,datatree,openfile,31451,"The Missing Merchant","horde") characterquests.charquestprintfaction(count,datatree,openfile,31452,"The Missing Merchant","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31453,"The Shado-Pan","horde") characterquests.charquestprintfaction(count,datatree,openfile,31455,"The Shado-Pan","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31456,"Muskpaw Ranch","alliance") characterquests.charquestprintfaction(count,datatree,openfile,31457,"Muskpaw Ranch","horde") characterquests.charquestprintfaction(count,datatree,openfile,31459,"Cho's Missive","horde") characterquests.charquestprintfaction(count,datatree,openfile,31460,"Cho's Missive","alliance") characterquests.charquestprint(count,datatree,openfile,31492,"The Torch of Strength") characterquests.charquestprintfaction(count,datatree,openfile,31511,"A Witness to History","horde") characterquests.charquestprintfaction(count,datatree,openfile,31512,"A Witness to History","alliance") characterquests.charquestprint(count,datatree,openfile,31517,"Contending With Bullies") characterquests.charquestprint(count,datatree,openfile,31518,"The Vale of Eternal Blossoms") characterquests.charquestprint(count,datatree,openfile,38936,"The Road to Kun-Lai") characterquests.charquestprintfaction(count,datatree,openfile,49541,"Warchief's Command: Kun-Lai Summit!","horde") characterquests.charquestprintfaction(count,datatree,openfile,49559,"Hero's Call: Kun-Lai Summit!","alliance") def z_83_90_Townlong_Steppes(count,datatree,openfile): characterquests.charquestheader(count,"83-90: Townlong Steppes",openfile) def z_84_90_Dread_Wastes(count,datatree,openfile): characterquests.charquestheader(count,"84-90: Dread Wastes",openfile) def z_85_90_Vale_of_Eternal_Blossoms(count,datatree,openfile): characterquests.charquestheader(count,"85-90: Vale of Eternal Blossoms",openfile) def z_85_90_Isle_of_Thunder(count,datatree,openfile): characterquests.charquestheader(count,"85-90: Isle of Thunder",openfile) def z_85_90_Timeless_Isle(count,datatree,openfile): characterquests.charquestheader(count,"85-90: Timeless Isle",openfile) def z_85_90_Pandaren_Campaign(count,datatree,openfile): characterquests.charquestheader(count,"85-90: Pandaren Campaign",openfile)
''' Default included TCP publishers. @author: Michael Eddington @version: $Id: tcp.py 2591 2011-11-11 11:27:57Z meddingt $ ''' # # Copyright (c) Michael Eddington # # 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. # # Authors: # Michael Eddington (mike@phed.org) # $Id: tcp.py 2591 2011-11-11 11:27:57Z meddingt $ import socket, time, sys from Peach.Engine.engine import Engine from Peach.Engine.common import SoftException, PeachException from Peach.publisher import Publisher from Peach.publisher import Timeout from Peach.publisher import PublisherSoftException import Peach def Debug(msg): if Peach.Engine.engine.Engine.debug: print msg #class Timeout(SoftException): # def __init__(self, msg): # self.msg = msg # # def __str__(self): # return self.msg class Tcp(Publisher): ''' A simple TCP client publisher. ''' def __init__(self, host, port, timeout = 0.25, throttle = 0): ''' @type host: string @param host: Remote host @type port: number @param port: Remote port @type timeout: number @param timeout: How long to wait for reponse @type throttle: number @param throttle: How long to wait between connections ''' Publisher.__init__(self) self._host = host try: self._port = int(port) except: raise PeachException("The Tcp publisher parameter for port was not a valid number.") try: self._timeout = float(timeout) except: raise PeachException("The Tcp publisher parameter for timeout was not a valid number.") try: self._throttle = float(throttle) except: raise PeachException("The Tcp publisher parameter for throttle was not a valid number.") self._socket = None def start(self): pass def stop(self): self.close() def connect(self): ''' Create connection. ''' self.close() if self._throttle > 0: time.sleep(self._throttle) # Try connecting many times # before we crash. for i in range(30): try: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._host,self._port)) exception = None break except: self._socket = None exception = sys.exc_info() # Wait half sec and try again time.sleep(1) if self._socket == None: value = "" try: value = str(exception[1]) except: pass raise PeachException("TCP onnection attempt failed: %s" % value) self.buff = "" self.pos = 0 def close(self): ''' Close connection if open. ''' try: if self._socket != None: self._socket.close() finally: self._socket = None self.buff = "" self.pos = 0 def send(self, data): ''' Send data via sendall. @type data: string @param data: Data to send ''' if Peach.Engine.engine.Engine.debug: print ">>>>>>>>>>>>>>>>" print "tcp.Tcp.send():" self.hexPrint(data) try: self._socket.sendall(data) except: if Peach.Engine.engine.Engine.debug: print "Tcp: Sendall failed: " + str(sys.exc_info()[1]) raise PublisherSoftException("sendall failed: " + str(sys.exc_info()[1])) def _receiveBySize(self, size): ''' This is now a buffered receiver. @rtype: string @return: received data. ''' # Do we already a have it? if size+self.pos < len(self.buff): ret = self.buff[self.pos:self.pos+size] self.pos += size return ret # Only ask for the diff of what we don't already have diffSize = (self.pos+size) - len(self.buff) try: if Peach.Engine.engine.Engine.debug: print "Asking for %d, need %d, have %d" % (size, diffSize, len(self.buff)-self.pos) self._socket.settimeout(self._timeout) ret = self._socket.recv(diffSize) if not ret: # Socket was closed if Peach.Engine.engine.Engine.debug: print "Socket is closed" raise PublisherSoftException("Socket is closed") if Peach.Engine.engine.Engine.debug: print "<<<<<<<<<<<<<<<<<" print "tcp.Tcp.receive():" self.hexPrint(ret) self.buff += ret except socket.error, e: if str(e).find('The socket operation could not complete without blocking') != -1: if Peach.Engine.engine.Engine.debug: print "timed out waiting for data" raise Timeout("Timed out waiting for data [%d:%d:%d:%d]" % (len(self.buff), (size+self.pos), size, diffSize)) elif str(e).find('An existing connection was forcibly') != -1: if Peach.Engine.engine.Engine.debug: print "Socket was closed!" raise PublisherSoftException("Socket is closed") else: if Peach.Engine.engine.Engine.debug: print "recv failed: " + str(sys.exc_info()[1]) raise PublisherSoftException("recv failed: " + str(sys.exc_info()[1])) finally: self._socket.settimeout(None) ret = self.buff[self.pos:] self.pos = len(self.buff) return ret def _receiveByAvailable(self): ''' Receive as much as possible prior to timeout. @rtype: string @return: received data. ''' self._socket.settimeout(self._timeout) try: ret = self._socket.recv(4096) if not ret: raise PublisherSoftException("Socket is closed") if Peach.Engine.engine.Engine.debug: print "<<<<<<<<<<<<<<<<<" print "tcp.Tcp.receive():" self.hexPrint(ret) self.buff += ret except socket.error, e: if str(e).find('The socket operation could not complete without blocking') == -1: pass else: raise PublisherSoftException("recv failed: " + str(sys.exc_info()[1])) self._socket.settimeout(None) ret = self.buff[self.pos:] self.pos = len(self.buff) return ret def receive(self, size = None): if size == None: return self._receiveByAvailable() else: return self._receiveBySize(size) class TcpListener(Tcp): ''' A TCP Listener publisher. This publisher supports the following state actions: * start - Start listening * stop - Stop listeningn nCMuBd7z3 * accept - Accept a client connection * close - Close a client connection ''' def __init__(self, host, port, timeout = 0.25): Tcp.__init__(self, host, port, timeout) self._listen = None self._clientAddr = None def start(self): self.close() if self._listen == None: # Try connection three times befor # exiting fuzzer run for i in range(3): try: self._listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._listen.bind((self._host,self._port)) self._listen.listen(1) exception = None break except: self._listen = None exception = sys.exc_info() time.sleep(0.5) if self._listen == None: value = "" try: value = str(exception[1]) except: pass raise PeachException("TCP bind attempt failed: %s" % value) self.buff = "" self.pos = 0 def stop(self): try: if self._socket != None: self._socket.close() except: pass finally: self._socket = None # Avoid TIME_WAIT state by not closing our listener #try: # if self._listen != None: # self._listen.close() #except: # pass # #finally: # self._listen = None def accept(self): self.buff = "" self.pos = 0 conn, addr = self._listen.accept() self._socket = conn self._clientAddr = addr def close(self): try: if self._socket != None: self._socket.close() except: pass finally: self._socket = None def connect(self): raise PeachException("Action 'connect' not supported") try: import win32gui, win32con, win32process import sys,time, os, signal class TcpListenerLaunchGui(TcpListener): ''' Does TcpListener goodness and also can laun a program. After some defined amount of time we will try and close the GUI application by sending WM_CLOSE than kill it. ''' def __init__(self, host, port, windowname, timeout = 0.25): TcpListener.__init__(self, host, port, timeout) self._windowName = windowname def stop(self): self.closeApp(self._windowName) TcpListener.stop(self) def call(self, method, args): ''' Launch program to consume file @type method: string @param method: Command to execute @type args: array of objects @param args: Arguments to pass ''' realArgs = [method, "/c", method] for a in args: realArgs.append(a) #print "Spawning %s" % method os.spawnv(os.P_NOWAIT, os.path.join( os.getenv('SystemRoot'), 'system32','cmd.exe'), realArgs) def enumCallback(hwnd, windowName): ''' Will get called by win32gui.EnumWindows, once for each top level application window. ''' try: # Get window title title = win32gui.GetWindowText(hwnd) # Is this our guy? if title.find(windowName) == -1: return (threadId, processId) = win32process.GetWindowThreadProcessId(hwnd) # Send WM_CLOSE message try: win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) win32gui.PostQuitMessage(hwnd) except: pass # Give it upto 5 sec for i in range(100): if win32process.GetExitCodeProcess(processId) != win32con.STILL_ACTIVE: # Process exited already return time.sleep(0.25) try: # Kill application win32process.TerminateProcess(processId, 0) except: pass except: pass enumCallback = staticmethod(enumCallback) def closeApp(self, title): ''' Close Application by window title ''' #print "CloseApp: %s" % title win32gui.EnumWindows(TcpListenerLaunchGui.enumCallback, title) except: pass # end
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from telemetry.core import system_info from telemetry.page import page as page_module from telemetry.page import page_set from telemetry.page import test_expectations VENDOR_NVIDIA = 0x10DE VENDOR_AMD = 0x1002 VENDOR_INTEL = 0x8086 VENDOR_STRING_IMAGINATION = 'Imagination Technologies' DEVICE_STRING_SGX = 'PowerVR SGX 554' class StubPlatform(object): def __init__(self, os_name, os_version_name=None): self.os_name = os_name self.os_version_name = os_version_name def GetOSName(self): return self.os_name def GetOSVersionName(self): return self.os_version_name class StubBrowser(object): def __init__(self, platform, gpu, device, vendor_string, device_string): self.platform = platform self.system_info = system_info.SystemInfo.FromDict({ 'model_name': '', 'gpu': { 'devices': [ {'vendor_id': gpu, 'device_id': device, 'vendor_string': vendor_string, 'device_string': device_string}, ] } }) @property def supports_system_info(self): return False if not self.system_info else True def GetSystemInfo(self): return self.system_info class StubSharedPageState(object): def __init__(self, browser): self.browser = browser class SampleTestExpectations(test_expectations.TestExpectations): def SetExpectations(self): self.Fail('page1.html', ['win', 'mac'], bug=123) self.Fail('page2.html', ['vista'], bug=123) self.Fail('page3.html', bug=123) self.Fail('page4.*', bug=123) self.Fail('http://test.com/page5.html', bug=123) self.Fail('page6.html', ['nvidia', 'intel'], bug=123) self.Fail('page7.html', [('nvidia', 0x1001), ('nvidia', 0x1002)], bug=123) self.Fail('page8.html', ['win', 'intel', ('amd', 0x1001)], bug=123) self.Fail('page9.html', ['imagination']) self.Fail('page10.html', [('imagination', 'PowerVR SGX 554')]) self.Fail('Pages.page_11') self.Fail('page12.html', ['mountainlion']) self.Fail('page13.html', ['mavericks']) self.Fail('page14.html', ['yosemite']) self.Fail('page15.html', ['amd', 'valid_condition_matched']) self.Fail('page16.html', ['amd', 'valid_condition_unmatched']) def IsValidUserDefinedCondition(self, condition): return condition in ('valid_condition_matched', 'valid_condition_unmatched') def ModifiersApply(self, shared_page_state, expectation): if not super(SampleTestExpectations, self).ModifiersApply(shared_page_state, expectation): return False return ((not expectation.user_defined_conditions) or 'valid_condition_matched' in expectation.user_defined_conditions) class TestExpectationsTest(unittest.TestCase): def setUp(self): self.expectations = SampleTestExpectations() def assertExpectationEquals(self, expected, page, platform='', gpu=0, device=0, vendor_string='', device_string=''): result = self.expectations.GetExpectationForPage(StubSharedPageState( StubBrowser(platform, gpu, device, vendor_string, device_string)), page) self.assertEquals(expected, result) # Pages with no expectations should always return 'pass' def testNoExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page0.html', ps) self.assertExpectationEquals('pass', page, StubPlatform('win')) # Pages with expectations for an OS should only return them when running on # that OS def testOSExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page1.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win')) self.assertExpectationEquals('fail', page, StubPlatform('mac')) self.assertExpectationEquals('pass', page, StubPlatform('linux')) # Pages with expectations for an OS version should only return them when # running on that OS version def testOSVersionExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page2.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win', 'vista')) self.assertExpectationEquals('pass', page, StubPlatform('win', 'win7')) # Pages with non-conditional expectations should always return that # expectation regardless of OS or OS version def testConditionlessExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page3.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win')) self.assertExpectationEquals('fail', page, StubPlatform('mac', 'lion')) self.assertExpectationEquals('fail', page, StubPlatform('linux')) # Expectations with wildcard characters should return for matching patterns def testWildcardExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page4.html', ps) page_js = page_module.Page('http://test.com/page4.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win')) self.assertExpectationEquals('fail', page_js, StubPlatform('win')) # Expectations with absolute paths should match the entire path def testAbsoluteExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page5.html', ps) page_org = page_module.Page('http://test.org/page5.html', ps) page_https = page_module.Page('https://test.com/page5.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win')) self.assertExpectationEquals('pass', page_org, StubPlatform('win')) self.assertExpectationEquals('pass', page_https, StubPlatform('win')) # Pages with expectations for a GPU should only return them when running with # that GPU def testGpuExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page6.html', ps) self.assertExpectationEquals('fail', page, gpu=VENDOR_NVIDIA) self.assertExpectationEquals('fail', page, gpu=VENDOR_INTEL) self.assertExpectationEquals('pass', page, gpu=VENDOR_AMD) # Pages with expectations for a GPU should only return them when running with # that GPU def testGpuDeviceIdExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page7.html', ps) self.assertExpectationEquals('fail', page, gpu=VENDOR_NVIDIA, device=0x1001) self.assertExpectationEquals('fail', page, gpu=VENDOR_NVIDIA, device=0x1002) self.assertExpectationEquals('pass', page, gpu=VENDOR_NVIDIA, device=0x1003) self.assertExpectationEquals('pass', page, gpu=VENDOR_AMD, device=0x1001) # Pages with multiple expectations should only return them when all criteria # is met def testMultipleExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page8.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('win'), VENDOR_AMD, 0x1001) self.assertExpectationEquals('fail', page, StubPlatform('win'), VENDOR_INTEL, 0x1002) self.assertExpectationEquals('pass', page, StubPlatform('win'), VENDOR_NVIDIA, 0x1001) self.assertExpectationEquals('pass', page, StubPlatform('mac'), VENDOR_AMD, 0x1001) self.assertExpectationEquals('pass', page, StubPlatform('win'), VENDOR_AMD, 0x1002) # Pages with expectations based on GPU vendor string. def testGpuVendorStringExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page9.html', ps) self.assertExpectationEquals('fail', page, vendor_string=VENDOR_STRING_IMAGINATION, device_string=DEVICE_STRING_SGX) self.assertExpectationEquals('fail', page, vendor_string=VENDOR_STRING_IMAGINATION, device_string='Triangle Monster 3000') self.assertExpectationEquals('pass', page, vendor_string='Acme', device_string=DEVICE_STRING_SGX) # Pages with expectations based on GPU vendor and renderer string pairs. def testGpuDeviceStringExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page10.html', ps) self.assertExpectationEquals('fail', page, vendor_string=VENDOR_STRING_IMAGINATION, device_string=DEVICE_STRING_SGX) self.assertExpectationEquals('pass', page, vendor_string=VENDOR_STRING_IMAGINATION, device_string='Triangle Monster 3000') self.assertExpectationEquals('pass', page, vendor_string='Acme', device_string=DEVICE_STRING_SGX) # Pages with user-defined expectations. def testUserDefinedExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page15.html', ps) self.assertExpectationEquals('fail', page, gpu=VENDOR_AMD) page = page_module.Page('http://test.com/page16.html', ps) self.assertExpectationEquals('pass', page, gpu=VENDOR_AMD) # Expectations can be set against page names as well as urls def testPageNameExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page11.html', ps, name='Pages.page_11') self.assertExpectationEquals('fail', page) # Verify version-specific Mac expectations. def testMacVersionExpectations(self): ps = page_set.PageSet() page = page_module.Page('http://test.com/page12.html', ps) self.assertExpectationEquals('fail', page, StubPlatform('mac', 'mountainlion')) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'mavericks')) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'yosemite')) ps = page_set.PageSet() page = page_module.Page('http://test.com/page13.html', ps) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'mountainlion')) self.assertExpectationEquals('fail', page, StubPlatform('mac', 'mavericks')) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'yosemite')) ps = page_set.PageSet() page = page_module.Page('http://test.com/page14.html', ps) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'mountainlion')) self.assertExpectationEquals('pass', page, StubPlatform('mac', 'mavericks')) self.assertExpectationEquals('fail', page, StubPlatform('mac', 'yosemite'))
"""Jinja2 processor test suite.""" import collections.abc import pathlib import textwrap import unittest.mock import bs4 import pytest import holocron from holocron._processors import jinja2 @pytest.fixture(scope="function") def testapp(): return holocron.Application({"url": "https://yoda.ua"}) def test_item(testapp): """Jinja2 processor has to work!""" stream = jinja2.process( testapp, [holocron.Item({"title": "History of the Force", "content": "the Force"})], ) assert isinstance(stream, collections.abc.Iterable) items = list(stream) assert items[:1] == [ holocron.Item({"title": "History of the Force", "content": unittest.mock.ANY}) ] soup = bs4.BeautifulSoup(items[0]["content"], "html.parser") assert soup.meta["charset"] == "UTF-8" assert soup.article.header.h1.string == "History of the Force" assert list(soup.article.stripped_strings)[1] == "the Force" # Since we don't know in which order statics are discovered, we sort them # so we can avoid possible flakes. static = sorted(items[1:], key=lambda d: d["source"]) assert static[0]["source"] == pathlib.Path("static", "logo.svg") assert static[0]["destination"] == static[0]["source"] assert static[1]["source"] == pathlib.Path("static", "pygments.css") assert static[1]["destination"] == static[1]["source"] assert static[2]["source"] == pathlib.Path("static", "style.css") assert static[2]["destination"] == static[2]["source"] assert len(static) == 3 def test_item_template(testapp, tmpdir): """Jinja2 processor has to respect item suggested template.""" tmpdir.ensure("theme_a", "templates", "holiday.j2").write_text( textwrap.dedent( """\ template: my super template rendered: {{ item.title }} """ ), encoding="UTF-8", ) stream = jinja2.process( testapp, [ holocron.Item( { "title": "History of the Force", "content": "the Force", "template": "holiday.j2", } ) ], themes=[tmpdir.join("theme_a").strpath], ) assert isinstance(stream, collections.abc.Iterable) assert list(stream) == [ holocron.Item( { "title": "History of the Force", "template": "holiday.j2", "content": textwrap.dedent( """\ template: my super template rendered: History of the Force""" ), } ) ] @pytest.mark.parametrize( ["amount"], [ pytest.param(0), pytest.param(1), pytest.param(2), pytest.param(5), pytest.param(10), ], ) def test_item_many(testapp, tmpdir, amount): """Jinja2 processor has to work with stream.""" stream = jinja2.process( testapp, [ holocron.Item( { "title": "History of the Force", "content": "the Force #%d" % i, } ) for i in range(amount) ], ) assert isinstance(stream, collections.abc.Iterable) items = list(stream) assert ( items[:amount] == [ holocron.Item( {"title": "History of the Force", "content": unittest.mock.ANY} ) ] * amount ) for i, item in enumerate(items[:amount]): soup = bs4.BeautifulSoup(item["content"], "html.parser") assert soup.meta["charset"] == "UTF-8" assert soup.article.header.h1.string == "History of the Force" assert list(soup.article.stripped_strings)[1] == "the Force #%d" % i # Since we don't know in which order statics are discovered, we sort them # so we can avoid possible flakes. static = sorted(items[amount:], key=lambda d: d["source"]) assert static[0]["source"] == pathlib.Path("static", "logo.svg") assert static[0]["destination"] == static[0]["source"] assert static[1]["source"] == pathlib.Path("static", "pygments.css") assert static[1]["destination"] == static[1]["source"] assert static[2]["source"] == pathlib.Path("static", "style.css") assert static[2]["destination"] == static[2]["source"] assert len(static) == 3 def test_args_themes(testapp, tmpdir): """Jinja2 processor has to respect themes argument.""" tmpdir.ensure("theme_a", "templates", "item.j2").write_text( textwrap.dedent( """\ template: my super template rendered: {{ item.title }} """ ), encoding="UTF-8", ) tmpdir.ensure("theme_a", "static", "style.css").write_text( "article { margin: 0 }", encoding="UTF-8" ) stream = jinja2.process( testapp, [holocron.Item({"title": "History of the Force", "content": "the Force"})], themes=[tmpdir.join("theme_a").strpath], ) assert isinstance(stream, collections.abc.Iterable) assert list(stream) == [ holocron.Item( { "title": "History of the Force", "content": textwrap.dedent( """\ template: my super template rendered: History of the Force""" ), } ), holocron.WebSiteItem( { "content": "article { margin: 0 }", "source": pathlib.Path("static", "style.css"), "destination": pathlib.Path("static", "style.css"), "created": unittest.mock.ANY, "updated": unittest.mock.ANY, "baseurl": testapp.metadata["url"], } ), ] def test_args_themes_two_themes(testapp, tmpdir): """Jinja2 processor has to respect themes argument.""" tmpdir.ensure("theme_a", "templates", "page.j2").write_text( textwrap.dedent( """\ template: my super template from theme_a rendered: {{ item.title }} """ ), encoding="UTF-8", ) tmpdir.ensure("theme_b", "templates", "page.j2").write_text( textwrap.dedent( """\ template: my super template from theme_b rendered: {{ item.title }} """ ), encoding="UTF-8", ) tmpdir.ensure("theme_b", "templates", "holiday.j2").write_text( textwrap.dedent( """\ template: my holiday template from theme_b rendered: {{ item.title }} """ ), encoding="UTF-8", ) stream = jinja2.process( testapp, [ holocron.Item( { "title": "History of the Force", "content": "the Force", "template": "page.j2", } ), holocron.Item( { "title": "History of the Force", "content": "the Force", "template": "holiday.j2", } ), ], themes=[ tmpdir.join("theme_a").strpath, tmpdir.join("theme_b").strpath, ], ) assert isinstance(stream, collections.abc.Iterable) assert list(stream) == [ holocron.Item( { "title": "History of the Force", "template": "page.j2", "content": textwrap.dedent( """\ template: my super template from theme_a rendered: History of the Force""" ), } ), holocron.Item( { "title": "History of the Force", "template": "holiday.j2", "content": textwrap.dedent( """\ template: my holiday template from theme_b rendered: History of the Force""" ), } ), ] @pytest.mark.parametrize( ["args", "error"], [ pytest.param( {"template": 42}, "template: 42 is not of type 'string'", id="template-int", ), pytest.param( {"context": 42}, "context: 42 is not of type 'object'", id="context-int", ), pytest.param( {"themes": {"foo": 1}}, "themes: {'foo': 1} is not of type 'array'", id="themes-dict", ), ], ) def test_args_bad_value(testapp, args, error): """Commit processor has to validate input arguments.""" with pytest.raises(ValueError) as excinfo: next(jinja2.process(testapp, [], **args)) assert str(excinfo.value) == error
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2015 Findspire from unittest import TestCase from django.core.urlresolvers import reverse from django.test import TestCase from workflow.apps.team.models import Person, Team, SkillCategory, SkillSubject, Skill class MiscTest(TestCase): fixtures = ['auth_user'] def test_index_not_logged(self): resp = self.client.get(reverse('team:index')) self.assertEqual(resp.status_code, 302) def test_index_logged(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) resp = self.client.get(reverse('team:index')) self.assertEqual(resp.status_code, 200) class PersonTest(TestCase): fixtures = ['auth_user', 'team_all'] def setUp(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) def test_person(self): # create resp = self.client.get(reverse('team:person_new')) self.assertEqual(resp.status_code, 200) data = { 'username': 'Mick', 'first_name': 'Mickael', 'last_name': 'Bay', 'arrival_date': '2015-01-01', 'contract_type': 1, 'skills': [1, 2, 3], } resp = self.client.post(reverse('team:person_new'), data) self.assertEqual(resp.status_code, 302) person_count = Person.objects.filter(user__username='Mick').count() self.assertEqual(person_count, 1) person = Person.objects.get(user__username='Mick') comp_list = [c.pk for c in Skill.objects.filter(person=person)] self.assertEqual(comp_list, [1, 2, 3]) # update person_pk = Person.objects.get(user__username='Mick').pk resp = self.client.get(reverse('team:person_edit', args=[person_pk])) self.assertEqual(resp.status_code, 200) data = { 'username': 'Mick', 'first_name': 'Anon', 'last_name': 'imous', 'arrival_date': '2015-01-01', 'contract_type': 1, 'skills': [1, 2, 4], } resp = self.client.post(reverse('team:person_edit', args=[person_pk]), data) self.assertEqual(resp.status_code, 302) person_count = Person.objects.filter(user__first_name='Mickael').count() self.assertEqual(person_count, 0) person_count = Person.objects.filter(user__first_name='Anon').count() self.assertEqual(person_count, 1) person = Person.objects.get(user__username='Mick') comp_list = [c.pk for c in Skill.objects.filter(person=person)] self.assertEqual(comp_list, [1, 2, 4]) def test_person_list(self): resp = self.client.get(reverse('team:person_list')) self.assertEqual(resp.status_code, 200) has_person = Person.objects.get(user__username='user 0') in resp.context[-1]['object_list'] self.assertEqual(has_person, True) def test_person_form_errors(self): data = { 'username': '', 'first_name': 'Mickael', 'last_name': 'Bay', 'arrival_date': '2015-01-01', 'contract_type': 1, 'skills': [1, 2, 3], } resp = self.client.post(reverse('team:person_new'), data) self.assertEqual(resp.status_code, 200) data = { 'username': 'Mick', 'first_name': 'Mickael', 'last_name': 'Bay', 'arrival_date': '', 'contract_type': 1, 'skills': [1, 2, 3], } resp = self.client.post(reverse('team:person_new'), data) self.assertEqual(resp.status_code, 200) class TeamTest(TestCase): fixtures = ['auth_user', 'team_all'] def setUp(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) def test_team(self): # create resp = self.client.get(reverse('team:team_new')) self.assertEqual(resp.status_code, 200) data = { 'name': 'DreamTeam', 'leader': 1, 'members': [1, 2, 3, 4, 5], } resp = self.client.post(reverse('team:team_new'), data) self.assertEqual(resp.status_code, 302) team_count = Team.objects.filter(name='DreamTeam').count() self.assertEqual(team_count, 1) # update team_pk = Team.objects.get(name='DreamTeam').pk resp = self.client.get(reverse('team:team_edit', args=[team_pk])) self.assertEqual(resp.status_code, 200) data = { 'name': 'XV de france', 'leader': 1, 'members': [1, 2, 3, 4, 5], } resp = self.client.post(reverse('team:team_edit', args=[team_pk]), data) self.assertEqual(resp.status_code, 302) team_count = Team.objects.filter(name='DreamTeam').count() self.assertEqual(team_count, 0) team_count = Team.objects.filter(name='XV de france').count() self.assertEqual(team_count, 1) def test_team_list(self): resp = self.client.get(reverse('team:team_list')) self.assertEqual(resp.status_code, 200) has_team = Team.objects.get(name='tech') in resp.context[-1]['object_list'] self.assertEqual(has_team, True) class SkillsCategoryTest(TestCase): fixtures = ['auth_user', 'team_all'] def setUp(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) def test_skill_category(self): # create resp = self.client.get(reverse('team:skill_category_new')) self.assertEqual(resp.status_code, 200) data = { 'name': 'Tests', } resp = self.client.post(reverse('team:skill_category_new'), data) self.assertEqual(resp.status_code, 302) comp_count = SkillCategory.objects.filter(name='Tests').count() self.assertEqual(comp_count, 1) # update comp_pk = SkillCategory.objects.get(name='Tests').pk resp = self.client.get(reverse('team:skill_category_edit', args=[comp_pk])) self.assertEqual(resp.status_code, 200) data = { 'name': 'Front-end', } resp = self.client.post(reverse('team:skill_category_edit', args=[comp_pk]), data) self.assertEqual(resp.status_code, 302) comp_count = SkillCategory.objects.filter(name='Tests').count() self.assertEqual(comp_count, 0) comp_count = SkillCategory.objects.filter(name='Front-end').count() self.assertEqual(comp_count, 1) class SkillsSubjectTest(TestCase): fixtures = ['auth_user', 'team_all'] def setUp(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) def test_skill_subject(self): # create resp = self.client.get(reverse('team:skill_subject_new')) self.assertEqual(resp.status_code, 200) data = { 'name': 'Some skills', 'category': SkillCategory.objects.get(name='Front').pk, 'description': 'Some description', } resp = self.client.post(reverse('team:skill_subject_new'), data) self.assertEqual(resp.status_code, 302) comp_count = SkillSubject.objects.filter(name='Some skills').count() self.assertEqual(comp_count, 1) # update comp_pk = SkillSubject.objects.get(name='Some skills').pk resp = self.client.get(reverse('team:skill_subject_edit', args=[comp_pk])) self.assertEqual(resp.status_code, 200) data = { 'name': 'Some other skills', 'category': SkillCategory.objects.get(name='Front').pk, 'description': 'Some description', } resp = self.client.post(reverse('team:skill_subject_edit', args=[comp_pk]), data) self.assertEqual(resp.status_code, 302) comp_count = SkillSubject.objects.filter(name='Some skills').count() self.assertEqual(comp_count, 0) comp_count = SkillSubject.objects.filter(name='Some other skills').count() self.assertEqual(comp_count, 1) def test_skill_subject_list(self): resp = self.client.get(reverse('team:skill_subject_list')) self.assertEqual(resp.status_code, 200) comp = SkillSubject.objects.get(name='HTML') # the following line is tricky, see the corresponding view to understand has_comp = any(comp in comp_list for comp_list in resp.context[-1]['categories'].values()) self.assertEqual(has_comp, True) class SkillTest(TestCase): fixtures = ['auth_user', 'team_all'] def setUp(self): resp = self.client.login(username='admin', password='admin') self.assertEqual(resp, True) def test_skill_list(self): # add skills data = { 'username': 'admin', 'first_name': 'Ad', 'last_name': 'min', 'arrival_date': '2015-01-01', 'contract_type': 1, 'skills': [1], } resp = self.client.post(reverse('team:person_edit', args=[1]), data) self.assertEqual(resp.status_code, 302) # update them resp = self.client.get(reverse('team:skill_instance_list', args=[1])) self.assertEqual(resp.context['myformset'].forms[0].instance.pk, 1) # management form, used internally by django. data = {'form-'+key: value for key, value in resp.context['myformset'].management_form.initial.items()} data.update({ 'form-0-id': 1, 'form-0-strength': 42, }) resp = self.client.post(reverse('team:skill_instance_list', args=[1]), data) self.assertEqual(resp.status_code, 302) skill = Skill.objects.get(pk=1) self.assertEqual(skill.strength, 42)
# -*- coding: utf-8 -*- # Copyright (c) 2010 matt # Copyright (c) 2010 Dieter Plaetinck # Copyright (c) 2010, 2012 roger # Copyright (c) 2011-2012 Florian Mounier # Copyright (c) 2011 Mounier Florian # Copyright (c) 2011 Timo Schmiade # Copyright (c) 2012 Mikkel Oscar Lyderik # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2012 Craig Barnes # Copyright (c) 2013 Tao Sauvage # Copyright (c) 2013 Tom Hunt # Copyright (c) 2014 Justin Bronder # # 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. # depends on python-mpd # TODO: check if UI hangs in case of network issues and such # TODO: some kind of templating to make shown info configurable # TODO: best practice to handle failures? just write to stderr? from __future__ import division import re import time import mpd from .. import utils, pangocffi from . import base from libqtile.log_utils import logger class Mpd(base.ThreadPoolText): """A widget for the Music Player Daemon (MPD)""" orientations = base.ORIENTATION_HORIZONTAL defaults = [ ("host", "localhost", "Host to connect to, can be either an IP " "address or a UNIX socket path"), ("port", 6600, "Port to connect to"), ("password", None, "Password to use"), ("fmt_playing", "%a - %t [%v%%]", "Format string to display when " "playing/paused"), ("fmt_stopped", "Stopped [%v%%]", "Format strings to display when " "stopped"), ("msg_nc", "Mpd off", "Which message to show when we're not " "connected"), ("do_color_progress", True, "Whether to indicate progress in song by " "altering message color"), ("foreground_progress", "ffffff", "Foreground progress colour"), ("reconnect", False, "Attempt to reconnect if initial connection failed"), ("reconnect_interval", 1, "Time to delay between connection attempts."), ("update_interval", 0.5, "Update Time in seconds.") ] def __init__(self, **config): super(Mpd, self).__init__('MPD Widget', **config) self.add_defaults(Mpd.defaults) self.inc = 2 self.client = mpd.MPDClient() self.connected = None self.stop = False def finalize(self): self.stop = True if self.connected: try: # The volume settings is kind of a dirty trick. There doesn't # seem to be a decent way to set a timeout for the idle # command. Therefore we need to trigger some events such that # if poll() is currently waiting on an idle event it will get # something so that it can exit. In practice, I can't tell the # difference in volume and hopefully no one else can either. self.client.volume(1) self.client.volume(-1) self.client.disconnect() except Exception: pass base._Widget.finalize(self) def connect(self, quiet=False): if self.connected: return True try: self.client.connect(host=self.host, port=self.port) except Exception: if not quiet: logger.exception('Failed to connect to mpd') return False if self.password: try: self.client.password(self.password) except Exception: logger.warning('Authentication failed. Disconnecting') try: self.client.disconnect() except Exception: pass return False self.connected = True return True def _configure(self, qtile, bar): super(Mpd, self)._configure(qtile, bar) self.layout = self.drawer.textlayout( self.text, self.foreground, self.font, self.fontsize, self.fontshadow, markup=True ) def to_minutes_seconds(self, stime): """Takes an integer time in seconds, transforms it into (HH:)?MM:SS. HH portion is only visible if total time is greater than an hour. """ if type(stime) != int: stime = int(stime) mm = stime // 60 ss = stime % 60 if mm >= 60: hh = mm // 60 mm = mm % 60 rv = "{}:{:02}:{:02}".format(hh, mm, ss) else: rv = "{}:{:02}".format(mm, ss) return rv def get_artist(self): return self.song['artist'] def get_album(self): return self.song['album'] def get_elapsed(self): elapsed = self.status['time'].split(':')[0] return self.to_minutes_seconds(elapsed) def get_file(self): return self.song['file'] def get_length(self): return self.to_minutes_seconds(self.song['time']) def get_number(self): return str(int(self.status['song']) + 1) def get_playlistlength(self): return self.status['playlistlength'] def get_status(self): n = self.status['state'] if n == "play": return "->" elif n == "pause": return "||" elif n == "stop": return "[]" def get_longstatus(self): n = self.status['state'] if n == "play": return "Playing" elif n == "pause": return "Paused" elif n == "stop": return "Stopped" def get_title(self): return self.song['title'] def get_track(self): # This occasionally has leading zeros we don't want. return str(int(self.song['track'].split('/')[0])) def get_volume(self): return self.status['volume'] def get_single(self): if self.status['single'] == '1': return '1' else: return '_' def get_repeat(self): if self.status['repeat'] == '1': return 'R' else: return '_' def get_shuffle(self): if self.status['random'] == '1': return 'S' else: return '_' formats = { 'a': get_artist, 'A': get_album, 'e': get_elapsed, 'f': get_file, 'l': get_length, 'n': get_number, 'p': get_playlistlength, 's': get_status, 'S': get_longstatus, 't': get_title, 'T': get_track, 'v': get_volume, '1': get_single, 'r': get_repeat, 'h': get_shuffle, '%': lambda x: '%', } def match_check(self, m): try: return self.formats[m.group(1)](self) except KeyError: return "(nil)" def do_format(self, string): return re.sub("%(.)", self.match_check, string) def _get_status(self): playing = self.msg_nc try: self.status = self.client.status() self.song = self.client.currentsong() if self.status['state'] != 'stop': text = self.do_format(self.fmt_playing) if self.do_color_progress and self.status.get('time'): try: elapsed, total = self.status['time'].split(':') percent = float(elapsed) / float(total) progress = int(percent * len(text)) except (ZeroDivisionError, ValueError): playing = pangocffi.markup_escape_text(text) else: playing = '<span color="{0}">{1}</span>{2}'.format( utils.hex(self.foreground_progress), pangocffi.markup_escape_text(text[:progress]), pangocffi.markup_escape_text(text[progress:]) ) else: playing = pangocffi.markup_escape_text(text) else: playing = self.do_format(self.fmt_stopped) except Exception: logger.exception('Mpd error on update') return playing def poll(self): was_connected = self.connected if not self.connected: if self.connected is None or self.reconnect: while not self.stop and not self.connect(quiet=True): time.sleep(self.reconnect_interval) else: return if self.stop: return True if was_connected: try: self.client.ping() except mpd.ConnectionError: self.client.disconnect() self.connected = False return self.msg_nc except Exception: logger.exception('Error communicating with mpd') self.client.disconnect() return return self._get_status() def button_press(self, x, y, button): if not self.connect(): return False try: status = self.client.status() if button == 3: if not status or status.get('state', '') == 'stop': self.client.play() else: self.client.pause() elif button == 4: self.client.previous() elif button == 5: self.client.next() elif button == 8: if status: self.client.setvol( max(int(status['volume']) - self.inc, 0) ) elif button == 9: if status: self.client.setvol( min(int(status['volume']) + self.inc, 100) ) except Exception: logger.exception('Mpd error on click')
""" Module to provide RabbitMQ compatibility to Salt. Todo: A lot, need to add cluster support, logging, and minion configuration data. """ import logging import os import random import re import string import salt.utils.itertools import salt.utils.json import salt.utils.path import salt.utils.platform import salt.utils.user from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) RABBITMQCTL = None RABBITMQ_PLUGINS = None def __virtual__(): """ Verify RabbitMQ is installed. """ global RABBITMQCTL global RABBITMQ_PLUGINS if salt.utils.platform.is_windows(): import winreg key = None try: key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\VMware, Inc.\\RabbitMQ Server", 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY, ) (dir_path, value_type) = winreg.QueryValueEx(key, "Install_Dir") if value_type != winreg.REG_SZ: raise TypeError( "Invalid RabbitMQ Server directory type: {}".format(value_type) ) if not os.path.isdir(dir_path): raise OSError("RabbitMQ directory not found: {}".format(dir_path)) subdir_match = "" for name in os.listdir(dir_path): if name.startswith("rabbitmq_server-"): subdir_path = os.path.join(dir_path, name) # Get the matching entry that is last in ASCII order. if os.path.isdir(subdir_path) and subdir_path > subdir_match: subdir_match = subdir_path if not subdir_match: raise OSError( '"rabbitmq_server-*" subdirectory not found in: {}'.format(dir_path) ) RABBITMQCTL = os.path.join(subdir_match, "sbin", "rabbitmqctl.bat") RABBITMQ_PLUGINS = os.path.join( subdir_match, "sbin", "rabbitmq-plugins.bat" ) except Exception: # pylint: disable=broad-except pass finally: if key is not None: winreg.CloseKey(key) else: RABBITMQCTL = salt.utils.path.which("rabbitmqctl") RABBITMQ_PLUGINS = salt.utils.path.which("rabbitmq-plugins") if not RABBITMQCTL: return (False, "Module rabbitmq: module only works when RabbitMQ is installed") return True def _check_response(response): if isinstance(response, dict): if response["retcode"] != 0 or response["stderr"]: raise CommandExecutionError( "RabbitMQ command failed: {}".format(response["stderr"]) ) else: if "Error" in response: raise CommandExecutionError("RabbitMQ command failed: {}".format(response)) def _format_response(response, msg): if isinstance(response, dict): if response["retcode"] != 0 or response["stderr"]: raise CommandExecutionError( "RabbitMQ command failed: {}".format(response["stderr"]) ) else: response = response["stdout"] else: if "Error" in response: raise CommandExecutionError("RabbitMQ command failed: {}".format(response)) return {msg: response} def _get_rabbitmq_plugin(): """ Returns the rabbitmq-plugin command path if we're running an OS that doesn't put it in the standard /usr/bin or /usr/local/bin This works by taking the rabbitmq-server version and looking for where it seems to be hidden in /usr/lib. """ global RABBITMQ_PLUGINS if RABBITMQ_PLUGINS is None: version = __salt__["pkg.version"]("rabbitmq-server").split("-")[0] RABBITMQ_PLUGINS = ( "/usr/lib/rabbitmq/lib/rabbitmq_server-{}/sbin/rabbitmq-plugins".format( version ) ) return RABBITMQ_PLUGINS def _safe_output(line): """ Looks for rabbitmqctl warning, or general formatting, strings that aren't intended to be parsed as output. Returns a boolean whether the line can be parsed as rabbitmqctl output. """ return not any( [ line.startswith("Listing") and line.endswith("..."), line.startswith("Listing") and "\t" not in line, "...done" in line, line.startswith("WARNING:"), len(line) == 0, ] ) def _strip_listing_to_done(output_list): """ Conditionally remove non-relevant first and last line, "Listing ..." - "...done". outputlist: rabbitmq command output split by newline return value: list, conditionally modified, may be empty. """ return [line for line in output_list if _safe_output(line)] def _output_to_dict(cmdoutput, values_mapper=None): """ Convert rabbitmqctl output to a dict of data cmdoutput: string output of rabbitmqctl commands values_mapper: function object to process the values part of each line """ if isinstance(cmdoutput, dict): if cmdoutput["retcode"] != 0 or cmdoutput["stderr"]: raise CommandExecutionError( "RabbitMQ command failed: {}".format(cmdoutput["stderr"]) ) cmdoutput = cmdoutput["stdout"] ret = {} if values_mapper is None: values_mapper = lambda string: string.split("\t") # remove first and last line: Listing ... - ...done data_rows = _strip_listing_to_done(cmdoutput.splitlines()) for row in data_rows: try: key, values = row.split("\t", 1) except ValueError: # If we have reached this far, we've hit an edge case where the row # only has one item: the key. The key doesn't have any values, so we # set it to an empty string to preserve rabbitmq reporting behavior. # e.g. A user's permission string for '/' is set to ['', '', ''], # Rabbitmq reports this only as '/' from the rabbitmqctl command. log.debug( "Could not find any values for key '%s'. " "Setting to '%s' to an empty string.", row, row, ) ret[row] = "" continue ret[key] = values_mapper(values) return ret def _output_to_list(cmdoutput): """ Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output). Ignores output lines that shouldn't be parsed, like warnings. cmdoutput: string output of rabbitmqctl commands """ return [ item for line in cmdoutput.splitlines() if _safe_output(line) for item in line.split() ] def _output_lines_to_list(cmdoutput): """ Convert rabbitmqctl output to a list of strings (assuming newline-delimited output). Ignores output lines that shouldn't be parsed, like warnings. cmdoutput: string output of rabbitmqctl commands """ return [line.strip() for line in cmdoutput.splitlines() if _safe_output(line)] def list_users(runas=None): """ Return a list of users based off of rabbitmqctl user_list. CLI Example: .. code-block:: bash salt '*' rabbitmq.list_users """ # Windows runas currently requires a password. # Due to this, don't use a default value for # runas in Windows. if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_users", "-q"], reset_system_locale=False, runas=runas, python_shell=False, ) # func to get tags from string such as "[admin, monitoring]" func = ( lambda string: [x.strip() for x in string[1:-1].split(",")] if "," in string else [x for x in string[1:-1].split(" ")] ) return _output_to_dict(res, func) def list_vhosts(runas=None): """ Return a list of vhost based on rabbitmqctl list_vhosts. CLI Example: .. code-block:: bash salt '*' rabbitmq.list_vhosts """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_vhosts", "-q"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return _output_to_list(res["stdout"]) def list_upstreams(runas=None): """ Returns a dict of upstreams based on rabbitmqctl list_parameters. :param str runas: The name of the user to run this command as. CLI Example: .. code-block:: bash salt '*' rabbitmq.list_upstreams .. versionadded:: 3000 """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() ret = {} res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_parameters", "-q"], reset_system_locale=False, runas=runas, python_shell=False, ) for raw_line in res["stdout"].split("\n"): if _safe_output(raw_line): (_, name, definition) = raw_line.split("\t") ret[name] = definition return ret def user_exists(name, runas=None): """ Return whether the user exists based on rabbitmqctl list_users. CLI Example: .. code-block:: bash salt '*' rabbitmq.user_exists rabbit_user """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() return name in list_users(runas=runas) def vhost_exists(name, runas=None): """ Return whether the vhost exists based on rabbitmqctl list_vhosts. CLI Example: .. code-block:: bash salt '*' rabbitmq.vhost_exists rabbit_host """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() return name in list_vhosts(runas=runas) def upstream_exists(name, runas=None): """ Return whether the upstreamexists based on rabbitmqctl list_parameters. :param str name: The name of the upstream to check for. :param str runas: The name of the user to run the command as. CLI Example: .. code-block:: bash salt '*' rabbitmq.upstream_exists rabbit_upstream .. versionadded:: 3000 """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() return name in list_upstreams(runas=runas) def add_user(name, password=None, runas=None): """ Add a rabbitMQ user via rabbitmqctl user_add <user> <password> CLI Example: .. code-block:: bash salt '*' rabbitmq.add_user rabbit_user password """ clear_pw = False if password is None: # Generate a random, temporary password. RabbitMQ requires one. clear_pw = True password = "".join( random.SystemRandom().choice(string.ascii_uppercase + string.digits) for x in range(15) ) if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() if salt.utils.platform.is_windows(): # On Windows, if the password contains a special character # such as '|', normal execution will fail. For example: # cmd: rabbitmq.add_user abc "asdf|def" # stderr: 'def' is not recognized as an internal or external # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True cmd = '"{}" add_user "{}" "{}"'.format(RABBITMQCTL, name, password) else: python_shell = False cmd = [RABBITMQCTL, "add_user", name, password] res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, output_loglevel="quiet", runas=runas, python_shell=python_shell, ) if clear_pw: # Now, Clear the random password from the account, if necessary try: clear_password(name, runas) except Exception: # pylint: disable=broad-except # Clearing the password failed. We should try to cleanup # and rerun and error. delete_user(name, runas) raise msg = "Added" return _format_response(res, msg) def delete_user(name, runas=None): """ Deletes a user via rabbitmqctl delete_user. CLI Example: .. code-block:: bash salt '*' rabbitmq.delete_user rabbit_user """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "delete_user", name], reset_system_locale=False, python_shell=False, runas=runas, ) msg = "Deleted" return _format_response(res, msg) def change_password(name, password, runas=None): """ Changes a user's password. CLI Example: .. code-block:: bash salt '*' rabbitmq.change_password rabbit_user password """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() if salt.utils.platform.is_windows(): # On Windows, if the password contains a special character # such as '|', normal execution will fail. For example: # cmd: rabbitmq.add_user abc "asdf|def" # stderr: 'def' is not recognized as an internal or external # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True cmd = '"{}" change_password "{}" "{}"'.format(RABBITMQCTL, name, password) else: python_shell = False cmd = [RABBITMQCTL, "change_password", name, password] res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, output_loglevel="quiet", python_shell=python_shell, ) msg = "Password Changed" return _format_response(res, msg) def clear_password(name, runas=None): """ Removes a user's password. CLI Example: .. code-block:: bash salt '*' rabbitmq.clear_password rabbit_user """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "clear_password", name], reset_system_locale=False, runas=runas, python_shell=False, ) msg = "Password Cleared" return _format_response(res, msg) def check_password(name, password, runas=None): """ .. versionadded:: 2016.3.0 Checks if a user's password is valid. CLI Example: .. code-block:: bash salt '*' rabbitmq.check_password rabbit_user password """ # try to get the rabbitmq-version - adapted from _get_rabbitmq_plugin if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() try: res = __salt__["cmd.run"]( [RABBITMQCTL, "status"], reset_system_locale=False, runas=runas, python_shell=False, ) # Check regex against older RabbitMQ version status output old_server_version = re.search(r'\{rabbit,"RabbitMQ","(.+)"\}', res) # Check regex against newer RabbitMQ version status output server_version = re.search(r"RabbitMQ version:\s*(.+)", res) if server_version is None and old_server_version is None: raise ValueError if old_server_version: server_version = old_server_version server_version = server_version.group(1).split("-")[0] version = [int(i) for i in server_version.split(".")] except ValueError: version = (0, 0, 0) if len(version) < 3: version = (0, 0, 0) # rabbitmq introduced a native api to check a username and password in version 3.5.7. if tuple(version) >= (3, 5, 7): if salt.utils.platform.is_windows(): # On Windows, if the password contains a special character # such as '|', normal execution will fail. For example: # cmd: rabbitmq.add_user abc "asdf|def" # stderr: 'def' is not recognized as an internal or external # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True cmd = '"{}" authenticate_user "{}" "{}"'.format(RABBITMQCTL, name, password) else: python_shell = False cmd = [RABBITMQCTL, "authenticate_user", name, password] res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, output_loglevel="quiet", python_shell=python_shell, ) if res["retcode"] != 0 or res["stderr"]: return False return True cmd = ( "rabbit_auth_backend_internal:check_user_login" '(<<"{}">>, [{{password, <<"{}">>}}]).'.format( name.replace('"', '\\"'), password.replace('"', '\\"') ) ) res = __salt__["cmd.run_all"]( [RABBITMQCTL, "eval", cmd], reset_system_locale=False, runas=runas, output_loglevel="quiet", python_shell=False, ) msg = "password-check" _response = _format_response(res, msg) _key = next(iter(_response)) if "invalid credentials" in _response[_key]: return False return True def add_vhost(vhost, runas=None): """ Adds a vhost via rabbitmqctl add_vhost. CLI Example: .. code-block:: bash salt '*' rabbitmq add_vhost '<vhost_name>' """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "add_vhost", vhost], reset_system_locale=False, runas=runas, python_shell=False, ) msg = "Added" return _format_response(res, msg) def delete_vhost(vhost, runas=None): """ Deletes a vhost rabbitmqctl delete_vhost. CLI Example: .. code-block:: bash salt '*' rabbitmq.delete_vhost '<vhost_name>' """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "delete_vhost", vhost], reset_system_locale=False, runas=runas, python_shell=False, ) msg = "Deleted" return _format_response(res, msg) def set_permissions(vhost, user, conf=".*", write=".*", read=".*", runas=None): """ Sets permissions for vhost via rabbitmqctl set_permissions CLI Example: .. code-block:: bash salt '*' rabbitmq.set_permissions myvhost myuser """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "set_permissions", "-p", vhost, user, conf, write, read], reset_system_locale=False, runas=runas, python_shell=False, ) msg = "Permissions Set" return _format_response(res, msg) def list_permissions(vhost, runas=None): """ Lists permissions for vhost via rabbitmqctl list_permissions CLI Example: .. code-block:: bash salt '*' rabbitmq.list_permissions /myvhost """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_permissions", "--formatter=json", "-p", vhost], reset_system_locale=False, runas=runas, python_shell=False, ) perms = salt.utils.json.loads(res["stdout"]) perms_dict = {} for perm in perms: user = perm["user"] perms_dict[user] = perm del perms_dict[user]["user"] return perms_dict def list_user_permissions(name, runas=None): """ List permissions for a user via rabbitmqctl list_user_permissions CLI Example: .. code-block:: bash salt '*' rabbitmq.list_user_permissions user """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_user_permissions", name, "--formatter=json"], reset_system_locale=False, runas=runas, python_shell=False, ) perms = salt.utils.json.loads(res["stdout"]) perms_dict = {} for perm in perms: vhost = perm["vhost"] perms_dict[vhost] = perm del perms_dict[vhost]["vhost"] return perms_dict def set_user_tags(name, tags, runas=None): """Add user tags via rabbitmqctl set_user_tags CLI Example: .. code-block:: bash salt '*' rabbitmq.set_user_tags myadmin administrator """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() if not isinstance(tags, (list, tuple)): tags = [tags] res = __salt__["cmd.run_all"]( [RABBITMQCTL, "set_user_tags", name] + list(tags), reset_system_locale=False, runas=runas, python_shell=False, ) msg = "Tag(s) set" return _format_response(res, msg) def status(runas=None): """ return rabbitmq status CLI Example: .. code-block:: bash salt '*' rabbitmq.status """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "status"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def cluster_status(runas=None): """ return rabbitmq cluster_status CLI Example: .. code-block:: bash salt '*' rabbitmq.cluster_status """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "cluster_status"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def join_cluster(host, user="rabbit", ram_node=None, runas=None): """ Join a rabbit cluster CLI Example: .. code-block:: bash salt '*' rabbitmq.join_cluster rabbit.example.com rabbit """ cmd = [RABBITMQCTL, "join_cluster"] if ram_node: cmd.append("--ram") cmd.append("{}@{}".format(user, host)) if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() stop_app(runas) res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) start_app(runas) return _format_response(res, "Join") def stop_app(runas=None): """ Stops the RabbitMQ application, leaving the Erlang node running. CLI Example: .. code-block:: bash salt '*' rabbitmq.stop_app """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "stop_app"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def start_app(runas=None): """ Start the RabbitMQ application. CLI Example: .. code-block:: bash salt '*' rabbitmq.start_app """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "start_app"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def reset(runas=None): """ Return a RabbitMQ node to its virgin state CLI Example: .. code-block:: bash salt '*' rabbitmq.reset """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "reset"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def force_reset(runas=None): """ Forcefully Return a RabbitMQ node to its virgin state CLI Example: .. code-block:: bash salt '*' rabbitmq.force_reset """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "force_reset"], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return res["stdout"] def list_queues(runas=None, *args): """ Returns queue details of the / virtual host CLI Example: .. code-block:: bash salt '*' rabbitmq.list_queues messages consumers """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [RABBITMQCTL, "list_queues", "-q"] cmd.extend(args) res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) _check_response(res) return _output_to_dict(res["stdout"]) def list_queues_vhost(vhost, runas=None, *args): """ Returns queue details of specified virtual host. This command will consider first parameter as the vhost name and rest will be treated as queueinfoitem. For getting details on vhost ``/``, use :mod:`list_queues <salt.modules.rabbitmq.list_queues>` instead). CLI Example: .. code-block:: bash salt '*' rabbitmq.list_queues messages consumers """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [RABBITMQCTL, "list_queues", "-q", "-p", vhost] cmd.extend(args) res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) _check_response(res) return _output_to_dict(res["stdout"]) def list_policies(vhost="/", runas=None): """ Return a dictionary of policies nested by vhost and name based on the data returned from rabbitmqctl list_policies. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.list_policies """ ret = {} if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "list_policies", "-q", "-p", vhost], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) output = res["stdout"] if __grains__["os_family"] != "FreeBSD": version = __salt__["pkg.version"]("rabbitmq-server").split("-")[0] else: version = __salt__["pkg.version"]("rabbitmq").split("-")[0] for line in _output_lines_to_list(output): parts = line.split("\t") if len(parts) not in (5, 6): continue vhost, name = parts[0], parts[1] if vhost not in ret: ret[vhost] = {} ret[vhost][name] = {} if _LooseVersion(version) >= _LooseVersion("3.7"): # in version 3.7 the position of apply_to and pattern has been # switched ret[vhost][name]["pattern"] = parts[2] ret[vhost][name]["apply_to"] = parts[3] ret[vhost][name]["definition"] = parts[4] ret[vhost][name]["priority"] = parts[5] else: # How many fields are there? - 'apply_to' was inserted in position # 2 at some point # and in version 3.7 the position of apply_to and pattern has been # switched offset = len(parts) - 5 if len(parts) == 6: ret[vhost][name]["apply_to"] = parts[2] ret[vhost][name].update( { "pattern": parts[offset + 2], "definition": parts[offset + 3], "priority": parts[offset + 4], } ) return ret def set_policy( vhost, name, pattern, definition, priority=None, runas=None, apply_to=None ): """ Set a policy based on rabbitmqctl set_policy. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.set_policy / HA '.*' '{"ha-mode":"all"}' """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() if isinstance(definition, dict): definition = salt.utils.json.dumps(definition) if not isinstance(definition, str): raise SaltInvocationError( "The 'definition' argument must be a dictionary or JSON string" ) cmd = [RABBITMQCTL, "set_policy", "-p", vhost] if priority: cmd.extend(["--priority", priority]) if apply_to: cmd.extend(["--apply-to", apply_to]) cmd.extend([name, pattern, definition]) res = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) log.debug("Set policy: %s", res["stdout"]) return _format_response(res, "Set") def delete_policy(vhost, name, runas=None): """ Delete a policy based on rabbitmqctl clear_policy. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.delete_policy / HA """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "clear_policy", "-p", vhost, name], reset_system_locale=False, runas=runas, python_shell=False, ) log.debug("Delete policy: %s", res["stdout"]) return _format_response(res, "Deleted") def policy_exists(vhost, name, runas=None): """ Return whether the policy exists based on rabbitmqctl list_policies. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.policy_exists / HA """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() policies = list_policies(runas=runas) return bool(vhost in policies and name in policies[vhost]) def list_available_plugins(runas=None): """ Returns a list of the names of all available plugins (enabled and disabled). CLI Example: .. code-block:: bash salt '*' rabbitmq.list_available_plugins """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [_get_rabbitmq_plugin(), "list", "-m"] ret = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) _check_response(ret) return _output_to_list(ret["stdout"]) def list_enabled_plugins(runas=None): """ Returns a list of the names of the enabled plugins. CLI Example: .. code-block:: bash salt '*' rabbitmq.list_enabled_plugins """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [_get_rabbitmq_plugin(), "list", "-m", "-e"] ret = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) _check_response(ret) return _output_to_list(ret["stdout"]) def plugin_is_enabled(name, runas=None): """ Return whether the plugin is enabled. CLI Example: .. code-block:: bash salt '*' rabbitmq.plugin_is_enabled rabbitmq_plugin_name """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() return name in list_enabled_plugins(runas) def enable_plugin(name, runas=None): """ Enable a RabbitMQ plugin via the rabbitmq-plugins command. CLI Example: .. code-block:: bash salt '*' rabbitmq.enable_plugin foo """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [_get_rabbitmq_plugin(), "enable", name] ret = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) return _format_response(ret, "Enabled") def disable_plugin(name, runas=None): """ Disable a RabbitMQ plugin via the rabbitmq-plugins command. CLI Example: .. code-block:: bash salt '*' rabbitmq.disable_plugin foo """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [_get_rabbitmq_plugin(), "disable", name] ret = __salt__["cmd.run_all"]( cmd, reset_system_locale=False, runas=runas, python_shell=False ) return _format_response(ret, "Disabled") def set_upstream( name, uri, prefetch_count=None, reconnect_delay=None, ack_mode=None, trust_user_id=None, exchange=None, max_hops=None, expires=None, message_ttl=None, ha_policy=None, queue=None, runas=None, ): """ Configures an upstream via rabbitmqctl set_parameter. This can be an exchange-upstream, a queue-upstream or both. :param str name: The name of the upstream to configure. The following parameters apply to federated exchanges and federated queues: :param str uri: The AMQP URI(s) for the upstream. :param int prefetch_count: The maximum number of unacknowledged messages copied over a link at any one time. Default: 1000 :param int reconnect_delay: The duration (in seconds) to wait before reconnecting to the broker after being disconnected. Default: 1 :param str ack_mode: Determines how the link should acknowledge messages. If set to ``on-confirm`` (the default), messages are acknowledged to the upstream broker after they have been confirmed downstream. This handles network errors and broker failures without losing messages, and is the slowest option. If set to ``on-publish``, messages are acknowledged to the upstream broker after they have been published downstream. This handles network errors without losing messages, but may lose messages in the event of broker failures. If set to ``no-ack``, message acknowledgements are not used. This is the fastest option, but may lose messages in the event of network or broker failures. :param bool trust_user_id: Determines how federation should interact with the validated user-id feature. If set to true, federation will pass through any validated user-id from the upstream, even though it cannot validate it itself. If set to false or not set, it will clear any validated user-id it encounters. You should only set this to true if you trust the upstream server (and by extension, all its upstreams) not to forge user-ids. The following parameters apply to federated exchanges only: :param str exchange: The name of the upstream exchange. Default is to use the same name as the federated exchange. :param int max_hops: The maximum number of federation links that a message published to a federated exchange can traverse before it is discarded. Default is 1. Note that even if max-hops is set to a value greater than 1, messages will never visit the same node twice due to travelling in a loop. However, messages may still be duplicated if it is possible for them to travel from the source to the destination via multiple routes. :param int expires: The expiry time (in milliseconds) after which an upstream queue for a federated exchange may be deleted, if a connection to the upstream broker is lost. The default is 'none', meaning the queue should never expire. This setting controls how long the upstream queue will last before it is eligible for deletion if the connection is lost. This value is used to set the "x-expires" argument for the upstream queue. :param int message_ttl: The expiry time for messages in the upstream queue for a federated exchange (see expires), in milliseconds. Default is ``None``, meaning messages should never expire. This does not apply to federated queues. This value is used to set the "x-message-ttl" argument for the upstream queue. :param str ha_policy: Determines the "x-ha-policy" argument for the upstream queue for a federated exchange (see expires). This is only of interest when connecting to old brokers which determine queue HA mode using this argument. Default is ``None``, meaning the queue is not HA. The following parameter applies to federated queues only: :param str queue: The name of the upstream queue. Default is to use the same name as the federated queue. :param str runas: The name of the user to run the command as. CLI Example: .. code-block:: bash salt '*' rabbitmq.set_upstream upstream_name ack_mode=on-confirm max_hops=1 \ trust_user_id=True uri=amqp://hostname .. versionadded:: 3000 """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() params = salt.utils.data.filter_falsey( { "uri": uri, "prefetch-count": prefetch_count, "reconnect-delay": reconnect_delay, "ack-mode": ack_mode, "trust-user-id": trust_user_id, "exchange": exchange, "max-hops": max_hops, "expires": expires, "message-ttl": message_ttl, "ha-policy": ha_policy, "queue": queue, } ) res = __salt__["cmd.run_all"]( [ RABBITMQCTL, "set_parameter", "federation-upstream", name, salt.utils.json.dumps(params), ], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return True def delete_upstream(name, runas=None): """ Deletes an upstream via rabbitmqctl clear_parameter. :param str name: The name of the upstream to delete. :param str runas: The name of the user to run the command as. CLI Example: .. code-block:: bash salt '*' rabbitmq.delete_upstream upstream_name .. versionadded:: 3000 """ if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() res = __salt__["cmd.run_all"]( [RABBITMQCTL, "clear_parameter", "federation-upstream", name], reset_system_locale=False, runas=runas, python_shell=False, ) _check_response(res) return True
# # Listens to the same http endpoints IMI will in production reads OBD files - fake calls - generates CDR and CSR files # import os from flask import Flask, render_template, request, flash, send_from_directory import argparse import csv from random import randint, choice import urllib2 import json import time import datetime import subprocess # # field names # REQUEST_ID = 'RequestId' SERVICE_ID = 'ServiceId' CALL_ID = 'CallId' MSISDN = 'Msisdn' CLI = 'Cli' PRIORITY = 'Priority' CALL_FLOW_URL = 'CallFlowURL' CONTENT_FILE_NAME = 'ContentFileName' CONTENT_FILE = 'ContentFile' WEEK_ID = 'WeekId' LANGUAGE_LOCATION_CODE = 'LanguageLocationCode' LANGUAGE_LOCATION_ID = 'LanguageLocationId' CIRCLE = 'Circle' SUBSCRIPTION_ORIGIN = 'SubscriptionOrigin' ATTEMPT_NO = 'AttemptNo' CALL_START_TIME = 'CallStartTime' CALL_ANSWER_TIME = 'CallAnswerTime' CALL_END_TIME = 'CallEndTime' CALL_DURATION_IN_PULSE = 'CallDurationInPulse' CALL_STATUS = 'CallStatus' STATUS_CODE = 'StatusCode' FINAL_STATUS = 'FinalStatus' ATTEMPTS = 'Attempts' MSG_PLAY_START_TIME = 'MsgPlayStartTime' MSG_PLAY_END_TIME = 'MsgPlayEndTime' CIRCLE_ID = 'CircleId' OPERATOR_ID = 'OperatorId' CALL_DISCONNECT_REASON = 'CallDisconnectReason' # # Final Status Codes # FS_SUCCESS = 1 FS_FAILED = 2 FS_REJECTED = 3 app = Flask(__name__) @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.route('/') def home(): stats = { 'foo': 'bar', 'baz': 123, } return render_template('index.html', stats=stats) @app.route('/cdr', methods=['POST']) def handle_cdr(): print "/cdr" print "request = {}".format(request.get_json()) return render_template('resp.html', resp="OK") @app.route('/obd', methods=['POST']) def handle_obd(): required_fields = [] errors = [] targetFileNotification = request.get_json() print "/obd" print "request = {}".format(targetFileNotification) if 'fileName' not in targetFileNotification: required_fields.append("fileName") if 'checksum' not in targetFileNotification: required_fields.append("checksum") if 'recordsCount' not in targetFileNotification: required_fields.append("recordsCount") if len(required_fields) > 0: errors.append("required {} missing: {}".format("fields" if len(required_fields) > 1 else "field", ', '.join(required_fields))) if len(errors) > 0: return render_template('400.html', errors=errors), 400 resp = '' file_name = targetFileNotification['fileName'] if os.path.isfile(obd_file_path(file_name)): resp = read_obd_file(file_name) else: print "{} is not a file".format(obd_file_path(file_name)) errors.append("Invalid file: {}".format(file_name)) if len(errors) > 0: return render_template('400.html', errors=errors), 400 return render_template('resp.html', resp=resp) def obd_file_path(name): homeDir = os.path.expanduser("~") return os.path.join(homeDir, args.obdfiles, name) def cdr_file(name): return "cdrDetail_{}".format(name) def csr_file(name): return "cdrSummary_{}".format(name) def cdr_file_path(name): homeDir = os.path.expanduser("~") return os.path.join(homeDir, args.cdrfiles, cdr_file(name)) def csr_file_path(name): homeDir = os.path.expanduser("~") return os.path.join(homeDir, args.cdrfiles, csr_file(name)) def make_call_id(): return "CID-{:10d}".format(randint(0, 9999999999)) # OBD_SUCCESS_CALL_CONNECTED(1001), successful_call_statuses = [1001] # OBD_FAILED_NOATTEMPT(2000), # OBD_FAILED_BUSY(2001), # OBD_FAILED_NOANSWER(2002), # OBD_FAILED_SWITCHEDOFF(2003), # OBD_FAILED_INVALIDNUMBER(2004), # OBD_FAILED_OTHERS(2005), failed_call_statuses = [2000, 2001, 2002, 2003, 2004, 2005] # Normal Drop: 1 successful_disconnect_statuses = [1] # VXML Runtime exception: 2 # Content Not found: 3 # Usage Cap exceeded: 4 # Error in the API: 5 # System Error: 6 failed_disconnect_statuses = [2, 3, 4, 5, 6] operators = ['D', 'A', 'B', 'L', 'C', 'H', 'I', 'M', 'R', 'E', 'S', 'Y', 'P', 'W', 'T', 'U', 'V'] def some_time_today(): today = datetime.datetime.now() - datetime.timedelta(hours = choice(range(10)), minutes = choice(range(50))) epoch = datetime.datetime(1970,1,1) return (today - epoch).total_seconds() def write_cdr_row(obd, writer, call_id, attempt, status, start_time, answer_time, end_time, duration, operator): msg_play_start_time = some_time_today() msg_play_end_time = msg_play_start_time + duration # assuming that duration is in seconds call_disconnect_reason = choice(successful_disconnect_statuses) if status in successful_call_statuses \ else choice(failed_disconnect_statuses) # REQUEST_ID, MSISDN, CALL_ID, ATTEMPT_NO, CALL_START_TIME, CALL_ANSWER_TIME, CALL_END_TIME, # CALL_DURATION_IN_PULSE, CALL_STATUS, LANGUAGE_LOCATION_ID, CONTENT_FILE, MSG_PLAY_START_TIME, MSG_PLAY_END_TIME, # CIRCLE_ID, OPERATOR_ID, PRIORITY, CALL_DISCONNECT_REASON, WEEK_ID writer.writerow([ # RequestId obd[REQUEST_ID], # Msisdn obd[MSISDN], # CallId call_id, # AttemptNo attempt, # CallStartTime start_time, # CallAnswerTime answer_time, # CallEndTime end_time, # CallDurationInPulse duration, # CallStatus status, # LanguageLocationId obd[LANGUAGE_LOCATION_CODE], # ContentFile obd[CONTENT_FILE], # MSG_PLAY_START_TIME msg_play_start_time, # MSG_PLAY_END_TIME, msg_play_end_time, # CIRCLE_ID obd[CIRCLE], # OPERATOR_ID operator, # PRIORITY obd[PRIORITY], # CALL_DISCONNECT_REASON call_disconnect_reason, # WEEK_ID obd[WEEK_ID] ]) def write_csr_row(obd, writer, attempts, status): # REQUEST_ID, SERVICE_ID, MSISDN, CLI, PRIORITY, CALL_FLOW_URL, CONTENT_FILE_NAME, WEEK_ID, LANGUAGE_LOCATION_CODE, # CIRCLE, FINAL_STATUS, STATUS_CODE, ATTEMPTS writer.writerow([ # RequestId obd[REQUEST_ID], # ServiceId obd[SERVICE_ID], # Msisdn obd[MSISDN], # Cli obd[CLI], # Priority obd[PRIORITY], # CallFlowURL obd[CALL_FLOW_URL], # ContentFileName obd[CONTENT_FILE], # WeekId obd[WEEK_ID], # LanguageLocationCode obd[LANGUAGE_LOCATION_CODE], # Circle obd[CIRCLE], # FinalStatus FS_SUCCESS if status in successful_call_statuses else FS_FAILED, # StatusCode status, # Attempts attempts ]) def obd_header(): return [REQUEST_ID, SERVICE_ID, MSISDN, CLI, PRIORITY, CALL_FLOW_URL, CONTENT_FILE_NAME, WEEK_ID, LANGUAGE_LOCATION_CODE, CIRCLE, SUBSCRIPTION_ORIGIN] def cdr_header(): return [REQUEST_ID, MSISDN, CALL_ID, ATTEMPT_NO, CALL_START_TIME, CALL_ANSWER_TIME, CALL_END_TIME, CALL_DURATION_IN_PULSE, CALL_STATUS, LANGUAGE_LOCATION_ID, CONTENT_FILE, MSG_PLAY_START_TIME, MSG_PLAY_END_TIME, CIRCLE_ID, OPERATOR_ID, PRIORITY, CALL_DISCONNECT_REASON, WEEK_ID] def csr_header(): return [REQUEST_ID, SERVICE_ID, MSISDN, CLI, PRIORITY, CALL_FLOW_URL, CONTENT_FILE_NAME, WEEK_ID, LANGUAGE_LOCATION_CODE, CIRCLE, FINAL_STATUS, STATUS_CODE, ATTEMPTS] # # pretend call - write to CDR and CSR # def mock_call(obd, cdr_writer, csr_writer): global args print "calling {}".format(obd) cdr_lines = 0 call_id = make_call_id() attempt = 0 # first some retries if randint(0, 100) <= args.retry: status = choice(failed_call_statuses) operator = choice(operators) for i in range(0, randint(0, args.maxretries)): attempt += 1 write_cdr_row(obd, cdr_writer, call_id, attempt, status, 123, 234, 345, 10, operator) cdr_lines += 1 # and then ultimately, succeed or fail... if randint(0, 100) > args.failure: status = choice(failed_call_statuses) write_cdr_row(obd, cdr_writer, call_id, attempt, status, 123, 234, 345, 10, operator) write_csr_row(obd, csr_writer, attempt + 1, status) return cdr_lines + 1 def parse_obd_row(row): return { REQUEST_ID: row[0], SERVICE_ID: row[1], MSISDN: row[2], CLI: row[3], PRIORITY: row[4], CALL_FLOW_URL: row[5], CONTENT_FILE: row[6], WEEK_ID: row[7], LANGUAGE_LOCATION_CODE: row[8], CIRCLE: row[9], SUBSCRIPTION_ORIGIN: row[10] } def obd_file_processed_url(): return "{}/module/imi/obdFileProcessedStatusNotification".format(args.server) def cdr_file_notification_url(): return "{}/module/imi/cdrFileNotification".format(args.server) def checksum(file): s = subprocess.check_output(["/usr/bin/md5sum", file]) return s.split(" ")[0] def read_obd_file(name): cdr_lines = 0 csr_lines = 0 try: print "OBD: {}".format(obd_file_path(name)) # iterate over OBD file with open(obd_file_path(name), 'r') as obdfile, \ open(cdr_file_path(name), 'w') as cdrfile, \ open(csr_file_path(name), 'w') as csrfile: obd_reader = csv.reader(obdfile) cdr_writer = csv.writer(cdrfile) cdr_writer.writerow(cdr_header()) csr_writer = csv.writer(csrfile) csr_writer.writerow(csr_header()) if obd_reader.next() != obd_header(): raise ImportError("Invalid header") for row in obd_reader: cdr_lines += mock_call(parse_obd_row(row), cdr_writer, csr_writer) csr_lines += 1 # send obdFileProcessedStatusNotification request to MOTECH after OBD file was 'checked' headers = {'Content-Type': 'application/json'} data = {u'fileProcessedStatus': 8000, u'fileName': name} json_string = json.dumps(data) request = urllib2.Request(obd_file_processed_url(), headers=headers, data=json_string) print "POST requ: {}".format(obd_file_processed_url()) print "POST data: {}".format(json_string) response = urllib2.urlopen(request, json.dumps(data)) print "POST resp: HTTP {} - {}".format(response.code, response.msg) # wait (to mock how long it takes to call everybody) before sending the next request time.sleep(args.wait) # send cdrFileNotification request to MOTECH when entire OBD file was 'called' data = { u'fileName': name, u'cdrDetail': { u'cdrFile': cdr_file(name), u'checksum': checksum(cdr_file_path(name)), u'recordsCount': cdr_lines }, u'cdrSummary': { u'cdrFile': csr_file(name), u'checksum': checksum(csr_file_path(name)), u'recordsCount': csr_lines } } json_string = json.dumps(data) request = urllib2.Request(cdr_file_notification_url(), headers=headers, data=json_string) print "POST requ: {}".format(cdr_file_notification_url()) print "POST data: {}".format(json_string) response = urllib2.urlopen(request) print "POST resp: HTTP {} - {}".format(response.code, response.msg) except Exception as e: error = "### EXCEPTION: {} ###".format(e) print error return error return "{} ({})\n{} ({})".format(cdr_file_path(name), cdr_lines, csr_file_path(name), csr_lines) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-s", "--server", help="MOTECH URL", default="http://localhost:8080/motech-platform-server") parser.add_argument("-o", "--obdfiles", help="location of the OBD files", default="obd-files-remote") parser.add_argument("-c", "--cdrfiles", help="location of the CDR files", default="cdr-files-remote") parser.add_argument("-f", "--failure", help="call failure percentage (0-100)", type=int, choices=range(0,101), default=30, metavar="[0-100]") parser.add_argument("-m", "--maxretries", help="maximum number of times a call is retried", type=int, default=3) parser.add_argument("-r", "--retry", help="retry percentage (0-100)", type=int, choices=range(0,101), default=50, metavar="[0-100]") parser.add_argument("-w", "--wait", help="seconds to wait before cdrFileNotification", type=int, default=0) args = parser.parse_args() #debug print "args={}".format(args) app.secret_key = 'utvsm9blavlu+1o18d0n9_xe5$&^ulw6d82gr*q&t&azwe-gf$' app.run(host='0.0.0.0')
''' The MIT License (MIT) Portions Copyright (c) 2015-2019, The OmniDB Team Portions Copyright (c) 2017-2019, 2ndQuadrant Limited 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 os.path import re from collections import OrderedDict from enum import Enum import OmniDB_app.include.Spartacus as Spartacus import OmniDB_app.include.Spartacus.Database as Database import OmniDB_app.include.Spartacus.Utils as Utils from urllib.parse import urlparse ''' ------------------------------------------------------------------------ Template ------------------------------------------------------------------------ ''' class TemplateType(Enum): EXECUTE = 1 SCRIPT = 2 class Template: def __init__(self, p_text, p_type=TemplateType.EXECUTE): self.v_text = p_text self.v_type = p_type ''' ------------------------------------------------------------------------ MariaDB ------------------------------------------------------------------------ ''' class MariaDB: def __init__(self, p_server, p_port, p_service, p_user, p_password, p_conn_id=0, p_alias='', p_conn_string='', p_parse_conn_string = False): self.v_alias = p_alias self.v_db_type = 'mariadb' self.v_conn_string = p_conn_string self.v_conn_string_error = '' self.v_conn_id = p_conn_id self.v_server = p_server self.v_active_server = p_server self.v_user = p_user self.v_active_user = p_user self.v_schema = p_service self.v_service = p_service self.v_active_service = p_service self.v_port = p_port if p_port is None or p_port == '': self.v_active_port = '3306' else: self.v_active_port = p_port #try to get info from connection string if p_conn_string!='' and p_parse_conn_string: try: parsed = urlparse(p_conn_string) if parsed.port!=None: self.v_active_port = str(parsed.port) if parsed.hostname!=None: self.v_active_server = parsed.hostname if parsed.username!=None: self.v_active_user = parsed.username if parsed.query!=None: self.v_conn_string_query = parsed.query parsed_database = parsed.path if len(parsed_database)>1: self.v_active_service = parsed_database[1:] except Exception as exc: self.v_conn_string_error = 'Syntax error in the connection string.' None self.v_connection = Spartacus.Database.MariaDB(self.v_active_server, self.v_active_port, self.v_active_service, self.v_active_user, p_password, p_conn_string) self.v_has_schema = True self.v_has_functions = True self.v_has_procedures = True self.v_has_sequences = False self.v_has_primary_keys = True self.v_has_foreign_keys = True self.v_has_uniques = True self.v_has_indexes = True self.v_has_checks = False self.v_has_excludes = False self.v_has_rules = False self.v_has_triggers = False self.v_has_partitions = False self.v_has_update_rule = True self.v_can_rename_table = True self.v_rename_table_command = "alter table #p_table_name# rename to #p_new_table_name#" self.v_create_pk_command = "constraint #p_constraint_name# primary key (#p_columns#)" self.v_create_fk_command = "constraint #p_constraint_name# foreign key (#p_columns#) references #p_r_table_name# (#p_r_columns#) #p_delete_update_rules#" self.v_create_unique_command = "constraint #p_constraint_name# unique (#p_columns#)" self.v_can_alter_type = True self.v_alter_type_command = "alter table #p_table_name# modify #p_column_name# #p_new_data_type#" self.v_can_alter_nullable = True self.v_set_nullable_command = "alter table #p_table_name# modify #p_column_name# null" self.v_drop_nullable_command = "alter table #p_table_name# modify #p_column_name# not null" self.v_can_rename_column = True self.v_rename_column_command = "alter table #p_table_name# rename column #p_column_name# to #p_new_column_name#" self.v_can_add_column = True self.v_add_column_command = "alter table #p_table_name# add #p_column_name# #p_data_type# #p_nullable#" self.v_can_drop_column = True self.v_drop_column_command = "alter table #p_table_name# drop column #p_column_name#" self.v_can_add_constraint = True self.v_add_pk_command = "alter table #p_table_name# add constraint #p_constraint_name# primary key (#p_columns#)" self.v_add_fk_command = "alter table #p_table_name# add constraint #p_constraint_name# foreign key (#p_columns#) references #p_r_table_name# (#p_r_columns#) #p_delete_update_rules#" self.v_add_unique_command = "alter table #p_table_name# add constraint #p_constraint_name# unique (#p_columns#)" self.v_can_drop_constraint = True self.v_drop_pk_command = "alter table #p_table_name# drop constraint #p_constraint_name#" self.v_drop_fk_command = "alter table #p_table_name# drop constraint #p_constraint_name#" self.v_drop_unique_command = "alter table #p_table_name# drop constraint #p_constraint_name#" self.v_create_index_command = "create index #p_index_name# on #p_table_name# (#p_columns#)"; self.v_create_unique_index_command = "create unique index #p_index_name# on #p_table_name# (#p_columns#)" self.v_drop_index_command = "drop index #p_schema_name#.#p_index_name#" self.v_update_rules = [ "NO ACTION", "RESTRICT", "SET NULL", "CASCADE" ] self.v_delete_rules = [ "NO ACTION", "RESTRICT", "SET NULL", "CASCADE" ] self.v_reserved_words = [] self.v_console_help = "Console tab. Type the commands in the editor below this box. \? to view command list." self.v_use_server_cursor = False def GetName(self): return self.v_service def GetVersion(self): return 'MariaDB ' + self.v_connection.ExecuteScalar('select version()') def GetUserName(self): return self.v_user def GetUserSuper(self): try: v_super = self.v_connection.ExecuteScalar(''' select super_priv from mysql.user where user = '{0}' '''.format(self.v_user)) if v_super == 'Y': return True else: return False except Exception as exc: return False def PrintDatabaseInfo(self): if self.v_conn_string=='': return self.v_active_user + '@' + self.v_active_service else: return self.v_active_user + '@' + self.v_active_service def PrintDatabaseDetails(self): if self.v_conn_string=='': return self.v_active_server + ':' + self.v_active_port else: return "<i title='{0}' class='fas fa-asterisk icon-conn-string'></i> ".format(self.v_conn_string) + self.v_active_server + ':' + self.v_active_port def HandleUpdateDeleteRules(self, p_update_rule, p_delete_rule): v_rules = '' if p_update_rule.strip() != '': v_rules += ' on update ' + p_delete_rule + ' ' if p_delete_rule.strip() != '': v_rules += ' on delete ' + p_delete_rule + ' ' return v_rules def TestConnection(self): v_return = '' if self.v_conn_string and self.v_conn_string_error!='': return self.v_conn_string_error try: self.v_connection.Open() self.v_connection.Close() v_return = 'Connection successful.' except Exception as exc: v_return = str(exc) return v_return def GetErrorPosition(self, p_error_message): vector = str(p_error_message).split('\n') v_return = None if len(vector) > 1 and vector[1][0:4]=='LINE': v_return = { 'row': vector[1].split(':')[0].split(' ')[1], 'col': vector[2].index('^') - len(vector[1].split(':')[0])-2 } return v_return def QueryRoles(self): return self.v_connection.Query(""" select concat('''',user,'''','@','''',host,'''') as role_name from mysql.user order by 1 """, True) def QueryDatabases(self): return self.v_connection.Query('show databases', True, True) def QueryTables(self, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_schema: v_filter = "and table_schema = '{0}' ".format(p_schema) else: v_filter = "and table_schema = '{0}' ".format(self.v_schema) return self.v_connection.Query(''' select table_name, table_schema from information_schema.tables where table_type in ('BASE TABLE', 'SYSTEM VIEW') {0} order by 2, 1 '''.format(v_filter), True) def QueryTablesFields(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct c.table_name as table_name, c.column_name, c.data_type, c.is_nullable as nullable, c.character_maximum_length as data_length, c.numeric_precision as data_precision, c.numeric_scale as data_scale, c.ordinal_position from information_schema.columns c, information_schema.tables t where t.table_name = c.table_name and t.table_type in ('BASE TABLE', 'SYSTEM VIEW') {0} order by c.table_name, c.ordinal_position '''.format(v_filter), True) def QueryTablesForeignKeys(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and i.table_schema = '{0}' and i.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and i.table_schema = '{0}' and i.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and i.table_schema = '{0}' ".format(p_schema) else: v_filter = "and i.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and i.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct i.constraint_name, i.table_name, k.referenced_table_name as r_table_name, k.table_schema, k.referenced_table_schema as r_table_schema, r.update_rule, r.delete_rule from information_schema.table_constraints i left join information_schema.key_column_usage k on i.constraint_name = k.constraint_name left join information_schema.referential_constraints r on i.constraint_name = r.constraint_name where i.constraint_type = 'FOREIGN KEY' {0} order by i.constraint_name, i.table_name '''.format(v_filter), True) def QueryTablesForeignKeysColumns(self, p_fkey, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and i.table_schema = '{0}' and i.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and i.table_schema = '{0}' and i.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and i.table_schema = '{0}' ".format(p_schema) else: v_filter = "and i.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and i.table_name = '{0}' ".format(p_table) v_filter = v_filter + "and i.constraint_name = '{0}' ".format(p_fkey) return self.v_connection.Query(''' select distinct i.constraint_name, i.table_name, k.referenced_table_name as r_table_name, k.column_name, k.referenced_column_name as r_column_name, k.table_schema, k.referenced_table_schema as r_table_schema, r.update_rule, r.delete_rule, k.ordinal_position from information_schema.table_constraints i left join information_schema.key_column_usage k on i.constraint_name = k.constraint_name left join information_schema.referential_constraints r on i.constraint_name = r.constraint_name where i.constraint_type = 'FOREIGN KEY' {0} order by i.constraint_name, i.table_name, k.ordinal_position '''.format(v_filter), True) def QueryTablesPrimaryKeys(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct concat('pk_', t.table_name) as constraint_name, t.table_name, t.table_schema from information_schema.table_constraints t where t.constraint_type = 'PRIMARY KEY' {0} order by t.table_schema, t.table_name '''.format(v_filter), True) def QueryTablesPrimaryKeysColumns(self, p_pkey, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) v_filter = "and concat('pk_', t.table_name) = '{0}' ".format(p_pkey) return self.v_connection.Query(''' select distinct k.column_name, k.ordinal_position from information_schema.table_constraints t join information_schema.key_column_usage k using (constraint_name, table_schema, table_name) where t.constraint_type = 'PRIMARY KEY' {0} order by k.ordinal_position '''.format(v_filter), True) def QueryTablesUniques(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct t.constraint_name, t.table_name, t.table_schema from information_schema.table_constraints t where t.constraint_type = 'UNIQUE' {0} order by t.table_schema, t.table_name '''.format(v_filter), True) def QueryTablesUniquesColumns(self, p_unique, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) v_filter = "and t.constraint_name = '{0}' ".format(p_unique) return self.v_connection.Query(''' select distinct k.column_name, k.ordinal_position from information_schema.table_constraints t join information_schema.key_column_usage k using (constraint_name, table_schema, table_name) where t.constraint_type = 'UNIQUE' {0} order by k.ordinal_position '''.format(v_filter), True) def QueryTablesIndexes(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct t.table_schema as schema_name, t.table_name, (case when t.index_name = 'PRIMARY' then concat('pk_', t.table_name) else t.index_name end) as index_name, case when t.non_unique = 1 then 'Non Unique' else 'Unique' end as uniqueness from information_schema.statistics t where 1 = 1 {0} order by 1, 2, 3 '''.format(v_filter), True) def QueryTablesIndexesColumns(self, p_index, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and t.table_schema = '{0}' and t.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and t.table_schema = '{0}' ".format(p_schema) else: v_filter = "and t.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and t.table_name = '{0}' ".format(p_table) v_filter = "and (case when t.index_name = 'PRIMARY' then concat('pk_', t.table_name) else t.index_name end) = '{0}' ".format(p_index) return self.v_connection.Query(''' select distinct t.column_name, t.seq_in_index from information_schema.statistics t where 1 = 1 {0} order by t.seq_in_index '''.format(v_filter), True) def QueryDataLimited(self, p_query, p_count=-1): if p_count != -1: try: self.v_connection.Open() v_data = self.v_connection.QueryBlock('select * from ( {0} ) t limit {1}'.format(p_query, p_count), p_count, True, True) self.v_connection.Close() return v_data except Spartacus.Database.Exception as exc: try: self.v_connection.Cancel() except: pass raise exc else: return self.v_connection.Query(p_query, True) def QueryTableRecords(self, p_column_list, p_table, p_filter, p_count=-1): v_limit = '' if p_count != -1: v_limit = ' limit ' + p_count return self.v_connection.Query(''' select * from ( select {0} from {1} t {2} ) t {3} '''.format( p_column_list, p_table, p_filter, v_limit ), True ) def QueryFunctions(self, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_schema: v_filter = "and t.routine_schema = '{0}' ".format(p_schema) else: v_filter = "and t.routine_schema = '{0}' ".format(self.v_schema) return self.v_connection.Query(''' select t.routine_schema as schema_name, t.routine_name as id, t.routine_name as name from information_schema.routines t where t.routine_type = 'FUNCTION' {0} order by 2 '''.format(v_filter), True) def QueryFunctionFields(self, p_function, p_schema): if p_schema: v_schema = p_schema else: v_schema = self.v_schema return self.v_connection.Query(''' select 'O' as type, concat('returns ', t.data_type) as name, 0 as seq from information_schema.routines t where t.routine_type = 'FUNCTION' and t.routine_schema = '{0}' and t.specific_name = '{1}' union select (case t.parameter_mode when 'IN' then 'I' when 'OUT' then 'O' else 'R' end) as type, concat(t.parameter_name, ' ', t.data_type) as name, t.ordinal_position+1 as seq from information_schema.parameters t where t.ordinal_position > 0 and t.specific_schema = '{0}' and t.specific_name = '{1}' order by 3 desc '''.format(v_schema, p_function), True) def GetFunctionDefinition(self, p_function): v_body = '--DROP FUNCTION {0};\n'.format(p_function) v_body = v_body + self.v_connection.Query('show create function {0}.{1}'.format(self.v_schema, p_function), True, True).Rows[0][2] return v_body def QueryProcedures(self, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_schema: v_filter = "and t.routine_schema = '{0}' ".format(p_schema) else: v_filter = "and t.routine_schema = '{0}' ".format(self.v_schema) return self.v_connection.Query(''' select t.routine_schema as schema_name, t.routine_name as id, t.routine_name as name from information_schema.routines t where t.routine_type = 'PROCEDURE' {0} order by 2 '''.format(v_filter), True) def QueryProcedureFields(self, p_procedure, p_schema): if p_schema: v_schema = p_schema else: v_schema = self.v_schema return self.v_connection.Query(''' select (case t.parameter_mode when 'IN' then 'I' when 'OUT' then 'O' else 'R' end) as type, concat(t.parameter_name, ' ', t.data_type) as name, t.ordinal_position+1 as seq from information_schema.parameters t where t.specific_schema = '{0}' and t.specific_name = '{1}' order by 3 desc '''.format(v_schema, p_procedure), True) def GetProcedureDefinition(self, p_procedure): v_body = '--DROP PROCEDURE {0};\n'.format(p_procedure) v_body = v_body + self.v_connection.Query('show create procedure {0}.{1}'.format(self.v_schema, p_procedure), True, True).Rows[0][2] return v_body def QuerySequences(self, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_schema: v_filter = "and table_schema = '{0}' ".format(p_schema) else: v_filter = "and table_schema = '{0}' ".format(self.v_schema) return self.v_connection.Query(''' select table_name as sequence_name, table_schema as sequence_schema from information_schema.tables where table_type = 'SEQUENCE' {0} order by 2, 1 '''.format(v_filter), True) def QueryViews(self, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_schema: v_filter = "and table_schema = '{0}' ".format(p_schema) else: v_filter = "and table_schema = '{0}' ".format(self.v_schema) return self.v_connection.Query(''' select table_name, table_schema from information_schema.views where 1=1 {0} order by 2, 1 '''.format(v_filter), True) def QueryViewFields(self, p_table=None, p_all_schemas=False, p_schema=None): v_filter = '' if not p_all_schemas: if p_table and p_schema: v_filter = "and c.table_schema = '{0}' and c.table_name = '{1}' ".format(p_schema, p_table) elif p_table: v_filter = "and c.table_schema = '{0}' and c.table_name = '{1}' ".format(self.v_schema, p_table) elif p_schema: v_filter = "and c.table_schema = '{0}' ".format(p_schema) else: v_filter = "and c.table_schema = '{0}' ".format(self.v_schema) else: if p_table: v_filter = "and c.table_name = '{0}' ".format(p_table) return self.v_connection.Query(''' select distinct c.table_name as table_name, c.column_name, c.data_type, c.is_nullable as nullable, c.character_maximum_length as data_length, c.numeric_precision as data_precision, c.numeric_scale as data_scale, c.ordinal_position from information_schema.columns c, information_schema.tables t where t.table_name = c.table_name and t.table_type = 'VIEW' {0} order by c.table_name, c.ordinal_position '''.format(v_filter), True) def GetViewDefinition(self, p_view, p_schema): if p_schema: v_schema = p_schema else: v_schema = self.v_schema return self.v_connection.Query('show create view {0}.{1}'.format(v_schema, p_view), True, True).Rows[0][1] def TemplateCreateRole(self): return Template('''CREATE USER name -- IDENTIFIED BY password -- REQUIRE NONE -- REQUIRE SSL -- REQUIRE X509 -- REQUIRE CIPHER 'cipher' -- REQUIRE ISSUER 'issuer' -- REQUIRE SUBJECT 'subject' -- WITH MAX_QUERIES_PER_HOUR count -- WITH MAX_UPDATES_PER_HOUR count -- WITH MAX_CONNECTIONS_PER_HOUR count -- WITH MAX_USER_CONNECTIONS count -- PASSWORD EXPIRE -- ACCOUNT { LOCK | UNLOCK } ''') def TemplateAlterRole(self): return Template('''ALTER USER #role_name# -- IDENTIFIED BY password -- REQUIRE NONE -- REQUIRE SSL -- REQUIRE X509 -- REQUIRE CIPHER 'cipher' -- REQUIRE ISSUER 'issuer' -- REQUIRE SUBJECT 'subject' -- WITH MAX_QUERIES_PER_HOUR count -- WITH MAX_UPDATES_PER_HOUR count -- WITH MAX_CONNECTIONS_PER_HOUR count -- WITH MAX_USER_CONNECTIONS count -- PASSWORD EXPIRE -- ACCOUNT { LOCK | UNLOCK } -- RENAME USER #role_name# TO new_name -- SET PASSWORD FOR #role_name# = password ''') def TemplateDropRole(self): return Template('DROP USER #role_name#') def TemplateCreateDatabase(self): return Template('''CREATE DATABASE name -- CHARACTER SET charset -- COLLATE collate ''') def TemplateAlterDatabase(self): return Template('''ALTER DATABASE #database_name# -- CHARACTER SET charset -- COLLATE collate ''') def TemplateDropDatabase(self): return Template('DROP DATABASE #database_name#') def TemplateCreateFunction(self): return Template('''CREATE FUNCTION #schema_name#.name ( -- argname argtype ) RETURNS rettype BEGIN -- DECLARE variables -- definition -- RETURN variable | value END; ''') def TemplateDropFunction(self): return Template('DROP FUNCTION #function_name#') def TemplateCreateProcedure(self): return Template('''CREATE PROCEDURE #schema_name#.name ( -- [argmode] argname argtype ) BEGIN -- DECLARE variables -- definition END; ''') def TemplateDropProcedure(self): return Template('DROP PROCEDURE #function_name#') def TemplateCreateTable(self): return Template('''CREATE -- TEMPORARY TABLE #schema_name#.table_name -- AS query ( column_name data_type -- NOT NULL -- NULL -- DEFAULT default_value -- AUTO_INCREMENT -- UNIQUE -- PRIMARY KEY -- COMMENT 'string' -- COLUMN_FORMAT { FIXED | DYNAMIC | DEFAULT } -- STORAGE { DISK | MEMORY | DEFAULT } -- [ GENERATED ALWAYS ] AS (expression) [ VIRTUAL | STORED ] -- [ CONSTRAINT [ symbol ] ] PRIMARY KEY [ USING { BTREE | HASH } ] ( column_name, ... ) -- { INDEX | KEY } [ index_name ] [ USING { BTREE | HASH } ] ( column_name, ... ) -- [ CONSTRAINT [ symbol ] ] UNIQUE [ INDEX | KEY ] [ index_name ] [ USING { BTREE | HASH } ] ( column_name, ... ) -- { FULLTEXT | SPATIAL } [ INDEX | KEY ] [ index_name ] [ USING { BTREE | HASH } ] ( column_name, ... ) -- [ CONSTRAINT [ symbol ] ] FOREIGN KEY [ index_name ] ( column_name, ... ) REFERENCES reftable ( refcolumn, ... ) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }] [ON UPDATE { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }] -- CHECK ( expr ) ) -- AUTO_INCREMENT value -- AVG_ROW_LENGTH value -- [ DEFAULT ] CHARACTER SET charset_name -- CHECKSUM { 0 | 1 } -- [ DEFAULT ] COLLATE collation_name -- COMMENT 'string' -- COMPRESSION { 'ZLIB' | 'LZ4' | 'NONE' } -- CONNECTION 'connect_string' -- { DATA | INDEX } DIRECTORY 'absolute path to directory' -- DELAY_KEY_WRITE { 0 | 1 } -- ENCRYPTION { 'Y' | 'N' } -- ENGINE engine_name -- INSERT_METHOD { NO | FIRST | LAST } -- KEY_BLOCK_SIZE value -- MAX_ROWS value -- MIN_ROWS value -- PACK_KEYS { 0 | 1 | DEFAULT } -- PASSWORD 'string' -- ROW_FORMAT { DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT } -- STATS_AUTO_RECALC { DEFAULT | 0 | 1 } -- STATS_PERSISTENT { DEFAULT | 0 | 1 } -- STATS_SAMPLE_PAGES value -- TABLESPACE tablespace_name [STORAGE { DISK | MEMORY | DEFAULT } ] ''') def TemplateAlterTable(self): return Template('''ALTER TABLE #table_name# -- ADD [ COLUMN ] col_name column_definition [ FIRST | AFTER col_name ] -- ADD [ COLUMN ] ( col_name column_definition , ... ) -- ADD { INDEX | KEY } [ index_name ] USING { BTREE | HASH } (index_col_name , ... ) -- ADD [ CONSTRAINT [ symbol ] ] PRIMARY KEY USING { BTREE | HASH } ( index_col_name , ... ) -- ADD [ CONSTRAINT [ symbol ] ] UNIQUE [ INDEX | KEY ] [ index_name ] USING { BTREE | HASH } ( index_col_name , ... ) -- ADD FULLTEXT [ INDEX | KEY ] ( index_col_name , ... ) -- ADD SPATIAL [ INDEX | KEY ] [ index_name ] (index_col_name , ... ) -- ADD [ CONSTRAINT [ symbol ] ] FOREIGN KEY [ index_name ] ( index_col_name , ... ) reference_definition -- ALGORITHM { DEFAULT | INPLACE | COPY } -- ALTER [ COLUMN ] col_name { SET DEFAULT literal | DROP DEFAULT } -- CHANGE [ COLUMN ] old_col_name new_col_name column_definition [ FIRST | AFTER col_name ] -- [DEFAULT] CHARACTER SET charset_name [ COLLATE collation_name ] -- CONVERT TO CHARACTER SET charset_name [ COLLATE collation_name ] -- { DISABLE | ENABLE } KEYS -- { DISCARD | IMPORT } TABLESPACE -- DROP [ COLUMN ] col_name -- DROP { INDEX | KEY } index_name -- DROP PRIMARY KEY -- DROP FOREIGN KEY fk_symbol -- FORCE -- LOCK { DEFAULT | NONE | SHARED | EXCLUSIVE } -- MODIFY [ COLUMN ] col_name column_definition [ FIRST | AFTER col_name ] -- ORDER BY col_name [, col_name] ... -- RENAME { INDEX | KEY } old_index_name TO new_index_name -- RENAME [ TO | AS ] new_tbl_name -- { WITHOUT | WITH } VALIDATION -- ADD PARTITION ( partition_definition ) -- DROP PARTITION partition_names -- DISCARD PARTITION { partition_names | ALL } TABLESPACE -- IMPORT PARTITION { partition_names | ALL } TABLESPACE -- TRUNCATE PARTITION { partition_names | ALL } -- COALESCE PARTITION number -- REORGANIZE PARTITION partition_names INTO ( partition_definitions ) -- EXCHANGE PARTITION partition_name WITH TABLE tbl_name [ { WITH | WITHOUT } VALIDATION ] -- ANALYZE PARTITION { partition_names | ALL } -- CHECK PARTITION { partition_names | ALL } -- OPTIMIZE PARTITION { partition_names | ALL } -- REBUILD PARTITION { partition_names | ALL } -- REPAIR PARTITION { partition_names | ALL } -- REMOVE PARTITIONING -- UPGRADE PARTITIONING -- AUTO_INCREMENT value -- AVG_ROW_LENGTH value -- [ DEFAULT ] CHARACTER SET charset_name -- CHECKSUM { 0 | 1 } -- [ DEFAULT ] COLLATE collation_name -- COMMENT 'string' -- COMPRESSION { 'ZLIB' | 'LZ4' | 'NONE' } -- CONNECTION 'connect_string' -- { DATA | INDEX } DIRECTORY 'absolute path to directory' -- DELAY_KEY_WRITE { 0 | 1 } -- ENCRYPTION { 'Y' | 'N' } -- ENGINE engine_name -- INSERT_METHOD { NO | FIRST | LAST } -- KEY_BLOCK_SIZE value -- MAX_ROWS value -- MIN_ROWS value -- PACK_KEYS { 0 | 1 | DEFAULT } -- PASSWORD 'string' -- ROW_FORMAT { DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT } -- STATS_AUTO_RECALC { DEFAULT | 0 | 1 } -- STATS_PERSISTENT { DEFAULT | 0 | 1 } -- STATS_SAMPLE_PAGES value -- TABLESPACE tablespace_name [STORAGE { DISK | MEMORY | DEFAULT } ] ''') def TemplateDropTable(self): return Template('''DROP TABLE #table_name# -- RESTRICT -- CASCADE ''') def TemplateCreateColumn(self): return Template('''ALTER TABLE #table_name# ADD name data_type --DEFAULT expr --NOT NULL ''') def TemplateAlterColumn(self): return Template('''ALTER TABLE #table_name# -- ALTER #column_name# { datatype | DEFAULT expr | [ NULL | NOT NULL ]} -- CHANGE COLUMN #column_name# TO new_name ''' ) def TemplateDropColumn(self): return Template('''ALTER TABLE #table_name# DROP COLUMN #column_name# ''') def TemplateCreatePrimaryKey(self): return Template('''ALTER TABLE #table_name# ADD CONSTRAINT name PRIMARY KEY ( column_name [, ... ] ) ''') def TemplateDropPrimaryKey(self): return Template('''ALTER TABLE #table_name# DROP PRIMARY KEY #constraint_name# --CASCADE ''') def TemplateCreateUnique(self): return Template('''ALTER TABLE #table_name# ADD CONSTRAINT name UNIQUE ( column_name [, ... ] ) ''') def TemplateDropUnique(self): return Template('''ALTER TABLE #table_name# DROP #constraint_name# ''') def TemplateCreateForeignKey(self): return Template('''ALTER TABLE #table_name# ADD CONSTRAINT name FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] ''') def TemplateDropForeignKey(self): return Template('''ALTER TABLE #table_name# DROP FOREIGN KEY #constraint_name# ''') def TemplateCreateIndex(self): return Template('''CREATE [ UNIQUE ] INDEX name ON #table_name# ( { column_name | ( expression ) } [ ASC | DESC ] ) ''') def TemplateDropIndex(self): return Template('DROP INDEX #index_name#') def TemplateCreateSequence(self): return Template('''CREATE SEQUENCE #schema_name#.name --INCREMENT BY increment --MINVALUE minvalue | NOMINVALUE --MAXVALUE maxvalue | NOMAXVALUE --START WITH start --CACHE cache | NOCACHE --CYCLE | NOCYCLE ''') def TemplateAlterSequence(self): return Template('''ALTER SEQUENCE #sequence_name# --INCREMENT BY increment --MINVALUE minvalue | NOMINVALUE --MAXVALUE maxvalue | NOMAXVALUE --START WITH start --CACHE cache | NOCACHE --CYCLE | NOCYCLE --RESTART WITH restart ''') def TemplateDropSequence(self): return Template('DROP SEQUENCE #sequence_name#') def TemplateCreateView(self): return Template('''CREATE OR REPLACE VIEW #schema_name#.name AS SELECT ... ''') def TemplateDropView(self): return Template('''DROP VIEW #view_name# -- RESTRICT -- CASCADE ''') def TemplateSelect(self, p_schema, p_table): v_sql = 'SELECT t.' v_fields = self.QueryTablesFields(p_table, False, p_schema) if len(v_fields.Rows) > 0: v_sql += '\n , t.'.join([r['column_name'] for r in v_fields.Rows]) v_sql += '\nFROM {0}.{1} t'.format(p_schema, p_table) v_pk = self.QueryTablesPrimaryKeys(p_table, False, p_schema) if len(v_pk.Rows) > 0: v_fields = self.QueryTablesPrimaryKeysColumns(v_pk.Rows[0]['constraint_name'], p_table, False, p_schema) if len(v_fields.Rows) > 0: v_sql += '\nORDER BY t.' v_sql += '\n , t.'.join([r['column_name'] for r in v_fields.Rows]) return Template(v_sql) def TemplateInsert(self, p_schema, p_table): v_fields = self.QueryTablesFields(p_table, False, p_schema) if len(v_fields.Rows) > 0: v_sql = 'INSERT INTO {0}.{1} (\n'.format(p_schema, p_table) v_pk = self.QueryTablesPrimaryKeys(p_table, False, p_schema) if len(v_pk.Rows) > 0: v_table_pk_fields = self.QueryTablesPrimaryKeysColumns(v_pk.Rows[0]['constraint_name'], p_table, False, p_schema) v_pk_fields = [r['column_name'] for r in v_table_pk_fields.Rows] v_values = [] v_first = True for r in v_fields.Rows: if v_first: v_sql += ' {0}'.format(r['column_name']) if r['column_name'] in v_pk_fields: v_values.append(' ? -- {0} {1} PRIMARY KEY'.format(r['column_name'], r['data_type'])) elif r['nullable'] == 'YES': v_values.append(' ? -- {0} {1} NULLABLE'.format(r['column_name'], r['data_type'])) else: v_values.append(' ? -- {0} {1}'.format(r['column_name'], r['data_type'])) v_first = False else: v_sql += '\n , {0}'.format(r['column_name']) if r['column_name'] in v_pk_fields: v_values.append('\n , ? -- {0} {1} PRIMARY KEY'.format(r['column_name'], r['data_type'])) elif r['nullable'] == 'YES': v_values.append('\n , ? -- {0} {1} NULLABLE'.format(r['column_name'], r['data_type'])) else: v_values.append('\n , ? -- {0} {1}'.format(r['column_name'], r['data_type'])) else: v_values = [] v_first = True for r in v_fields.Rows: if v_first: v_sql += ' {0}'.format(r['column_name']) if r['nullable'] == 'YES': v_values.append(' ? -- {0} {1} NULLABLE'.format(r['column_name'], r['data_type'])) else: v_values.append(' ? -- {0} {1}'.format(r['column_name'], r['data_type'])) v_first = False else: v_sql += '\n , {0}'.format(r['column_name']) if r['nullable'] == 'YES': v_values.append('\n , ? -- {0} {1} NULLABLE'.format(r['column_name'], r['data_type'])) else: v_values.append('\n , ? -- {0} {1}'.format(r['column_name'], r['data_type'])) v_sql += '\n) VALUES (\n' for v in v_values: v_sql += v v_sql += '\n)' else: v_sql = '' return Template(v_sql) def TemplateUpdate(self, p_schema, p_table): v_fields = self.QueryTablesFields(p_table, False, p_schema) if len(v_fields.Rows) > 0: v_sql = 'UPDATE {0}.{1}\nSET '.format(p_schema, p_table) v_pk = self.QueryTablesPrimaryKeys(p_table, False, p_schema) if len(v_pk.Rows) > 0: v_table_pk_fields = self.QueryTablesPrimaryKeysColumns(v_pk.Rows[0]['constraint_name'], p_table, False, p_schema) v_pk_fields = [r['column_name'] for r in v_table_pk_fields.Rows] v_values = [] v_first = True for r in v_fields.Rows: if v_first: if r['column_name'] in v_pk_fields: v_sql += '{0} = ? -- {1} PRIMARY KEY'.format(r['column_name'], r['data_type']) elif r['nullable'] == 'YES': v_sql += '{0} = ? -- {1} NULLABLE'.format(r['column_name'], r['data_type']) else: v_sql += '{0} = ? -- {1}'.format(r['column_name'], r['data_type']) v_first = False else: if r['column_name'] in v_pk_fields: v_sql += '\n , {0} = ? -- {1} PRIMARY KEY'.format(r['column_name'], r['data_type']) elif r['nullable'] == 'YES': v_sql += '\n , {0} = ? -- {1} NULLABLE'.format(r['column_name'], r['data_type']) else: v_sql += '\n , {0} = ? -- {1}'.format(r['column_name'], r['data_type']) else: v_values = [] v_first = True for r in v_fields.Rows: if v_first: if r['nullable'] == 'YES': v_sql += '{0} = ? -- {1} NULLABLE'.format(r['column_name'], r['data_type']) else: v_sql += '{0} = ? -- {1}'.format(r['column_name'], r['data_type']) v_first = False else: if r['nullable'] == 'YES': v_sql += '\n , {0} = ? -- {1} NULLABLE'.format(r['column_name'], r['data_type']) else: v_sql += '\n , {0} = ? -- {1}'.format(r['column_name'], r['data_type']) v_sql += '\nWHERE condition' else: v_sql = '' return Template(v_sql) def TemplateDelete(self): return Template('''DELETE FROM #table_name# WHERE condition ''') def GetProperties(self, p_schema, p_table, p_object, p_type): if p_type == 'table': return self.v_connection.Query(''' select table_schema as "Table Schema", table_name as "Table Name", table_type as "Table Type", engine as "Engine", version as "Version", row_format as "Row Format", table_rows as "Table Rows", avg_row_length as "Average Row Length", data_length as "Data Length", max_data_length as "Max Data Length", index_length as "Index Length", data_free as "Data Free", auto_increment as "Auto Increment", create_time as "Create Time", update_time as "Update Time", check_time as "Check Time", table_collation as "Table Collaction", checksum as "Checksum" from information_schema.tables where table_schema = '{0}' and table_name = '{1}' '''.format(p_schema, p_object), True).Transpose('Property', 'Value') elif p_type == 'view': return self.v_connection.Query(''' select table_schema as "View Schema", table_name as "View Name", check_option as "Check Option", is_updatable as "Is Updatable", security_type as "Security Type", character_set_client as "Character Set Client", collation_connection as "Collation Connection", algorithm as "Algorithm" from information_schema.views where table_schema = '{0}' and table_name = '{1}' '''.format(p_schema, p_object), True).Transpose('Property', 'Value') elif p_type == 'function': return self.v_connection.Query(''' select routine_schema as "Routine Schema", routine_name as "Routine Name", routine_type as "Routine Type", data_type as "Data Type", character_maximum_length as "Character Maximum Length", character_octet_length as "Character Octet Length", numeric_precision as "Numeric Precision", numeric_scale as "Numeric Scale", datetime_precision as "Datetime Precision", character_set_name as "Character Set Name", collation_name as "Collation Name", routine_body as "Routine Body", external_name as "External Name", external_language as "External Language", parameter_style as "Parameter Style", is_deterministic as "Is Deterministic", sql_data_access as "SQL Data Access", sql_path as "SQL Path", security_type as "Security Type", created as "Created", last_altered as "Last Altered", character_set_client as "Character Set Client", collation_connection as "Collation Connection", database_collation as "Database Collation" from information_schema.routines where routine_type = 'FUNCTION' and routine_schema = '{0}' and routine_name = '{1}' '''.format(p_schema, p_object), True).Transpose('Property', 'Value') elif p_type == 'procedure': return self.v_connection.Query(''' select routine_schema as "Routine Schema", routine_name as "Routine Name", routine_type as "Routine Type", data_type as "Data Type", character_maximum_length as "Character Maximum Length", character_octet_length as "Character Octet Length", numeric_precision as "Numeric Precision", numeric_scale as "Numeric Scale", datetime_precision as "Datetime Precision", character_set_name as "Character Set Name", collation_name as "Collation Name", routine_body as "Routine Body", external_name as "External Name", external_language as "External Language", parameter_style as "Parameter Style", is_deterministic as "Is Deterministic", sql_data_access as "SQL Data Access", sql_path as "SQL Path", security_type as "Security Type", created as "Created", last_altered as "Last Altered", character_set_client as "Character Set Client", collation_connection as "Collation Connection", database_collation as "Database Collation" from information_schema.routines where routine_type = 'PROCEDURE' and routine_schema = '{0}' and routine_name = '{1}' '''.format(p_schema, p_object), True).Transpose('Property', 'Value') elif p_type == 'sequence': return self.v_connection.Query(''' select next_not_cached_value as "Next Not Cached Value", minimum_value as "Min Value", maximum_value as "Max Value", start_value as "Start Value", increment as "Increment By", cache_size as "Cache Size", (case when 0 then 'No Cycle' else 'Cycle' end) as "Cycle Option", cycle_count as "Cycle Count" from {0}.{1} '''.format(p_schema, p_object), True).Transpose('Property', 'Value') else: return None def GetDDL(self, p_schema, p_table, p_object, p_type): if p_type == 'function' or p_type == 'procedure': return self.v_connection.Query('show create {0} {1}.{2}'.format(p_type, p_schema, p_object), True, True).Rows[0][2] else: return self.v_connection.Query('show create {0} {1}.{2}'.format(p_type, p_schema, p_object), True, True).Rows[0][1] def GetAutocompleteValues(self, p_columns, p_filter): return None
# Copyright (c) 2015-2020 The Botogram Authors (see AUTHORS) # # 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 importlib import json from .. import syntaxes from .. import utils from ..utils.deprecations import _deprecated_message from ..exceptions import InlineMessageUnsupportedActionException from .base import multiple _objects_module = None def _objects(): global _objects_module # This is lazily loaded to avoid circular dependencies if _objects_module is None: _objects_module = importlib.import_module("..objects", __package__) return _objects_module def _require_api(func): """Decorator which forces to have the api on an object""" @utils.wraps(func) def __(self, *args, **kwargs): if not hasattr(self, "_api") or self._api is None: raise RuntimeError("An API instance must be provided") return func(self, *args, **kwargs) return __ class ChatMixin: """Add some methods for chats""" def _get_call_args(self, reply_to, extra, attach, notify): """Get default API call arguments""" # Convert instance of Message to ids in reply_to if hasattr(reply_to, "id"): reply_to = reply_to.id args = {"chat_id": self.id} if reply_to is not None: args["reply_to_message_id"] = reply_to if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -4 ) args["reply_markup"] = json.dumps(extra.serialize()) if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = json.dumps(attach._serialize_attachment( self )) if not notify: args["disable_notification"] = True return args @staticmethod def _get_file_args(path, file_id, url): args = None if path is not None and file_id is None and url is None: file = open(path, "rb") elif file_id is not None and path is None and url is None: args = file_id file = None elif url is not None and file_id is None and path is None: args = url file = None elif path is None and file_id is None and url is None: raise TypeError("path or file_id or URL is missing") else: raise TypeError("Only one among path, file_id and URL must be" + "passed") return args, file @_require_api def send(self, message, preview=True, reply_to=None, syntax=None, extra=None, attach=None, notify=True): """Send a message""" args = self._get_call_args(reply_to, extra, attach, notify) args["text"] = message args["disable_web_page_preview"] = not preview syntax = syntaxes.guess_syntax(message, syntax) if syntax is not None: args["parse_mode"] = syntax return self._api.call("sendMessage", args, expect=_objects().Message) @_require_api def send_photo(self, path=None, file_id=None, url=None, caption=None, syntax=None, reply_to=None, extra=None, attach=None, notify=True): """Send a photo""" args = self._get_call_args(reply_to, extra, attach, notify) if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax files = dict() args["photo"], files["photo"] = self._get_file_args(path, file_id, url) if files["photo"] is None: del files["photo"] return self._api.call("sendPhoto", args, files, expect=_objects().Message) @_require_api def send_audio(self, path=None, file_id=None, url=None, duration=None, thumb=None, performer=None, title=None, reply_to=None, extra=None, attach=None, notify=True, caption=None, *, syntax=None): """Send an audio track""" args = self._get_call_args(reply_to, extra, attach, notify) if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax if duration is not None: args["duration"] = duration if performer is not None: args["performer"] = performer if title is not None: args["title"] = title files = dict() args["audio"], files["audio"] = self._get_file_args(path, file_id, url) if files["audio"] is None: del files["audio"] if thumb is not None: files["thumb"] = thumb return self._api.call("sendAudio", args, files, expect=_objects().Message) @_require_api def send_voice(self, path=None, file_id=None, url=None, duration=None, title=None, reply_to=None, extra=None, attach=None, notify=True, caption=None, *, syntax=None): """Send a voice message""" args = self._get_call_args(reply_to, extra, attach, notify) if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax if duration is not None: args["duration"] = duration if title is not None: args["title"] = title syntax = syntaxes.guess_syntax(caption, syntax) if syntax is not None: args["parse_mode"] = syntax files = dict() args["voice"], files["voice"] = self._get_file_args(path, file_id, url) if files["voice"] is None: del files["voice"] return self._api.call("sendVoice", args, files, expect=_objects().Message) @_require_api def send_video(self, path=None, file_id=None, url=None, duration=None, caption=None, streaming=True, thumb=None, reply_to=None, extra=None, attach=None, notify=True, *, syntax=None): """Send a video""" args = self._get_call_args(reply_to, extra, attach, notify) args["supports_streaming"] = streaming if duration is not None: args["duration"] = duration if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax files = dict() args["video"], files["video"] = self._get_file_args(path, file_id, url) if files["video"] is None: del files["video"] if thumb is not None: files["thumb"] = thumb return self._api.call("sendVideo", args, files, expect=_objects().Message) @_require_api def send_video_note(self, path=None, file_id=None, duration=None, diameter=None, thumb=None, reply_to=None, extra=None, attach=None, notify=True): """Send a video note""" args = self._get_call_args(reply_to, extra, attach, notify) if duration is not None: args["duration"] = duration if diameter is not None: args["length"] = diameter files = dict() args["video_note"], files["video_note"] = self._get_file_args(path, file_id, None) if files["video_note"] is None: del files["video_note"] if thumb is not None: files["thumb"] = thumb return self._api.call("sendVideoNote", args, files, expect=_objects().Message) @_require_api def send_gif(self, path=None, file_id=None, url=None, duration=None, width=None, height=None, caption=None, thumb=None, reply_to=None, extra=None, attach=None, notify=True, syntax=None): """Send an animation""" args = self._get_call_args(reply_to, extra, attach, notify) if duration is not None: args["duration"] = duration if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax if width is not None: args["width"] = width if height is not None: args["height"] = height files = dict() args["animation"], files["animation"] = self._get_file_args(path, file_id, url) if files["animation"] is None: del files["animation"] if thumb is not None: files["thumb"] = thumb return self._api.call("sendAnimation", args, files, expect=_objects().Message) @_require_api def send_file(self, path=None, file_id=None, url=None, thumb=None, reply_to=None, extra=None, attach=None, notify=True, caption=None, *, syntax=None): """Send a generic file""" args = self._get_call_args(reply_to, extra, attach, notify) if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax files = dict() args["document"], files["document"] = self._get_file_args(path, file_id, url) if files["document"] is None: del files["document"] if thumb is not None: files["thumb"] = thumb return self._api.call("sendDocument", args, files, expect=_objects().Message) @_require_api def send_location(self, latitude, longitude, live_period=None, reply_to=None, extra=None, attach=None, notify=True): """Send a geographic location, set live_period to a number between 60 and 86400 if it's a live location""" args = self._get_call_args(reply_to, extra, attach, notify) args["latitude"] = latitude args["longitude"] = longitude if live_period: if live_period < 60 or live_period > 86400: raise ValueError( "live_period must be a number between 60 and 86400") args["live_period"] = live_period return self._api.call("sendLocation", args, expect=_objects().Message) @_require_api def send_venue(self, latitude, longitude, title, address, foursquare=None, reply_to=None, extra=None, attach=None, notify=True): """Send a venue""" args = self._get_call_args(reply_to, extra, attach, notify) args["latitude"] = latitude args["longitude"] = longitude args["title"] = title args["address"] = address if foursquare is not None: args["foursquare_id"] = foursquare self._api.call("sendVenue", args, expect=_objects().Message) @_require_api def send_sticker(self, sticker=None, reply_to=None, extra=None, attach=None, notify=True, *, path=None, file_id=None, url=None): """Send a sticker""" if sticker is not None: if path is not None: raise TypeError("The sticker argument is overridden by " + "the path one") path = sticker _deprecated_message( "The sticker parameter", "1.0", "use the path parameter", -3 ) args = self._get_call_args(reply_to, extra, attach, notify) files = dict() args["sticker"], files["sticker"] = self._get_file_args(path, file_id, url) if files["sticker"] is None: del files["sticker"] return self._api.call("sendSticker", args, files, expect=_objects().Message) @_require_api def send_contact(self, phone, first_name, last_name=None, vcard=None, *, reply_to=None, extra=None, attach=None, notify=True): """Send a contact""" args = self._get_call_args(reply_to, extra, attach, notify) args["phone_number"] = phone args["first_name"] = first_name if last_name is not None: args["last_name"] = last_name if vcard is not None: args["vcard"] = vcard return self._api.call("sendContact", args, expect=_objects().Message) @_require_api def send_poll(self, question, *kargs, reply_to=None, extra=None, attach=None, notify=True): """Send a poll""" args = self._get_call_args(reply_to, extra, attach, notify) args["question"] = question args["options"] = json.dumps(list(kargs)) return self._api.call("sendPoll", args, expect=_objects().Message) @_require_api def delete_message(self, message): """Delete a message from chat""" if hasattr(message, "message_id"): message = message.message_id return self._api.call("deleteMessage", { "chat_id": self.id, "message_id": message, }) @_require_api def set_photo(self, path): """Set a new chat photo""" args = {"chat_id": self.id} files = {"photo": open(path, "rb")} self._api.call("setChatPhoto", args, files) @_require_api def remove_photo(self): """Remove the current chat photo""" args = {"chat_id": self.id} self._api.call("deleteChatPhoto", args) @_require_api def send_album(self, album=None, reply_to=None, notify=True): """Send a Album""" albums = SendAlbum(self, reply_to, notify) if album is not None: albums._content = album._content albums._file = album._file albums._used = True return albums.send() return albums class MessageMixin: """Add some methods for messages""" def _get_call_args(self, attach): if self.is_inline: args = {"inline_message_id": self.inline_message_id} else: args = {"message_id": self.id, "chat_id": self.chat.id} if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) if self.is_inline: chat = None else: chat = self.chat args["reply_markup"] = json.dumps(attach._serialize_attachment( chat )) return args @_require_api def forward_to(self, to, notify=True): """Forward the message to another user""" if hasattr(to, "id"): to = to.id args = dict() args["chat_id"] = to args["from_chat_id"] = self.chat.id args["message_id"] = self.message_id if not notify: args["disable_notification"] = True return self._api.call("forwardMessage", args, expect=_objects().Message) @_require_api def edit(self, text, syntax=None, preview=True, extra=None, attach=None): """Edit this message""" args = self._get_call_args(attach) args["text"] = text syntax = syntaxes.guess_syntax(text, syntax) if syntax is not None: args["parse_mode"] = syntax if not preview: args["disable_web_page_preview"] = True if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -3 ) args["reply_markup"] = json.dumps(extra.serialize()) self._api.call("editMessageText", args) self.text = text @_require_api def edit_caption(self, caption, extra=None, attach=None, *, syntax=None): """Edit this message's caption""" args = self._get_call_args(attach) args["caption"] = caption syntax = syntaxes.guess_syntax(caption, syntax) if syntax is not None: args["parse_mode"] = syntax if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -3 ) args["reply_markup"] = json.dumps(extra.serialize()) self._api.call("editMessageCaption", args) self.caption = caption @_require_api def edit_attach(self, attach): """Edit this message's attachment""" args = {"message_id": self.id, "chat_id": self.chat.id} if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = json.dumps(attach._serialize_attachment( self.chat )) self._api.call("editMessageReplyMarkup", args) @_require_api def edit_live_location(self, latitude, longitude, extra=None, attach=None): """Edit this message's live location position""" args = {"message_id": self.id, "chat_id": self.chat.id} args["latitude"] = latitude args["longitude"] = longitude if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -3 ) args["reply_markup"] = json.dumps(extra.serialize()) if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = json.dumps(attach._serialize_attachment( self.chat )) self._api.call("editMessageLiveLocation", args) @_require_api def stop_live_location(self, extra=None, attach=None): """Stop this message's live location""" args = {"message_id": self.id, "chat_id": self.chat.id} if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -3 ) args["reply_markup"] = json.dumps(extra.serialize()) if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = json.dumps(attach._serialize_attachment( self.chat )) self._api.call("stopMessageLiveLocation", args) @_require_api def reply(self, *args, **kwargs): """Reply to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send(*args, reply_to=self, **kwargs) @_require_api def reply_with_photo(self, *args, **kwargs): """Reply with a photo to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_photo(*args, reply_to=self, **kwargs) @_require_api def reply_with_audio(self, *args, **kwargs): """Reply with an audio track to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_audio(*args, reply_to=self, **kwargs) @_require_api def reply_with_voice(self, *args, **kwargs): """Reply with a voice message to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_voice(*args, reply_to=self, **kwargs) @_require_api def reply_with_video(self, *args, **kwargs): """Reply with a video to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_video(*args, reply_to=self, **kwargs) @_require_api def reply_with_video_note(self, *args, **kwargs): if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) """Reply with a video note to the current message""" return self.chat.send_video_note(*args, reply_to=self, **kwargs) @_require_api def reply_with_gif(self, *args, **kwargs): return self.chat.send_gif(*args, reply_to=self, **kwargs) @_require_api def reply_with_file(self, *args, **kwargs): """Reply with a generic file to the current chat""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_file(*args, reply_to=self, **kwargs) @_require_api def reply_with_location(self, *args, **kwargs): """Reply with a geographic location to the current chat""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_location(*args, reply_to=self, **kwargs) @_require_api def reply_with_venue(self, *args, **kwargs): """Reply with a venue to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_venue(*args, reply_to=self, **kwargs) @_require_api def reply_with_sticker(self, *args, **kwargs): """Reply with a sticker to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_sticker(*args, reply_to=self, **kwargs) @_require_api def reply_with_contact(self, *args, **kwargs): """Reply with a contact to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_contact(*args, reply_to=self, **kwargs) @_require_api def reply_with_album(self, *args, **kwargs): """Reply with an album to the current message""" if self.is_inline: raise InlineMessageUnsupportedActionException( "You can't use reply_to with a message sent via inline mode" ) return self.chat.send_album(*args, reply_to=self, **kwargs) @_require_api def reply_with_poll(self, *args, **kwargs): """Reply with a poll to the current message""" return self.chat.send_poll(*args, reply_to=self, **kwargs) @_require_api def delete(self): """Delete the message""" if self.is_inline: raise AttributeError("inline error delete") return self._api.call("deleteMessage", { "chat_id": self.chat.id, "message_id": self.id, }) @_require_api def stop_poll(self, extra=None, attach=None): """Stops a poll""" args = dict() args["chat_id"] = self.chat.id args["message_id"] = self.id if extra is not None: _deprecated_message( "The extra parameter", "1.0", "use the attach parameter", -3 ) args["reply_markup"] = json.dumps(extra.serialize()) if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = json.dumps(attach._serialize_attachment( self.chat )) return self._api.call("stopPoll", args, expect=_objects().Poll) class FileMixin: """Add some methods for files""" @_require_api def save(self, path): """Save the file to a particular path""" response = self._api.call("getFile", {"file_id": self.file_id}) # Save the file to the wanted path downloaded = self._api.file_content(response["result"]["file_path"]) with open(path, 'wb') as f: f.write(downloaded) class Album: """Factory for albums""" def __init__(self): self._content = [] self._file = [] def add_photo(self, path=None, url=None, file_id=None, caption=None, syntax=None): """Add a photo the the album instance""" args = {"type": "photo"} if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax if path is not None and file_id is None and url is None: name = "photo" + str(len(self._file)) args["media"] = "attach://" + name self._file.append((name, (path, open(path, "rb")))) elif file_id is not None and path is None and url is None: args["media"] = file_id elif url is not None and file_id is None and path is None: args["media"] = url elif path is None and file_id is None and url is None: raise TypeError("path or file_id or URL is missing") else: raise TypeError("Only one among path, file_id and URL must be" + "passed") self._content.append(args) def add_video(self, path=None, file_id=None, url=None, duration=None, caption=None, syntax=None): """Add a video the the album instance""" args = {"type": "video"} if duration is not None: args["duration"] = duration if caption is not None: args["caption"] = caption if syntax is not None: syntax = syntaxes.guess_syntax(caption, syntax) args["parse_mode"] = syntax if path is not None and file_id is None and url is None: name = "photo" + str(len(self._file)) args["media"] = "attach://" + name self._file.append((name, (path, open(path, "rb")))) elif file_id is not None and path is None and url is None: args["media"] = file_id elif url is not None and file_id is None and path is None: args["media"] = url elif path is None and file_id is None and url is None: raise TypeError("path or file_id or URL is missing") else: raise TypeError("Only one among path, file_id and URL must be" + "passed") self._content.append(args) class SendAlbum(Album): """Send the album instance to the chat passed as argument""" def __init__(self, chat, reply_to=None, notify=True): super(SendAlbum, self).__init__() self._get_call_args = chat._get_call_args self._api = chat._api self.reply_to = reply_to self.notify = notify self._used = False def __enter__(self): self._used = True return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: self.send() def send(self): """Send the Album to telgram""" args = self._get_call_args(self.reply_to, None, None, self.notify) args["media"] = json.dumps(self._content) return self._api.call("sendMediaGroup", args, self._file, expect=multiple(_objects().Message)) def __del__(self): if not self._used: utils.warn(1, "error_with_album", "you should use `with` to use send_album\ -- check the documentation") class InlineMixin: """Helper class for rendering inline elements""" @staticmethod def _get_call_args(result_type, title, attach, content): args = { "id": None, # Will be smartly assigned in the hook "type": result_type, } if title is not None: args["title"] = title if attach is not None: if not hasattr(attach, "_serialize_attachment"): raise ValueError("%s is not an attachment" % attach) args["reply_markup"] = attach._serialize_attachment() if content is not None: args["input_message_content"] = content._serialize() return args @staticmethod def _inject_file_args(args, file_id, url): result_type = args["type"] if file_id is not None and url is None: args[result_type + "_file_id"] = file_id elif file_id is None and url is not None: args[result_type + "_url"] = url elif file_id is None and url is None: raise TypeError("file_id or URL is missing") else: raise TypeError("Only one among file_id and URL must be passed") return args @staticmethod def _inject_thumb_args(args, url, width=None, height=None): if url is not None: args["thumb_url"] = url if width is not None: args["thumb_width"] = width if height is not None: args["thumb_height"] = height return args @staticmethod def _inject_caption_args(args, caption, syntax): if caption is not None: args["caption"] = caption if syntax is not None: args["parse_mode"] = syntax else: args["parse_mode"] = syntaxes.guess_syntax(caption, syntax) return args def article(self, title, content, description=None, url=None, hide_url=None, thumb_url=None, thumb_width=None, thumb_height=None, attach=None): """Render an inline article result""" args = self._get_call_args("article", title, attach, content) args = self._inject_thumb_args(args, thumb_url, thumb_width, thumb_height) if description is not None: args["description"] = description if url is not None: args["url"] = url if hide_url is not None: args["hide_url"] = hide_url return args def photo(self, file_id=None, url=None, width=None, height=None, title=None, content=None, thumb_url=None, description=None, caption=None, syntax=None, attach=None): """Render an inline photo result""" args = self._get_call_args("photo", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_thumb_args(args, thumb_url, None, None) args = self._inject_caption_args(args, caption, syntax) if description is not None: args["description"] = description if width is not None: args["photo_width"] = width if height is not None: args["photo_height"] = height return args def audio(self, file_id=None, url=None, title=None, performer=None, duration=None, caption=None, content=None, syntax=None, attach=None): """Render an inline audio result""" args = self._get_call_args("audio", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_caption_args(args, caption, syntax) if performer is not None: args["performer"] = performer if duration is not None: args["audio_duration"] = duration if caption is not None: args["caption"] = caption return args def voice(self, file_id=None, url=None, title=None, content=None, duration=None, caption=None, syntax=None, attach=None): """Render an inline voice result""" args = self._get_call_args("voice", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_caption_args(args, caption, syntax) if duration is not None: args["voice_duration"] = duration return args def video(self, file_id=None, url=None, title=None, content=None, thumb_url=None, description=None, mime_type=None, width=None, height=None, duration=None, caption=None, syntax=None, attach=None): """Render an inline video result""" args = self._get_call_args("video", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_thumb_args(args, thumb_url, None, None) args = self._inject_caption_args(args, caption, syntax) if description is not None: args["description"] = description if mime_type is not None: args["mime_type"] = mime_type if width is not None: args["video_width"] = width if height is not None: args["video_height"] = height if duration is not None: args["duration"] = duration return args def file(self, file_id=None, url=None, title=None, content=None, thumb_url=None, thumb_width=None, thumb_height=None, description=None, mime_type=None, caption=None, syntax=None, attach=None): """Render an inline document result""" args = self._get_call_args("document", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_thumb_args(args, thumb_url, thumb_width, thumb_height) args = self._inject_caption_args(args, caption, syntax) if description is not None: args["description"] = description if mime_type is not None: args["mime_type"] = mime_type return args def location(self, latitude, longitude, title, live_period=None, content=None, thumb_url=None, thumb_width=None, thumb_height=None, attach=None): """Render an inline location result""" args = self._get_call_args("location", title, attach, content) args = self._inject_thumb_args(args, thumb_url, thumb_width, thumb_height) args["latitude"] = latitude args["longitude"] = longitude args["title"] = title if live_period is not None: args["live_period"] = live_period return args def venue(self, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, content=None, thumb_url=None, thumb_width=None, thumb_height=None, attach=None): """Render an inline venue result""" args = self._get_call_args("venue", title, attach, content) args = self._inject_thumb_args(args, thumb_url, thumb_width, thumb_height) args["latitude"] = latitude args["longitude"] = longitude args["title"] = title args["address"] = address if foursquare_id is not None: args["foursquare_id"] = foursquare_id if foursquare_type is not None: args["foursquare_type"] = foursquare_type return args def sticker(self, file_id, content=None, attach=None): """Render an inline sticker result""" args = self._get_call_args("sticker", None, attach, content) args["sticker_file_id"] = file_id return args def contact(self, phone, first_name, last_name=None, vcard=None, content=None, thumb_url=None, thumb_width=None, thumb_height=None, attach=None): """Render an inline contact result""" args = self._get_call_args("contact", None, attach, content) args = self._inject_thumb_args(args, thumb_url, thumb_width, thumb_height) args["phone_number"] = phone args["first_name"] = first_name if last_name is not None: args["last_name"] = last_name if vcard is not None: args["vcard"] = vcard return args def gif(self, file_id=None, url=None, title=None, content=None, thumb_url=None, width=None, height=None, duration=None, caption=None, syntax=None, attach=None): """Render an inline gif result""" args = self._get_call_args("gif", title, attach, content) args = self._inject_file_args(args, file_id, url) args = self._inject_thumb_args(args, thumb_url, None, None) args = self._inject_caption_args(args, caption, syntax) if width is not None: args["gif_width"] = width if height is not None: args["gif_height"] = height if duration is not None: args["gif_duration"] = duration return args def mpeg4_gif(self, file_id=None, url=None, title=None, content=None, thumb_url=None, width=None, height=None, duration=None, caption=None, syntax=None, attach=None): """Render an inline Mpeg4Gif result""" args = self._get_call_args("mpeg4_gif", title, attach, content) args = self._inject_thumb_args(args, thumb_url, None, None) args = self._inject_caption_args(args, caption, syntax) if file_id is not None and url is None: args["mpeg4_file_id"] = file_id elif file_id is None and url is not None: args["mpeg4_url"] = url elif file_id is None and url is None: raise TypeError("file_id or URL is missing") else: raise TypeError("Only one among file_id and URL must be passed") if width is not None: args["mpeg4_width"] = width if height is not None: args["mpeg4_height"] = height if duration is not None: args["mpeg4_duration"] = duration return args
#!/usr/bin/env python import numpy as np import json from VOTUtils import initLogger from VOTSpectrum import VOTSpectrum from VOTResponse import VOTResponse class VOT: def __init__(self, source = "custom", input = "Plain", output = "Plain", jsonString = '[]', dataOut = False, sparseData = False, **pars): ''' There are several ways to run this code. You can provide execute it by providing it one of the built in sources to see what an example output looks like. Availalble built-ins include 'PG1553', 'Crab', 'PKS2233' and '4C5517' (you must give those exact strings. There are many options surrounding each of the custom sources (for example, you can pass a different redshift or average zenith angle). You can also define a custom source by passing 'custom' to the source variable. You'll then need to define the full spectral shape. See '--help custom' for more details. ''' self.logger = initLogger('VOT') if (input == "JSON"): jsonObject = json.loads(jsonString) pars = jsonObject[0] source = pars['source'] sources = {"PG1553" : self.calcPG1553, "Crab" : self.calcCrab, "PKS2233" : self.calcPKS2233, "4C5517" : self.calc4C5517, "custom" : self.calculateRateAndTime} sources[source](**pars) self.Print(output, dataOut, sparseData) def calculateRateAndTime(self, eMin = 0.1, eMax = 100000, Nbins = 10000, redshift = 0.1, eblModel = "Dominguez", instrument = "VERITAS", zenith = 20, spectralModel="PowerLaw", **spectralPars): ''' - custom source - This is the main way to calculates the rate in a VHE instrument based on an input spectral function. Parameter Definitions * eMin: minimum energy for the spectral calculations (GeV) * eMax: maximum energy for the spectral calculations (GeV) * Nbins: number of bins in the spectral calculations * redshift: redshift of the object * eblModel: [Dominguez, Simple, NULL]. Use 'NULL' if you don't want any EBL absorption. Try '--help EBL' for more details. * instrument: [VERITAS]. Try '--help instrument' for more details. * zenith: average zenith angle of the observations (degrees) * spectralModel: spectral shape of the source. See below for more details. * spectralPars: parameters of the spectral shape. See below for more details Details eMin/eMax: Note that the underlying algorithms use the safe energies of the experiments for the actual rate and time calculation and not these values. These are just for the underlying spectral calculations. spectralModel: can choose between many of the 2FGL spectral models along with some others. Current options inlclude [PowerLaw, PowerLaw2, BrokenPowerLaw, LogParabola, HESSExpCutoff]. Try '--help spectrum' for more details. spectralPars: the parameters of the model. In general the variable names match those as in the 2FGL models found on the FSSC website. See the underlying function VOTSpectrum.VOT for more details. All energy units should be in 'GeV' and differential fluxes in 's^-1 cm^-2 GeV^-1'. Try '--help spectrum' for more details. If running from the command line you'll need to supply all of the spectral parameters direclty there. ''' self.VS = VOTSpectrum([],[],eMin, eMax, Nbins, eblModel,redshift,spectralModel,**spectralPars) self.VR = VOTResponse(instrument,zenith=zenith, azimuth=0, noise=4.07) if(not self.VR.EASummary): return self.EACurve_interpolated = self.VR.interpolateEA(self.VS.EBins, self.VR.EACurve) self.rate = self.VR.convolveSpectrum(self.VS.EBins, self.VS.dNdE_absorbed, self.EACurve_interpolated, 10**self.VR.EASummary['minSafeE'], 10**self.VR.EASummary['maxSafeE']) def calcPG1553(self, eMin = 0.1, eMax = 100000, Nbins = 10000, eblModel="Dominguez", instrument = "VERITAS", zenith=20, **pars): '''This should return about 100 gammas/hour if you use the defaults.''' self.calculateRateAndTime(eMin, eMax, Nbins, 0.5, eblModel, instrument, zenith, spectralModel="PowerLaw", N0 = 2.6e-9, index=-1.66533, E0 = 2.4) def calcCrab(self, eMin = 0.1, eMax = 100000, Nbins = 10000, eblModel="Null", instrument = "VERITAS", zenith=20, **pars): '''This should give out on the order of 660 gammas/hour if you use the defaults.''' self.calculateRateAndTime(eMin, eMax, Nbins,0.0, eblModel, instrument, zenith, spectralModel="HESSExpCutoff", N0 = 3.76e-14, index=-2.39, E0 = 1000., EC = 14000.) def calcPKS2233(self, eMin = 0.1, eMax = 100000, Nbins=10000, eblModel="Dominguez", instrument = "VERITAS", zenith=40, **pars): '''This should give out on the order of 0.98 gammas/hour if you use the defaults.''' self.calculateRateAndTime(eMin, eMax, Nbins, 0.325, eblModel, instrument, zenith, spectralModel="PowerLaw2", N = 3.8e-9, index=-2.23955, E1 = 1.0, E2 = 100.) def calc4C5517(self, eMin = 0.1, eMax = 100000, Nbins=10000, eblModel="Dominguez", instrument = "VERITAS", zenith=20, **pars): self.calculateRateAndTime(eMin, eMax, Nbins, 0.8955, eblModel, instrument, zenith, spectralModel="LogParabola", N0 = 1.359e-11, alpha=-1.8772, beta=-0.067012, Eb = 0.9085) def Print(self, style = "Plain", dataOut = False, sparseData = False): Emin = 10**self.VR.EASummary['minSafeE'] Emax = 10**self.VR.EASummary['maxSafeE'] crabFlux = 100*self.rate*60./self.VR.crabRate detTime = np.interp([crabFlux*0.01], self.VR.SensCurve[:,0], self.VR.SensCurve[:,1]) if(style == "None"): return self.rate*60., crabFlux, detTime[0] if(style == "Plain"): self.logger.info("Using " + self.VR.EAFile) self.logger.info("Using " + self.VR.EATable) self.logger.info("Safe energy range: {:,.2f} to {:,.2f} GeV".format(Emin, Emax)) self.logger.info("dNdE at 1 GeV: {:,.2e} s^-1 cm^-2 GeV^-1".format(np.interp(1., self.VS.EBins, self.VS.dNdE))) self.logger.info("dNdE at 400 GeV: {:,.2e} s^-1 cm^-2 GeV^-1".format(np.interp(400., self.VS.EBins, self.VS.dNdE))) self.logger.info("dNdE at 1 TeV: {:,.2e} s^-1 cm^-2 GeV^-1".format(np.interp(1000., self.VS.EBins, self.VS.dNdE))) self.logger.info("tau at min safe E: {:,.2f}".format(np.interp(Emin, self.VS.EBins, self.VS.interpolated_taus[0:,0]))) self.logger.info("tau at max safe E: {:,.2f}".format(np.interp(Emax, self.VS.EBins, self.VS.interpolated_taus[0:,0]))) self.logger.info("Predicted counts/hour: {:,.2e}".format(self.rate*60.)) self.logger.info("This is approximately {:,.4f}% of the Crab Nebula's Flux".format(crabFlux)) self.logger.info("This will take approximately {:,.4f} hours to detect at a 5 sigma level".format(detTime[0])) if(style == "JSON"): if dataOut: spectrum = np.dstack((self.VS.EBins, self.VS.dNdE))[0].tolist() spectrum_abs = np.dstack((self.VS.EBins, self.VS.dNdE_absorbed))[0].tolist() tau = np.dstack((self.VS.EBins, self.VS.interpolated_taus[0:,0]))[0].tolist() ea = np.dstack((self.VS.EBins, self.EACurve_interpolated))[0].tolist() if sparseData: span = 10 else: span = 1 print json.dumps([{"EAFile" : { "unit": "file name", "value": self.VR.EAFile}, "EATable": {"unit": "table name", "value": self.VR.EATable}, "Emin": {"unit": "GeV", "value": Emin}, "Emax": {"unit": "GeV", "value": Emax}, "Rate": {"unit": "counts/hour", "value": self.rate*60.}, "Crab": {"unit": "% Crab", "value": crabFlux}, "DetTime": {"unit": "Hours", "value":detTime}}, {"name" : "Spectrum", "xaxis" : "E (GeV)", "yaxis" : "dNdE (s^-1 cm^-2 GeV^-1)", "data": spectrum[::span]}, {"name" : "Absorbed Spectrum", "xaxis" : "E (GeV)", "yaxis" : "dNdE (s^-1 cm^-2 GeV^-1)", "data": spectrum_abs[::span]}, {"name" : "Tau", "xaxis" : "E (GeV)", "yaxis" : "Tau (Arb.)", "data": tau[::span]}, {"name" : "Effective Area", "xaxis" : "E (GeV)", "yaxis" : "Area (cm^2)", "data": ea[::span]}, ]) else: print json.dumps([{"EAFile" : { "unit": "file name", "value": self.VR.EAFile}, "EATable": {"unit": "table name", "value": self.VR.EATable}, "Emin": {"unit": "GeV", "value": Emin}, "Emax": {"unit": "GeV", "value": Emax}, "Rate": {"unit": "counts/hour", "value": self.rate*60.}, "Crab": {"unit": "% Crab", "value": crabFlux}, "DetTime": {"unit": "Hours", "value":detTime[0]}}, ]) def printCLIHelp(**opts): import os import sys """This function prints out the help for the CLI.""" if(opts): if(opts["subhelp"]): if(opts["subhelp"] == "spectrum"): print VOTSpectrum.Spectrum.__doc__ elif(opts["subhelp"] == "EBL"): print VOTSpectrum.helpEBL.__doc__ elif(opts["subhelp"] == "instrument"): print VOTResponse.loadEA.__doc__ elif(opts["subhelp"] == "custom"): print VOT.calculateRateAndTime.__doc__ elif(opts["subhelp"] == "sources"): print VOT.__init__.__doc__ else: print "Unknown help option" printCLIHelp() else: cmd = os.path.basename(sys.argv[0]) print """ - VHEObserversTools - Calculate rates in a VHE detector given an input source function, a given EBL model and redshift and VHE effective areas. %s (-h|--help) ... This help text. You can also get help for specific things by typing '--help spectrum', '--help EBL', '--help instrument', '--help sources' or '--help custom'. %s (--source = <source>) ... <source> can be a built-in source ('Crab', 'PG1153', '4C5517' or 'PKS2233') or custom (user-inputed spectrum). See '--help sources' or '--help custom' for more details. %s (--input = <input>) ... <input> can be 'Plain' (default) or 'JSON'. If the input is 'JSON' you must supply a json string via the 'jsonInput' option. %s (--output = <output>) ... <output> can be 'Plain' (default) or 'JSON'. Prints the result out with plain descriptive text or as a json string. The json string also includes all of the data arrays. %s (--jsonInput = <jsonString>) ... <jsonString> is a well formatted json string used for json input. As an example, this is a json string for a custom source which could be used as input: '[{"source":"custom", "eMin":0.1, "eMax":100000, "Nbins":10000, "redshift":0.8955, "eblModel":"Dominguez","instrument":"VERITAS", "zenith":20, "spectralModel":"LogParabola", "N0":1.359e-11, "alpha":-1.8772, "beta":-0.067012, "Eb":0.9085}]' %s (--dataOut) ... If this is present, the various arrays used for calculations are outputted in the json string as three arrays. One is the spectrum, one is the absorbed spectrum, one are the tau values and the last is the effective area curve. Each json element contains a 'name' element (the name of the array), an 'xaxis' element (the name and units of the x axis variable), a 'yaxis' element (the name and units of the y axis variabl) and a 'data' element (the data as x,y pairs). %s (--sparseData) ... If this is present, the outputted data arrays will be sparse (every 10th element). """ %(cmd, cmd, cmd, cmd, cmd, cmd, cmd ) def cli(): import getopt import sys """Command line interface. Call this without any options for usage notes.""" try: opts, args = getopt.getopt(sys.argv[1:], 'h', ['help=', 'source=', 'input=', 'output=', 'jsonInput=', 'dataOut', 'sparseData', ]) source = "custom" input = "Plain" output = "Plain" jsonString = '[]' dataOut = False sparseData = False for opt, val in opts: if opt in ('-h'): printCLIHelp() if opt in ('--help'): printCLIHelp(subhelp=val) return if opt in ('--source'): source = val if opt in ('--input'): input = val if opt in ('--output'): output = val if opt in ('--jsonInput'): jsonString = val if opt in ('--dataOut'): dataOut = True if opt in ('--sparseData'): sparseData = True if not opts: raise getopt.GetoptError("Must specify an option, printing help.") VOT(source, input, output, jsonString, dataOut, sparseData) except getopt.error as e: print "Command Line Error: " + e.msg printCLIHelp() if __name__ == '__main__': cli()
import linecache import os.path import re import sys import traceback # @Reimport from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_dont_trace from _pydevd_bundle import pydevd_vars from _pydevd_bundle.pydevd_breakpoints import get_exception_breakpoint from _pydevd_bundle.pydevd_comm import CMD_STEP_CAUGHT_EXCEPTION, CMD_STEP_RETURN, CMD_STEP_OVER, CMD_SET_BREAK, \ CMD_STEP_INTO, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE, CMD_SET_NEXT_STATEMENT, CMD_STEP_INTO_MY_CODE from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, get_thread_id, STATE_RUN, dict_iter_values, IS_PY3K, \ dict_keys, RETURN_VALUES_DICT from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, just_raised, remove_exception_from_frame from _pydevd_bundle.pydevd_utils import get_clsname_for_code from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame try: from inspect import CO_GENERATOR except: CO_GENERATOR = 0 try: from _pydevd_bundle.pydevd_signature import send_signature_call_trace, send_signature_return_trace except ImportError: def send_signature_call_trace(*args, **kwargs): pass basename = os.path.basename IGNORE_EXCEPTION_TAG = re.compile('[^#]*#.*@IgnoreException') DEBUG_START = ('pydevd.py', 'run') DEBUG_START_PY3K = ('_pydev_execfile.py', 'execfile') TRACE_PROPERTY = 'pydevd_traceproperty.py' get_file_type = DONT_TRACE.get def handle_breakpoint_condition(py_db, info, breakpoint, new_frame): condition = breakpoint.condition try: return eval(condition, new_frame.f_globals, new_frame.f_locals) except: if type(condition) != type(''): if hasattr(condition, 'encode'): condition = condition.encode('utf-8') msg = 'Error while evaluating expression: %s\n' % (condition,) sys.stderr.write(msg) traceback.print_exc() if not py_db.suspend_on_breakpoint_exception: return False else: try: # add exception_type and stacktrace into thread additional info etype, value, tb = sys.exc_info() try: error = ''.join(traceback.format_exception_only(etype, value)) stack = traceback.extract_stack(f=tb.tb_frame.f_back) # On self.set_suspend(thread, CMD_SET_BREAK) this info will be # sent to the client. info.conditional_breakpoint_exception = \ ('Condition:\n' + condition + '\n\nError:\n' + error, stack) finally: etype, value, tb = None, None, None except: traceback.print_exc() return True def handle_breakpoint_expression(breakpoint, info, new_frame): try: try: val = eval(breakpoint.expression, new_frame.f_globals, new_frame.f_locals) except: val = sys.exc_info()[1] finally: if val is not None: info.pydev_message = str(val) #======================================================================================================================= # PyDBFrame #======================================================================================================================= # IFDEF CYTHON # cdef class PyDBFrame: # ELSE class PyDBFrame: '''This makes the tracing for a given frame, so, the trace_dispatch is used initially when we enter into a new context ('call') and then is reused for the entire context. ''' # ENDIF #Note: class (and not instance) attributes. #Same thing in the main debugger but only considering the file contents, while the one in the main debugger #considers the user input (so, the actual result must be a join of both). filename_to_lines_where_exceptions_are_ignored = {} filename_to_stat_info = {} # IFDEF CYTHON # cdef tuple _args # cdef int should_skip # def __init__(self, tuple args): # self._args = args # In the cython version we don't need to pass the frame # self.should_skip = -1 # On cythonized version, put in instance. # ELSE should_skip = -1 # Default value in class (put in instance on set). def __init__(self, args): #args = main_debugger, filename, base, info, t, frame #yeap, much faster than putting in self and then getting it from self later on self._args = args # ENDIF def set_suspend(self, *args, **kwargs): self._args[0].set_suspend(*args, **kwargs) def do_wait_suspend(self, *args, **kwargs): self._args[0].do_wait_suspend(*args, **kwargs) # IFDEF CYTHON # def trace_exception(self, frame, str event, arg): # cdef bint flag; # ELSE def trace_exception(self, frame, event, arg): # ENDIF if event == 'exception': flag, frame = self.should_stop_on_exception(frame, event, arg) if flag: self.handle_exception(frame, event, arg) return self.trace_dispatch return self.trace_exception def trace_return(self, frame, event, arg): if event == 'return': main_debugger, filename = self._args[0], self._args[1] send_signature_return_trace(main_debugger, frame, filename, arg) return self.trace_return # IFDEF CYTHON # def should_stop_on_exception(self, frame, str event, arg): # cdef PyDBAdditionalThreadInfo info; # cdef bint flag; # ELSE def should_stop_on_exception(self, frame, event, arg): # ENDIF # main_debugger, _filename, info, _thread = self._args main_debugger = self._args[0] info = self._args[2] flag = False # STATE_SUSPEND = 2 if info.pydev_state != 2: #and breakpoint is not None: exception, value, trace = arg if trace is not None: #on jython trace is None on the first event exception_breakpoint = get_exception_breakpoint( exception, main_debugger.break_on_caught_exceptions) if exception_breakpoint is not None: add_exception_to_frame(frame, (exception, value, trace)) if exception_breakpoint.condition is not None: eval_result = handle_breakpoint_condition(main_debugger, info, exception_breakpoint, frame) if not eval_result: return False, frame if exception_breakpoint.ignore_libraries: if exception_breakpoint.notify_on_first_raise_only: if main_debugger.first_appearance_in_scope(trace): add_exception_to_frame(frame, (exception, value, trace)) try: info.pydev_message = exception_breakpoint.qname except: info.pydev_message = exception_breakpoint.qname.encode('utf-8') flag = True else: pydev_log.debug("Ignore exception %s in library %s" % (exception, frame.f_code.co_filename)) flag = False else: if not exception_breakpoint.notify_on_first_raise_only or just_raised(trace): add_exception_to_frame(frame, (exception, value, trace)) try: info.pydev_message = exception_breakpoint.qname except: info.pydev_message = exception_breakpoint.qname.encode('utf-8') flag = True else: flag = False else: try: if main_debugger.plugin is not None: result = main_debugger.plugin.exception_break(main_debugger, self, frame, self._args, arg) if result: flag, frame = result except: flag = False if flag: if exception_breakpoint is not None and exception_breakpoint.expression is not None: handle_breakpoint_expression(exception_breakpoint, info, frame) else: remove_exception_from_frame(frame) return flag, frame def handle_exception(self, frame, event, arg): try: # print 'handle_exception', frame.f_lineno, frame.f_code.co_name # We have 3 things in arg: exception type, description, traceback object trace_obj = arg[2] main_debugger = self._args[0] if not hasattr(trace_obj, 'tb_next'): return #Not always there on Jython... initial_trace_obj = trace_obj if trace_obj.tb_next is None and trace_obj.tb_frame is frame: #I.e.: tb_next should be only None in the context it was thrown (trace_obj.tb_frame is frame is just a double check). if main_debugger.break_on_exceptions_thrown_in_same_context: #Option: Don't break if an exception is caught in the same function from which it is thrown return else: #Get the trace_obj from where the exception was raised... while trace_obj.tb_next is not None: trace_obj = trace_obj.tb_next if main_debugger.ignore_exceptions_thrown_in_lines_with_ignore_exception: for check_trace_obj in (initial_trace_obj, trace_obj): filename = get_abs_path_real_path_and_base_from_frame(check_trace_obj.tb_frame)[1] filename_to_lines_where_exceptions_are_ignored = self.filename_to_lines_where_exceptions_are_ignored lines_ignored = filename_to_lines_where_exceptions_are_ignored.get(filename) if lines_ignored is None: lines_ignored = filename_to_lines_where_exceptions_are_ignored[filename] = {} try: curr_stat = os.stat(filename) curr_stat = (curr_stat.st_size, curr_stat.st_mtime) except: curr_stat = None last_stat = self.filename_to_stat_info.get(filename) if last_stat != curr_stat: self.filename_to_stat_info[filename] = curr_stat lines_ignored.clear() try: linecache.checkcache(filename) except: #Jython 2.1 linecache.checkcache() from_user_input = main_debugger.filename_to_lines_where_exceptions_are_ignored.get(filename) if from_user_input: merged = {} merged.update(lines_ignored) #Override what we have with the related entries that the user entered merged.update(from_user_input) else: merged = lines_ignored exc_lineno = check_trace_obj.tb_lineno # print ('lines ignored', lines_ignored) # print ('user input', from_user_input) # print ('merged', merged, 'curr', exc_lineno) if exc_lineno not in merged: #Note: check on merged but update lines_ignored. try: line = linecache.getline(filename, exc_lineno, check_trace_obj.tb_frame.f_globals) except: #Jython 2.1 line = linecache.getline(filename, exc_lineno) if IGNORE_EXCEPTION_TAG.match(line) is not None: lines_ignored[exc_lineno] = 1 return else: #Put in the cache saying not to ignore lines_ignored[exc_lineno] = 0 else: #Ok, dict has it already cached, so, let's check it... if merged.get(exc_lineno, 0): return thread = self._args[3] try: frame_id_to_frame = {} frame_id_to_frame[id(frame)] = frame f = trace_obj.tb_frame while f is not None: frame_id_to_frame[id(f)] = f f = f.f_back f = None thread_id = get_thread_id(thread) pydevd_vars.add_additional_frame_by_id(thread_id, frame_id_to_frame) try: main_debugger.send_caught_exception_stack(thread, arg, id(frame)) self.set_suspend(thread, CMD_STEP_CAUGHT_EXCEPTION) self.do_wait_suspend(thread, frame, event, arg) main_debugger.send_caught_exception_stack_proceeded(thread) finally: pydevd_vars.remove_additional_frame_by_id(thread_id) except: traceback.print_exc() main_debugger.set_trace_for_frame_and_parents(frame) finally: #Clear some local variables... trace_obj = None initial_trace_obj = None check_trace_obj = None f = None frame_id_to_frame = None main_debugger = None thread = None def get_func_name(self, frame): code_obj = frame.f_code func_name = code_obj.co_name try: cls_name = get_clsname_for_code(code_obj, frame) if cls_name is not None: return "%s.%s" % (cls_name, func_name) else: return func_name except: traceback.print_exc() return func_name def manage_return_values(self, main_debugger, frame, event, arg): def get_func_name(frame): code_obj = frame.f_code func_name = code_obj.co_name try: cls_name = get_clsname_for_code(code_obj, frame) if cls_name is not None: return "%s.%s" % (cls_name, func_name) else: return func_name except: traceback.print_exc() return func_name try: if main_debugger.show_return_values: if event == "return" and hasattr(frame, "f_code") and hasattr(frame.f_code, "co_name"): if hasattr(frame, "f_back") and hasattr(frame.f_back, "f_locals"): if RETURN_VALUES_DICT not in dict_keys(frame.f_back.f_locals): frame.f_back.f_locals[RETURN_VALUES_DICT] = {} name = get_func_name(frame) frame.f_back.f_locals[RETURN_VALUES_DICT][name] = arg if main_debugger.remove_return_values_flag: # Showing return values was turned off, we should remove them from locals dict. # The values can be in the current frame or in the back one if RETURN_VALUES_DICT in dict_keys(frame.f_locals): frame.f_locals.pop(RETURN_VALUES_DICT) if hasattr(frame, "f_back") and hasattr(frame.f_back, "f_locals"): if RETURN_VALUES_DICT in dict_keys(frame.f_back.f_locals): frame.f_back.f_locals.pop(RETURN_VALUES_DICT) main_debugger.remove_return_values_flag = False except: main_debugger.remove_return_values_flag = False traceback.print_exc() # IFDEF CYTHON # cpdef trace_dispatch(self, frame, str event, arg): # cdef str filename; # cdef bint is_exception_event; # cdef bint has_exception_breakpoints; # cdef bint can_skip; # cdef PyDBAdditionalThreadInfo info; # cdef int step_cmd; # cdef int line; # cdef bint is_line; # cdef bint is_call; # cdef bint is_return; # cdef str curr_func_name; # cdef bint exist_result; # cdef bint stop; # cdef dict frame_skips_cache; # cdef tuple frame_cache_key; # cdef tuple line_cache_key; # cdef int breakpoints_in_line_cache; # cdef int breakpoints_in_frame_cache; # cdef bint has_breakpoint_in_frame; # ELSE def trace_dispatch(self, frame, event, arg): # ENDIF main_debugger, filename, info, thread, frame_skips_cache, frame_cache_key = self._args # print('frame trace_dispatch', frame.f_lineno, frame.f_code.co_name, event, info.pydev_step_cmd) try: info.is_tracing = True line = frame.f_lineno line_cache_key = (frame_cache_key, line) if main_debugger._finish_debugging_session: return None plugin_manager = main_debugger.plugin is_exception_event = event == 'exception' has_exception_breakpoints = main_debugger.break_on_caught_exceptions or main_debugger.has_plugin_exception_breaks if is_exception_event: if has_exception_breakpoints: flag, frame = self.should_stop_on_exception(frame, event, arg) if flag: self.handle_exception(frame, event, arg) return self.trace_dispatch is_line = False is_return = False is_call = False else: is_line = event == 'line' is_return = event == 'return' is_call = event == 'call' if not is_line and not is_return and not is_call: # I believe this can only happen in jython on some frontiers on jython and java code, which we don't want to trace. return None need_trace_return = False if is_call and main_debugger.signature_factory: need_trace_return = send_signature_call_trace(main_debugger, frame, filename) if is_return and main_debugger.signature_factory: send_signature_return_trace(main_debugger, frame, filename, arg) stop_frame = info.pydev_step_stop step_cmd = info.pydev_step_cmd if is_exception_event: breakpoints_for_file = None # CMD_STEP_OVER = 108 if stop_frame and stop_frame is not frame and step_cmd == 108 and \ arg[0] in (StopIteration, GeneratorExit) and arg[2] is None: info.pydev_step_cmd = 107 # CMD_STEP_INTO = 107 info.pydev_step_stop = None else: # If we are in single step mode and something causes us to exit the current frame, we need to make sure we break # eventually. Force the step mode to step into and the step stop frame to None. # I.e.: F6 in the end of a function should stop in the next possible position (instead of forcing the user # to make a step in or step over at that location). # Note: this is especially troublesome when we're skipping code with the # @DontTrace comment. if stop_frame is frame and is_return and step_cmd in (109, 108): # CMD_STEP_RETURN = 109, CMD_STEP_OVER = 108 if not frame.f_code.co_flags & 0x20: # CO_GENERATOR = 0x20 (inspect.CO_GENERATOR) info.pydev_step_cmd = 107 # CMD_STEP_INTO = 107 info.pydev_step_stop = None breakpoints_for_file = main_debugger.breakpoints.get(filename) can_skip = False if info.pydev_state == 1: # STATE_RUN = 1 #we can skip if: #- we have no stop marked #- we should make a step return/step over and we're not in the current frame # CMD_STEP_RETURN = 109, CMD_STEP_OVER = 108 can_skip = (step_cmd == -1 and stop_frame is None) \ or (step_cmd in (109, 108) and stop_frame is not frame) if can_skip: if plugin_manager is not None and main_debugger.has_plugin_line_breaks: can_skip = not plugin_manager.can_not_skip(main_debugger, self, frame) # CMD_STEP_OVER = 108 if can_skip and is_return and main_debugger.show_return_values and info.pydev_step_cmd == 108 and frame.f_back is info.pydev_step_stop: # trace function for showing return values after step over can_skip = False # Let's check to see if we are in a function that has a breakpoint. If we don't have a breakpoint, # we will return nothing for the next trace # also, after we hit a breakpoint and go to some other debugging state, we have to force the set trace anyway, # so, that's why the additional checks are there. if not breakpoints_for_file: if can_skip: if has_exception_breakpoints: return self.trace_exception else: if need_trace_return: return self.trace_return else: return None else: # When cached, 0 means we don't have a breakpoint and 1 means we have. if can_skip: breakpoints_in_line_cache = frame_skips_cache.get(line_cache_key, -1) if breakpoints_in_line_cache == 0: return self.trace_dispatch breakpoints_in_frame_cache = frame_skips_cache.get(frame_cache_key, -1) if breakpoints_in_frame_cache != -1: # Gotten from cache. has_breakpoint_in_frame = breakpoints_in_frame_cache == 1 else: has_breakpoint_in_frame = False # Checks the breakpoint to see if there is a context match in some function curr_func_name = frame.f_code.co_name #global context is set with an empty name if curr_func_name in ('?', '<module>'): curr_func_name = '' for breakpoint in dict_iter_values(breakpoints_for_file): #jython does not support itervalues() #will match either global or some function if breakpoint.func_name in ('None', curr_func_name): has_breakpoint_in_frame = True break # Cache the value (1 or 0 or -1 for default because of cython). if has_breakpoint_in_frame: frame_skips_cache[frame_cache_key] = 1 else: frame_skips_cache[frame_cache_key] = 0 if can_skip and not has_breakpoint_in_frame: if has_exception_breakpoints: return self.trace_exception else: if need_trace_return: return self.trace_return else: return None #We may have hit a breakpoint or we are already in step mode. Either way, let's check what we should do in this frame #print('NOT skipped', frame.f_lineno, frame.f_code.co_name, event) try: flag = False #return is not taken into account for breakpoint hit because we'd have a double-hit in this case #(one for the line and the other for the return). stop_info = {} breakpoint = None exist_result = False stop = False bp_type = None if not is_return and info.pydev_state != STATE_SUSPEND and breakpoints_for_file is not None and line in breakpoints_for_file: breakpoint = breakpoints_for_file[line] new_frame = frame stop = True if step_cmd == CMD_STEP_OVER and stop_frame is frame and (is_line or is_return): stop = False #we don't stop on breakpoint if we have to stop by step-over (it will be processed later) elif plugin_manager is not None and main_debugger.has_plugin_line_breaks: result = plugin_manager.get_breakpoint(main_debugger, self, frame, event, self._args) if result: exist_result = True flag, breakpoint, new_frame, bp_type = result if breakpoint: #ok, hit breakpoint, now, we have to discover if it is a conditional breakpoint # lets do the conditional stuff here if stop or exist_result: condition = breakpoint.condition if condition is not None: eval_result = handle_breakpoint_condition(main_debugger, info, breakpoint, new_frame) if not eval_result: return self.trace_dispatch if breakpoint.expression is not None: handle_breakpoint_expression(breakpoint, info, new_frame) if not main_debugger.first_breakpoint_reached: if is_call: back = frame.f_back if back is not None: # When we start debug session, we call execfile in pydevd run function. It produces an additional # 'call' event for tracing and we stop on the first line of code twice. _, back_filename, base = get_abs_path_real_path_and_base_from_frame(back) if (base == DEBUG_START[0] and back.f_code.co_name == DEBUG_START[1]) or \ (base == DEBUG_START_PY3K[0] and back.f_code.co_name == DEBUG_START_PY3K[1]): stop = False main_debugger.first_breakpoint_reached = True else: # if the frame is traced after breakpoint stop, # but the file should be ignored while stepping because of filters if step_cmd != -1: if main_debugger.is_filter_enabled and main_debugger.is_ignored_by_filters(filename): # ignore files matching stepping filters return self.trace_dispatch if main_debugger.is_filter_libraries and main_debugger.not_in_scope(filename): # ignore library files while stepping return self.trace_dispatch if main_debugger.show_return_values or main_debugger.remove_return_values_flag: self.manage_return_values(main_debugger, frame, event, arg) if stop: self.set_suspend(thread, CMD_SET_BREAK) if breakpoint and breakpoint.suspend_policy == "ALL": main_debugger.suspend_all_other_threads(thread) elif flag and plugin_manager is not None: result = plugin_manager.suspend(main_debugger, thread, frame, bp_type) if result: frame = result # if thread has a suspend flag, we suspend with a busy wait if info.pydev_state == STATE_SUSPEND: self.do_wait_suspend(thread, frame, event, arg) return self.trace_dispatch else: if breakpoint is None and not (is_return or is_exception_event): # No stop from anyone and no breakpoint found in line (cache that). frame_skips_cache[line_cache_key] = 0 except: traceback.print_exc() raise #step handling. We stop when we hit the right frame try: should_skip = 0 if pydevd_dont_trace.should_trace_hook is not None: if self.should_skip == -1: # I.e.: cache the result on self.should_skip (no need to evaluate the same frame multiple times). # Note that on a code reload, we won't re-evaluate this because in practice, the frame.f_code # Which will be handled by this frame is read-only, so, we can cache it safely. if not pydevd_dont_trace.should_trace_hook(frame, filename): # -1, 0, 1 to be Cython-friendly should_skip = self.should_skip = 1 else: should_skip = self.should_skip = 0 else: should_skip = self.should_skip plugin_stop = False if should_skip: stop = False elif step_cmd == CMD_STEP_INTO: stop = is_line or is_return if plugin_manager is not None: result = plugin_manager.cmd_step_into(main_debugger, frame, event, self._args, stop_info, stop) if result: stop, plugin_stop = result elif step_cmd == CMD_STEP_INTO_MY_CODE: if not main_debugger.not_in_scope(frame.f_code.co_filename): stop = is_line elif step_cmd == CMD_STEP_OVER: stop = stop_frame is frame and (is_line or is_return) if frame.f_code.co_flags & CO_GENERATOR: if is_return: stop = False if plugin_manager is not None: result = plugin_manager.cmd_step_over(main_debugger, frame, event, self._args, stop_info, stop) if result: stop, plugin_stop = result elif step_cmd == CMD_SMART_STEP_INTO: stop = False if info.pydev_smart_step_stop is frame: info.pydev_func_name = '.invalid.' # Must match the type in cython info.pydev_smart_step_stop = None if is_line or is_exception_event: curr_func_name = frame.f_code.co_name #global context is set with an empty name if curr_func_name in ('?', '<module>') or curr_func_name is None: curr_func_name = '' if curr_func_name == info.pydev_func_name: stop = True elif step_cmd == CMD_STEP_RETURN: stop = is_return and stop_frame is frame elif step_cmd == CMD_RUN_TO_LINE or step_cmd == CMD_SET_NEXT_STATEMENT: try: stop, _, response_msg = main_debugger.set_next_statement(frame, event, info.pydev_func_name, info.pydev_next_line) except ValueError: pass else: stop = False if stop and step_cmd != -1 and is_return and IS_PY3K and hasattr(frame, "f_back"): f_code = getattr(frame.f_back, 'f_code', None) if f_code is not None: back_filename = os.path.basename(f_code.co_filename) file_type = get_file_type(back_filename) if file_type == PYDEV_FILE: stop = False if plugin_stop: stopped_on_plugin = plugin_manager.stop(main_debugger, frame, event, self._args, stop_info, arg, step_cmd) elif stop: if is_line: self.set_suspend(thread, step_cmd) self.do_wait_suspend(thread, frame, event, arg) else: #return event back = frame.f_back if back is not None: #When we get to the pydevd run function, the debugging has actually finished for the main thread #(note that it can still go on for other threads, but for this one, we just make it finish) #So, just setting it to None should be OK _, back_filename, base = get_abs_path_real_path_and_base_from_frame(back) if base == DEBUG_START[0] and back.f_code.co_name == DEBUG_START[1]: back = None elif base == TRACE_PROPERTY: # We dont want to trace the return event of pydevd_traceproperty (custom property for debugging) #if we're in a return, we want it to appear to the user in the previous frame! return None elif pydevd_dont_trace.should_trace_hook is not None: if not pydevd_dont_trace.should_trace_hook(back, back_filename): # In this case, we'll have to skip the previous one because it shouldn't be traced. # Also, we have to reset the tracing, because if the parent's parent (or some # other parent) has to be traced and it's not currently, we wouldn't stop where # we should anymore (so, a step in/over/return may not stop anywhere if no parent is traced). # Related test: _debugger_case17a.py main_debugger.set_trace_for_frame_and_parents(back, overwrite_prev_trace=True) return None if back is not None: #if we're in a return, we want it to appear to the user in the previous frame! self.set_suspend(thread, step_cmd) self.do_wait_suspend(thread, back, event, arg) else: #in jython we may not have a back frame info.pydev_step_stop = None info.pydev_step_cmd = -1 info.pydev_state = STATE_RUN except KeyboardInterrupt: raise except: try: traceback.print_exc() info.pydev_step_cmd = -1 except: return None #if we are quitting, let's stop the tracing retVal = None if not main_debugger.quitting: retVal = self.trace_dispatch return retVal finally: info.is_tracing = False #end trace_dispatch
import re import typing as t import warnings from .user_agent import UserAgent as _BaseUserAgent if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment class _UserAgentParser: platform_rules: t.ClassVar[t.Iterable[t.Tuple[str, str]]] = ( (" cros ", "chromeos"), ("iphone|ios", "iphone"), ("ipad", "ipad"), (r"darwin\b|mac\b|os\s*x", "macos"), ("win", "windows"), (r"android", "android"), ("netbsd", "netbsd"), ("openbsd", "openbsd"), ("freebsd", "freebsd"), ("dragonfly", "dragonflybsd"), ("(sun|i86)os", "solaris"), (r"x11\b|lin(\b|ux)?", "linux"), (r"nintendo\s+wii", "wii"), ("irix", "irix"), ("hp-?ux", "hpux"), ("aix", "aix"), ("sco|unix_sv", "sco"), ("bsd", "bsd"), ("amiga", "amiga"), ("blackberry|playbook", "blackberry"), ("symbian", "symbian"), ) browser_rules: t.ClassVar[t.Iterable[t.Tuple[str, str]]] = ( ("googlebot", "google"), ("msnbot", "msn"), ("yahoo", "yahoo"), ("ask jeeves", "ask"), (r"aol|america\s+online\s+browser", "aol"), (r"opera|opr", "opera"), ("edge|edg", "edge"), ("chrome|crios", "chrome"), ("seamonkey", "seamonkey"), ("firefox|firebird|phoenix|iceweasel", "firefox"), ("galeon", "galeon"), ("safari|version", "safari"), ("webkit", "webkit"), ("camino", "camino"), ("konqueror", "konqueror"), ("k-meleon", "kmeleon"), ("netscape", "netscape"), (r"msie|microsoft\s+internet\s+explorer|trident/.+? rv:", "msie"), ("lynx", "lynx"), ("links", "links"), ("Baiduspider", "baidu"), ("bingbot", "bing"), ("mozilla", "mozilla"), ) _browser_version_re = r"(?:{pattern})[/\sa-z(]*(\d+[.\da-z]+)?" _language_re = re.compile( r"(?:;\s*|\s+)(\b\w{2}\b(?:-\b\w{2}\b)?)\s*;|" r"(?:\(|\[|;)\s*(\b\w{2}\b(?:-\b\w{2}\b)?)\s*(?:\]|\)|;)" ) def __init__(self) -> None: self.platforms = [(b, re.compile(a, re.I)) for a, b in self.platform_rules] self.browsers = [ (b, re.compile(self._browser_version_re.format(pattern=a), re.I)) for a, b in self.browser_rules ] def __call__( self, user_agent: str ) -> t.Tuple[t.Optional[str], t.Optional[str], t.Optional[str], t.Optional[str]]: platform: t.Optional[str] browser: t.Optional[str] version: t.Optional[str] language: t.Optional[str] for platform, regex in self.platforms: # noqa: B007 match = regex.search(user_agent) if match is not None: break else: platform = None # Except for Trident, all browser key words come after the last ')' last_closing_paren = 0 if ( not re.compile(r"trident/.+? rv:", re.I).search(user_agent) and ")" in user_agent and user_agent[-1] != ")" ): last_closing_paren = user_agent.rindex(")") for browser, regex in self.browsers: # noqa: B007 match = regex.search(user_agent[last_closing_paren:]) if match is not None: version = match.group(1) break else: browser = version = None match = self._language_re.search(user_agent) if match is not None: language = match.group(1) or match.group(2) else: language = None return platform, browser, version, language # It wasn't public, but users might have imported it anyway, show a # warning if a user created an instance. class UserAgentParser(_UserAgentParser): """A simple user agent parser. Used by the `UserAgent`. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use a dedicated parser library instead. """ def __init__(self) -> None: warnings.warn( "'UserAgentParser' is deprecated and will be removed in" " Werkzeug 2.1. Use a dedicated parser library instead.", DeprecationWarning, stacklevel=2, ) super().__init__() class _deprecated_property(property): def __init__(self, fget: t.Callable[["_UserAgent"], t.Any]) -> None: super().__init__(fget) self.message = ( "The built-in user agent parser is deprecated and will be" f" removed in Werkzeug 2.1. The {fget.__name__!r} property" " will be 'None'. Subclass 'werkzeug.user_agent.UserAgent'" " and set 'Request.user_agent_class' to use a different" " parser." ) def __get__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: warnings.warn(self.message, DeprecationWarning, stacklevel=3) return super().__get__(*args, **kwargs) # This is what Request.user_agent returns for now, only show warnings on # attribute access, not creation. class _UserAgent(_BaseUserAgent): _parser = _UserAgentParser() def __init__(self, string: str) -> None: super().__init__(string) info = self._parser(string) self._platform, self._browser, self._version, self._language = info @_deprecated_property def platform(self) -> t.Optional[str]: # type: ignore return self._platform @_deprecated_property def browser(self) -> t.Optional[str]: # type: ignore return self._browser @_deprecated_property def version(self) -> t.Optional[str]: # type: ignore return self._version @_deprecated_property def language(self) -> t.Optional[str]: # type: ignore return self._language # This is what users might be importing, show warnings on create. class UserAgent(_UserAgent): """Represents a parsed user agent header value. This uses a basic parser to try to extract some information from the header. :param environ_or_string: The header value to parse, or a WSGI environ containing the header. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Subclass :class:`werkzeug.user_agent.UserAgent` (note the new module name) to use a dedicated parser instead. .. versionchanged:: 2.0 Passing a WSGI environ is deprecated and will be removed in 2.1. """ def __init__(self, environ_or_string: "t.Union[str, WSGIEnvironment]") -> None: if isinstance(environ_or_string, dict): warnings.warn( "Passing an environ to 'UserAgent' is deprecated and" " will be removed in Werkzeug 2.1. Pass the header" " value string instead.", DeprecationWarning, stacklevel=2, ) string = environ_or_string.get("HTTP_USER_AGENT", "") else: string = environ_or_string warnings.warn( "The 'werkzeug.useragents' module is deprecated and will be" " removed in Werkzeug 2.1. The new base API is" " 'werkzeug.user_agent.UserAgent'.", DeprecationWarning, stacklevel=2, ) super().__init__(string)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 base64 from datetime import datetime import eventlet from eventlet.support import greenlets as greenlet from heat.engine import event from heat.common import exception from heat.db import api as db_api from heat.common import identifier from heat.engine import timestamp from heat.engine.properties import Properties from heat.openstack.common import log as logging logger = logging.getLogger(__name__) _resource_classes = {} def get_types(): '''Return an iterator over the list of valid resource types''' return iter(_resource_classes) def get_class(resource_type): '''Return the Resource class for a given resource type''' cls = _resource_classes.get(resource_type) if cls is None: msg = "Unknown resource Type : %s" % resource_type raise exception.StackValidationFailed(message=msg) else: return cls def _register_class(resource_type, resource_class): logger.info(_('Registering resource type %s') % resource_type) if resource_type in _resource_classes: logger.warning(_('Replacing existing resource type %s') % resource_type) _resource_classes[resource_type] = resource_class class Metadata(object): ''' A descriptor for accessing the metadata of a resource while ensuring the most up-to-date data is always obtained from the database. ''' def __get__(self, resource, resource_class): '''Return the metadata for the owning resource.''' if resource is None: return None if resource.id is None: return resource.parsed_template('Metadata') rs = db_api.resource_get(resource.stack.context, resource.id) rs.refresh(attrs=['rsrc_metadata']) return rs.rsrc_metadata def __set__(self, resource, metadata): '''Update the metadata for the owning resource.''' if resource.id is None: raise exception.ResourceNotAvailable(resource_name=resource.name) rs = db_api.resource_get(resource.stack.context, resource.id) rs.update_and_save({'rsrc_metadata': metadata}) class Resource(object): # Status strings CREATE_IN_PROGRESS = 'IN_PROGRESS' CREATE_FAILED = 'CREATE_FAILED' CREATE_COMPLETE = 'CREATE_COMPLETE' DELETE_IN_PROGRESS = 'DELETE_IN_PROGRESS' DELETE_FAILED = 'DELETE_FAILED' DELETE_COMPLETE = 'DELETE_COMPLETE' UPDATE_IN_PROGRESS = 'UPDATE_IN_PROGRESS' UPDATE_FAILED = 'UPDATE_FAILED' UPDATE_COMPLETE = 'UPDATE_COMPLETE' # Status values, returned from subclasses to indicate update method UPDATE_REPLACE = 'UPDATE_REPLACE' UPDATE_INTERRUPTION = 'UPDATE_INTERRUPTION' UPDATE_NO_INTERRUPTION = 'UPDATE_NO_INTERRUPTION' UPDATE_NOT_IMPLEMENTED = 'UPDATE_NOT_IMPLEMENTED' # If True, this resource must be created before it can be referenced. strict_dependency = True created_time = timestamp.Timestamp(db_api.resource_get, 'created_at') updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at') metadata = Metadata() # Resource implementation set this to the subset of template keys # which are supported for handle_update, used by update_template_diff update_allowed_keys = () # Resource implementation set this to the subset of resource properties # supported for handle_update, used by update_template_diff_properties update_allowed_properties = () def __new__(cls, name, json, stack): '''Create a new Resource of the appropriate class for its type.''' if cls != Resource: # Call is already for a subclass, so pass it through return super(Resource, cls).__new__(cls) # Select the correct subclass to instantiate ResourceClass = get_class(json['Type']) return ResourceClass(name, json, stack) def __init__(self, name, json_snippet, stack): if '/' in name: raise ValueError(_('Resource name may not contain "/"')) self.stack = stack self.context = stack.context self.name = name self.json_snippet = json_snippet self.t = stack.resolve_static_data(json_snippet) self.cached_t = None self.properties = Properties(self.properties_schema, self.t.get('Properties', {}), self.stack.resolve_runtime_data, self.name) resource = db_api.resource_get_by_name_and_stack(self.context, name, stack.id) if resource: self.resource_id = resource.nova_instance self.state = resource.state self.state_description = resource.state_description self.id = resource.id else: self.resource_id = None self.state = None self.state_description = '' self.id = None def __eq__(self, other): '''Allow == comparison of two resources''' # For the purposes of comparison, we declare two resource objects # equal if their names and parsed_templates are the same if isinstance(other, Resource): return (self.name == other.name) and ( self.parsed_template() == other.parsed_template()) return NotImplemented def __ne__(self, other): '''Allow != comparison of two resources''' result = self.__eq__(other) if result is NotImplemented: return result return not result def type(self): return self.t['Type'] def identifier(self): '''Return an identifier for this resource''' return identifier.ResourceIdentifier(resource_name=self.name, **self.stack.identifier()) def parsed_template(self, section=None, default={}, cached=False): ''' Return the parsed template data for the resource. May be limited to only one section of the data, in which case a default value may also be supplied. ''' if cached and self.cached_t: t = self.cached_t else: t = self.t if section is None: template = t else: template = t.get(section, default) return self.stack.resolve_runtime_data(template) def cache_template(self): ''' make a cache of the resource's parsed template this can then be used via parsed_template(cached=True) ''' self.cached_t = self.stack.resolve_runtime_data(self.t) def update_template_diff(self, json_snippet=None): ''' Returns the difference between json_template and self.t If something has been removed in json_snippet which exists in self.t we set it to None. If any keys have changed which are not in update_allowed_keys, raises NotImplementedError ''' update_allowed_set = set(self.update_allowed_keys) # Create a set containing the keys in both current and update template current_template = self.parsed_template(cached=True) template_keys = set(current_template.keys()) new_template = self.stack.resolve_runtime_data(json_snippet) template_keys.update(set(new_template.keys())) # Create a set of keys which differ (or are missing/added) changed_keys_set = set([k for k in template_keys if current_template.get(k) != new_template.get(k)]) if not changed_keys_set.issubset(update_allowed_set): badkeys = changed_keys_set - update_allowed_set raise NotImplementedError("Cannot update keys %s for %s" % (badkeys, self.name)) return dict((k, new_template.get(k)) for k in changed_keys_set) def update_template_diff_properties(self, json_snippet=None): ''' Returns the changed Properties between json_template and self.t If a property has been removed in json_snippet which exists in self.t we set it to None. If any properties have changed which are not in update_allowed_properties, raises NotImplementedError ''' update_allowed_set = set(self.update_allowed_properties) # Create a set containing the keys in both current and update template tmpl = self.parsed_template(cached=True) current_properties = tmpl.get('Properties', {}) template_properties = set(current_properties.keys()) updated_properties = json_snippet.get('Properties', {}) template_properties.update(set(updated_properties.keys())) # Create a set of keys which differ (or are missing/added) changed_properties_set = set(k for k in template_properties if current_properties.get(k) != updated_properties.get(k)) if not changed_properties_set.issubset(update_allowed_set): badkeys = changed_properties_set - update_allowed_set raise NotImplementedError("Cannot update properties %s for %s" % (badkeys, self.name)) return dict((k, updated_properties.get(k)) for k in changed_properties_set) def __str__(self): return '%s "%s"' % (self.__class__.__name__, self.name) def _add_dependencies(self, deps, fragment): if isinstance(fragment, dict): for key, value in fragment.items(): if key in ('DependsOn', 'Ref'): target = self.stack.resources[value] if key == 'DependsOn' or target.strict_dependency: deps += (self, target) elif key != 'Fn::GetAtt': self._add_dependencies(deps, value) elif isinstance(fragment, list): for item in fragment: self._add_dependencies(deps, item) def add_dependencies(self, deps): self._add_dependencies(deps, self.t) deps += (self, None) def keystone(self): return self.stack.clients.keystone() def nova(self, service_type='compute'): return self.stack.clients.nova(service_type) def swift(self): return self.stack.clients.swift() def quantum(self): return self.stack.clients.quantum() def cinder(self): return self.stack.clients.cinder() def create(self): ''' Create the resource. Subclasses should provide a handle_create() method to customise creation. ''' if self.state in (self.CREATE_IN_PROGRESS, self.CREATE_COMPLETE): return 'Resource creation already requested' logger.info('creating %s' % str(self)) # Re-resolve the template, since if the resource Ref's # the AWS::StackId pseudo parameter, it will change after # the parser.Stack is stored (which is after the resources # are __init__'d, but before they are create()'d) self.t = self.stack.resolve_static_data(self.json_snippet) self.properties = Properties(self.properties_schema, self.t.get('Properties', {}), self.stack.resolve_runtime_data, self.name) try: self.properties.validate() self.state_set(self.CREATE_IN_PROGRESS) if callable(getattr(self, 'handle_create', None)): self.handle_create() while not self.check_active(): eventlet.sleep(1) except greenlet.GreenletExit: raise except Exception as ex: logger.exception('create %s', str(self)) self.state_set(self.CREATE_FAILED, str(ex)) return str(ex) or "Error : %s" % type(ex) else: self.state_set(self.CREATE_COMPLETE) def check_active(self): ''' Check if the resource is active (ready to move to the CREATE_COMPLETE state). By default this happens as soon as the handle_create() method has completed successfully, but subclasses may customise this by overriding this function. ''' return True def update(self, json_snippet=None): ''' update the resource. Subclasses should provide a handle_update() method to customise update, the base-class handle_update will fail by default. ''' if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS): return 'Resource update already requested' if not json_snippet: return 'Must specify json snippet for resource update!' logger.info('updating %s' % str(self)) result = self.UPDATE_NOT_IMPLEMENTED try: self.state_set(self.UPDATE_IN_PROGRESS) properties = Properties(self.properties_schema, json_snippet.get('Properties', {}), self.stack.resolve_runtime_data, self.name) properties.validate() if callable(getattr(self, 'handle_update', None)): result = self.handle_update(json_snippet) except Exception as ex: logger.exception('update %s : %s' % (str(self), str(ex))) self.state_set(self.UPDATE_FAILED, str(ex)) return str(ex) or "Error : %s" % type(ex) else: # If resource was updated (with or without interruption), # then we set the resource to UPDATE_COMPLETE if not result == self.UPDATE_REPLACE: self.t = self.stack.resolve_static_data(json_snippet) self.state_set(self.UPDATE_COMPLETE) return result def physical_resource_name(self): return '%s.%s' % (self.stack.name, self.name) def physical_resource_name_find(self, resource_name): if resource_name in self.stack: return '%s.%s' % (self.stack.name, resource_name) else: raise IndexError('no such resource') def validate(self): logger.info('Validating %s' % str(self)) return self.properties.validate() def delete(self): ''' Delete the resource. Subclasses should provide a handle_delete() method to customise deletion. ''' if self.state == self.DELETE_COMPLETE: return if self.state == self.DELETE_IN_PROGRESS: return 'Resource deletion already in progress' if self.state == self.CREATE_FAILED: return # Further resources will not be created in a CREATE_FAILED stack. # The state of these resources is None. Do not delete as an # undeleteable stack will result if self.state is None: return logger.info('deleting %s (inst:%s db_id:%s)' % (str(self), self.resource_id, str(self.id))) self.state_set(self.DELETE_IN_PROGRESS) try: if callable(getattr(self, 'handle_delete', None)): self.handle_delete() except Exception as ex: logger.exception('Delete %s', str(self)) self.state_set(self.DELETE_FAILED, str(ex)) return str(ex) or "Error : %s" % type(ex) self.state_set(self.DELETE_COMPLETE) def destroy(self): ''' Delete the resource and remove it from the database. ''' result = self.delete() if result: return result if self.id is None: return try: db_api.resource_get(self.context, self.id).delete() except exception.NotFound: # Don't fail on delete if the db entry has # not been created yet. pass except Exception as ex: logger.exception('Delete %s from DB' % str(self)) return str(ex) or "Error : %s" % type(ex) self.id = None def resource_id_set(self, inst): self.resource_id = inst if self.id is not None: try: rs = db_api.resource_get(self.context, self.id) rs.update_and_save({'nova_instance': self.resource_id}) except Exception as ex: logger.warn('db error %s' % str(ex)) def _store(self): '''Create the resource in the database''' try: rs = {'state': self.state, 'stack_id': self.stack.id, 'nova_instance': self.resource_id, 'name': self.name, 'rsrc_metadata': self.metadata, 'stack_name': self.stack.name} new_rs = db_api.resource_create(self.context, rs) self.id = new_rs.id self.stack.updated_time = datetime.utcnow() except Exception as ex: logger.error('DB error %s' % str(ex)) def _add_event(self, new_state, reason): '''Add a state change event to the database''' ev = event.Event(self.context, self.stack, self, new_state, reason, self.resource_id, self.properties) try: ev.store() except Exception as ex: logger.error('DB error %s' % str(ex)) def _store_or_update(self, new_state, reason): self.state = new_state self.state_description = reason if self.id is not None: try: rs = db_api.resource_get(self.context, self.id) rs.update_and_save({'state': self.state, 'state_description': reason, 'nova_instance': self.resource_id}) self.stack.updated_time = datetime.utcnow() except Exception as ex: logger.error('DB error %s' % str(ex)) # store resource in DB on transition to CREATE_IN_PROGRESS # all other transistions (other than to DELETE_COMPLETE) # should be handled by the update_and_save above.. elif new_state == self.CREATE_IN_PROGRESS: self._store() def state_set(self, new_state, reason="state changed"): old_state = self.state self._store_or_update(new_state, reason) if new_state != old_state: self._add_event(new_state, reason) def FnGetRefId(self): ''' http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\ intrinsic-function-reference-ref.html ''' if self.resource_id is not None: return unicode(self.resource_id) else: return unicode(self.name) def FnGetAtt(self, key): ''' http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\ intrinsic-function-reference-getatt.html ''' return unicode(self.name) def FnBase64(self, data): ''' http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\ intrinsic-function-reference-base64.html ''' return base64.b64encode(data) def handle_update(self, json_snippet=None): raise NotImplementedError("Update not implemented for Resource %s" % type(self)) def metadata_update(self, new_metadata=None): ''' No-op for resources which don't explicitly override this method ''' if new_metadata: logger.warning("Resource %s does not implement metadata update" % self.name)
# -*- coding: utf-8 -*- from pathlib import Path from .campos import Campo from .campos import CampoBool from .campos import CampoAlfanumerico from .campos import CampoCPF from .campos import CampoCPFouCNPJ from .campos import CampoCNPJ from .campos import CampoData from .campos import CampoFixo from .campos import CampoNumerico from .campos import CampoRegex from .blocos import Bloco from .registros import Registro import json import re import types ECD='ecd' ECF='ecf' EFD_ICMS_IPI='efd_icms_ipi' EFD_PIS_COFINS='efd_pis_cofins' class Escrituracao(object): """ >>> escrituracao = Escrituracao(ECD, 2016) >>> escrituracao <sped.escrituracao.Escrituracao(ecd, 2016)> >>> escrituracao = Escrituracao(ECD, 2017) >>> escrituracao <sped.escrituracao.Escrituracao(ecd, 2017)> >>> escrituracao.registro_abertura.__class__ == escrituracao.registros.Registro0000 True >>> escrituracao.registro_encerramento.__class__ == escrituracao.registros.Registro9999 True >>> escrituracao._blocos['0'].registro_abertura.__class__ == escrituracao.registros.Registro0001 True >>> escrituracao._blocos['0'].registro_encerramento.__class__ == escrituracao.registros.Registro0990 True >>> escrituracao.registros.Registro == escrituracao._registro_escrituracao True >>> registro = escrituracao.registros.Registro0000() >>> registro <sped.escrituracao.Registro0000> >>> isinstance(registro, escrituracao._registro_escrituracao) True >>> registro.escrituracao <sped.escrituracao.Escrituracao(ecd, 2017)> >>> registro.IDENT_MF = 'M' Traceback (most recent call last): ... sped.erros.FormatoInvalidoError: Registro0000 -> IDENT_MF >>> registro.IDENT_MF = True >>> registro.IDENT_MF = False >>> registro.CNPJ = '1' Traceback (most recent call last): ... sped.erros.FormatoInvalidoError: Registro0000 -> CNPJ >>> registro.CNPJ = '10711130000196' >>> r = escrituracao.registros.Registro0000('|0000|LECD|01012015|31122015|EMPRESA TESTE|11111111000199|AM||3434401|99999||0|1|0||0|0||N|N|') >>> r.CNPJ '11111111000199' >>> r.IDENT_MF False >>> r = escrituracao.registros.Registro0000('|0000|LECD|01012017|31122017|GINX LTDA - ME|10711130000196|PR||4106902|01015622961||0|1|0||0|0||N|N|') >>> r.COD_SCP >>> r.TIP_ECD '0' >>> escrituracao = Escrituracao(ECF, 2017) >>> escrituracao <sped.escrituracao.Escrituracao(ecf, 2017)> """ def __init__(self, tipo: str, ano_calendario: int): self._tipo = tipo self._ano_calendario = ano_calendario self._registros = types.ModuleType('registros') self._blocos = {} self._registro_escrituracao = type('Registro', (Registro,), { 'escrituracao': self }) self._add_registro(self._registro_escrituracao) sped_path = Path(__file__).parent leiaute_path = '%s/leiautes/%s_%s.json' % (sped_path, self._tipo, self._ano_calendario) leiaute_ecd = Path(leiaute_path) with leiaute_ecd.open(encoding='utf-8', newline='\n') as f: p = json.load(f) for bloco in p['blocos']: self._blocos[bloco['nome']] = Bloco(bloco['nome']) for registro in p['registros']: campos = [] for campo in registro['campos']: indice = campo['indice'] nome = campo['nome'] valores = campo['valores'] regras = campo['regras'] tipo = campo['tipo'] obrigatorio = campo['obrigatorio'] # Campos Fixo m = re.match(r'"([a-z0-9]+)"', valores, re.IGNORECASE) if m: campos.append(CampoFixo(indice, nome, m.group(1))) continue m = re.match(r'\[([a-z0-9]+)\]', valores, re.IGNORECASE) if m: campos.append(CampoFixo(indice, nome, m.group(1))) continue # Campos Regex m = re.match(r'\[([^\]]+)\]', valores) if m: valoresValidos = m.groups()[0].replace(' ', '').replace('"', '').replace('\n', '').replace(',', ';').split(';') if set(valoresValidos) == set(['S', 'N']): campos.append(CampoBool(indice, nome, obrigatorio=obrigatorio)) continue else: campos.append(CampoRegex(indice, nome, obrigatorio=obrigatorio, regex='|'.join(valoresValidos))) continue # Campos Data if nome.startswith('DT_') or nome.startswith('DATA_'): campos.append(CampoData(indice, nome, obrigatorio=obrigatorio)) continue # Campo CNPJ ou CPF if 'REGRA_VALIDA_CNPJ' in regras and 'REGRA_VALIDA_CPF' in regras or nome == 'IDENT_CPF_CNPJ' or nome == 'CPF_CNPJ': campos.append(CampoCPFouCNPJ(indice, nome, obrigatorio=obrigatorio)) continue # Campo CNPJ if 'REGRA_VALIDA_CNPJ' in regras or nome == 'CNPJ': campos.append(CampoCNPJ(indice, nome, obrigatorio=obrigatorio)) continue # Campo CPF if 'REGRA_VALIDA_CPF' in regras: campos.append(CampoCPF(indice, nome, obrigatorio=obrigatorio)) continue # CampoAlfaNumerico if tipo == 'C': campos.append(CampoAlfanumerico(indice, nome, obrigatorio=obrigatorio, tamanho=campo['tamanho'])) continue # Campos Decimal if tipo == 'N': campos.append(CampoNumerico(indice, nome, obrigatorio=obrigatorio, precisao=campo['decimal'])) continue # Campos Decimal if tipo == 'NS': campos.append(CampoNumerico(indice, nome, obrigatorio=obrigatorio, precisao=campo['decimal'])) continue # CampoNumerico if indice is not None: campos.append(Campo(indice, nome, obrigatorio=obrigatorio)) nome_registro = registro['nome'] r = type('Registro' + registro['codigo'], (self._registro_escrituracao,), { 'campos': campos }) if re.match(r'ABERTURA DO ARQUIVO DIGITAL', nome_registro): self.registro_abertura = r() if re.match(r'ENCERRAMENTO DO ARQUIVO DIGITAL', nome_registro): self.registro_encerramento = r() m = re.match(r'ABERTURA DO BLOCO (.)', nome_registro) if m: self._blocos[m.group(1)].registro_abertura = r() m = re.match(r'ENCERRAMENTO DO BLOCO (.)', nome_registro) if m: self._blocos[m.group(1)].registro_encerramento = r() self._add_registro(r) def _add_registro(self, registro: type): setattr(self._registros, registro.__name__, registro) @property def blocos(self) -> list: return self._blocos @property def registros(self) -> types.ModuleType: return self._registros def prepare(self): bloco_9 = self._blocos['9'] for bloco in self._blocos.values(): regs = {} for reg in bloco.registros: if reg.REG not in regs: regs[reg.REG] = 0 regs[reg.REG] += 1 if bloco == self._blocos['0']: regs['0000'] = 1 if bloco == bloco_9: regs['9999'] = 1 regs['9900'] += len(regs.keys()) for reg in regs.keys(): registro = self.registros.Registro9900() # pylint: disable=E1101 try: registro.REG_BLC = reg except: for rrr in bloco.registros: print(rrr) print(locals()) raise registro.QTD_REG_BLC = regs[reg] bloco_9.add(registro) reg_count = 2 for bloco in self._blocos.values(): reg_count += len(bloco.registros) self.registro_encerramento[2] = reg_count def write_to(self, buff): buff.write('%s\r\n' % self.registro_abertura) reg_count = 2 for bloco in self._blocos.values(): reg_count += len(bloco.registros) for registro in bloco.registros: buff.write('%s\r\n' % registro) self.registro_encerramento[2] = reg_count buff.write('%s\r\n' % self.registro_encerramento) def add(self, registro: Registro): pass def __repr__(self): return '<%s.%s(%s, %s)>' % (self.__class__.__module__, self.__class__.__name__, self._tipo, self._ano_calendario)
""" How to run locally: Start your local registry: `INDEX_ENDPOINT=https://indexstaging-docker.dotcloud.com \ SETTINGS_FLAVOR=test DOCKER_REGISTRY_CONFIG=config_sample.yml docker-registry` Start the tests: `DOCKER_REGISTRY_ENDPOINT=http://localhost:5000 SETTINGS_FLAVOR=test \ DOCKER_REGISTRY_CONFIG=config_sample.yml DOCKER_CREDS=USER:PASS \ nosetests --tests=tests/workflow.py` """ import hashlib import os import requests sess = requests.Session() adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) sess.mount('https://', adapter) requests = sess from docker_registry.lib import checksums import docker_registry.storage as storage import base from docker_registry.core import compat json = compat.json StringIO = compat.StringIO ua = 'docker/1.0.0 registry test pretending to be docker' class TestWorkflow(base.TestCase): # Dev server needs to run on port 5000 in order to run this test registry_endpoint = os.environ.get( 'DOCKER_REGISTRY_ENDPOINT', 'https://registrystaging-docker.dotcloud.com') index_endpoint = os.environ.get( 'DOCKER_INDEX_ENDPOINT', 'https://indexstaging-docker.dotcloud.com') user_credentials = os.environ['DOCKER_CREDS'].split(':') def generate_chunk(self, data): bufsize = 1024 io = StringIO(data) while True: buf = io.read(bufsize) if not buf: return yield buf io.close() def upload_image(self, image_id, parent_id, token): layer = self.gen_random_string(7 * 1024 * 1024) json_obj = { 'id': image_id } if parent_id: json_obj['parent'] = parent_id json_data = json.dumps(json_obj) h = hashlib.sha256(json_data + '\n') h.update(layer) layer_checksum = 'sha256:{0}'.format(h.hexdigest()) resp = requests.put('{0}/v1/images/{1}/json'.format( self.registry_endpoint, image_id), data=json_data, headers={'Authorization': 'Token ' + token, 'User-Agent': ua, 'X-Docker-Checksum': layer_checksum}, ) self.assertEqual(resp.status_code, 200, resp.text) resp = requests.put('{0}/v1/images/{1}/layer'.format( self.registry_endpoint, image_id), data=self.generate_chunk(layer), headers={'Authorization': 'Token ' + token, 'User-Agent': ua}, ) resp = requests.put('{0}/v1/images/{1}/checksum'.format( self.registry_endpoint, image_id), data={}, headers={'Authorization': 'Token ' + token, 'X-Docker-Checksum-Payload': layer_checksum, 'User-Agent': ua} ) self.assertEqual(resp.status_code, 200, resp.text) return {'id': image_id, 'checksum': layer_checksum} def update_tag(self, namespace, repos, image_id, tag_name): resp = requests.put('{0}/v1/repositories/{1}/{2}/tags/{3}'.format( self.registry_endpoint, namespace, repos, tag_name), data=json.dumps(image_id), ) self.assertEqual(resp.status_code, 200, resp.text) def docker_push(self): # Test Push self.image_id = self.gen_random_string() self.parent_id = self.gen_random_string() image_id = self.image_id parent_id = self.parent_id namespace = self.user_credentials[0] repos = self.gen_random_string() # Docker -> Index images_json = json.dumps([{'id': image_id}, {'id': parent_id}]) resp = requests.put('{0}/v1/repositories/{1}/{2}/'.format( self.index_endpoint, namespace, repos), auth=tuple(self.user_credentials), headers={'X-Docker-Token': 'true', 'User-Agent': ua}, data=images_json) self.assertEqual(resp.status_code, 200, resp.text) self.token = resp.headers.get('x-docker-token') # Docker -> Registry images_json = [] images_json.append(self.upload_image(parent_id, None, self.token)) images_json.append(self.upload_image(image_id, parent_id, self.token)) # Updating the tags does not need a token, it will use the Cookie self.update_tag(namespace, repos, image_id, 'latest') # Docker -> Index resp = requests.put('{0}/v1/repositories/{1}/{2}/images'.format( self.index_endpoint, namespace, repos), auth=tuple(self.user_credentials), headers={'X-Endpoints': self.registry_endpoint, 'User-Agent': ua}, data=json.dumps(images_json)) self.assertEqual(resp.status_code, 204) return (namespace, repos) def fetch_image(self, image_id): """Return image json metadata, checksum and its blob.""" resp = requests.get('{0}/v1/images/{1}/json'.format( self.registry_endpoint, image_id), ) self.assertEqual(resp.status_code, 200, resp.text) resp = requests.get('{0}/v1/images/{1}/json'.format( self.registry_endpoint, image_id), headers={'Authorization': 'Token ' + self.token} ) self.assertEqual(resp.status_code, 200, resp.text) json_data = resp.text checksum = resp.headers['x-docker-payload-checksum'] resp = requests.get('{0}/v1/images/{1}/layer'.format( self.registry_endpoint, image_id), ) self.assertEqual(resp.status_code, 200, resp.text) resp = requests.get('{0}/v1/images/{1}/layer'.format( self.registry_endpoint, image_id), headers={'Authorization': 'Token ' + self.token} ) self.assertEqual(resp.status_code, 200, resp.text) return (json_data, checksum, resp.text) def docker_pull(self, namespace, repos): # Test pull # Docker -> Index resp = requests.get('{0}/v1/repositories/{1}/{2}/images'.format( self.index_endpoint, namespace, repos),) self.assertEqual(resp.status_code, 200) resp = requests.get('{0}/v1/repositories/{1}/{2}/images'.format( self.index_endpoint, namespace, repos), auth=tuple(self.user_credentials), headers={'X-Docker-Token': 'true'}) self.assertEqual(resp.status_code, 200) self.token = resp.headers.get('x-docker-token') # Here we should use the 'X-Endpoints' returned in a real environment # Docker -> Registry resp = requests.get('{0}/v1/repositories/{1}/{2}/tags/latest'.format( self.registry_endpoint, namespace, repos), headers={'Authorization': 'Token ' + self.token}) self.assertEqual(resp.status_code, 200, resp.text) resp = requests.get('{0}/v1/repositories/{1}/{2}/tags/latest'.format( self.registry_endpoint, namespace, repos), ) self.assertEqual(resp.status_code, 200, resp.text) # Docker -> Registry # Note(dmp): unicode patch XXX not applied assume requests does the job image_id = json.loads(resp.text) resp = requests.get('{0}/v1/images/{1}/ancestry'.format( self.registry_endpoint, image_id), ) self.assertEqual(resp.status_code, 200, resp.text) # Note(dmp): unicode patch XXX not applied assume requests does the job ancestry = json.loads(resp.text) # We got the ancestry, let's fetch all the images there for image_id in ancestry: json_data, checksum, blob = self.fetch_image(image_id) # check queried checksum and local computed checksum from the image # are the same tmpfile = StringIO() tmpfile.write(blob) tmpfile.seek(0) computed_checksum = checksums.compute_simple(tmpfile, json_data) tmpfile.close() self.assertEqual(checksum, computed_checksum) # Remove the repository resp = requests.delete('{0}/v1/repositories/{1}/{2}/images'.format( self.registry_endpoint, namespace, repos), ) self.assertEqual(resp.status_code, 204, resp.text) # Remove image_id, then parent_id store = storage.load() try: store.remove(os.path.join(store.images, self.image_id)) except Exception: pass try: store.remove(os.path.join(store.images, self.parent_id)) except Exception: pass def test_workflow(self): (namespace, repos) = self.docker_push() self.docker_pull(namespace, repos)
# Copyright (c) 2019 PaddlePaddle 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 print_function import unittest import numpy as np import sys sys.path.append("..") from op_test import OpTest from op_test_xpu import XPUOpTest import paddle.fluid as fluid import paddle def gather_nd_grad(x, index): dout_shape = index.shape[:-1] + x.shape[index.shape[-1]:] numel = 1 for i in dout_shape: numel = numel * i dout = np.full(dout_shape, 1. / numel) dx = np.full_like(x, 0) index = tuple(index.reshape(-1, index.shape[-1]).T) np.add.at(dx, index, dout) return dx def test_class1(op_type, typename): class TestGatherNdOpWithEmptyIndex(XPUOpTest): #Index has empty element, which means copy entire tensor def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" xnp = np.random.random((5, 20)).astype(typename) self.inputs = { 'X': xnp, 'Index': np.array([[], []]).astype("int32") } self.outputs = { 'Out': np.vstack((xnp[np.newaxis, :], xnp[np.newaxis, :])) } def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_1".format(op_type, typename) TestGatherNdOpWithEmptyIndex.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithEmptyIndex def test_class2(op_type, typename): class TestGatherNdOpWithIndex1(OpTest): def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" xnp = np.random.random((5, 20)).astype(typename) self.inputs = {'X': xnp, 'Index': np.array([1]).astype("int32")} self.outputs = {'Out': self.inputs["X"][self.inputs["Index"]]} def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_2".format(op_type, typename) TestGatherNdOpWithIndex1.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithIndex1 def test_class3(op_type, typename): class TestGatherNdOpWithLowIndex(OpTest): #Index has low rank, X has high rank def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" xnp = np.random.uniform(0, 100, (10, 10)).astype(typename) index = np.array([[1], [2]]).astype("int64") self.inputs = {'X': xnp, 'Index': index} self.outputs = {'Out': xnp[tuple(index.T)]} self.x_grad = gather_nd_grad(xnp, index) def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_3".format(op_type, typename) TestGatherNdOpWithLowIndex.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithLowIndex def test_class4(op_type, typename): class TestGatherNdOpIndex1(OpTest): #Index has low rank, X has high rank def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" xnp = np.random.uniform(0, 100, (10, 10)).astype(typename) index = np.array([1, 2]).astype("int64") self.inputs = {'X': xnp, 'Index': index} self.outputs = {'Out': xnp[tuple(index.T)]} def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_4".format(op_type, typename) TestGatherNdOpIndex1.__name__ = cls_name globals()[cls_name] = TestGatherNdOpIndex1 def test_class5(op_type, typename): class TestGatherNdOpWithSameIndexAsX(OpTest): #Index has same rank as X's rank def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" xnp = np.random.uniform(0, 100, (10, 10)).astype(typename) index = np.array([[1, 1], [2, 1]]).astype("int64") self.inputs = {'X': xnp, 'Index': index} self.outputs = {'Out': xnp[tuple(index.T)]} #[25, 22] def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_5".format(op_type, typename) TestGatherNdOpWithSameIndexAsX.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithSameIndexAsX def test_class6(op_type, typename): class TestGatherNdOpWithHighRankSame(OpTest): #Both Index and X have high rank, and Rank(Index) = Rank(X) def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" shape = (5, 2, 3, 1, 10) xnp = np.random.rand(*shape).astype(typename) index = np.vstack([np.random.randint( 0, s, size=2) for s in shape]).T self.inputs = {'X': xnp, 'Index': index.astype("int32")} self.outputs = {'Out': xnp[tuple(index.T)]} def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_6".format(op_type, typename) TestGatherNdOpWithHighRankSame.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithHighRankSame def test_class7(op_type, typename): class TestGatherNdOpWithHighRankDiff(OpTest): #Both Index and X have high rank, Rank(Index) < Rank(X) def setUp(self): self.set_xpu() self.place = paddle.XPUPlace(0) self.op_type = "gather_nd" shape = (2, 3, 4, 1, 10) xnp = np.random.rand(*shape).astype(typename) index = np.vstack( [np.random.randint( 0, s, size=200) for s in shape]).T index_re = index.reshape([20, 5, 2, 5]) self.inputs = {'X': xnp, 'Index': index_re.astype("int32")} self.outputs = {'Out': xnp[tuple(index.T)].reshape([20, 5, 2])} def set_xpu(self): self.__class__.use_xpu = True def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): pass cls_name = "{0}_{1}_7".format(op_type, typename) TestGatherNdOpWithHighRankDiff.__name__ = cls_name globals()[cls_name] = TestGatherNdOpWithHighRankDiff class TestGatherNdAPI(unittest.TestCase): def test_imperative(self): paddle.disable_static() input_1 = np.array([[1, 2], [3, 4], [5, 6]]) index_1 = np.array([[1]]) input = fluid.dygraph.to_variable(input_1) index = fluid.dygraph.to_variable(index_1) output = paddle.fluid.layers.gather(input, index) output_np = output.numpy() expected_output = np.array([3, 4]) self.assertTrue(np.allclose(output_np, expected_output)) paddle.enable_static() for _typename in {'float32', 'int', 'int64'}: test_class1('gather_nd', _typename) test_class2('gather_nd', _typename) test_class3('gather_nd', _typename) test_class4('gather_nd', _typename) test_class5('gather_nd', _typename) test_class6('gather_nd', _typename) test_class7('gather_nd', _typename) if __name__ == "__main__": unittest.main()
# -*- 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 'InvBlueprintType.production_time' db.add_column('eve_db_invblueprinttype', 'production_time', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True), keep_default=False) # Deleting field 'InvType.radius' db.delete_column('eve_db_invtype', 'radius') def backwards(self, orm): # Deleting field 'InvBlueprintType.production_time' db.delete_column('eve_db_invblueprinttype', 'production_time') # Adding field 'InvType.radius' db.add_column('eve_db_invtype', 'radius', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False) models = { 'eve_db.agtagent': { 'Meta': {'ordering': "['id']", 'object_name': 'AgtAgent'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'division': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCDivision']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapDenormalize']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'quality': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.AgtAgentType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.agtagenttype': { 'Meta': {'ordering': "['id']", 'object_name': 'AgtAgentType'}, 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'eve_db.chrancestry': { 'Meta': {'ordering': "['id']", 'object_name': 'ChrAncestry'}, 'bloodline': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrBloodline']", 'null': 'True', 'blank': 'True'}), 'charisma_bonus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'intelligence_bonus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'memory_bonus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'perception_bonus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'short_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'willpower_bonus': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'eve_db.chrattribute': { 'Meta': {'ordering': "['id']", 'object_name': 'ChrAttribute'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'short_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'eve_db.chrbloodline': { 'Meta': {'ordering': "['id']", 'object_name': 'ChrBloodline'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'female_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'male_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'race': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'bloodline_set'", 'null': 'True', 'to': "orm['eve_db.ChrRace']"}), 'short_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'short_female_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'short_male_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'starter_ship_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'bloodline_starter_ship_set'", 'null': 'True', 'to': "orm['eve_db.InvType']"}), 'starting_charisma': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'starting_intelligence': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'starting_memory': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'starting_perception': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'starting_willpower': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'eve_db.chrfaction': { 'Meta': {'ordering': "['id']", 'object_name': 'ChrFaction'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'faction_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'size_factor': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'faction_set'", 'null': 'True', 'to': "orm['eve_db.MapSolarSystem']"}), 'station_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'station_system_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'eve_db.chrrace': { 'Meta': {'ordering': "['id']", 'object_name': 'ChrRace'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'short_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'eve_db.crpactivity': { 'Meta': {'ordering': "['id']", 'object_name': 'CrpActivity'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'eve_db.crpnpccorporation': { 'Meta': {'ordering': "['id']", 'object_name': 'CrpNPCCorporation'}, 'border_systems': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'corridor_systems': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'enemy_corp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'enemy_of_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'extent': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'faction': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrFaction']", 'null': 'True', 'blank': 'True'}), 'friendly_corp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'friendly_with_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'fringe_systems': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'hub_systems': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'initial_share_price': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'investor1': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'invested1_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'investor1_shares': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'investor2': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'invested2_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'investor2_shares': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'investor3': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'invested3_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'investor3_shares': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'investor4': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'invested4_set'", 'null': 'True', 'to': "orm['eve_db.CrpNPCCorporation']"}), 'investor4_shares': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'min_security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'public_share_percent': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'size': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'size_factor': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapSolarSystem']", 'null': 'True', 'blank': 'True'}), 'station_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'station_system_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'stations_are_scattered': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'eve_db.crpnpccorporationdivision': { 'Meta': {'ordering': "['id']", 'unique_together': "(('corporation', 'division'),)", 'object_name': 'CrpNPCCorporationDivision'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']"}), 'division': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCDivision']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.crpnpccorporationresearchfield': { 'Meta': {'ordering': "['id']", 'unique_together': "(('skill', 'corporation'),)", 'object_name': 'CrpNPCCorporationResearchField'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'skill': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.crpnpccorporationtrade': { 'Meta': {'ordering': "['id']", 'unique_together': "(('corporation', 'type'),)", 'object_name': 'CrpNPCCorporationTrade'}, 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.crpnpcdivision': { 'Meta': {'ordering': "['id']", 'object_name': 'CrpNPCDivision'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'leader_type': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, 'eve_db.crtcategory': { 'Meta': {'ordering': "['id']", 'object_name': 'CrtCategory'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) }, 'eve_db.crtcertificate': { 'Meta': {'ordering': "['id']", 'object_name': 'CrtCertificate'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrtCategory']", 'null': 'True', 'blank': 'True'}), 'cert_class': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrtClass']", 'null': 'True', 'blank': 'True'}), 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'grade': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'icon_num': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}) }, 'eve_db.crtclass': { 'Meta': {'ordering': "['id']", 'object_name': 'CrtClass'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) }, 'eve_db.crtrecommendation': { 'Meta': {'ordering': "['id']", 'object_name': 'CrtRecommendation'}, 'certificate': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrtCertificate']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'recommendation_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'ship_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.crtrelationship': { 'Meta': {'ordering': "['id']", 'object_name': 'CrtRelationship'}, 'child': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'child_crtrelationship_set'", 'null': 'True', 'to': "orm['eve_db.CrtCertificate']"}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'parent_crtrelationship_set'", 'null': 'True', 'to': "orm['eve_db.CrtCertificate']"}), 'parent_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'parent_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.dgmattributecategory': { 'Meta': {'ordering': "['id']", 'object_name': 'DgmAttributeCategory'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'eve_db.dgmattributetype': { 'Meta': {'ordering': "['id']", 'object_name': 'DgmAttributeType'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.DgmAttributeCategory']", 'null': 'True', 'blank': 'True'}), 'default_value': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'high_is_good': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_stackable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '75'}), 'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveUnit']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.dgmeffect': { 'Meta': {'ordering': "['id']", 'object_name': 'DgmEffect'}, 'category': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'disallow_auto_repeat': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'discharge_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectdischargeattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'distribution': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'duration_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectdurationeattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'falloff_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectfalloffattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'fitting_usage_chance_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectfittingusagechanceattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'guid': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'has_electronic_chance': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'has_propulsion_chance': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'has_range_chance': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_assistance': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_offensive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_warp_safe': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'npc_activation_chance_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectnpcactivationchanceattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'npc_usage_chance_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectnpcusagechanceattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'post_expression': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'pre_expression': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'range_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffectrangeattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}), 'sfx_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'tracking_speed_attribute': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inventoryeffecttrackingspeedattribute'", 'null': 'True', 'to': "orm['eve_db.DgmAttributeType']"}) }, 'eve_db.dgmtypeattribute': { 'Meta': {'ordering': "['id']", 'unique_together': "(('inventory_type', 'attribute'),)", 'object_name': 'DgmTypeAttribute'}, 'attribute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.DgmAttributeType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inventory_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']"}), 'value_float': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'value_int': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.dgmtypeeffect': { 'Meta': {'ordering': "['id']", 'unique_together': "(('type', 'effect'),)", 'object_name': 'DgmTypeEffect'}, 'effect': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.DgmEffect']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']"}) }, 'eve_db.evegraphic': { 'Meta': {'ordering': "['id']", 'object_name': 'EveGraphic'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'file': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_obsolete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}) }, 'eve_db.eveicon': { 'Meta': {'ordering': "['id']", 'object_name': 'EveIcon'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'file': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}) }, 'eve_db.eveunit': { 'Meta': {'ordering': "['id']", 'object_name': 'EveUnit'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '75'}) }, 'eve_db.invblueprinttype': { 'Meta': {'ordering': "['blueprint_type']", 'object_name': 'InvBlueprintType'}, 'blueprint_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'blueprint_type_set'", 'unique': 'True', 'primary_key': 'True', 'to': "orm['eve_db.InvType']"}), 'material_modifier': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'max_production_limit': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'parent_blueprint_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'parent_blueprint_type_set'", 'null': 'True', 'to': "orm['eve_db.InvType']"}), 'product_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'blueprint_product_type_set'", 'to': "orm['eve_db.InvType']"}), 'production_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'productivity_modifier': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'research_copy_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'research_material_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'research_productivity_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'research_tech_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'tech_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'waste_factor': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.invcategory': { 'Meta': {'ordering': "['id']", 'object_name': 'InvCategory'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'eve_db.invcontrabandtype': { 'Meta': {'ordering': "['id']", 'unique_together': "(('faction', 'type'),)", 'object_name': 'InvContrabandType'}, 'attack_min_sec': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'confiscate_min_sec': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'faction': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrFaction']"}), 'fine_by_value': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'standing_loss': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']"}) }, 'eve_db.invflag': { 'Meta': {'ordering': "['id']", 'object_name': 'InvFlag'}, 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'type_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) }, 'eve_db.invgroup': { 'Meta': {'ordering': "['id']", 'object_name': 'InvGroup'}, 'allow_anchoring': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'allow_manufacture': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'allow_recycle': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvCategory']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_anchored': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_fittable_non_singleton': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'use_base_price': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'eve_db.invmarketgroup': { 'Meta': {'ordering': "['id']", 'object_name': 'InvMarketGroup'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'has_items': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvMarketGroup']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.invmetagroup': { 'Meta': {'ordering': "['id']", 'object_name': 'InvMetaGroup'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'eve_db.invmetatype': { 'Meta': {'ordering': "['type']", 'object_name': 'InvMetaType'}, 'meta_group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvMetaGroup']"}), 'parent_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inventorymetatype_parent_type_set'", 'to': "orm['eve_db.InvType']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inventorymetatype_type_set'", 'unique': 'True', 'primary_key': 'True', 'to': "orm['eve_db.InvType']"}) }, 'eve_db.invname': { 'Meta': {'ordering': "['id']", 'object_name': 'InvName'}, 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) }, 'eve_db.invposresource': { 'Meta': {'ordering': "['id']", 'unique_together': "(('control_tower_type', 'resource_type'),)", 'object_name': 'InvPOSResource'}, 'control_tower_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tower_resource_set'", 'to': "orm['eve_db.InvType']"}), 'faction': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrFaction']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'min_security_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'purpose': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvPOSResourcePurpose']", 'null': 'True', 'blank': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'pos_resource_set'", 'to': "orm['eve_db.InvType']"}) }, 'eve_db.invposresourcepurpose': { 'Meta': {'ordering': "['id']", 'object_name': 'InvPOSResourcePurpose'}, 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'purpose': ('django.db.models.fields.CharField', [], {'max_length': '75', 'blank': 'True'}) }, 'eve_db.invtype': { 'Meta': {'ordering': "['id']", 'object_name': 'InvType'}, 'base_price': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'capacity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'chance_of_duplicating': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvGroup']", 'null': 'True', 'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'market_group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvMarketGroup']", 'null': 'True', 'blank': 'True'}), 'mass': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'portion_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'race': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrRace']", 'null': 'True', 'blank': 'True'}), 'volume': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.invtypematerial': { 'Meta': {'ordering': "['id']", 'unique_together': "(('type', 'material_type'),)", 'object_name': 'InvTypeMaterial'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'material_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'itemtype_set'", 'to': "orm['eve_db.InvType']"}), 'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'material_set'", 'to': "orm['eve_db.InvType']"}) }, 'eve_db.invtypereaction': { 'Meta': {'ordering': "['id']", 'unique_together': "(('reaction_type', 'input', 'type'),)", 'object_name': 'InvTypeReaction'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'reaction_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inventorytypereactions_reaction_type_set'", 'to': "orm['eve_db.InvType']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inventorytypereactions_type_set'", 'to': "orm['eve_db.InvType']"}) }, 'eve_db.mapcelestialstatistic': { 'Meta': {'ordering': "['celestial']", 'object_name': 'MapCelestialStatistic'}, 'age': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'celestial': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapDenormalize']", 'unique': 'True', 'primary_key': 'True'}), 'density': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'eccentricity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'escape_velocity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'is_fragmented': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'life': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'luminosity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'mass': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'mass_dust': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'mass_gas': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'orbit_period': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'orbit_radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'pressure': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'rotation_rate': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'spectral_class': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'surface_gravity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'temperature': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapconstellation': { 'Meta': {'ordering': "['id']", 'object_name': 'MapConstellation'}, 'faction': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrFaction']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapRegion']", 'null': 'True', 'blank': 'True'}), 'sovereignty_grace_start_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'sovereignty_start_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapconstellationjump': { 'Meta': {'ordering': "['id']", 'unique_together': "(('from_constellation', 'to_constellation'),)", 'object_name': 'MapConstellationJump'}, 'from_constellation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'constellation_jumps_from_constellation_set'", 'to': "orm['eve_db.MapConstellation']"}), 'from_region': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'constellation_jumps_from_region_set'", 'to': "orm['eve_db.MapRegion']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'to_constellation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'constellation_jumps_to_constellation_set'", 'to': "orm['eve_db.MapConstellation']"}), 'to_region': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'constellation_jumps_to_region_set'", 'to': "orm['eve_db.MapRegion']"}) }, 'eve_db.mapdenormalize': { 'Meta': {'ordering': "['id']", 'object_name': 'MapDenormalize'}, 'celestial_index': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'constellation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapConstellation']", 'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvGroup']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'orbit_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'orbit_index': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapRegion']", 'null': 'True', 'blank': 'True'}), 'security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapSolarSystem']", 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapjump': { 'Meta': {'ordering': "['origin_gate']", 'object_name': 'MapJump'}, 'destination_gate': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stargate_jump_destination_set'", 'to': "orm['eve_db.MapDenormalize']"}), 'origin_gate': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stargate_jump_origin_set'", 'unique': 'True', 'primary_key': 'True', 'to': "orm['eve_db.MapDenormalize']"}) }, 'eve_db.maplandmark': { 'Meta': {'ordering': "['id']", 'object_name': 'MapLandmark'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'icon': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.EveIcon']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'importance': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapSolarSystem']", 'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapregion': { 'Meta': {'ordering': "['id']", 'object_name': 'MapRegion'}, 'faction': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.ChrFaction']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapregionjump': { 'Meta': {'ordering': "['id']", 'unique_together': "(('from_region', 'to_region'),)", 'object_name': 'MapRegionJump'}, 'from_region': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'region_jumps_from_region_set'", 'to': "orm['eve_db.MapRegion']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'to_region': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'region_jumps_to_region_set'", 'to': "orm['eve_db.MapRegion']"}) }, 'eve_db.mapsolarsystem': { 'Meta': {'ordering': "['id']", 'object_name': 'MapSolarSystem'}, 'constellation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapConstellation']", 'null': 'True', 'blank': 'True'}), 'faction': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'solarsystem_set'", 'null': 'True', 'to': "orm['eve_db.ChrFaction']"}), 'has_interconstellational_link': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'has_interregional_link': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_border_system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_corridor_system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_fringe_system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_hub_system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_international': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'luminosity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapRegion']", 'null': 'True', 'blank': 'True'}), 'security_class': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'security_level': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'sovereignty_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'sovereignty_start_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'sun_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']", 'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.mapsolarsystemjump': { 'Meta': {'ordering': "['id']", 'unique_together': "(('from_solar_system', 'to_solar_system'),)", 'object_name': 'MapSolarSystemJump'}, 'from_constellation': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'solar_system_jumps_from_constellation_set'", 'null': 'True', 'to': "orm['eve_db.MapConstellation']"}), 'from_region': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'solar_system_jumps_from_region_set'", 'null': 'True', 'to': "orm['eve_db.MapRegion']"}), 'from_solar_system': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'solar_system_jumps_from_solar_system_set'", 'to': "orm['eve_db.MapSolarSystem']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'to_constellation': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'solar_system_jumps_to_constellation_set'", 'null': 'True', 'to': "orm['eve_db.MapConstellation']"}), 'to_region': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'solar_system_jumps_to_region_set'", 'null': 'True', 'to': "orm['eve_db.MapRegion']"}), 'to_solar_system': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'solar_system_jumps_to_solar_system_set'", 'to': "orm['eve_db.MapSolarSystem']"}) }, 'eve_db.mapuniverse': { 'Meta': {'ordering': "['id']", 'object_name': 'MapUniverse'}, 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'radius': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'x_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_max': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z_min': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.planetschematic': { 'Meta': {'ordering': "['id']", 'object_name': 'PlanetSchematic'}, 'cycle_time': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'pin_map': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'usable_schematics'", 'symmetrical': 'False', 'through': "orm['eve_db.PlanetSchematicsPinMap']", 'to': "orm['eve_db.InvType']"}), 'type_map': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'used_with_schematic'", 'symmetrical': 'False', 'through': "orm['eve_db.PlanetSchematicsTypeMap']", 'to': "orm['eve_db.InvType']"}) }, 'eve_db.planetschematicspinmap': { 'Meta': {'ordering': "['schematic', 'type']", 'unique_together': "(('schematic', 'type'),)", 'object_name': 'PlanetSchematicsPinMap'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'schematic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.PlanetSchematic']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']"}) }, 'eve_db.planetschematicstypemap': { 'Meta': {'ordering': "['schematic', 'is_input', 'type']", 'unique_together': "(('schematic', 'type'),)", 'object_name': 'PlanetSchematicsTypeMap'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_input': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'schematic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.PlanetSchematic']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvType']"}) }, 'eve_db.ramactivity': { 'Meta': {'ordering': "['id']", 'object_name': 'RamActivity'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'icon_filename': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '75', 'blank': 'True'}) }, 'eve_db.ramassemblyline': { 'Meta': {'ordering': "['id']", 'object_name': 'RamAssemblyLine'}, 'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamActivity']", 'null': 'True', 'blank': 'True'}), 'assembly_line_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamAssemblyLineType']", 'null': 'True', 'blank': 'True'}), 'cost_install': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'cost_per_hour': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'discount_per_good_standing_point': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'maximum_char_security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'maximum_corp_security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'minimum_char_security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'minimum_corp_security': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'minimum_standing': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'station': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaStation']", 'null': 'True', 'blank': 'True'}), 'surcharge_per_bad_standing_point': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'ui_grouping_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.ramassemblylinestations': { 'Meta': {'ordering': "['id']", 'unique_together': "(('station', 'assembly_line_type'),)", 'object_name': 'RamAssemblyLineStations'}, 'assembly_line_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamAssemblyLineType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapRegion']", 'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapSolarSystem']", 'null': 'True', 'blank': 'True'}), 'station': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaStation']"}), 'station_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaStationType']", 'null': 'True', 'blank': 'True'}) }, 'eve_db.ramassemblylinetype': { 'Meta': {'ordering': "['id']", 'object_name': 'RamAssemblyLineType'}, 'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamActivity']", 'null': 'True', 'blank': 'True'}), 'base_material_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'base_time_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'min_cost_per_hour': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'volume': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.ramassemblylinetypedetailpercategory': { 'Meta': {'ordering': "['id']", 'unique_together': "(('assembly_line_type', 'category'),)", 'object_name': 'RamAssemblyLineTypeDetailPerCategory'}, 'assembly_line_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamAssemblyLineType']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvCategory']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'material_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'time_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.ramassemblylinetypedetailpergroup': { 'Meta': {'ordering': "['id']", 'unique_together': "(('assembly_line_type', 'group'),)", 'object_name': 'RamAssemblyLineTypeDetailPerGroup'}, 'assembly_line_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamAssemblyLineType']"}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.InvGroup']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'material_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'time_multiplier': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.ramtyperequirement': { 'Meta': {'ordering': "['id']", 'unique_together': "(('type', 'activity_type', 'required_type'),)", 'object_name': 'RamTypeRequirement'}, 'activity_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.RamActivity']"}), 'damage_per_job': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'recycle': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'required_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'required_type'", 'to': "orm['eve_db.InvType']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'type_requirement'", 'to': "orm['eve_db.InvType']"}) }, 'eve_db.staoperation': { 'Meta': {'ordering': "['id']", 'object_name': 'StaOperation'}, 'activity_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'amarr_station_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'amarr_station_operation_set'", 'null': 'True', 'to': "orm['eve_db.StaStationType']"}), 'border': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'caldari_station_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'caldari_station_operation_set'", 'null': 'True', 'to': "orm['eve_db.StaStationType']"}), 'corridor': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'fringe': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'gallente_station_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'gallente_station_operation_set'", 'null': 'True', 'to': "orm['eve_db.StaStationType']"}), 'hub': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'jove_station_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'jove_station_operation_set'", 'null': 'True', 'to': "orm['eve_db.StaStationType']"}), 'minmatar_station_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'minmatar_station_operation_set'", 'null': 'True', 'to': "orm['eve_db.StaStationType']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'ratio': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.staoperationservices': { 'Meta': {'ordering': "['id']", 'unique_together': "(('operation', 'service'),)", 'object_name': 'StaOperationServices'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'operation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaOperation']"}), 'service': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaService']"}) }, 'eve_db.staservice': { 'Meta': {'ordering': "['id']", 'object_name': 'StaService'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'eve_db.stastation': { 'Meta': {'ordering': "['id']", 'object_name': 'StaStation'}, 'constellation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapConstellation']", 'null': 'True', 'blank': 'True'}), 'corporation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.CrpNPCCorporation']", 'null': 'True', 'blank': 'True'}), 'docking_cost_per_volume': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'max_ship_volume_dockable': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'office_rental_cost': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'operation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaOperation']", 'null': 'True', 'blank': 'True'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapRegion']", 'null': 'True', 'blank': 'True'}), 'reprocessing_efficiency': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'reprocessing_hangar_flag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'reprocessing_stations_take': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'security': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'solar_system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.MapSolarSystem']", 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaStationType']", 'null': 'True', 'blank': 'True'}), 'x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, 'eve_db.stastationtype': { 'Meta': {'ordering': "['id']", 'object_name': 'StaStationType'}, 'dock_entry_x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'dock_entry_y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'dock_entry_z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'dock_orientation_x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'dock_orientation_y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'dock_orientation_z': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'primary_key': 'True'}), 'is_conquerable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'office_slots': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'operation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eve_db.StaOperation']", 'null': 'True', 'blank': 'True'}), 'reprocessing_efficiency': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['eve_db']
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-16 07:54 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Chip', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.CharField(max_length=40)), ('pet_name', models.CharField(blank=True, max_length=60, null=True)), ('address', models.CharField(blank=True, max_length=120, null=True)), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ], options={ 'db_table': 'core_chip_tbl', 'managed': True, 'permissions': (('view_chip', 'Can View Chip'),), }, ), migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], options={ 'db_table': 'core_city_tbl', 'managed': True, 'permissions': (('view_city', 'Can View City'),), }, ), migrations.CreateModel( name='Commission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('percent', models.IntegerField()), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'core_commission_tbl', 'managed': True, 'permissions': (('view_commission', 'Can View Commission'),), }, ), migrations.CreateModel( name='Country', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('phone_code', models.CharField(max_length=8, null=True)), ], options={ 'db_table': 'core_country_tbl', 'managed': True, 'permissions': (('view_country, ', 'Can View Country'),), }, ), migrations.CreateModel( name='History', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=60)), ('info', models.CharField(max_length=60)), ('ip', models.CharField(max_length=20)), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'core_history_tbl', 'managed': True, 'permissions': (('view_history', 'Can View History'),), }, ), migrations.CreateModel( name='Orders', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.IntegerField()), ('amount', models.IntegerField()), ('price', models.IntegerField()), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ], options={ 'db_table': 'core_orders_tbl', 'managed': True, 'permissions': (('view_orders', 'Can View Orders'),), }, ), migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60)), ('description', models.CharField(blank=True, max_length=120, null=True)), ('company', models.CharField(blank=True, max_length=60, null=True)), ('price_original', models.IntegerField()), ('price_discounted', models.IntegerField()), ('stock_original', models.IntegerField()), ('stock_current', models.IntegerField()), ('prescription_required', models.BooleanField(default=False)), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('image_path', models.CharField(default=b'non-image.jpg', max_length=120)), ], options={ 'db_table': 'core_product_tbl', 'managed': True, 'permissions': (('view_product', 'Can View Product'),), }, ), migrations.CreateModel( name='ProductCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default=b'Empty', max_length=60)), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ], options={ 'db_table': 'core_product_category_tbl', 'managed': True, 'permissions': (('view_productcategory', 'Can View IProduct Category'),), }, ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_number_home', models.CharField(blank=True, max_length=20)), ('phone_number_mobile', models.CharField(blank=True, max_length=20)), ('address', models.CharField(blank=True, max_length=60)), ('license_number', models.CharField(blank=True, max_length=40)), ('city', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.City')), ('country', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Country')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['user__date_joined'], 'managed': True, 'permissions': (('view_profile', 'Can View profile'),), }, ), migrations.CreateModel( name='ServiceCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60)), ('creation_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ('last_update_date', models.DateTimeField(default=datetime.datetime(2017, 1, 16, 9, 54, 21, 158000))), ], options={ 'db_table': 'core_service_category_tbl', 'managed': True, 'permissions': (('view_servicecategory', 'Can View Service Category'),), }, ), migrations.CreateModel( name='Status', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], options={ 'db_table': 'core_status_tbl', 'managed': True, 'permissions': (('view_status', 'Can View Status'),), }, ), migrations.AddField( model_name='product', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.ProductCategory'), ), migrations.AddField( model_name='product', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='orders', name='product', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Product'), ), migrations.AddField( model_name='orders', name='status', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='core.Status'), ), migrations.AddField( model_name='orders', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='city', name='country', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cities', to='core.Country'), ), ]
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import utool as ut import plottool_ibeis as pt import plottool_ibeis.plot_helpers as ph from ibeis.viz import viz_helpers as vh (print, rrr, profile) = ut.inject2(__name__) def _get_annot_pair_info(ibs, aid1, aid2, qreq_, draw_fmatches, **kwargs): kpts1 = kwargs.get('kpts1', None) kpts2 = kwargs.get('kpts2', None) as_fpath = kwargs.get('as_fpath', False) kpts2_list = None if kpts2 is None else [kpts2] rchip1, kpts1 = get_query_annot_pair_info(ibs, aid1, qreq_, draw_fmatches, kpts1=kpts1, as_fpath=as_fpath) annot2_data_list = get_data_annot_pair_info(ibs, [aid2], qreq_, draw_fmatches, as_fpath=as_fpath, kpts2_list=kpts2_list) rchip2, kpts2 = ut.get_list_column(annot2_data_list , 0) return rchip1, rchip2, kpts1, kpts2 def get_query_annot_pair_info(ibs, qaid, qreq_, draw_fmatches, kpts1=None, as_fpath=False): #print('!!! qqreq_ = %r' % (qreq_,)) query_config2_ = (None if qreq_ is None else qreq_.extern_query_config2) tblhack = getattr(qreq_, 'tablename', None) #print('!!! query_config2_ = %r' % (query_config2_,)) if (not tblhack or tblhack == 'BC_DTW') and getattr(qreq_, '_isnewreq', None): if hasattr(qreq_, 'get_fmatch_overlayed_chip') and draw_fmatches and draw_fmatches != 'hackoff': rchip1 = qreq_.get_fmatch_overlayed_chip(qaid, config=query_config2_) draw_fmatches = False else: rchip1 = ibs.depc_annot.get_property('chips', qaid, 'img', config=query_config2_) draw_fmatches = False else: rchip1 = vh.get_chips(ibs, [qaid], config2_=query_config2_, as_fpath=as_fpath)[0] if draw_fmatches: if kpts1 is None: kpts1 = vh.get_kpts(ibs, [qaid], config2_=query_config2_)[0] else: kpts1 = None return rchip1, kpts1 def get_data_annot_pair_info(ibs, aid_list, qreq_, draw_fmatches, scale_down=False, kpts2_list=None, as_fpath=False): data_config2_ = (None if qreq_ is None else qreq_.extern_data_config2) #print('!!! data_config2_ = %r' % (data_config2_,)) #print('!!! dqreq_ = %r' % (qreq_,)) tblhack = getattr(qreq_, 'tablename', None) if (not tblhack or tblhack == 'BC_DTW') and getattr(qreq_, '_isnewreq', None): if hasattr(qreq_, 'get_fmatch_overlayed_chip') and draw_fmatches and draw_fmatches != 'hackoff': rchip2_list = qreq_.get_fmatch_overlayed_chip(aid_list, config=data_config2_) #rchip2_list = ibs.depc_annot.get_property('chips', aid_list, 'img', config=data_config2_) draw_fmatches = False else: rchip2_list = ibs.depc_annot.get_property('chips', aid_list, 'img', config=data_config2_) draw_fmatches = False #vh.get_chips(ibs, aid_list, config2_=data_config2_) else: rchip2_list = vh.get_chips(ibs, aid_list, config2_=data_config2_, as_fpath=as_fpath) if draw_fmatches: if kpts2_list is None: kpts2_list = vh.get_kpts(ibs, aid_list, config2_=data_config2_) else: kpts2_list = [None] * len(aid_list) if scale_down: pass return rchip2_list, kpts2_list #@ut.tracefunc_xml def show_name_matches(ibs, qaid, name_daid_list, name_fm_list, name_fs_list, name_H1_list, name_featflag_list, qreq_=None, **kwargs): """ Called from chip_match.py Args: ibs (IBEISController): ibeis controller object qaid (int): query annotation id name_daid_list (list): name_fm_list (list): name_fs_list (list): name_H1_list (list): name_featflag_list (list): qreq_ (QueryRequest): query request object with hyper-parameters(default = None) Kwargs: draw_fmatches, name_rank, fnum, pnum, colorbar_, nonvote_mode, fastmode, show_matches, fs, fm_norm, lbl1, lbl2, rect, draw_border, cmap, H1, H2, scale_factor1, scale_factor2, draw_pts, draw_ell, draw_lines, show_nMatches, all_kpts, in_image, show_query, draw_lbl, name_annot_scores, score, rawscore, aid2_raw_rank, show_name, show_nid, show_aid, show_annot_score, show_truth, name_score, show_name_score, show_name_rank, show_timedelta CommandLine: python -m ibeis.viz.viz_matches --exec-show_name_matches python -m ibeis.viz.viz_matches --test-show_name_matches --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_matches import * # NOQA >>> from ibeis.algo.hots import chip_match >>> from ibeis.algo.hots import name_scoring >>> import vtool_ibeis as vt >>> from ibeis.algo.hots import _pipeline_helpers as plh # NOQA >>> import numpy as np >>> func = chip_match.ChipMatch.show_single_namematch >>> sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True, >>> strip_docstr=True) >>> setup = ut.regex_replace('viz_matches.show_name_matches', '#', sourcecode) >>> homog = False >>> print(ut.indent(setup, '>>> ')) >>> ibs, qreq_, cm_list = plh.testdata_post_sver('PZ_MTEST', qaid_list=[1]) >>> cm = cm_list[0] >>> cm.score_name_nsum(qreq_) >>> dnid = ibs.get_annot_nids(cm.qaid) >>> # +--- COPIED SECTION >>> locals_ = locals() >>> var_list = ut.exec_func_src( >>> func, locals_=locals_, >>> sentinal='name_annot_scores = cm.annot_score_list.take(sorted_groupxs') >>> exec(ut.execstr_dict(var_list)) >>> # L___ COPIED SECTION >>> kwargs = {} >>> show_name_matches(ibs, qaid, name_daid_list, name_fm_list, >>> name_fs_list, name_h1_list, name_featflag_list, >>> qreq_=qreq_, **kwargs) >>> ut.quit_if_noshow() >>> ut.show_if_requested() """ #print("SHOW NAME MATCHES") #print(ut.repr2(kwargs, nl=True)) #from ibeis import constants as const from ibeis import tag_funcs draw_fmatches = kwargs.pop('draw_fmatches', True) rchip1, kpts1 = get_query_annot_pair_info(ibs, qaid, qreq_, draw_fmatches) rchip2_list, kpts2_list = get_data_annot_pair_info(ibs, name_daid_list, qreq_, draw_fmatches) heatmask = kwargs.pop('heatmask', False) if heatmask: from vtool_ibeis.coverage_kpts import make_kpts_heatmask import numpy as np import vtool_ibeis as vt wh1 = vt.get_size(rchip1) fx1 = np.unique(np.hstack([fm.T[0] for fm in name_fm_list])) heatmask1 = make_kpts_heatmask(kpts1[fx1], wh1) rchip1 = vt.overlay_alpha_images(heatmask1, rchip1) # Hack cast back to uint8 rchip1 = (rchip1 * 255).astype(np.uint8) rchip2_list_ = rchip2_list rchip2_list = [] for rchip2, kpts2, fm in zip(rchip2_list_, kpts2_list, name_fm_list): fx2 = fm.T[1] wh2 = vt.get_size(rchip2) heatmask2 = make_kpts_heatmask(kpts2[fx2], wh2) rchip2 = vt.overlay_alpha_images(heatmask2, rchip2) # Hack cast back to uint8 rchip2 = (rchip2 * 255).astype(np.uint8) rchip2_list.append(rchip2) # fm_list = name_fm_list fs_list = name_fs_list featflag_list = name_featflag_list offset_list, sf_list, bbox_list = show_multichip_match(rchip1, rchip2_list, kpts1, kpts2_list, fm_list, fs_list, featflag_list, **kwargs) aid_list = [qaid] + name_daid_list annotate_matches3(ibs, aid_list, bbox_list, offset_list, name_fm_list, name_fs_list, qreq_=None, **kwargs) ax = pt.gca() title = vh.get_query_text(ibs, None, name_daid_list, False, qaid=qaid, **kwargs) pt.set_title(title, ax) # Case tags annotmatch_rowid_list = ibs.get_annotmatch_rowid_from_superkey( [qaid] * len(name_daid_list), name_daid_list) annotmatch_rowid_list = ut.filter_Nones(annotmatch_rowid_list) tags_list = ibs.get_annotmatch_case_tags(annotmatch_rowid_list) if not ut.get_argflag('--show'): # False: tags_list = tag_funcs.consolodate_annotmatch_tags(tags_list) tag_list = ut.unique_ordered(ut.flatten(tags_list)) name_rank = kwargs.get('name_rank', None) truth = get_multitruth(ibs, aid_list) xlabel = {1: 'Correct ID', 0: 'Incorrect ID', 2: 'Unknown ID'}[truth] if False: if name_rank is None: xlabel = {1: 'Genuine', 0: 'Imposter', 2: 'Unknown'}[truth] #xlabel = {1: 'True', 0: 'False', 2: 'Unknown'}[truth] else: if name_rank == 0: xlabel = { 1: 'True Positive', 0: 'False Positive', 2: 'Unknown'}[truth] else: xlabel = { 1: 'False Negative', 0: 'True Negative', 2: 'Unknown'}[truth] if len(tag_list) > 0: xlabel += '\n' + ', '.join(tag_list) noshow_truth = ut.get_argflag('--noshow_truth') if not noshow_truth: pt.set_xlabel(xlabel) return ax def get_multitruth(ibs, aid_list): import numpy as np if ibs.is_aid_unknown(aid_list[0]): return 2 name_equality = (ibs.get_annot_nids(aid_list[0]) == np.array(ibs.get_annot_nids(aid_list[1:]))) truth = 1 if np.all(name_equality) else (2 if np.any(name_equality) else 0) return truth def annotate_matches3(ibs, aid_list, bbox_list, offset_list, name_fm_list, name_fs_list, qreq_=None, **kwargs): """ TODO: use this as the main function. """ # TODO Use this function when you clean show_matches in_image = kwargs.get('in_image', False) #show_query = kwargs.get('show_query', True) draw_border = kwargs.get('draw_border', True) draw_lbl = kwargs.get('draw_lbl', True) notitle = kwargs.get('notitle', False) # List of annotation scores for each annot in the name #printDBG('[viz] annotate_matches3()') #truth = ibs.get_match_truth(aid1, aid2) #name_equality = ( # np.array(ibs.get_annot_nids(aid_list[1:])) == ibs.get_annot_nids(aid_list[0]) #).tolist() #truth = 1 if all(name_equality) else (2 if any(name_equality) else 0) #truth_color = vh.get_truth_color(truth) ## Build title #score = kwargs.pop('score', None) #rawscore = kwargs.pop('rawscore', None) #aid2_raw_rank = kwargs.pop('aid2_raw_rank', None) #print(kwargs) #title = vh.get_query_text(ibs, None, aid2, truth, qaid=aid1, **kwargs) # Build xlbl ax = pt.gca() ph.set_plotdat(ax, 'viztype', 'multi_match') ph.set_plotdat(ax, 'qaid', aid_list[0]) ph.set_plotdat(ax, 'num_matches', len(aid_list) - 1) ph.set_plotdat(ax, 'aid_list', aid_list[1:]) for count, aid in enumerate(aid_list, start=1): ph.set_plotdat(ax, 'aid%d' % (count,), aid) #name_equality = (ibs.get_annot_nids(aid_list[0]) == # np.array(ibs.get_annot_nids(aid_list[1:]))) #truth = 1 if np.all(name_equality) else (2 if np.any(name_equality) else 0) truth = get_multitruth(ibs, aid_list) if any(ibs.is_aid_unknown(aid_list[1:])) or ibs.is_aid_unknown(aid_list[0]): truth = ibs.const.EVIDENCE_DECISION.UNKNOWN truth_color = vh.get_truth_color(truth) name_annot_scores = kwargs.get('name_annot_scores', None) if len(aid_list) == 2: # HACK; generalize to multple annots title = vh.get_query_text(ibs, None, aid_list[1], truth, qaid=aid_list[0], **kwargs) if not notitle: pt.set_title(title, ax) if draw_lbl: # Build labels nid_list = ibs.get_annot_nids(aid_list, distinguish_unknowns=False) name_list = ibs.get_annot_names(aid_list) lbls_list = [[] for _ in range(len(aid_list))] if kwargs.get('show_name', False): for count, (lbls, name) in enumerate(zip(lbls_list, name_list)): lbls.append(ut.repr2((name))) if kwargs.get('show_nid', True): for count, (lbls, nid) in enumerate(zip(lbls_list, nid_list)): # only label the first two images with nids LABEL_ALL_NIDS = False if count <= 1 or LABEL_ALL_NIDS: #lbls.append(vh.get_nidstrs(nid)) lbls.append(('q' if count == 0 else '') + vh.get_nidstrs(nid)) if kwargs.get('show_aid', True): for count, (lbls, aid) in enumerate(zip(lbls_list, aid_list)): lbls.append(('q' if count == 0 else '') + vh.get_aidstrs(aid)) if (kwargs.get('show_annot_score', True) and name_annot_scores is not None): max_digits = kwargs.get('score_precision', None) for (lbls, score) in zip(lbls_list[1:], name_annot_scores): lbls.append(ut.num_fmt(score, max_digits=max_digits)) lbl_list = [' : '.join(lbls) for lbls in lbls_list] else: lbl_list = [None] * len(aid_list) # Plot annotations over images if in_image: in_image_bbox_list = vh.get_bboxes(ibs, aid_list, offset_list) in_image_theta_list = ibs.get_annot_thetas(aid_list) # HACK! #if show_query: # pt.draw_bbox(bbox1, bbox_color=pt.ORANGE, lbl=lbl1, theta=theta1) bbox_color = pt.ORANGE bbox_color = truth_color if draw_border else pt.ORANGE for bbox, theta, lbl in zip(in_image_bbox_list, in_image_theta_list, lbl_list): pt.draw_bbox(bbox, bbox_color=bbox_color, lbl=lbl, theta=theta) pass else: xy, w, h = pt.get_axis_xy_width_height(ax) if draw_border: pt.draw_border(ax, color=truth_color, lw=4) if draw_lbl: # Custom user lbl for chips 1 and 2 for bbox, lbl in zip(bbox_list, lbl_list): (x, y, w, h) = bbox pt.absolute_lbl(x + w, y, lbl) # No matches draw a red box if True: no_matches = ( name_fm_list is None or all([True if fm is None else len(fm) == 0 for fm in name_fm_list]) ) if no_matches: xy, w, h = pt.get_axis_xy_width_height(ax) #axes_bbox = (xy[0], xy[1], w, h) if draw_border: pass #pt.draw_boxedX(axes_bbox, theta=0) def annotate_matches2(ibs, aid1, aid2, fm, fs, offset1=(0, 0), offset2=(0, 0), xywh2=None, # (0, 0, 0, 0), xywh1=None, # (0, 0, 0, 0), qreq_=None, **kwargs): """ TODO: use this as the main function. """ if True: aid_list = [aid1, aid2] bbox_list = [xywh1, xywh2] offset_list = [offset1, offset2] name_fm_list = [fm] name_fs_list = [fs] return annotate_matches3(ibs, aid_list, bbox_list, offset_list, name_fm_list, name_fs_list, qreq_=qreq_, **kwargs) else: # TODO: make sure all of this functionality is incorporated into annotate_matches3 in_image = kwargs.get('in_image', False) show_query = kwargs.get('show_query', True) draw_border = kwargs.get('draw_border', True) draw_lbl = kwargs.get('draw_lbl', True) notitle = kwargs.get('notitle', False) truth = ibs.get_match_truth(aid1, aid2) truth_color = vh.get_truth_color(truth) # Build title title = vh.get_query_text(ibs, None, aid2, truth, qaid=aid1, **kwargs) # Build xlbl ax = pt.gca() ph.set_plotdat(ax, 'viztype', 'matches') ph.set_plotdat(ax, 'qaid', aid1) ph.set_plotdat(ax, 'aid1', aid1) ph.set_plotdat(ax, 'aid2', aid2) if draw_lbl: name1, name2 = ibs.get_annot_names([aid1, aid2]) nid1, nid2 = ibs.get_annot_name_rowids([aid1, aid2], distinguish_unknowns=False) #lbl1 = repr(name1) + ' : ' + 'q' + vh.get_aidstrs(aid1) #lbl2 = repr(name2) + ' : ' + vh.get_aidstrs(aid2) lbl1_list = [] lbl2_list = [] if kwargs.get('show_aid', True): lbl1_list.append('q' + vh.get_aidstrs(aid1)) lbl2_list.append(vh.get_aidstrs(aid2)) if kwargs.get('show_name', True): lbl1_list.append(repr((name1))) lbl2_list.append(repr((name2))) if kwargs.get('show_nid', True): lbl1_list.append(vh.get_nidstrs(nid1)) lbl2_list.append(vh.get_nidstrs(nid2)) lbl1 = ' : '.join(lbl1_list) lbl2 = ' : '.join(lbl2_list) else: lbl1, lbl2 = None, None if vh.NO_LBL_OVERRIDE: title = '' if not notitle: pt.set_title(title, ax) # Plot annotations over images if in_image: bbox1, bbox2 = vh.get_bboxes(ibs, [aid1, aid2], [offset1, offset2]) theta1, theta2 = ibs.get_annot_thetas([aid1, aid2]) # HACK! if show_query: pt.draw_bbox(bbox1, bbox_color=pt.ORANGE, lbl=lbl1, theta=theta1) bbox_color2 = truth_color if draw_border else pt.ORANGE pt.draw_bbox(bbox2, bbox_color=bbox_color2, lbl=lbl2, theta=theta2) else: xy, w, h = pt.get_axis_xy_width_height(ax) bbox2 = (xy[0], xy[1], w, h) theta2 = 0 if xywh2 is None: #xywh2 = (xy[0], xy[1], w, h) # weird when sidebyside is off y seems to be inverted xywh2 = (0, 0, w, h) if not show_query and xywh1 is None: data_config2 = (None if qreq_ is None else qreq_.extern_data_config2) # FIXME, pass data in kpts2 = ibs.get_annot_kpts([aid2], config2_=data_config2)[0] #pt.draw_kpts2(kpts2.take(fm.T[1], axis=0)) # Draw any selected matches #sm_kw = dict(rect=True, colors=pt.BLUE) pt.plot_fmatch(None, xywh2, None, kpts2, fm, fs=fs, **kwargs) if draw_border: pt.draw_border(ax, truth_color, 4, offset=offset2) if draw_lbl: # Custom user lbl for chips 1 and 2 if show_query: (x1, y1, w1, h1) = xywh1 pt.absolute_lbl(x1 + w1, y1, lbl1) (x2, y2, w2, h2) = xywh2 pt.absolute_lbl(x2 + w2, y2, lbl2) if True: # No matches draw a red box if fm is None or len(fm) == 0: if draw_border: pass #pt.draw_boxedX(bbox2, theta=theta2) #@ut.indent_func #@ut.tracefunc_xml def show_matches2(ibs, aid1, aid2, fm=None, fs=None, fm_norm=None, sel_fm=[], H1=None, H2=None, qreq_=None, **kwargs): """ TODO: DEPRICATE and use special case of show_name_matches Integrate ChipMatch Used in: Found 1 line(s) in '/home/joncrall/code/ibeis_cnn/ibeis_cnn/ingest_ibeis.py': ingest_ibeis.py : 827 | >>> ibeis.viz.viz_matches.show_matches2(ibs, aid1, aid2, fm=None, kpts1=kpts1, kpts2=kpts2) ---------------------- Found 4 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/viz_matches.py': viz_matches.py : 423 |def show_matches2(ibs, aid1, aid2, fm=None, fs=None, fm_norm=None, sel_fm=[], viz_matches.py : 430 | python -m ibeis.viz.viz_matches --exec-show_matches2 --show viz_matches.py : 431 | python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show viz_matches.py : 515 | return show_matches2(ibs, aid1, aid2, fm, fs, qreq_=qreq_, **kwargs) ---------------------- Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/viz/interact/interact_matches.py': interact_matches.py : 372 | tup = viz.viz_matches.show_matches2(ibs, self.qaid, self.daid, ---------------------- Found 2 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/chip_match.py': chip_match.py : 204 | viz_matches.show_matches2(qreq_.ibs, cm.qaid, daid, qreq_=qreq_, chip_match.py : 219 | ibeis.viz.viz_matches.show_matches2 ---------------------- Found 1 line(s) in '/home/joncrall/code/ibeis/ibeis/algo/hots/scoring.py': scoring.py : 562 | viz.viz_matches.show_matches2(qreq_.ibs, qaid, daid, fm, fs, CommandLine: python -m ibeis.viz.viz_matches --exec-show_matches2 --show python -m ibeis --tf ChipMatch.ishow_single_annotmatch show_matches2 --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.algo.hots.chip_match import * # NOQA >>> import ibeis >>> cm, qreq_ = ibeis.testdata_cm(defaultdb='PZ_MTEST', default_qaids=[18]) >>> cm.score_name_nsum(qreq_) >>> daid = cm.get_top_aids()[0] >>> cm.show_single_annotmatch(qreq_, daid) >>> ut.show_if_requested() """ if qreq_ is None: print('[viz_matches] WARNING: qreq_ is None') kwargs = kwargs.copy() in_image = kwargs.get('in_image', False) draw_fmatches = kwargs.pop('draw_fmatches', True) # Read query and result info (chips, names, ...) rchip1, rchip2, kpts1, kpts2 = _get_annot_pair_info(ibs, aid1, aid2, qreq_, draw_fmatches, **kwargs) ut.delete_keys(kwargs, ['kpts1', 'kpts2']) if fm is None: assert len(kpts1) == len(kpts2), 'keypoints should be in correspondence' import numpy as np fm = np.vstack((np.arange(len(kpts1)), np.arange(len(kpts1)))).T # Build annotation strings / colors lbl1 = 'q' + vh.get_aidstrs(aid1) lbl2 = vh.get_aidstrs(aid2) if in_image: # HACK! lbl1 = None lbl2 = None # Draws the chips and keypoint matches try: ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm, fs=fs, fm_norm=fm_norm, H1=H1, H2=H2, lbl1=lbl1, lbl2=lbl2, sel_fm=sel_fm, **kwargs) except Exception as ex: ut.printex(ex, 'consider qr.remove_corrupted_queries', '[viz_matches]') print('') raise # Moved the code into show_chipmatch #if len(sel_fm) > 0: # # Draw any selected matches # sm_kw = dict(rect=True, colors=pt.BLUE) # pt.plot_fmatch(xywh1, xywh2, kpts1, kpts2, sel_fm, **sm_kw) (x1, y1, w1, h1) = xywh1 (x2, y2, w2, h2) = xywh2 offset1 = (x1, y1) offset2 = (x2, y2) annotate_matches2(ibs, aid1, aid2, fm, fs, xywh2=xywh2, xywh1=xywh1, offset1=offset1, offset2=offset2, **kwargs) return ax, xywh1, xywh2 # OLD QRES BASED FUNCS STILL IN USE #@ut.indent_func def show_matches(ibs, cm, aid2, sel_fm=[], qreq_=None, **kwargs): """ DEPRICATE shows single annotated match result. Args: ibs (IBEISController): cm (ChipMatch): object of feature correspondences and scores aid2 (int): result annotation id sel_fm (list): selected features match indices Kwargs: vert (bool) Returns: tuple: (ax, xywh1, xywh2) """ fm = cm.aid2_fm.get(aid2, []) fs = cm.aid2_fs.get(aid2, []) aid1 = cm.qaid return show_matches2(ibs, aid1, aid2, fm, fs, qreq_=qreq_, **kwargs) @profile def show_multichip_match(rchip1, rchip2_list, kpts1, kpts2_list, fm_list, fs_list, featflag_list, fnum=None, pnum=None, **kwargs): """ move to df2 rchip = rchip1 H = H1 = None target_wh = None """ import vtool_ibeis.image as gtool import plottool_ibeis as pt import numpy as np import vtool_ibeis as vt kwargs = kwargs.copy() colorbar_ = kwargs.pop('colorbar_', True) stack_larger = kwargs.pop('stack_larger', False) stack_side = kwargs.pop('stack_side', False) # mode for features disabled by name scoring NONVOTE_MODE = kwargs.get('nonvote_mode', 'filter') def preprocess_chips(rchip, H, target_wh): rchip_ = rchip if H is None else gtool.warpHomog(rchip, H, target_wh) return rchip_ if fnum is None: fnum = pt.next_fnum() target_wh1 = None H1 = None rchip1_ = preprocess_chips(rchip1, H1, target_wh1) # Hack to visually identify the query rchip1_ = vt.draw_border( rchip1_, out=rchip1_, thickness=15, color=(pt.UNKNOWN_PURP[0:3] * 255).astype(np.uint8).tolist()) wh1 = gtool.get_size(rchip1_) rchip2_list_ = [preprocess_chips(rchip2, None, wh1) for rchip2 in rchip2_list] wh2_list = [gtool.get_size(rchip2) for rchip2 in rchip2_list_] num = 0 if len(rchip2_list) < 3 else 1 #vert = True if len(rchip2_list) > 1 else False vert = True if len(rchip2_list) > 1 else None #num = 0 if False and kwargs.get('fastmode', False): # This doesn't actually help the speed very much stackkw = dict( # Hack draw results faster Q #initial_sf=.4, #initial_sf=.9, use_larger=stack_larger, #use_larger=True, ) else: stackkw = dict() #use_larger = True #vert = kwargs.get('fastmode', False) if stack_side: # hack to stack all database images vertically num = 0 # TODO: heatmask match_img, offset_list, sf_list = vt.stack_image_list_special( rchip1_, rchip2_list_, num=num, vert=vert, **stackkw) wh_list = np.array(ut.flatten([[wh1], wh2_list])) * sf_list offset1 = offset_list[0] wh1 = wh_list[0] sf1 = sf_list[0] fig, ax = pt.imshow(match_img, fnum=fnum, pnum=pnum) if kwargs.get('show_matches', True): ut.flatten(fs_list) #ut.embed() flat_fs, cumlen_list = ut.invertible_flatten2(fs_list) flat_colors = pt.scores_to_color(np.array(flat_fs), 'hot') colors_list = ut.unflatten2(flat_colors, cumlen_list) for _tup in zip(offset_list[1:], wh_list[1:], sf_list[1:], kpts2_list, fm_list, fs_list, featflag_list, colors_list): offset2, wh2, sf2, kpts2, fm2_, fs2_, featflags, colors = _tup xywh1 = (offset1[0], offset1[1], wh1[0], wh1[1]) xywh2 = (offset2[0], offset2[1], wh2[0], wh2[1]) #colors = pt.scores_to_color(fs2) if kpts1 is not None and kpts2 is not None: if NONVOTE_MODE == 'filter': fm2 = fm2_.compress(featflags, axis=0) fs2 = fs2_.compress(featflags, axis=0) elif NONVOTE_MODE == 'only': fm2 = fm2_.compress(np.logical_not(featflags), axis=0) fs2 = fs2_.compress(np.logical_not(featflags), axis=0) else: # TODO: optional coloring of nonvotes instead fm2 = fm2_ fs2 = fs2_ pt.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm2, fs2, fm_norm=None, H1=None, H2=None, scale_factor1=sf1, scale_factor2=sf2, colorbar_=False, colors=colors, **kwargs) if colorbar_: pt.colorbar(flat_fs, flat_colors) bbox_list = [(x, y, w, h) for (x, y), (w, h) in zip(offset_list, wh_list)] return offset_list, sf_list, bbox_list if __name__ == '__main__': """ CommandLine: python -m ibeis.viz.viz_matches --test-show_matches --show python -m ibeis.viz.viz_matches python -m ibeis.viz.viz_matches --allexamples python -m ibeis.viz.viz_matches --allexamples --noface --nosrc """ import multiprocessing multiprocessing.freeze_support() # for win32 import utool as ut # NOQA ut.doctest_funcs()
# 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. """Generic utils.""" import codecs import cStringIO import datetime import logging import os import pipes import platform import Queue import re import stat import subprocess import sys import tempfile import threading import time import urlparse import subprocess2 RETRY_MAX = 3 RETRY_INITIAL_SLEEP = 0.5 START = datetime.datetime.now() _WARNINGS = [] # These repos are known to cause OOM errors on 32-bit platforms, due the the # very large objects they contain. It is not safe to use threaded index-pack # when cloning/fetching them. THREADED_INDEX_PACK_BLACKLIST = [ 'https://chromium.googlesource.com/chromium/reference_builds/chrome_win.git' ] class Error(Exception): """gclient exception class.""" def __init__(self, msg, *args, **kwargs): index = getattr(threading.currentThread(), 'index', 0) if index: msg = '\n'.join('%d> %s' % (index, l) for l in msg.splitlines()) super(Error, self).__init__(msg, *args, **kwargs) def Elapsed(until=None): if until is None: until = datetime.datetime.now() return str(until - START).partition('.')[0] def PrintWarnings(): """Prints any accumulated warnings.""" if _WARNINGS: print >> sys.stderr, '\n\nWarnings:' for warning in _WARNINGS: print >> sys.stderr, warning def AddWarning(msg): """Adds the given warning message to the list of accumulated warnings.""" _WARNINGS.append(msg) def SplitUrlRevision(url): """Splits url and returns a two-tuple: url, rev""" if url.startswith('ssh:'): # Make sure ssh://user-name@example.com/~/test.git@stable works regex = r'(ssh://(?:[-.\w]+@)?[-\w:\.]+/[-~\w\./]+)(?:@(.+))?' components = re.search(regex, url).groups() else: components = url.rsplit('@', 1) if re.match(r'^\w+\@', url) and '@' not in components[0]: components = [url] if len(components) == 1: components += [None] return tuple(components) def IsDateRevision(revision): """Returns true if the given revision is of the form "{ ... }".""" return bool(revision and re.match(r'^\{.+\}$', str(revision))) def MakeDateRevision(date): """Returns a revision representing the latest revision before the given date.""" return "{" + date + "}" def SyntaxErrorToError(filename, e): """Raises a gclient_utils.Error exception with the human readable message""" try: # Try to construct a human readable error message if filename: error_message = 'There is a syntax error in %s\n' % filename else: error_message = 'There is a syntax error\n' error_message += 'Line #%s, character %s: "%s"' % ( e.lineno, e.offset, re.sub(r'[\r\n]*$', '', e.text)) except: # Something went wrong, re-raise the original exception raise e else: raise Error(error_message) class PrintableObject(object): def __str__(self): output = '' for i in dir(self): if i.startswith('__'): continue output += '%s = %s\n' % (i, str(getattr(self, i, ''))) return output def FileRead(filename, mode='rU'): with open(filename, mode=mode) as f: # codecs.open() has different behavior than open() on python 2.6 so use # open() and decode manually. s = f.read() try: return s.decode('utf-8') except UnicodeDecodeError: return s def FileWrite(filename, content, mode='w'): with codecs.open(filename, mode=mode, encoding='utf-8') as f: f.write(content) def safe_rename(old, new): """Renames a file reliably. Sometimes os.rename does not work because a dying git process keeps a handle on it for a few seconds. An exception is then thrown, which make the program give up what it was doing and remove what was deleted. The only solution is to catch the exception and try again until it works. """ # roughly 10s retries = 100 for i in range(retries): try: os.rename(old, new) break except OSError: if i == (retries - 1): # Give up. raise # retry logging.debug("Renaming failed from %s to %s. Retrying ..." % (old, new)) time.sleep(0.1) def rmtree(path): """shutil.rmtree() on steroids. Recursively removes a directory, even if it's marked read-only. shutil.rmtree() doesn't work on Windows if any of the files or directories are read-only, which svn repositories and some .svn files are. We need to be able to force the files to be writable (i.e., deletable) as we traverse the tree. Even with all this, Windows still sometimes fails to delete a file, citing a permission error (maybe something to do with antivirus scans or disk indexing). The best suggestion any of the user forums had was to wait a bit and try again, so we do that too. It's hand-waving, but sometimes it works. :/ On POSIX systems, things are a little bit simpler. The modes of the files to be deleted doesn't matter, only the modes of the directories containing them are significant. As the directory tree is traversed, each directory has its mode set appropriately before descending into it. This should result in the entire tree being removed, with the possible exception of *path itself, because nothing attempts to change the mode of its parent. Doing so would be hazardous, as it's not a directory slated for removal. In the ordinary case, this is not a problem: for our purposes, the user will never lack write permission on *path's parent. """ if not os.path.exists(path): return if os.path.islink(path) or not os.path.isdir(path): raise Error('Called rmtree(%s) in non-directory' % path) if sys.platform == 'win32': # Give up and use cmd.exe's rd command. path = os.path.normcase(path) for _ in xrange(3): exitcode = subprocess.call(['cmd.exe', '/c', 'rd', '/q', '/s', path]) if exitcode == 0: return else: print >> sys.stderr, 'rd exited with code %d' % exitcode time.sleep(3) raise Exception('Failed to remove path %s' % path) # On POSIX systems, we need the x-bit set on the directory to access it, # the r-bit to see its contents, and the w-bit to remove files from it. # The actual modes of the files within the directory is irrelevant. os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) def remove(func, subpath): func(subpath) for fn in os.listdir(path): # If fullpath is a symbolic link that points to a directory, isdir will # be True, but we don't want to descend into that as a directory, we just # want to remove the link. Check islink and treat links as ordinary files # would be treated regardless of what they reference. fullpath = os.path.join(path, fn) if os.path.islink(fullpath) or not os.path.isdir(fullpath): remove(os.remove, fullpath) else: # Recurse. rmtree(fullpath) remove(os.rmdir, path) def safe_makedirs(tree): """Creates the directory in a safe manner. Because multiple threads can create these directories concurently, trap the exception and pass on. """ count = 0 while not os.path.exists(tree): count += 1 try: os.makedirs(tree) except OSError, e: # 17 POSIX, 183 Windows if e.errno not in (17, 183): raise if count > 40: # Give up. raise def CommandToStr(args): """Converts an arg list into a shell escaped string.""" return ' '.join(pipes.quote(arg) for arg in args) def CheckCallAndFilterAndHeader(args, always=False, header=None, **kwargs): """Adds 'header' support to CheckCallAndFilter. If |always| is True, a message indicating what is being done is printed to stdout all the time even if not output is generated. Otherwise the message header is printed only if the call generated any ouput. """ stdout = kwargs.setdefault('stdout', sys.stdout) if header is None: header = "\n________ running '%s' in '%s'\n" % ( ' '.join(args), kwargs.get('cwd', '.')) if always: stdout.write(header) else: filter_fn = kwargs.get('filter_fn') def filter_msg(line): if line is None: stdout.write(header) elif filter_fn: filter_fn(line) kwargs['filter_fn'] = filter_msg kwargs['call_filter_on_first_line'] = True # Obviously. kwargs.setdefault('print_stdout', True) return CheckCallAndFilter(args, **kwargs) class Wrapper(object): """Wraps an object, acting as a transparent proxy for all properties by default. """ def __init__(self, wrapped): self._wrapped = wrapped def __getattr__(self, name): return getattr(self._wrapped, name) class AutoFlush(Wrapper): """Creates a file object clone to automatically flush after N seconds.""" def __init__(self, wrapped, delay): super(AutoFlush, self).__init__(wrapped) if not hasattr(self, 'lock'): self.lock = threading.Lock() self.__last_flushed_at = time.time() self.delay = delay @property def autoflush(self): return self def write(self, out, *args, **kwargs): self._wrapped.write(out, *args, **kwargs) should_flush = False self.lock.acquire() try: if self.delay and (time.time() - self.__last_flushed_at) > self.delay: should_flush = True self.__last_flushed_at = time.time() finally: self.lock.release() if should_flush: self.flush() class Annotated(Wrapper): """Creates a file object clone to automatically prepends every line in worker threads with a NN> prefix. """ def __init__(self, wrapped, include_zero=False): super(Annotated, self).__init__(wrapped) if not hasattr(self, 'lock'): self.lock = threading.Lock() self.__output_buffers = {} self.__include_zero = include_zero @property def annotated(self): return self def write(self, out): index = getattr(threading.currentThread(), 'index', 0) if not index and not self.__include_zero: # Unindexed threads aren't buffered. return self._wrapped.write(out) self.lock.acquire() try: # Use a dummy array to hold the string so the code can be lockless. # Strings are immutable, requiring to keep a lock for the whole dictionary # otherwise. Using an array is faster than using a dummy object. if not index in self.__output_buffers: obj = self.__output_buffers[index] = [''] else: obj = self.__output_buffers[index] finally: self.lock.release() # Continue lockless. obj[0] += out while '\n' in obj[0]: line, remaining = obj[0].split('\n', 1) if line: self._wrapped.write('%d>%s\n' % (index, line)) obj[0] = remaining def flush(self): """Flush buffered output.""" orphans = [] self.lock.acquire() try: # Detect threads no longer existing. indexes = (getattr(t, 'index', None) for t in threading.enumerate()) indexes = filter(None, indexes) for index in self.__output_buffers: if not index in indexes: orphans.append((index, self.__output_buffers[index][0])) for orphan in orphans: del self.__output_buffers[orphan[0]] finally: self.lock.release() # Don't keep the lock while writting. Will append \n when it shouldn't. for orphan in orphans: if orphan[1]: self._wrapped.write('%d>%s\n' % (orphan[0], orphan[1])) return self._wrapped.flush() def MakeFileAutoFlush(fileobj, delay=10): autoflush = getattr(fileobj, 'autoflush', None) if autoflush: autoflush.delay = delay return fileobj return AutoFlush(fileobj, delay) def MakeFileAnnotated(fileobj, include_zero=False): if getattr(fileobj, 'annotated', None): return fileobj return Annotated(fileobj) GCLIENT_CHILDREN = [] GCLIENT_CHILDREN_LOCK = threading.Lock() class GClientChildren(object): @staticmethod def add(popen_obj): with GCLIENT_CHILDREN_LOCK: GCLIENT_CHILDREN.append(popen_obj) @staticmethod def remove(popen_obj): with GCLIENT_CHILDREN_LOCK: GCLIENT_CHILDREN.remove(popen_obj) @staticmethod def _attemptToKillChildren(): global GCLIENT_CHILDREN with GCLIENT_CHILDREN_LOCK: zombies = [c for c in GCLIENT_CHILDREN if c.poll() is None] for zombie in zombies: try: zombie.kill() except OSError: pass with GCLIENT_CHILDREN_LOCK: GCLIENT_CHILDREN = [k for k in GCLIENT_CHILDREN if k.poll() is not None] @staticmethod def _areZombies(): with GCLIENT_CHILDREN_LOCK: return bool(GCLIENT_CHILDREN) @staticmethod def KillAllRemainingChildren(): GClientChildren._attemptToKillChildren() if GClientChildren._areZombies(): time.sleep(0.5) GClientChildren._attemptToKillChildren() with GCLIENT_CHILDREN_LOCK: if GCLIENT_CHILDREN: print >> sys.stderr, 'Could not kill the following subprocesses:' for zombie in GCLIENT_CHILDREN: print >> sys.stderr, ' ', zombie.pid def CheckCallAndFilter(args, stdout=None, filter_fn=None, print_stdout=None, call_filter_on_first_line=False, retry=False, **kwargs): """Runs a command and calls back a filter function if needed. Accepts all subprocess2.Popen() parameters plus: print_stdout: If True, the command's stdout is forwarded to stdout. filter_fn: A function taking a single string argument called with each line of the subprocess2's output. Each line has the trailing newline character trimmed. stdout: Can be any bufferable output. retry: If the process exits non-zero, sleep for a brief interval and try again, up to RETRY_MAX times. stderr is always redirected to stdout. """ assert print_stdout or filter_fn stdout = stdout or sys.stdout output = cStringIO.StringIO() filter_fn = filter_fn or (lambda x: None) sleep_interval = RETRY_INITIAL_SLEEP run_cwd = kwargs.get('cwd', os.getcwd()) for _ in xrange(RETRY_MAX + 1): kid = subprocess2.Popen( args, bufsize=0, stdout=subprocess2.PIPE, stderr=subprocess2.STDOUT, **kwargs) GClientChildren.add(kid) # Do a flush of stdout before we begin reading from the subprocess2's stdout stdout.flush() # Also, we need to forward stdout to prevent weird re-ordering of output. # This has to be done on a per byte basis to make sure it is not buffered: # normally buffering is done for each line, but if svn requests input, no # end-of-line character is output after the prompt and it would not show up. try: in_byte = kid.stdout.read(1) if in_byte: if call_filter_on_first_line: filter_fn(None) in_line = '' while in_byte: output.write(in_byte) if print_stdout: stdout.write(in_byte) if in_byte not in ['\r', '\n']: in_line += in_byte else: filter_fn(in_line) in_line = '' in_byte = kid.stdout.read(1) # Flush the rest of buffered output. This is only an issue with # stdout/stderr not ending with a \n. if len(in_line): filter_fn(in_line) rv = kid.wait() # Don't put this in a 'finally,' since the child may still run if we get # an exception. GClientChildren.remove(kid) except KeyboardInterrupt: print >> sys.stderr, 'Failed while running "%s"' % ' '.join(args) raise if rv == 0: return output.getvalue() if not retry: break print ("WARNING: subprocess '%s' in %s failed; will retry after a short " 'nap...' % (' '.join('"%s"' % x for x in args), run_cwd)) time.sleep(sleep_interval) sleep_interval *= 2 raise subprocess2.CalledProcessError( rv, args, kwargs.get('cwd', None), None, None) class GitFilter(object): """A filter_fn implementation for quieting down git output messages. Allows a custom function to skip certain lines (predicate), and will throttle the output of percentage completed lines to only output every X seconds. """ PERCENT_RE = re.compile('(.*) ([0-9]{1,3})% .*') def __init__(self, time_throttle=0, predicate=None, out_fh=None): """ Args: time_throttle (int): GitFilter will throttle 'noisy' output (such as the XX% complete messages) to only be printed at least |time_throttle| seconds apart. predicate (f(line)): An optional function which is invoked for every line. The line will be skipped if predicate(line) returns False. out_fh: File handle to write output to. """ self.last_time = 0 self.time_throttle = time_throttle self.predicate = predicate self.out_fh = out_fh or sys.stdout self.progress_prefix = None def __call__(self, line): # git uses an escape sequence to clear the line; elide it. esc = line.find(unichr(033)) if esc > -1: line = line[:esc] if self.predicate and not self.predicate(line): return now = time.time() match = self.PERCENT_RE.match(line) if match: if match.group(1) != self.progress_prefix: self.progress_prefix = match.group(1) elif now - self.last_time < self.time_throttle: return self.last_time = now self.out_fh.write('[%s] ' % Elapsed()) print >> self.out_fh, line def FindGclientRoot(from_dir, filename='.gclient'): """Tries to find the gclient root.""" real_from_dir = os.path.realpath(from_dir) path = real_from_dir while not os.path.exists(os.path.join(path, filename)): split_path = os.path.split(path) if not split_path[1]: return None path = split_path[0] # If we did not find the file in the current directory, make sure we are in a # sub directory that is controlled by this configuration. if path != real_from_dir: entries_filename = os.path.join(path, filename + '_entries') if not os.path.exists(entries_filename): # If .gclient_entries does not exist, a previous call to gclient sync # might have failed. In that case, we cannot verify that the .gclient # is the one we want to use. In order to not to cause too much trouble, # just issue a warning and return the path anyway. print >> sys.stderr, ("%s file in parent directory %s might not be the " "file you want to use" % (filename, path)) return path scope = {} try: exec(FileRead(entries_filename), scope) except SyntaxError, e: SyntaxErrorToError(filename, e) all_directories = scope['entries'].keys() path_to_check = real_from_dir[len(path)+1:] while path_to_check: if path_to_check in all_directories: return path path_to_check = os.path.dirname(path_to_check) return None logging.info('Found gclient root at ' + path) return path def PathDifference(root, subpath): """Returns the difference subpath minus root.""" root = os.path.realpath(root) subpath = os.path.realpath(subpath) if not subpath.startswith(root): return None # If the root does not have a trailing \ or /, we add it so the returned # path starts immediately after the seperator regardless of whether it is # provided. root = os.path.join(root, '') return subpath[len(root):] def FindFileUpwards(filename, path=None): """Search upwards from the a directory (default: current) to find a file. Returns nearest upper-level directory with the passed in file. """ if not path: path = os.getcwd() path = os.path.realpath(path) while True: file_path = os.path.join(path, filename) if os.path.exists(file_path): return path (new_path, _) = os.path.split(path) if new_path == path: return None path = new_path def GetMacWinOrLinux(): """Returns 'mac', 'win', or 'linux', matching the current platform.""" if sys.platform.startswith(('cygwin', 'win')): return 'win' elif sys.platform.startswith('linux'): return 'linux' elif sys.platform == 'darwin': return 'mac' raise Error('Unknown platform: ' + sys.platform) def GetExeSuffix(): """Returns '' or '.exe' depending on how executables work on this platform.""" if sys.platform.startswith(('cygwin', 'win')): return '.exe' return '' def GetGClientRootAndEntries(path=None): """Returns the gclient root and the dict of entries.""" config_file = '.gclient_entries' root = FindFileUpwards(config_file, path) if not root: print "Can't find %s" % config_file return None config_path = os.path.join(root, config_file) env = {} execfile(config_path, env) config_dir = os.path.dirname(config_path) return config_dir, env['entries'] def lockedmethod(method): """Method decorator that holds self.lock for the duration of the call.""" def inner(self, *args, **kwargs): try: try: self.lock.acquire() except KeyboardInterrupt: print >> sys.stderr, 'Was deadlocked' raise return method(self, *args, **kwargs) finally: self.lock.release() return inner class WorkItem(object): """One work item.""" # On cygwin, creating a lock throwing randomly when nearing ~100 locks. # As a workaround, use a single lock. Yep you read it right. Single lock for # all the 100 objects. lock = threading.Lock() def __init__(self, name): # A unique string representing this work item. self._name = name self.outbuf = cStringIO.StringIO() self.start = self.finish = None def run(self, work_queue): """work_queue is passed as keyword argument so it should be the last parameters of the function when you override it.""" pass @property def name(self): return self._name class ExecutionQueue(object): """Runs a set of WorkItem that have interdependencies and were WorkItem are added as they are processed. In gclient's case, Dependencies sometime needs to be run out of order due to From() keyword. This class manages that all the required dependencies are run before running each one. Methods of this class are thread safe. """ def __init__(self, jobs, progress, ignore_requirements, verbose=False): """jobs specifies the number of concurrent tasks to allow. progress is a Progress instance.""" # Set when a thread is done or a new item is enqueued. self.ready_cond = threading.Condition() # Maximum number of concurrent tasks. self.jobs = jobs # List of WorkItem, for gclient, these are Dependency instances. self.queued = [] # List of strings representing each Dependency.name that was run. self.ran = [] # List of items currently running. self.running = [] # Exceptions thrown if any. self.exceptions = Queue.Queue() # Progress status self.progress = progress if self.progress: self.progress.update(0) self.ignore_requirements = ignore_requirements self.verbose = verbose self.last_join = None self.last_subproc_output = None def enqueue(self, d): """Enqueue one Dependency to be executed later once its requirements are satisfied. """ assert isinstance(d, WorkItem) self.ready_cond.acquire() try: self.queued.append(d) total = len(self.queued) + len(self.ran) + len(self.running) logging.debug('enqueued(%s)' % d.name) if self.progress: self.progress._total = total + 1 self.progress.update(0) self.ready_cond.notifyAll() finally: self.ready_cond.release() def out_cb(self, _): self.last_subproc_output = datetime.datetime.now() return True @staticmethod def format_task_output(task, comment=''): if comment: comment = ' (%s)' % comment if task.start and task.finish: elapsed = ' (Elapsed: %s)' % ( str(task.finish - task.start).partition('.')[0]) else: elapsed = '' return """ %s%s%s ---------------------------------------- %s ----------------------------------------""" % ( task.name, comment, elapsed, task.outbuf.getvalue().strip()) def flush(self, *args, **kwargs): """Runs all enqueued items until all are executed.""" kwargs['work_queue'] = self self.last_subproc_output = self.last_join = datetime.datetime.now() self.ready_cond.acquire() try: while True: # Check for task to run first, then wait. while True: if not self.exceptions.empty(): # Systematically flush the queue when an exception logged. self.queued = [] self._flush_terminated_threads() if (not self.queued and not self.running or self.jobs == len(self.running)): logging.debug('No more worker threads or can\'t queue anything.') break # Check for new tasks to start. for i in xrange(len(self.queued)): # Verify its requirements. if (self.ignore_requirements or not (set(self.queued[i].requirements) - set(self.ran))): # Start one work item: all its requirements are satisfied. self._run_one_task(self.queued.pop(i), args, kwargs) break else: # Couldn't find an item that could run. Break out the outher loop. break if not self.queued and not self.running: # We're done. break # We need to poll here otherwise Ctrl-C isn't processed. try: self.ready_cond.wait(10) # If we haven't printed to terminal for a while, but we have received # spew from a suprocess, let the user know we're still progressing. now = datetime.datetime.now() if (now - self.last_join > datetime.timedelta(seconds=60) and self.last_subproc_output > self.last_join): if self.progress: print >> sys.stdout, '' sys.stdout.flush() elapsed = Elapsed() print >> sys.stdout, '[%s] Still working on:' % elapsed sys.stdout.flush() for task in self.running: print >> sys.stdout, '[%s] %s' % (elapsed, task.item.name) sys.stdout.flush() except KeyboardInterrupt: # Help debugging by printing some information: print >> sys.stderr, ( ('\nAllowed parallel jobs: %d\n# queued: %d\nRan: %s\n' 'Running: %d') % ( self.jobs, len(self.queued), ', '.join(self.ran), len(self.running))) for i in self.queued: print >> sys.stderr, '%s (not started): %s' % ( i.name, ', '.join(i.requirements)) for i in self.running: print >> sys.stderr, self.format_task_output(i.item, 'interrupted') raise # Something happened: self.enqueue() or a thread terminated. Loop again. finally: self.ready_cond.release() assert not self.running, 'Now guaranteed to be single-threaded' if not self.exceptions.empty(): if self.progress: print >> sys.stdout, '' # To get back the stack location correctly, the raise a, b, c form must be # used, passing a tuple as the first argument doesn't work. e, task = self.exceptions.get() print >> sys.stderr, self.format_task_output(task.item, 'ERROR') raise e[0], e[1], e[2] elif self.progress: self.progress.end() def _flush_terminated_threads(self): """Flush threads that have terminated.""" running = self.running self.running = [] for t in running: if t.isAlive(): self.running.append(t) else: t.join() self.last_join = datetime.datetime.now() sys.stdout.flush() if self.verbose: print >> sys.stdout, self.format_task_output(t.item) if self.progress: self.progress.update(1, t.item.name) if t.item.name in self.ran: raise Error( 'gclient is confused, "%s" is already in "%s"' % ( t.item.name, ', '.join(self.ran))) if not t.item.name in self.ran: self.ran.append(t.item.name) def _run_one_task(self, task_item, args, kwargs): if self.jobs > 1: # Start the thread. index = len(self.ran) + len(self.running) + 1 new_thread = self._Worker(task_item, index, args, kwargs) self.running.append(new_thread) new_thread.start() else: # Run the 'thread' inside the main thread. Don't try to catch any # exception. try: task_item.start = datetime.datetime.now() print >> task_item.outbuf, '[%s] Started.' % Elapsed(task_item.start) task_item.run(*args, **kwargs) task_item.finish = datetime.datetime.now() print >> task_item.outbuf, '[%s] Finished.' % Elapsed(task_item.finish) self.ran.append(task_item.name) if self.verbose: if self.progress: print >> sys.stdout, '' print >> sys.stdout, self.format_task_output(task_item) if self.progress: self.progress.update(1, ', '.join(t.item.name for t in self.running)) except KeyboardInterrupt: print >> sys.stderr, self.format_task_output(task_item, 'interrupted') raise except Exception: print >> sys.stderr, self.format_task_output(task_item, 'ERROR') raise class _Worker(threading.Thread): """One thread to execute one WorkItem.""" def __init__(self, item, index, args, kwargs): threading.Thread.__init__(self, name=item.name or 'Worker') logging.info('_Worker(%s) reqs:%s' % (item.name, item.requirements)) self.item = item self.index = index self.args = args self.kwargs = kwargs self.daemon = True def run(self): """Runs in its own thread.""" logging.debug('_Worker.run(%s)' % self.item.name) work_queue = self.kwargs['work_queue'] try: self.item.start = datetime.datetime.now() print >> self.item.outbuf, '[%s] Started.' % Elapsed(self.item.start) self.item.run(*self.args, **self.kwargs) self.item.finish = datetime.datetime.now() print >> self.item.outbuf, '[%s] Finished.' % Elapsed(self.item.finish) except KeyboardInterrupt: logging.info('Caught KeyboardInterrupt in thread %s', self.item.name) logging.info(str(sys.exc_info())) work_queue.exceptions.put((sys.exc_info(), self)) raise except Exception: # Catch exception location. logging.info('Caught exception in thread %s', self.item.name) logging.info(str(sys.exc_info())) work_queue.exceptions.put((sys.exc_info(), self)) finally: logging.info('_Worker.run(%s) done', self.item.name) work_queue.ready_cond.acquire() try: work_queue.ready_cond.notifyAll() finally: work_queue.ready_cond.release() def GetEditor(git, git_editor=None): """Returns the most plausible editor to use. In order of preference: - GIT_EDITOR/SVN_EDITOR environment variable - core.editor git configuration variable (if supplied by git-cl) - VISUAL environment variable - EDITOR environment variable - vi (non-Windows) or notepad (Windows) In the case of git-cl, this matches git's behaviour, except that it does not include dumb terminal detection. In the case of gcl, this matches svn's behaviour, except that it does not accept a command-line flag or check the editor-cmd configuration variable. """ if git: editor = os.environ.get('GIT_EDITOR') or git_editor else: editor = os.environ.get('SVN_EDITOR') if not editor: editor = os.environ.get('VISUAL') if not editor: editor = os.environ.get('EDITOR') if not editor: if sys.platform.startswith('win'): editor = 'notepad' else: editor = 'vi' return editor def RunEditor(content, git, git_editor=None): """Opens up the default editor in the system to get the CL description.""" file_handle, filename = tempfile.mkstemp(text=True, prefix='cl_description') # Make sure CRLF is handled properly by requiring none. if '\r' in content: print >> sys.stderr, ( '!! Please remove \\r from your change description !!') fileobj = os.fdopen(file_handle, 'w') # Still remove \r if present. fileobj.write(re.sub('\r?\n', '\n', content)) fileobj.close() try: editor = GetEditor(git, git_editor=git_editor) if not editor: return None cmd = '%s %s' % (editor, filename) if sys.platform == 'win32' and os.environ.get('TERM') == 'msys': # Msysgit requires the usage of 'env' to be present. cmd = 'env ' + cmd try: # shell=True to allow the shell to handle all forms of quotes in # $EDITOR. subprocess2.check_call(cmd, shell=True) except subprocess2.CalledProcessError: return None return FileRead(filename) finally: os.remove(filename) def UpgradeToHttps(url): """Upgrades random urls to https://. Do not touch unknown urls like ssh:// or git://. Do not touch http:// urls with a port number, Fixes invalid GAE url. """ if not url: return url if not re.match(r'[a-z\-]+\://.*', url): # Make sure it is a valid uri. Otherwise, urlparse() will consider it a # relative url and will use http:///foo. Note that it defaults to http:// # for compatibility with naked url like "localhost:8080". url = 'http://%s' % url parsed = list(urlparse.urlparse(url)) # Do not automatically upgrade http to https if a port number is provided. if parsed[0] == 'http' and not re.match(r'^.+?\:\d+$', parsed[1]): parsed[0] = 'https' return urlparse.urlunparse(parsed) def ParseCodereviewSettingsContent(content): """Process a codereview.settings file properly.""" lines = (l for l in content.splitlines() if not l.strip().startswith("#")) try: keyvals = dict([x.strip() for x in l.split(':', 1)] for l in lines if l) except ValueError: raise Error( 'Failed to process settings, please fix. Content:\n\n%s' % content) def fix_url(key): if keyvals.get(key): keyvals[key] = UpgradeToHttps(keyvals[key]) fix_url('CODE_REVIEW_SERVER') fix_url('VIEW_VC') return keyvals def NumLocalCpus(): """Returns the number of processors. Python on OSX 10.6 raises a NotImplementedError exception. """ try: import multiprocessing return multiprocessing.cpu_count() except: # pylint: disable=W0702 # Mac OS 10.6 only # pylint: disable=E1101 return int(os.sysconf('SC_NPROCESSORS_ONLN')) def DefaultDeltaBaseCacheLimit(): """Return a reasonable default for the git config core.deltaBaseCacheLimit. The primary constraint is the address space of virtual memory. The cache size limit is per-thread, and 32-bit systems can hit OOM errors if this parameter is set too high. """ if platform.architecture()[0].startswith('64'): return '2g' else: return '512m' def DefaultIndexPackConfig(url=''): """Return reasonable default values for configuring git-index-pack. Experiments suggest that higher values for pack.threads don't improve performance.""" cache_limit = DefaultDeltaBaseCacheLimit() result = ['-c', 'core.deltaBaseCacheLimit=%s' % cache_limit] if url in THREADED_INDEX_PACK_BLACKLIST: result.extend(['-c', 'pack.threads=1']) return result
"""Handle MySensors gateways.""" import asyncio from collections import defaultdict import logging import socket import sys import async_timeout import voluptuous as vol from homeassistant.const import CONF_OPTIMISTIC, EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.setup import async_setup_component from .const import ( CONF_BAUD_RATE, CONF_DEVICE, CONF_GATEWAYS, CONF_NODES, CONF_PERSISTENCE, CONF_PERSISTENCE_FILE, CONF_RETAIN, CONF_TCP_PORT, CONF_TOPIC_IN_PREFIX, CONF_TOPIC_OUT_PREFIX, CONF_VERSION, DOMAIN, MYSENSORS_GATEWAY_READY, MYSENSORS_GATEWAYS, ) from .handler import HANDLERS from .helpers import discover_mysensors_platform, validate_child, validate_node _LOGGER = logging.getLogger(__name__) GATEWAY_READY_TIMEOUT = 15.0 MQTT_COMPONENT = "mqtt" def is_serial_port(value): """Validate that value is a windows serial port or a unix device.""" if sys.platform.startswith("win"): ports = ("COM{}".format(idx + 1) for idx in range(256)) if value in ports: return value raise vol.Invalid(f"{value} is not a serial port") return cv.isdevice(value) def is_socket_address(value): """Validate that value is a valid address.""" try: socket.getaddrinfo(value, None) return value except OSError: raise vol.Invalid("Device is not a valid domain name or ip address") def get_mysensors_gateway(hass, gateway_id): """Return MySensors gateway.""" if MYSENSORS_GATEWAYS not in hass.data: hass.data[MYSENSORS_GATEWAYS] = {} gateways = hass.data.get(MYSENSORS_GATEWAYS) return gateways.get(gateway_id) async def setup_gateways(hass, config): """Set up all gateways.""" conf = config[DOMAIN] gateways = {} for index, gateway_conf in enumerate(conf[CONF_GATEWAYS]): persistence_file = gateway_conf.get( CONF_PERSISTENCE_FILE, hass.config.path("mysensors{}.pickle".format(index + 1)), ) ready_gateway = await _get_gateway(hass, config, gateway_conf, persistence_file) if ready_gateway is not None: gateways[id(ready_gateway)] = ready_gateway return gateways async def _get_gateway(hass, config, gateway_conf, persistence_file): """Return gateway after setup of the gateway.""" from mysensors import mysensors conf = config[DOMAIN] persistence = conf[CONF_PERSISTENCE] version = conf[CONF_VERSION] device = gateway_conf[CONF_DEVICE] baud_rate = gateway_conf[CONF_BAUD_RATE] tcp_port = gateway_conf[CONF_TCP_PORT] in_prefix = gateway_conf.get(CONF_TOPIC_IN_PREFIX, "") out_prefix = gateway_conf.get(CONF_TOPIC_OUT_PREFIX, "") if device == MQTT_COMPONENT: if not await async_setup_component(hass, MQTT_COMPONENT, config): return None mqtt = hass.components.mqtt retain = conf[CONF_RETAIN] def pub_callback(topic, payload, qos, retain): """Call MQTT publish function.""" mqtt.async_publish(topic, payload, qos, retain) def sub_callback(topic, sub_cb, qos): """Call MQTT subscribe function.""" @callback def internal_callback(msg): """Call callback.""" sub_cb(msg.topic, msg.payload, msg.qos) hass.async_create_task(mqtt.async_subscribe(topic, internal_callback, qos)) gateway = mysensors.AsyncMQTTGateway( pub_callback, sub_callback, in_prefix=in_prefix, out_prefix=out_prefix, retain=retain, loop=hass.loop, event_callback=None, persistence=persistence, persistence_file=persistence_file, protocol_version=version, ) else: try: await hass.async_add_job(is_serial_port, device) gateway = mysensors.AsyncSerialGateway( device, baud=baud_rate, loop=hass.loop, event_callback=None, persistence=persistence, persistence_file=persistence_file, protocol_version=version, ) except vol.Invalid: try: await hass.async_add_job(is_socket_address, device) # valid ip address gateway = mysensors.AsyncTCPGateway( device, port=tcp_port, loop=hass.loop, event_callback=None, persistence=persistence, persistence_file=persistence_file, protocol_version=version, ) except vol.Invalid: # invalid ip address return None gateway.metric = hass.config.units.is_metric gateway.optimistic = conf[CONF_OPTIMISTIC] gateway.device = device gateway.event_callback = _gw_callback_factory(hass, config) gateway.nodes_config = gateway_conf[CONF_NODES] if persistence: await gateway.start_persistence() return gateway async def finish_setup(hass, hass_config, gateways): """Load any persistent devices and platforms and start gateway.""" discover_tasks = [] start_tasks = [] for gateway in gateways.values(): discover_tasks.append(_discover_persistent_devices(hass, hass_config, gateway)) start_tasks.append(_gw_start(hass, gateway)) if discover_tasks: # Make sure all devices and platforms are loaded before gateway start. await asyncio.wait(discover_tasks) if start_tasks: await asyncio.wait(start_tasks) async def _discover_persistent_devices(hass, hass_config, gateway): """Discover platforms for devices loaded via persistence file.""" tasks = [] new_devices = defaultdict(list) for node_id in gateway.sensors: if not validate_node(gateway, node_id): continue node = gateway.sensors[node_id] for child in node.children.values(): validated = validate_child(gateway, node_id, child) for platform, dev_ids in validated.items(): new_devices[platform].extend(dev_ids) for platform, dev_ids in new_devices.items(): tasks.append(discover_mysensors_platform(hass, hass_config, platform, dev_ids)) if tasks: await asyncio.wait(tasks) async def _gw_start(hass, gateway): """Start the gateway.""" # Don't use hass.async_create_task to avoid holding up setup indefinitely. connect_task = hass.loop.create_task(gateway.start()) @callback def gw_stop(event): """Trigger to stop the gateway.""" hass.async_create_task(gateway.stop()) if not connect_task.done(): connect_task.cancel() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, gw_stop) if gateway.device == "mqtt": # Gatways connected via mqtt doesn't send gateway ready message. return gateway_ready = asyncio.Future() gateway_ready_key = MYSENSORS_GATEWAY_READY.format(id(gateway)) hass.data[gateway_ready_key] = gateway_ready try: with async_timeout.timeout(GATEWAY_READY_TIMEOUT): await gateway_ready except asyncio.TimeoutError: _LOGGER.warning( "Gateway %s not ready after %s secs so continuing with setup", gateway.device, GATEWAY_READY_TIMEOUT, ) finally: hass.data.pop(gateway_ready_key, None) def _gw_callback_factory(hass, hass_config): """Return a new callback for the gateway.""" @callback def mysensors_callback(msg): """Handle messages from a MySensors gateway.""" _LOGGER.debug("Node update: node %s child %s", msg.node_id, msg.child_id) msg_type = msg.gateway.const.MessageType(msg.type) msg_handler = HANDLERS.get(msg_type.name) if msg_handler is None: return hass.async_create_task(msg_handler(hass, hass_config, msg)) return mysensors_callback
# Copyright (c) 2011 OpenStack Foundation # # 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. """Compute-related Utilities and helpers.""" import contextlib import functools import inspect import itertools import math import string import traceback import netifaces from oslo_log import log from oslo_serialization import jsonutils import six from nova import block_device from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_states import nova.conf from nova import exception from nova import notifications from nova.notifications.objects import aggregate as aggregate_notification from nova.notifications.objects import base as notification_base from nova.notifications.objects import compute_task as task_notification from nova.notifications.objects import exception as notification_exception from nova.notifications.objects import flavor as flavor_notification from nova.notifications.objects import instance as instance_notification from nova.notifications.objects import keypair as keypair_notification from nova.notifications.objects import libvirt as libvirt_notification from nova.notifications.objects import metrics as metrics_notification from nova.notifications.objects import request_spec as reqspec_notification from nova.notifications.objects import scheduler as scheduler_notification from nova.notifications.objects import server_group as sg_notification from nova.notifications.objects import volume as volume_notification from nova import objects from nova.objects import fields from nova import rpc from nova import safe_utils from nova import utils from nova.virt import driver CONF = nova.conf.CONF LOG = log.getLogger(__name__) def exception_to_dict(fault, message=None): """Converts exceptions to a dict for use in notifications.""" # TODO(johngarbutt) move to nova/exception.py to share with wrap_exception code = 500 if hasattr(fault, "kwargs"): code = fault.kwargs.get('code', 500) # get the message from the exception that was thrown # if that does not exist, use the name of the exception class itself try: if not message: message = fault.format_message() # These exception handlers are broad so we don't fail to log the fault # just because there is an unexpected error retrieving the message except Exception: try: message = six.text_type(fault) except Exception: message = None if not message: message = fault.__class__.__name__ # NOTE(dripton) The message field in the database is limited to 255 chars. # MySQL silently truncates overly long messages, but PostgreSQL throws an # error if we don't truncate it. u_message = utils.safe_truncate(message, 255) fault_dict = dict(exception=fault) fault_dict["message"] = u_message fault_dict["code"] = code return fault_dict def _get_fault_details(exc_info, error_code): details = '' if exc_info and error_code == 500: tb = exc_info[2] if tb: details = ''.join(traceback.format_tb(tb)) return six.text_type(details) def add_instance_fault_from_exc(context, instance, fault, exc_info=None, fault_message=None): """Adds the specified fault to the database.""" fault_obj = objects.InstanceFault(context=context) fault_obj.host = CONF.host fault_obj.instance_uuid = instance.uuid fault_obj.update(exception_to_dict(fault, message=fault_message)) code = fault_obj.code fault_obj.details = _get_fault_details(exc_info, code) fault_obj.create() def get_device_name_for_instance(instance, bdms, device): """Validates (or generates) a device name for instance. This method is a wrapper for get_next_device_name that gets the list of used devices and the root device from a block device mapping. """ mappings = block_device.instance_block_mapping(instance, bdms) return get_next_device_name(instance, mappings.values(), mappings['root'], device) def default_device_names_for_instance(instance, root_device_name, *block_device_lists): """Generate missing device names for an instance.""" dev_list = [bdm.device_name for bdm in itertools.chain(*block_device_lists) if bdm.device_name] if root_device_name not in dev_list: dev_list.append(root_device_name) for bdm in itertools.chain(*block_device_lists): dev = bdm.device_name if not dev: dev = get_next_device_name(instance, dev_list, root_device_name) bdm.device_name = dev bdm.save() dev_list.append(dev) def get_next_device_name(instance, device_name_list, root_device_name=None, device=None): """Validates (or generates) a device name for instance. If device is not set, it will generate a unique device appropriate for the instance. It uses the root_device_name (if provided) and the list of used devices to find valid device names. If the device name is valid but applicable to a different backend (for example /dev/vdc is specified but the backend uses /dev/xvdc), the device name will be converted to the appropriate format. """ req_prefix = None req_letter = None if device: try: req_prefix, req_letter = block_device.match_device(device) except (TypeError, AttributeError, ValueError): raise exception.InvalidDevicePath(path=device) if not root_device_name: root_device_name = block_device.DEFAULT_ROOT_DEV_NAME try: prefix = block_device.match_device( block_device.prepend_dev(root_device_name))[0] except (TypeError, AttributeError, ValueError): raise exception.InvalidDevicePath(path=root_device_name) # NOTE(vish): remove this when xenapi is setting default_root_device if driver.is_xenapi(): prefix = '/dev/xvd' if req_prefix != prefix: LOG.debug("Using %(prefix)s instead of %(req_prefix)s", {'prefix': prefix, 'req_prefix': req_prefix}) used_letters = set() for device_path in device_name_list: letter = block_device.get_device_letter(device_path) used_letters.add(letter) # NOTE(vish): remove this when xenapi is properly setting # default_ephemeral_device and default_swap_device if driver.is_xenapi(): flavor = instance.get_flavor() if flavor.ephemeral_gb: used_letters.add('b') if flavor.swap: used_letters.add('c') if not req_letter: req_letter = _get_unused_letter(used_letters) if req_letter in used_letters: raise exception.DevicePathInUse(path=device) return prefix + req_letter def get_root_bdm(context, instance, bdms=None): if bdms is None: if isinstance(instance, objects.Instance): uuid = instance.uuid else: uuid = instance['uuid'] bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, uuid) return bdms.root_bdm() def is_volume_backed_instance(context, instance, bdms=None): root_bdm = get_root_bdm(context, instance, bdms) if root_bdm is not None: return root_bdm.is_volume # in case we hit a very old instance without root bdm, we _assume_ that # instance is backed by a volume, if and only if image_ref is not set if isinstance(instance, objects.Instance): return not instance.image_ref return not instance['image_ref'] def heal_reqspec_is_bfv(ctxt, request_spec, instance): """Calculates the is_bfv flag for a RequestSpec created before Rocky. Starting in Rocky, new instances have their RequestSpec created with the "is_bfv" flag to indicate if they are volume-backed which is used by the scheduler when determining root disk resource allocations. RequestSpecs created before Rocky will not have the is_bfv flag set so we need to calculate it here and update the RequestSpec. :param ctxt: nova.context.RequestContext auth context :param request_spec: nova.objects.RequestSpec used for scheduling :param instance: nova.objects.Instance being scheduled """ if 'is_bfv' in request_spec: return # Determine if this is a volume-backed instance and set the field # in the request spec accordingly. request_spec.is_bfv = is_volume_backed_instance(ctxt, instance) request_spec.save() def convert_mb_to_ceil_gb(mb_value): gb_int = 0 if mb_value: gb_float = mb_value / 1024.0 # ensure we reserve/allocate enough space by rounding up to nearest GB gb_int = int(math.ceil(gb_float)) return gb_int def _get_unused_letter(used_letters): doubles = [first + second for second in string.ascii_lowercase for first in string.ascii_lowercase] all_letters = set(list(string.ascii_lowercase) + doubles) letters = list(all_letters - used_letters) # NOTE(vish): prepend ` so all shorter sequences sort first letters.sort(key=lambda x: x.rjust(2, '`')) return letters[0] def get_value_from_system_metadata(instance, key, type, default): """Get a value of a specified type from image metadata. @param instance: The instance object @param key: The name of the property to get @param type: The python type the value is be returned as @param default: The value to return if key is not set or not the right type """ value = instance.system_metadata.get(key, default) try: return type(value) except ValueError: LOG.warning("Metadata value %(value)s for %(key)s is not of " "type %(type)s. Using default value %(default)s.", {'value': value, 'key': key, 'type': type, 'default': default}, instance=instance) return default def notify_usage_exists(notifier, context, instance_ref, host, current_period=False, ignore_missing_network_data=True, system_metadata=None, extra_usage_info=None): """Generates 'exists' unversioned legacy and transformed notification for an instance for usage auditing purposes. :param notifier: a messaging.Notifier :param context: request context for the current operation :param instance_ref: nova.objects.Instance object from which to report usage :param host: the host emitting the notification :param current_period: if True, this will generate a usage for the current usage period; if False, this will generate a usage for the previous audit period. :param ignore_missing_network_data: if True, log any exceptions generated while getting network info; if False, raise the exception. :param system_metadata: system_metadata override for the instance. If None, the instance_ref.system_metadata will be used. :param extra_usage_info: Dictionary containing extra values to add or override in the notification if not None. """ audit_start, audit_end = notifications.audit_period_bounds(current_period) bw = notifications.bandwidth_usage(context, instance_ref, audit_start, ignore_missing_network_data) if system_metadata is None: system_metadata = utils.instance_sys_meta(instance_ref) # add image metadata to the notification: image_meta = notifications.image_meta(system_metadata) extra_info = dict(audit_period_beginning=str(audit_start), audit_period_ending=str(audit_end), bandwidth=bw, image_meta=image_meta) if extra_usage_info: extra_info.update(extra_usage_info) notify_about_instance_usage(notifier, context, instance_ref, 'exists', extra_usage_info=extra_info) audit_period = instance_notification.AuditPeriodPayload( audit_period_beginning=audit_start, audit_period_ending=audit_end) bandwidth = [instance_notification.BandwidthPayload( network_name=label, in_bytes=b['bw_in'], out_bytes=b['bw_out']) for label, b in bw.items()] payload = instance_notification.InstanceExistsPayload( context=context, instance=instance_ref, audit_period=audit_period, bandwidth=bandwidth) notification = instance_notification.InstanceExistsNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.EXISTS), payload=payload) notification.emit(context) def notify_about_instance_usage(notifier, context, instance, event_suffix, network_info=None, extra_usage_info=None, fault=None): """Send an unversioned legacy notification about an instance. All new notifications should use notify_about_instance_action which sends a versioned notification. :param notifier: a messaging.Notifier :param event_suffix: Event type like "delete.start" or "exists" :param network_info: Networking information, if provided. :param extra_usage_info: Dictionary containing extra values to add or override in the notification. """ if not extra_usage_info: extra_usage_info = {} usage_info = notifications.info_from_instance(context, instance, network_info, populate_image_ref_url=True, **extra_usage_info) if fault: # NOTE(johngarbutt) mirrors the format in wrap_exception fault_payload = exception_to_dict(fault) LOG.debug(fault_payload["message"], instance=instance) usage_info.update(fault_payload) if event_suffix.endswith("error"): method = notifier.error else: method = notifier.info method(context, 'compute.instance.%s' % event_suffix, usage_info) def _get_fault_and_priority_from_exc_and_tb(exception, tb): fault = None priority = fields.NotificationPriority.INFO if exception: priority = fields.NotificationPriority.ERROR fault = notification_exception.ExceptionPayload.from_exc_and_traceback( exception, tb) return fault, priority @rpc.if_notifications_enabled def notify_about_instance_action(context, instance, host, action, phase=None, source=fields.NotificationSource.COMPUTE, exception=None, bdms=None, tb=None): """Send versioned notification about the action made on the instance :param instance: the instance which the action performed on :param host: the host emitting the notification :param action: the name of the action :param phase: the phase of the action :param source: the source of the notification :param exception: the thrown exception (used in error notifications) :param bdms: BlockDeviceMappingList object for the instance. If it is not provided then we will load it from the db if so configured :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceActionPayload( context=context, instance=instance, fault=fault, bdms=bdms) notification = instance_notification.InstanceActionNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=source), event_type=notification_base.EventType( object='instance', action=action, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_instance_create(context, instance, host, phase=None, exception=None, bdms=None, tb=None): """Send versioned notification about instance creation :param context: the request context :param instance: the instance being created :param host: the host emitting the notification :param phase: the phase of the creation :param exception: the thrown exception (used in error notifications) :param bdms: BlockDeviceMappingList object for the instance. If it is not provided then we will load it from the db if so configured :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceCreatePayload( context=context, instance=instance, fault=fault, bdms=bdms) notification = instance_notification.InstanceCreateNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.CREATE, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_scheduler_action(context, request_spec, action, phase=None, source=fields.NotificationSource.SCHEDULER): """Send versioned notification about the action made by the scheduler :param context: the RequestContext object :param request_spec: the RequestSpec object :param action: the name of the action :param phase: the phase of the action :param source: the source of the notification """ payload = reqspec_notification.RequestSpecPayload( request_spec=request_spec) notification = scheduler_notification.SelectDestinationsNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=CONF.host, source=source), event_type=notification_base.EventType( object='scheduler', action=action, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_volume_attach_detach(context, instance, host, action, phase, volume_id=None, exception=None, tb=None): """Send versioned notification about the action made on the instance :param instance: the instance which the action performed on :param host: the host emitting the notification :param action: the name of the action :param phase: the phase of the action :param volume_id: id of the volume will be attached :param exception: the thrown exception (used in error notifications) :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceActionVolumePayload( context=context, instance=instance, fault=fault, volume_id=volume_id) notification = instance_notification.InstanceActionVolumeNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=action, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_instance_rescue_action(context, instance, host, rescue_image_ref, phase=None, exception=None, tb=None): """Send versioned notification about the action made on the instance :param instance: the instance which the action performed on :param host: the host emitting the notification :param rescue_image_ref: the rescue image ref :param phase: the phase of the action :param exception: the thrown exception (used in error notifications) :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceActionRescuePayload( context=context, instance=instance, fault=fault, rescue_image_ref=rescue_image_ref) notification = instance_notification.InstanceActionRescueNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.RESCUE, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_keypair_action(context, keypair, action, phase): """Send versioned notification about the keypair action on the instance :param context: the request context :param keypair: the keypair which the action performed on :param action: the name of the action :param phase: the phase of the action """ payload = keypair_notification.KeypairPayload(keypair=keypair) notification = keypair_notification.KeypairNotification( priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.API), event_type=notification_base.EventType( object='keypair', action=action, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_volume_swap(context, instance, host, phase, old_volume_id, new_volume_id, exception=None, tb=None): """Send versioned notification about the volume swap action on the instance :param context: the request context :param instance: the instance which the action performed on :param host: the host emitting the notification :param phase: the phase of the action :param old_volume_id: the ID of the volume that is copied from and detached :param new_volume_id: the ID of the volume that is copied to and attached :param exception: an exception :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceActionVolumeSwapPayload( context=context, instance=instance, fault=fault, old_volume_id=old_volume_id, new_volume_id=new_volume_id) instance_notification.InstanceActionVolumeSwapNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.VOLUME_SWAP, phase=phase), payload=payload).emit(context) @rpc.if_notifications_enabled def notify_about_instance_snapshot(context, instance, host, phase, snapshot_image_id): """Send versioned notification about the snapshot action executed on the instance :param context: the request context :param instance: the instance from which a snapshot image is being created :param host: the host emitting the notification :param phase: the phase of the action :param snapshot_image_id: the ID of the snapshot """ payload = instance_notification.InstanceActionSnapshotPayload( context=context, instance=instance, fault=None, snapshot_image_id=snapshot_image_id) instance_notification.InstanceActionSnapshotNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.SNAPSHOT, phase=phase), payload=payload).emit(context) @rpc.if_notifications_enabled def notify_about_resize_prep_instance(context, instance, host, phase, new_flavor): """Send versioned notification about the instance resize action on the instance :param context: the request context :param instance: the instance which the resize action performed on :param host: the host emitting the notification :param phase: the phase of the action :param new_flavor: new flavor """ payload = instance_notification.InstanceActionResizePrepPayload( context=context, instance=instance, fault=None, new_flavor=flavor_notification.FlavorPayload(flavor=new_flavor)) instance_notification.InstanceActionResizePrepNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='instance', action=fields.NotificationAction.RESIZE_PREP, phase=phase), payload=payload).emit(context) def notify_about_server_group_update(context, event_suffix, sg_payload): """Send a notification about server group update. :param event_suffix: Event type like "create.start" or "create.end" :param sg_payload: payload for server group update """ notifier = rpc.get_notifier(service='servergroup') notifier.info(context, 'servergroup.%s' % event_suffix, sg_payload) def notify_about_aggregate_update(context, event_suffix, aggregate_payload): """Send a notification about aggregate update. :param event_suffix: Event type like "create.start" or "create.end" :param aggregate_payload: payload for aggregate update """ aggregate_identifier = aggregate_payload.get('aggregate_id', None) if not aggregate_identifier: aggregate_identifier = aggregate_payload.get('name', None) if not aggregate_identifier: LOG.debug("No aggregate id or name specified for this " "notification and it will be ignored") return notifier = rpc.get_notifier(service='aggregate', host=aggregate_identifier) notifier.info(context, 'aggregate.%s' % event_suffix, aggregate_payload) @rpc.if_notifications_enabled def notify_about_aggregate_action(context, aggregate, action, phase): payload = aggregate_notification.AggregatePayload(aggregate) notification = aggregate_notification.AggregateNotification( priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.API), event_type=notification_base.EventType( object='aggregate', action=action, phase=phase), payload=payload) notification.emit(context) def notify_about_host_update(context, event_suffix, host_payload): """Send a notification about host update. :param event_suffix: Event type like "create.start" or "create.end" :param host_payload: payload for host update. It is a dict and there should be at least the 'host_name' key in this dict. """ host_identifier = host_payload.get('host_name') if not host_identifier: LOG.warning("No host name specified for the notification of " "HostAPI.%s and it will be ignored", event_suffix) return notifier = rpc.get_notifier(service='api', host=host_identifier) notifier.info(context, 'HostAPI.%s' % event_suffix, host_payload) @rpc.if_notifications_enabled def notify_about_server_group_action(context, group, action): payload = sg_notification.ServerGroupPayload(group) notification = sg_notification.ServerGroupNotification( priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.API), event_type=notification_base.EventType( object='server_group', action=action), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_server_group_add_member(context, group_id): group = objects.InstanceGroup.get_by_uuid(context, group_id) payload = sg_notification.ServerGroupPayload(group) notification = sg_notification.ServerGroupNotification( priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.API), event_type=notification_base.EventType( object='server_group', action=fields.NotificationAction.ADD_MEMBER), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_instance_rebuild(context, instance, host, action=fields.NotificationAction.REBUILD, phase=None, source=fields.NotificationSource.COMPUTE, exception=None, bdms=None, tb=None): """Send versioned notification about instance rebuild :param instance: the instance which the action performed on :param host: the host emitting the notification :param action: the name of the action :param phase: the phase of the action :param source: the source of the notification :param exception: the thrown exception (used in error notifications) :param bdms: BlockDeviceMappingList object for the instance. If it is not provided then we will load it from the db if so configured :param tb: the traceback (used in error notifications) """ fault, priority = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = instance_notification.InstanceActionRebuildPayload( context=context, instance=instance, fault=fault, bdms=bdms) notification = instance_notification.InstanceActionRebuildNotification( context=context, priority=priority, publisher=notification_base.NotificationPublisher( host=host, source=source), event_type=notification_base.EventType( object='instance', action=action, phase=phase), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_metrics_update(context, host, host_ip, nodename, monitor_metric_list): """Send versioned notification about updating metrics :param context: the request context :param host: the host emitting the notification :param host_ip: the IP address of the host :param nodename: the node name :param monitor_metric_list: the MonitorMetricList object """ payload = metrics_notification.MetricsPayload( host=host, host_ip=host_ip, nodename=nodename, monitor_metric_list=monitor_metric_list) notification = metrics_notification.MetricsNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='metrics', action=fields.NotificationAction.UPDATE), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_libvirt_connect_error(context, ip, exception, tb): """Send a versioned notification about libvirt connect error. :param context: the request context :param ip: the IP address of the host :param exception: the thrown exception :param tb: the traceback """ fault, _ = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = libvirt_notification.LibvirtErrorPayload(ip=ip, reason=fault) notification = libvirt_notification.LibvirtErrorNotification( priority=fields.NotificationPriority.ERROR, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='libvirt', action=fields.NotificationAction.CONNECT, phase=fields.NotificationPhase.ERROR), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_volume_usage(context, vol_usage, host): """Send versioned notification about the volume usage :param context: the request context :param vol_usage: the volume usage object :param host: the host emitting the notification """ payload = volume_notification.VolumeUsagePayload( vol_usage=vol_usage) notification = volume_notification.VolumeUsageNotification( context=context, priority=fields.NotificationPriority.INFO, publisher=notification_base.NotificationPublisher( host=host, source=fields.NotificationSource.COMPUTE), event_type=notification_base.EventType( object='volume', action=fields.NotificationAction.USAGE), payload=payload) notification.emit(context) @rpc.if_notifications_enabled def notify_about_compute_task_error(context, action, instance_uuid, request_spec, state, exception, tb): """Send a versioned notification about compute task error. :param context: the request context :param action: the name of the action :param instance_uuid: the UUID of the instance :param request_spec: the request spec object or the dict includes request spec information :param state: the vm state of the instance :param exception: the thrown exception :param tb: the traceback """ if (request_spec is not None and not isinstance(request_spec, objects.RequestSpec)): request_spec = objects.RequestSpec.from_primitives( context, request_spec, {}) fault, _ = _get_fault_and_priority_from_exc_and_tb(exception, tb) payload = task_notification.ComputeTaskPayload( instance_uuid=instance_uuid, request_spec=request_spec, state=state, reason=fault) notification = task_notification.ComputeTaskNotification( priority=fields.NotificationPriority.ERROR, publisher=notification_base.NotificationPublisher( host=CONF.host, source=fields.NotificationSource.CONDUCTOR), event_type=notification_base.EventType( object='compute_task', action=action, phase=fields.NotificationPhase.ERROR), payload=payload) notification.emit(context) def refresh_info_cache_for_instance(context, instance): """Refresh the info cache for an instance. :param instance: The instance object. """ if instance.info_cache is not None and not instance.deleted: # Catch the exception in case the instance got deleted after the check # instance.deleted was executed try: instance.info_cache.refresh() except exception.InstanceInfoCacheNotFound: LOG.debug("Can not refresh info_cache because instance " "was not found", instance=instance) def get_reboot_type(task_state, current_power_state): """Checks if the current instance state requires a HARD reboot.""" if current_power_state != power_state.RUNNING: return 'HARD' if task_state in task_states.soft_reboot_states: return 'SOFT' return 'HARD' def get_machine_ips(): """Get the machine's ip addresses :returns: list of Strings of ip addresses """ addresses = [] for interface in netifaces.interfaces(): try: iface_data = netifaces.ifaddresses(interface) for family in iface_data: if family not in (netifaces.AF_INET, netifaces.AF_INET6): continue for address in iface_data[family]: addr = address['addr'] # If we have an ipv6 address remove the # %ether_interface at the end if family == netifaces.AF_INET6: addr = addr.split('%')[0] addresses.append(addr) except ValueError: pass return addresses def upsize_quota_delta(new_flavor, old_flavor): """Calculate deltas required to adjust quota for an instance upsize. :param new_flavor: the target instance type :param old_flavor: the original instance type """ def _quota_delta(resource): return (new_flavor[resource] - old_flavor[resource]) deltas = {} if _quota_delta('vcpus') > 0: deltas['cores'] = _quota_delta('vcpus') if _quota_delta('memory_mb') > 0: deltas['ram'] = _quota_delta('memory_mb') return deltas def get_headroom(quotas, usages, deltas): headroom = {res: quotas[res] - usages[res] for res in quotas.keys()} # If quota_cores is unlimited [-1]: # - set cores headroom based on instances headroom: if quotas.get('cores') == -1: if deltas.get('cores'): hc = headroom.get('instances', 1) * deltas['cores'] headroom['cores'] = hc / deltas.get('instances', 1) else: headroom['cores'] = headroom.get('instances', 1) # If quota_ram is unlimited [-1]: # - set ram headroom based on instances headroom: if quotas.get('ram') == -1: if deltas.get('ram'): hr = headroom.get('instances', 1) * deltas['ram'] headroom['ram'] = hr / deltas.get('instances', 1) else: headroom['ram'] = headroom.get('instances', 1) return headroom def check_num_instances_quota(context, instance_type, min_count, max_count, project_id=None, user_id=None, orig_num_req=None): """Enforce quota limits on number of instances created.""" # project_id is used for the TooManyInstances error message if project_id is None: project_id = context.project_id # Determine requested cores and ram req_cores = max_count * instance_type.vcpus req_ram = max_count * instance_type.memory_mb deltas = {'instances': max_count, 'cores': req_cores, 'ram': req_ram} try: objects.Quotas.check_deltas(context, deltas, project_id, user_id=user_id, check_project_id=project_id, check_user_id=user_id) except exception.OverQuota as exc: quotas = exc.kwargs['quotas'] overs = exc.kwargs['overs'] usages = exc.kwargs['usages'] # This is for the recheck quota case where we used a delta of zero. if min_count == max_count == 0: # orig_num_req is the original number of instances requested in the # case of a recheck quota, for use in the over quota exception. req_cores = orig_num_req * instance_type.vcpus req_ram = orig_num_req * instance_type.memory_mb requested = {'instances': orig_num_req, 'cores': req_cores, 'ram': req_ram} (overs, reqs, total_alloweds, useds) = get_over_quota_detail( deltas, overs, quotas, requested) msg = "Cannot run any more instances of this type." params = {'overs': overs, 'pid': project_id, 'msg': msg} LOG.debug("%(overs)s quota exceeded for %(pid)s. %(msg)s", params) raise exception.TooManyInstances(overs=overs, req=reqs, used=useds, allowed=total_alloweds) # OK, we exceeded quota; let's figure out why... headroom = get_headroom(quotas, usages, deltas) allowed = headroom.get('instances', 1) # Reduce 'allowed' instances in line with the cores & ram headroom if instance_type.vcpus: allowed = min(allowed, headroom['cores'] // instance_type.vcpus) if instance_type.memory_mb: allowed = min(allowed, headroom['ram'] // instance_type.memory_mb) # Convert to the appropriate exception message if allowed <= 0: msg = "Cannot run any more instances of this type." elif min_count <= allowed <= max_count: # We're actually OK, but still need to check against allowed return check_num_instances_quota(context, instance_type, min_count, allowed, project_id=project_id, user_id=user_id) else: msg = "Can only run %s more instances of this type." % allowed num_instances = (str(min_count) if min_count == max_count else "%s-%s" % (min_count, max_count)) requested = dict(instances=num_instances, cores=req_cores, ram=req_ram) (overs, reqs, total_alloweds, useds) = get_over_quota_detail( headroom, overs, quotas, requested) params = {'overs': overs, 'pid': project_id, 'min_count': min_count, 'max_count': max_count, 'msg': msg} if min_count == max_count: LOG.debug("%(overs)s quota exceeded for %(pid)s," " tried to run %(min_count)d instances. " "%(msg)s", params) else: LOG.debug("%(overs)s quota exceeded for %(pid)s," " tried to run between %(min_count)d and" " %(max_count)d instances. %(msg)s", params) raise exception.TooManyInstances(overs=overs, req=reqs, used=useds, allowed=total_alloweds) return max_count def get_over_quota_detail(headroom, overs, quotas, requested): reqs = [] useds = [] total_alloweds = [] for resource in overs: reqs.append(str(requested[resource])) useds.append(str(quotas[resource] - headroom[resource])) total_alloweds.append(str(quotas[resource])) (overs, reqs, useds, total_alloweds) = map(', '.join, ( overs, reqs, useds, total_alloweds)) return overs, reqs, total_alloweds, useds def remove_shelved_keys_from_system_metadata(instance): # Delete system_metadata for a shelved instance for key in ['shelved_at', 'shelved_image_id', 'shelved_host']: if key in instance.system_metadata: del (instance.system_metadata[key]) def may_have_ports_or_volumes(instance): """Checks to see if an instance may have ports or volumes based on vm_state This is primarily only useful when instance.host is None. :param instance: The nova.objects.Instance in question. :returns: True if the instance may have ports of volumes, False otherwise """ # NOTE(melwitt): When an instance build fails in the compute manager, # the instance host and node are set to None and the vm_state is set # to ERROR. In the case, the instance with host = None has actually # been scheduled and may have ports and/or volumes allocated on the # compute node. if instance.vm_state in (vm_states.SHELVED_OFFLOADED, vm_states.ERROR): return True return False def get_stashed_volume_connector(bdm, instance): """Lookup a connector dict from the bdm.connection_info if set Gets the stashed connector dict out of the bdm.connection_info if set and the connector host matches the instance host. :param bdm: nova.objects.block_device.BlockDeviceMapping :param instance: nova.objects.instance.Instance :returns: volume connector dict or None """ if 'connection_info' in bdm and bdm.connection_info is not None: # NOTE(mriedem): We didn't start stashing the connector in the # bdm.connection_info until Mitaka so it might not be there on old # attachments. Also, if the volume was attached when the instance # was in shelved_offloaded state and it hasn't been unshelved yet # we don't have the attachment/connection information either. connector = jsonutils.loads(bdm.connection_info).get('connector') if connector: if connector.get('host') == instance.host: return connector LOG.debug('Found stashed volume connector for instance but ' 'connector host %(connector_host)s does not match ' 'the instance host %(instance_host)s.', {'connector_host': connector.get('host'), 'instance_host': instance.host}, instance=instance) if (instance.host is None and may_have_ports_or_volumes(instance)): LOG.debug('Allowing use of stashed volume connector with ' 'instance host None because instance with ' 'vm_state %(vm_state)s has been scheduled in ' 'the past.', {'vm_state': instance.vm_state}, instance=instance) return connector class EventReporter(object): """Context manager to report instance action events.""" def __init__(self, context, event_name, host, *instance_uuids): self.context = context self.event_name = event_name self.instance_uuids = instance_uuids self.host = host def __enter__(self): for uuid in self.instance_uuids: objects.InstanceActionEvent.event_start( self.context, uuid, self.event_name, want_result=False, host=self.host) return self def __exit__(self, exc_type, exc_val, exc_tb): for uuid in self.instance_uuids: objects.InstanceActionEvent.event_finish_with_failure( self.context, uuid, self.event_name, exc_val=exc_val, exc_tb=exc_tb, want_result=False) return False def wrap_instance_event(prefix): """Wraps a method to log the event taken on the instance, and result. This decorator wraps a method to log the start and result of an event, as part of an action taken on an instance. """ @utils.expects_func_args('instance') def helper(function): @functools.wraps(function) def decorated_function(self, context, *args, **kwargs): wrapped_func = safe_utils.get_wrapped_function(function) keyed_args = inspect.getcallargs(wrapped_func, self, context, *args, **kwargs) instance_uuid = keyed_args['instance']['uuid'] event_name = '{0}_{1}'.format(prefix, function.__name__) host = self.host if hasattr(self, 'host') else None with EventReporter(context, event_name, host, instance_uuid): return function(self, context, *args, **kwargs) return decorated_function return helper class UnlimitedSemaphore(object): def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass @property def balance(self): return 0 # This semaphore is used to enforce a limit on disk-IO-intensive operations # (image downloads, image conversions) at any given time. # It is initialized at ComputeManager.init_host() disk_ops_semaphore = UnlimitedSemaphore() @contextlib.contextmanager def notify_about_instance_delete(notifier, context, instance, delete_type='delete', source=fields.NotificationSource.API): try: notify_about_instance_usage(notifier, context, instance, "%s.start" % delete_type) # Note(gibi): force_delete types will be handled in a # subsequent patch if delete_type in ['delete', 'soft_delete']: notify_about_instance_action( context, instance, host=CONF.host, source=source, action=delete_type, phase=fields.NotificationPhase.START) yield finally: notify_about_instance_usage(notifier, context, instance, "%s.end" % delete_type) if delete_type in ['delete', 'soft_delete']: notify_about_instance_action( context, instance, host=CONF.host, source=source, action=delete_type, phase=fields.NotificationPhase.END)
""" SuperFences. pymdownx.superfences Nested Fenced Code Blocks This is a modification of the original Fenced Code Extension. Algorithm has been rewritten to allow for fenced blocks in blockquotes, lists, etc. And also , allow for special UML fences like 'flow' for flowcharts and `sequence` for sequence diagrams. Modified: 2014 - 2017 Isaac Muse <isaacmuse@gmail.com> --- Fenced Code Extension for Python Markdown ========================================= This extension adds Fenced Code Blocks to Python-Markdown. See <https://pythonhosted.org/Markdown/extensions/fenced_code_blocks.html> for documentation. Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/). All changes Copyright 2008-2014 The Python Markdown Project License: [BSD](http://www.opensource.org/licenses/bsd-license.php) """ from __future__ import absolute_import from __future__ import unicode_literals from markdown.extensions import Extension from markdown.preprocessors import Preprocessor from markdown.blockprocessors import CodeBlockProcessor from markdown import util as md_util from . import highlight as hl import re SOH = '\u0001' EOT = '\u0004' PREFIX_CHARS = ('>', ' ', '\t') RE_NESTED_FENCE_START = re.compile( r'''(?x) (?P<fence>~{3,}|`{3,})[ \t]* # Fence opening (\{? # Language opening \.?(?P<lang>[\w#.+-]*))?[ \t]* # Language (?: (hl_lines=(?P<quot>"|')(?P<hl_lines>\d+(?:[ \t]+\d+)*)(?P=quot))?[ \t]*| # highlight lines (linenums=(?P<quot2>"|') # Line numbers (?P<linestart>[\d]+) # Line number start (?:[ \t]+(?P<linestep>[\d]+))? # Line step (?:[ \t]+(?P<linespecial>[\d]+))? # Line special (?P=quot2))?[ \t]* ){,2} }?[ \t]*$ # Language closing ''' ) NESTED_FENCE_END = r'%s[ \t]*$' def _escape(txt): """Basic html escaping.""" txt = txt.replace('&', '&amp;') txt = txt.replace('<', '&lt;') txt = txt.replace('>', '&gt;') txt = txt.replace('"', '&quot;') return txt class CodeStash(object): """ Stash code for later retrieval. Store original fenced code here in case we were too greedy and need to restore in an indented code block. """ def __init__(self): """Initialize.""" self.stash = {} def __len__(self): # pragma: no cover """Length of stash.""" return len(self.stash) def get(self, key, default=None): """Get the code from the key.""" code = self.stash.get(key, default) return code def remove(self, key): """Remove the stashed code.""" del self.stash[key] def store(self, key, code, indent_level): """Store the code in the stash.""" self.stash[key] = (code, indent_level) def clear_stash(self): """Clear the stash.""" self.stash = {} def fence_code_format(source, language, css_class): """Format source as code blocks.""" return '<pre class="%s"><code>%s</code></pre>' % (css_class, _escape(source)) def fence_div_format(source, language, css_class): """Format source as div.""" return '<div class="%s">%s</div>' % (css_class, _escape(source)) class SuperFencesCodeExtension(Extension): """SuperFences code block extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.superfences = [] self.config = { 'disable_indented_code_blocks': [False, "Disable indented code blocks - Default: False"], 'custom_fences': [ [ {'name': 'flow', 'class': 'uml-flowchart'}, {'name': 'sequence', 'class': 'uml-sequence-diagram'} ], 'Specify custom fences. Default: See documentation.' ], 'highlight_code': [True, "Highlight code - Default: True"], 'css_class': [ '', "Set class name for wrapper element. The default of CodeHilite or Highlight will be used" "if nothing is set. - " "Default: ''" ], 'preserve_tabs': [False, "Preserve tabs in fences - Default: False"] } super(SuperFencesCodeExtension, self).__init__(*args, **kwargs) def extend_super_fences(self, name, formatter): """Extend SuperFences with the given name, language, and formatter.""" self.superfences.append( { "name": name, "test": lambda l, language=name: language == l, "formatter": formatter } ) def extendMarkdown(self, md, md_globals): """Add fenced block preprocessor to the Markdown instance.""" # Not super yet, so let's make it super md.registerExtension(self) config = self.getConfigs() # Default fenced blocks self.superfences.insert( 0, { "name": "superfences", "test": lambda language: True, "formatter": None } ) # UML blocks custom_fences = config.get('custom_fences', []) for custom in custom_fences: name = custom.get('name') class_name = custom.get('class') fence_format = custom.get('format', fence_code_format) if name is not None and class_name is not None: self.extend_super_fences( name, lambda s, l, c=class_name, f=fence_format: f(s, l, c) ) self.markdown = md self.patch_fenced_rule() for entry in self.superfences: entry["stash"] = CodeStash() def patch_fenced_rule(self): """ Patch Python Markdown with our own fenced block extension. We don't attempt to protect against a user loading the `fenced_code` extension with this. Most likely they will have issues, but they shouldn't have loaded them together in the first place :). """ config = self.getConfigs() fenced = SuperFencesBlockPreprocessor(self.markdown) indented_code = SuperFencesCodeBlockProcessor(self) fenced.config = config fenced.extension = self indented_code.config = config indented_code.markdown = self.markdown indented_code.extension = self self.superfences[0]["formatter"] = fenced.highlight self.markdown.parser.blockprocessors['code'] = indented_code if config["preserve_tabs"]: self.markdown.preprocessors.add('fenced_code_block', fenced, "<normalize_whitespace") post_fenced = SuperFencesBlockPostNormalizePreprocessor(self.markdown) self.markdown.preprocessors.add('fenced_code_post_norm', post_fenced, ">normalize_whitespace") else: self.markdown.preprocessors.add('fenced_code_block', fenced, ">normalize_whitespace") def reset(self): """Clear the stash.""" for entry in self.superfences: entry["stash"].clear_stash() class SuperFencesBlockPostNormalizePreprocessor(Preprocessor): """Preprocessor to clean up normalization bypass hack.""" TEMP_PLACEHOLDER_RE = re.compile( r'^([\> ]*)%s(%s)%s$' % ( SOH, md_util.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)', EOT ) ) def run(self, lines): """Search for fenced blocks.""" new_lines = [] for line in lines: line = self.TEMP_PLACEHOLDER_RE.sub(r'\1' + md_util.STX + r'\2' + md_util.ETX, line) new_lines.append(line) return new_lines class SuperFencesBlockPreprocessor(Preprocessor): """ Preprocessor to find fenced code blocks. Because this is done as a preprocessor, it might be too greedy. We will stash the blocks code and restore if we mistakenly processed text from an indented code block. """ CODE_WRAP = '<pre%s><code%s>%s</code></pre>' def __init__(self, md): """Initialize.""" super(SuperFencesBlockPreprocessor, self).__init__(md) self.markdown = md self.tab_len = self.markdown.tab_length self.checked_hl_settings = False self.codehilite_conf = {} def normalize_ws(self, text): """Normalize whitespace.""" return text.expandtabs(self.tab_len) def rebuild_block(self, lines): """Dedent the fenced block lines.""" return '\n'.join([line[self.ws_virtual_len:] for line in lines]) def get_hl_settings(self): """Check for CodeHilite extension to get its config.""" if not self.checked_hl_settings: self.checked_hl_settings = True self.highlight_code = self.config['highlight_code'] config = hl.get_hl_settings(self.markdown) css_class = self.config['css_class'] self.css_class = css_class if css_class else config['css_class'] self.extend_pygments_lang = config.get('extend_pygments_lang', None) self.guess_lang = config['guess_lang'] self.pygments_style = config['pygments_style'] self.use_pygments = config['use_pygments'] self.noclasses = config['noclasses'] self.linenums = config['linenums'] def clear(self): """Reset the class variables.""" self.ws = None self.ws_len = 0 self.ws_virtual_len = 0 self.fence = None self.lang = None self.hl_lines = None self.linestart = None self.linestep = None self.linespecial = None self.quote_level = 0 self.code = [] self.empty_lines = 0 self.fence_end = None def eval_fence(self, ws, content, start, end): """Evaluate a normal fence.""" if (ws + content).strip() == '': # Empty line is okay self.empty_lines += 1 self.code.append(ws + content) elif len(ws) != self.ws_virtual_len and content != '': # Not indented enough self.clear() elif self.fence_end.match(content) is not None and not content.startswith((' ', '\t')): # End of fence self.process_nested_block(ws, content, start, end) else: # Content line self.empty_lines = 0 self.code.append(ws + content) def eval_quoted(self, ws, content, quote_level, start, end): """Evaluate fence inside a blockquote.""" if quote_level > self.quote_level: # Quote level exceeds the starting quote level self.clear() elif quote_level <= self.quote_level: if content == '': # Empty line is okay self.code.append(ws + content) self.empty_lines += 1 elif len(ws) < self.ws_len: # Not indented enough self.clear() elif self.empty_lines and quote_level < self.quote_level: # Quote levels don't match and we are signified # the end of the block with an empty line self.clear() elif self.fence_end.match(content) is not None: # End of fence self.process_nested_block(ws, content, start, end) else: # Content line self.empty_lines = 0 self.code.append(ws + content) def process_nested_block(self, ws, content, start, end): """Process the contents of the nested block.""" self.last = ws + self.normalize_ws(content) code = None for entry in reversed(self.extension.superfences): if entry["test"](self.lang): code = entry["formatter"](self.rebuild_block(self.code), self.lang) break if code is not None: self._store(self.normalize_ws('\n'.join(self.code)) + '\n', code, start, end, entry) self.clear() def parse_hl_lines(self, hl_lines): """Parse the lines to highlight.""" return list(map(int, hl_lines.strip().split())) if hl_lines else [] def parse_line_start(self, linestart): """Parse line start.""" return int(linestart) if linestart else -1 def parse_line_step(self, linestep): """Parse line start.""" step = int(linestep) if linestep else -1 return step if step > 1 else -1 def parse_line_special(self, linespecial): """Parse line start.""" return int(linespecial) if linespecial else -1 def parse_fence_line(self, line): """Parse fence line.""" ws_len = 0 ws_virtual_len = 0 ws = [] index = 0 for c in line: if ws_virtual_len >= self.ws_virtual_len: break if c not in PREFIX_CHARS: break ws_len += 1 if c == '\t': tab_size = self.tab_len - (index % self.tab_len) ws_virtual_len += tab_size ws.append(' ' * tab_size) else: tab_size = 1 ws_virtual_len += 1 ws.append(c) index += tab_size return ''.join(ws), line[ws_len:] def parse_whitespace(self, line): """Parse the whitespace (blockquote syntax is counted as well).""" self.ws_len = 0 self.ws_virtual_len = 0 ws = [] for c in line: if c not in PREFIX_CHARS: break self.ws_len += 1 ws.append(c) ws = self.normalize_ws(''.join(ws)) self.ws_virtual_len = len(ws) return ws def search_nested(self, lines): """Search for nested fenced blocks.""" count = 0 for line in lines: if self.fence is None: ws = self.parse_whitespace(line) # Found the start of a fenced block. m = RE_NESTED_FENCE_START.match(line, self.ws_len) if m is not None: start = count self.first = ws + self.normalize_ws(m.group(0)) self.ws = ws self.quote_level = self.ws.count(">") self.empty_lines = 0 self.fence = m.group('fence') self.lang = m.group('lang') self.hl_lines = m.group('hl_lines') self.linestart = m.group('linestart') self.linestep = m.group('linestep') self.linespecial = m.group('linespecial') self.fence_end = re.compile(NESTED_FENCE_END % self.fence) else: # Evaluate lines # - Determine if it is the ending line or content line # - If is a content line, make sure it is all indentend # with the opening and closing lines (lines with just # whitespace will be stripped so those don't matter). # - When content lines are inside blockquotes, make sure # the nested block quote levels make sense according to # blockquote rules. ws, content = self.parse_fence_line(line) end = count + 1 quote_level = ws.count(">") if self.quote_level: # Handle blockquotes self.eval_quoted(ws, content, quote_level, start, end) elif quote_level == 0: # Handle all other cases self.eval_fence(ws, content, start, end) else: # Looks like we got a blockquote line # when not in a blockquote. self.clear() count += 1 # Now that we are done iterating the lines, # let's replace the original content with the # fenced blocks. while len(self.stack): fenced, start, end = self.stack.pop() if self.preserve_tabs: lines = lines[:start] + [fenced.replace(md_util.STX, SOH, 1)[:-1] + EOT] + lines[end:] else: lines = lines[:start] + [fenced] + lines[end:] return lines def highlight(self, src, language): """ Syntax highlight the code block. If config is not empty, then the CodeHilite extension is enabled, so we call into it to highlight the code. """ if self.highlight_code: linestep = self.parse_line_step(self.linestep) linestart = self.parse_line_start(self.linestart) linespecial = self.parse_line_special(self.linespecial) hl_lines = self.parse_hl_lines(self.hl_lines) el = hl.Highlight( guess_lang=self.guess_lang, pygments_style=self.pygments_style, use_pygments=self.use_pygments, noclasses=self.noclasses, linenums=self.linenums, extend_pygments_lang=self.extend_pygments_lang ).highlight( src, language, self.css_class, hl_lines=hl_lines, linestart=linestart, linestep=linestep, linespecial=linespecial ) else: # Format as a code block. el = self.CODE_WRAP % ('', '', _escape(src)) return el def _store(self, source, code, start, end, obj): """ Store the fenced blocks in the stack to be replaced when done iterating. Store the original text in case we need to restore if we are too greedy. """ # Save the fenced blocks to add once we are done iterating the lines placeholder = self.markdown.htmlStash.store(code, safe=True) self.stack.append(('%s%s' % (self.ws, placeholder), start, end)) if not self.disabled_indented: # If an indented block consumes this placeholder, # we can restore the original source obj["stash"].store( placeholder[1:-1], "%s\n%s%s" % (self.first, self.normalize_ws(source), self.last), self.ws_virtual_len ) def run(self, lines): """Search for fenced blocks.""" self.get_hl_settings() self.clear() self.stack = [] self.disabled_indented = self.config.get("disable_indented_code_blocks", False) self.preserve_tabs = self.config.get("preserve_tabs", False) lines = self.search_nested(lines) return lines class SuperFencesCodeBlockProcessor(CodeBlockProcessor): """Process indented code blocks to see if we accidentally processed its content as a fenced block.""" FENCED_BLOCK_RE = re.compile( r'^([\> ]*)%s(%s)%s$' % ( md_util.HTML_PLACEHOLDER[0], md_util.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)', md_util.HTML_PLACEHOLDER[-1] ) ) def test(self, parent, block): """Test method that is one day to be deprecated.""" return True def reindent(self, text, pos, level): """Reindent the code to where it is supposed to be.""" indented = [] for line in text.split('\n'): index = pos - level indented.append(line[index:]) return '\n'.join(indented) def revert_greedy_fences(self, block): """Revert a prematurely converted fenced block.""" new_block = [] for line in block.split('\n'): m = self.FENCED_BLOCK_RE.match(line) if m: key = m.group(2) indent_level = len(m.group(1)) original = None for entry in self.extension.superfences: stash = entry["stash"] original, pos = stash.get(key) if original is not None: code = self.reindent(original, pos, indent_level) new_block.append(code) stash.remove(key) break if original is None: # pragma: no cover # Too much work to test this. This is just a fall back in case # we find a placeholder, and we went to revert it and it wasn't in our stash. # Most likely this would be caused by someone else. We just want to put it # back in the block if we can't revert it. Maybe we can do a more directed # unit test in the future. new_block.append(line) else: new_block.append(line) return '\n'.join(new_block) def run(self, parent, blocks): """Look for and parse code block.""" handled = False if not self.config.get("disable_indented_code_blocks", False): handled = CodeBlockProcessor.test(self, parent, blocks[0]) if handled: if self.config.get("nested", True): blocks[0] = self.revert_greedy_fences(blocks[0]) handled = CodeBlockProcessor.run(self, parent, blocks) is not False return handled def makeExtension(*args, **kwargs): """Return extension.""" return SuperFencesCodeExtension(*args, **kwargs)
"""Functions for signing notebooks""" #----------------------------------------------------------------------------- # Copyright (C) 2014, The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import base64 from contextlib import contextmanager import hashlib from hmac import HMAC import io import os from IPython.utils.py3compat import string_types, unicode_type, cast_bytes from IPython.utils.traitlets import Instance, Bytes, Enum, Any, Unicode, Bool from IPython.config import LoggingConfigurable, MultipleInstanceError from IPython.core.application import BaseIPythonApplication, base_flags from .current import read, write #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- try: # Python 3 algorithms = hashlib.algorithms_guaranteed except AttributeError: algorithms = hashlib.algorithms def yield_everything(obj): """Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing. """ if isinstance(obj, dict): for key in sorted(obj): value = obj[key] yield cast_bytes(key) for b in yield_everything(value): yield b elif isinstance(obj, (list, tuple)): for element in obj: for b in yield_everything(element): yield b elif isinstance(obj, unicode_type): yield obj.encode('utf8') else: yield unicode_type(obj).encode('utf8') @contextmanager def signature_removed(nb): """Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature. """ save_signature = nb['metadata'].pop('signature', None) try: yield finally: if save_signature is not None: nb['metadata']['signature'] = save_signature class NotebookNotary(LoggingConfigurable): """A class for computing and verifying notebook signatures.""" profile_dir = Instance("IPython.core.profiledir.ProfileDir") def _profile_dir_default(self): from IPython.core.application import BaseIPythonApplication app = None try: if BaseIPythonApplication.initialized(): app = BaseIPythonApplication.instance() except MultipleInstanceError: pass if app is None: # create an app, without the global instance app = BaseIPythonApplication() app.initialize(argv=[]) return app.profile_dir algorithm = Enum(algorithms, default_value='sha256', config=True, help="""The hashing algorithm used to sign notebooks.""" ) def _algorithm_changed(self, name, old, new): self.digestmod = getattr(hashlib, self.algorithm) digestmod = Any() def _digestmod_default(self): return getattr(hashlib, self.algorithm) secret_file = Unicode(config=True, help="""The file where the secret key is stored.""" ) def _secret_file_default(self): if self.profile_dir is None: return '' return os.path.join(self.profile_dir.security_dir, 'notebook_secret') secret = Bytes(config=True, help="""The secret key with which notebooks are signed.""" ) def _secret_default(self): # note : this assumes an Application is running if os.path.exists(self.secret_file): with io.open(self.secret_file, 'rb') as f: return f.read() else: secret = base64.encodestring(os.urandom(1024)) self._write_secret_file(secret) return secret def _write_secret_file(self, secret): """write my secret to my secret_file""" self.log.info("Writing notebook-signing key to %s", self.secret_file) with io.open(self.secret_file, 'wb') as f: f.write(secret) try: os.chmod(self.secret_file, 0o600) except OSError: self.log.warn( "Could not set permissions on %s", self.secret_file ) return secret def compute_signature(self, nb): """Compute a notebook's signature by hashing the entire contents of the notebook via HMAC digest. """ hmac = HMAC(self.secret, digestmod=self.digestmod) # don't include the previous hash in the content to hash with signature_removed(nb): # sign the whole thing for b in yield_everything(nb): hmac.update(b) return hmac.hexdigest() def check_signature(self, nb): """Check a notebook's stored signature If a signature is stored in the notebook's metadata, a new signature is computed and compared with the stored value. Returns True if the signature is found and matches, False otherwise. The following conditions must all be met for a notebook to be trusted: - a signature is stored in the form 'scheme:hexdigest' - the stored scheme matches the requested scheme - the requested scheme is available from hashlib - the computed hash from notebook_signature matches the stored hash """ stored_signature = nb['metadata'].get('signature', None) if not stored_signature \ or not isinstance(stored_signature, string_types) \ or ':' not in stored_signature: return False stored_algo, sig = stored_signature.split(':', 1) if self.algorithm != stored_algo: return False my_signature = self.compute_signature(nb) return my_signature == sig def sign(self, nb): """Sign a notebook, indicating that its output is trusted stores 'algo:hmac-hexdigest' in notebook.metadata.signature e.g. 'sha256:deadbeef123...' """ signature = self.compute_signature(nb) nb['metadata']['signature'] = "%s:%s" % (self.algorithm, signature) def mark_cells(self, nb, trusted): """Mark cells as trusted if the notebook's signature can be verified Sets ``cell.trusted = True | False`` on all code cells, depending on whether the stored signature can be verified. This function is the inverse of check_cells """ if not nb['worksheets']: # nothing to mark if there are no cells return for cell in nb['worksheets'][0]['cells']: if cell['cell_type'] == 'code': cell['trusted'] = trusted def _check_cell(self, cell): """Do we trust an individual cell? Return True if: - cell is explicitly trusted - cell has no potentially unsafe rich output If a cell has no output, or only simple print statements, it will always be trusted. """ # explicitly trusted if cell.pop("trusted", False): return True # explicitly safe output safe = { 'text/plain', 'image/png', 'image/jpeg', 'text', 'png', 'jpg', # v3-style short keys } for output in cell['outputs']: output_type = output['output_type'] if output_type in ('pyout', 'display_data'): # if there are any data keys not in the safe whitelist output_keys = set(output).difference({"output_type", "prompt_number", "metadata"}) if output_keys.difference(safe): return False return True def check_cells(self, nb): """Return whether all code cells are trusted If there are no code cells, return True. This function is the inverse of mark_cells. """ if not nb['worksheets']: return True trusted = True for cell in nb['worksheets'][0]['cells']: if cell['cell_type'] != 'code': continue # only distrust a cell if it actually has some output to distrust if not self._check_cell(cell): trusted = False return trusted trust_flags = { 'reset' : ( {'TrustNotebookApp' : { 'reset' : True}}, """Generate a new key for notebook signature. All previously signed notebooks will become untrusted. """ ), } trust_flags.update(base_flags) trust_flags.pop('init') class TrustNotebookApp(BaseIPythonApplication): description="""Sign one or more IPython notebooks with your key, to trust their dynamic (HTML, Javascript) output. Otherwise, you will have to re-execute the notebook to see output. """ examples = """ipython trust mynotebook.ipynb and_this_one.ipynb""" flags = trust_flags reset = Bool(False, config=True, help="""If True, generate a new key for notebook signature. After reset, all previously signed notebooks will become untrusted. """ ) notary = Instance(NotebookNotary) def _notary_default(self): return NotebookNotary(parent=self, profile_dir=self.profile_dir) def sign_notebook(self, notebook_path): if not os.path.exists(notebook_path): self.log.error("Notebook missing: %s" % notebook_path) self.exit(1) with io.open(notebook_path, encoding='utf8') as f: nb = read(f, 'json') if self.notary.check_signature(nb): print("Notebook already signed: %s" % notebook_path) else: print("Signing notebook: %s" % notebook_path) self.notary.sign(nb) with io.open(notebook_path, 'w', encoding='utf8') as f: write(nb, f, 'json') def generate_new_key(self): """Generate a new notebook signature key""" print("Generating new notebook key: %s" % self.notary.secret_file) self.notary._write_secret_file(os.urandom(1024)) def start(self): if self.reset: self.generate_new_key() return if not self.extra_args: self.log.critical("Specify at least one notebook to sign.") self.exit(1) for notebook_path in self.extra_args: self.sign_notebook(notebook_path)
from xscontainer import api_helper from xscontainer import ssh_helper from xscontainer import util from xscontainer.util import log import re import simplejson DOCKER_SOCKET_PATH = '/var/run/docker.sock' ERROR_CAUSE_NETWORK = ( "Error: Cannot find a valid IP that allows SSH connections to " "the VM. Please make sure that Tools are installed, a " "network route is set up, there is a SSH server running inside " "the VM that is reachable from Dom0.") def prepare_request_cmd(): return ("ncat -U %s" % (DOCKER_SOCKET_PATH)) def prepare_request_stdin(request_type, request): return ("%s %s HTTP/1.0\r\n\r\n" % (request_type, request)) def _interact_with_api(session, vmuuid, request_type, request, message_error=False): provided_stdin = prepare_request_stdin(request_type, request) stdout = ssh_helper.execute_ssh(session, vmuuid, prepare_request_cmd(), stdin_input=provided_stdin) headerend = stdout.index('\r\n\r\n') header = stdout[:headerend] body = stdout[headerend + 4:] # ToDo: Should use re headersplits = header.split('\r\n', 2)[0].split(' ') # protocol = headersplits[0] statuscode = headersplits[1] if statuscode[0] != '2': # this did not work status = ' '.join(headersplits[2:]) failure_title = "Container Management Error" failure_body = body.strip() if failure_body == "": if statuscode == "304": # 304 does not have a body and is quite common. failure_body = ("The requested operation is currently not " "possible. Please try again later.") else: failure_body = ("The requested operation failed.") failure_body = failure_body + " (" + statuscode + ")" if ":" in failure_body: (failure_title, failure_body) = failure_body.split(":", 1) if message_error: api_helper.send_message(session, vmuuid, failure_title, failure_body) message = ("Request '%s' led to status %s - %s: %s" % (request, status, failure_title, failure_body)) log.info(message) raise util.XSContainerException(message) return body def _get_api_json(session, vmuuid, request): stdout = _interact_with_api(session, vmuuid, 'GET', request) results = simplejson.loads(stdout) return results def _post_api(session, vmuuid, request): stdout = _interact_with_api(session, vmuuid, 'POST', request, message_error=True) return stdout def _verify_or_throw_container(container): if not re.match('^[a-z0-9_.-]+$', container): raise util.XSContainerException("Invalid container") def patch_docker_ps_status(ps_dict): """ Patch the status returned by Docker PS in order to avoid a stale value being presented to the user. Due to the fact that xscontainer only updates docker info when a docker event happens, it does not register the regular status updates for the increase in container run time. E.g. "Up 40 seconds" ... "Up 4 hours". The tempoary solution is to just return "Up", "Up (Paused)" or Exited (rc). """ status = ps_dict["Status"] if status.startswith("Up"): if status.endswith("(Paused)"): ps_dict["Status"] = "Up (Paused)" else: ps_dict["Status"] = "Up" elif status.startswith("Exited ("): closing_bracket_index = status.rfind(')') if closing_bracket_index: ps_dict["Status"] = ps_dict["Status"][0:closing_bracket_index + 1] return def get_ps_dict(session, vmuuid): container_results = _get_api_json(session, vmuuid, '/containers/json?all=1&size=1') return_results = [] for container_result in container_results: container_result['Names'] = container_result['Names'][0][1:] # Do some patching for XC - ToDo: patch XC to not require these container_result['Container'] = container_result['Id'][:10] patch_docker_ps_status(container_result) patched_result = {} for (key, value) in container_result.iteritems(): patched_result[key.lower()] = value return_results.append({'entry': patched_result}) return return_results def get_ps_xml(session, vmuuid): result = {'docker_ps': get_ps_dict(session, vmuuid)} return util.converttoxml(result) def get_info_dict(session, vmuuid): return _get_api_json(session, vmuuid, '/info') def get_info_xml(session, vmuuid): result = {'docker_info': get_info_dict(session, vmuuid)} return util.converttoxml(result) def get_version_dict(session, vmuuid): return _get_api_json(session, vmuuid, '/version') def get_version_xml(session, vmuuid): result = {'docker_version': get_version_dict(session, vmuuid)} return util.converttoxml(result) # ToDo: Must remove this cmd, really def passthrough(session, vmuuid, command): cmd = [command] result = ssh_helper.execute_ssh(session, vmuuid, cmd) return result def get_inspect_dict(session, vmuuid, container): _verify_or_throw_container(container) result = _get_api_json(session, vmuuid, '/containers/%s/json' % (container)) return result def get_inspect_xml(session, vmuuid, container): result = {'docker_inspect': get_inspect_dict(session, vmuuid, container)} return util.converttoxml(result) def get_top_dict(session, vmuuid, container): _verify_or_throw_container(container) result = _get_api_json(session, vmuuid, '/containers/%s/top' % (container)) titles = result['Titles'] psentries = [] for process in result['Processes']: process_dict = {} item = 0 if len(titles) > len(process): raise util.XSContainerException("Can't parse top output") for title in titles: process_dict.update({title: process[item]}) item = item + 1 psentries.append({'Process': process_dict}) return psentries def get_top_xml(session, vmuuid, container): result = {'docker_top': get_top_dict(session, vmuuid, container)} return util.converttoxml(result) def _run_container_cmd(session, vmuuid, container, command): _verify_or_throw_container(container) result = _post_api(session, vmuuid, '/containers/%s/%s' % (container, command)) return result def start(session, vmuuid, container): result = _run_container_cmd(session, vmuuid, container, 'start') return result def stop(session, vmuuid, container): result = _run_container_cmd(session, vmuuid, container, 'stop') return result def restart(session, vmuuid, container): result = _run_container_cmd(session, vmuuid, container, 'restart') return result def pause(session, vmuuid, container): result = _run_container_cmd(session, vmuuid, container, 'pause') update_docker_ps_workaround(session, vmuuid) return result def unpause(session, vmuuid, container): result = _run_container_cmd(session, vmuuid, container, 'unpause') update_docker_ps_workaround(session, vmuuid) return result def update_docker_info(thevm): thevm.update_other_config('docker_info', get_info_xml(thevm.get_session(), thevm.get_uuid())) def update_docker_version(thevm): thevm.update_other_config('docker_version', get_version_xml(thevm.get_session(), thevm.get_uuid())) def update_docker_ps(thevm): thevm.update_other_config('docker_ps', get_ps_xml(thevm.get_session(), thevm.get_uuid())) def update_docker_ps_workaround(session, vm_uuid): """ Only recent docker versions support sending events for pause and unpause. This works around this - at least when we post the command. """ client = api_helper.XenAPIClient(session) thevm = api_helper.VM(client, uuid=vm_uuid) record = thevm.get_other_config() if 'docker_ps' in record: update_docker_ps(thevm) def wipe_docker_other_config(thevm): thevm.remove_from_other_config('docker_ps') thevm.remove_from_other_config('docker_info') thevm.remove_from_other_config('docker_version') def determine_error_cause(session, vmuuid): cause = "" try: api_helper.get_suitable_vm_ip(session, vmuuid) except util.XSContainerException: cause = ERROR_CAUSE_NETWORK # No reason to continue, if there is no network connection return cause try: ssh_helper.execute_ssh(session, vmuuid, ['echo', 'hello world']) except ssh_helper.AuthenticationException: cause = (cause + "Unable to verify key-based authentication. " + "Please prepare the VM to install a key.") # No reason to continue, if there is no SSH connection return cause except ssh_helper.VmHostKeyException: cause = (cause + "The SSH host key of the VM has unexpectedly" + " changed, which could potentially be a security breach." + " If you think this is safe and expected, you" + " can reset the record stored in XS using xe" + " vm-param-remove uuid=<vm-uuid> param-name=other-config" + " param-key=xscontainer-sshhostkey") # No reason to continue, if there is no SSH connection return cause except ssh_helper.SshException: cause = (cause + "Unable to connect to the VM using SSH. Please " + "check the logs inside the VM and also try manually.") # No reason to continue, if there is no SSH connection return cause # @todo: we could alternatively support socat # @todo: we could probably prepare this as part of xscontainer-prepare-vm try: ssh_helper.execute_ssh(session, vmuuid, ['command -v ncat']) except util.XSContainerException: cause = (cause + "Unable to find ncat inside the VM. Please install " + "ncat. ") try: ssh_helper.execute_ssh(session, vmuuid, ['test', '-S', DOCKER_SOCKET_PATH]) except util.XSContainerException: cause = (cause + "Unable to find the Docker unix socket at %s." % (DOCKER_SOCKET_PATH) + " Please install and run Docker.") # No reason to continue, if there is no docker socket return cause try: ssh_helper.execute_ssh(session, vmuuid, ['test -r "%s" && test -w "%s" ' % (DOCKER_SOCKET_PATH, DOCKER_SOCKET_PATH)]) except util.XSContainerException: cause = (cause + "Unable to access the Docker unix socket. " + "Please make sure the specified user account " + "belongs to the docker account group.") if cause == "": cause = "Unable to determine cause of failure." return cause
""" Catalog table tools """ import os import inspect from collections import OrderedDict import glob import traceback import numpy as np import astropy.io.fits as pyfits import astropy.units as u import astropy.coordinates as coord from astropy.table import Table from . import utils __all__ = ["table_to_radec", "table_to_regions", "randomize_segmentation_labels", "get_ukidss_catalog", "get_sdss_catalog", "get_twomass_catalog", "get_irsa_catalog", "get_gaia_radec_at_time", "get_gaia_DR2_vizier_columns", "get_gaia_DR2_vizier", "gaia_dr2_conesearch_query", "get_gaia_DR2_catalog", "gen_tap_box_query", "query_tap_catalog", "get_hubble_source_catalog", "get_nsc_catalog", "get_desdr1_catalog", "get_skymapper_catalog", "get_panstarrs_catalog", "get_radec_catalog"] def table_to_radec(table, output='coords.radec'): """Make a "radec" ascii file with ra, dec columns from a table object """ if 'X_WORLD' in table.colnames: rc, dc = 'X_WORLD', 'Y_WORLD' elif 'x_world' in table.colnames: rc, dc = 'x_world', 'y_world' elif 'ra' in table.colnames: rc, dc = 'ra', 'dec' else: raise ValueError("Couldn't identify sky coordinates (x_world, ra)") table[rc, dc].write(output, format='ascii.commented_header', overwrite=True) def table_to_regions(table, output='ds9.reg', comment=None, header='global color=green width=1', size=0.5, use_ellipse=False, use_world=True, verbose=True, unit_offset_colums=['x'], scale_major=1, extra=None): """Make a DS9 region file from a table object """ fp = open(output, 'w') fp.write(header+'\n') if ('X_WORLD' in table.colnames) & (use_world): xc, yc = 'X_WORLD', 'Y_WORLD' is_world = True elif ('ra' in table.colnames) & (use_world): xc, yc = 'ra', 'dec' is_world = True elif ('x_world' in table.colnames) & (use_world): xc, yc = 'x_world', 'y_world' is_world = True elif 'x_image' in table.colnames: xc, yc = 'x_image','y_image' is_world = False elif 'x' in table.colnames: xc, yc = 'x','y' is_world = False else: raise ValueError("Couldn't identify ra/dec or x/y columns") xdata = table[xc]*1 ydata = table[yc]*1 if xc in unit_offset_colums: if verbose: print(f'Unit offset for columns {xc}, {yc}') xdata += 1 ydata += 1 if is_world: fp.write('fk5\n') sec='"' else: fp.write('image\n') sec='' # GAIA if 'solution_id' in table.colnames: e = np.sqrt(table['ra_error']**2+table['dec_error']**2)/1000. e = np.maximum(e, 0.1) else: e = np.ones(len(table))*size if use_ellipse: if is_world: if 'a_world' in table.colnames: amaj = table['a_world']*3600*scale_major amin = table['b_world']*3600*scale_major etheta = table['theta_world']/np.pi*180#+90 else: use_ellipse = False else: if 'a_image' in table.colnames: amaj = table['a_image']*scale_major amin = table['b_image']*scale_major etheta = table['theta_image']/np.pi*180#+90 else: use_ellipse = False if verbose: print(f'{output}: x = {xc}, y={yc}, ellipse={use_ellipse}') if use_ellipse: regstr = 'ellipse({x:.7f}, {y:.7f}, {a:.3f}{sec}, {b:.3f}{sec}, {theta:.1f})' lines = [regstr.format(x=xdata[i], y=ydata[i], a=amaj[i], b=amin[i], sec=sec, theta=etheta[i]) for i in range(len(table))] else: regstr = 'circle({0:.7f}, {1:.7f}, {2:.3f}{3})' lines = [regstr.format(xdata[i], ydata[i], e[i], sec) for i in range(len(table))] if comment is not None: for i in range(len(table)): lines[i] += ' # text={{{0}}}'.format(comment[i]) if extra is not None: for i, li in enumerate(lines): if '#' not in li: lines[i] += ' #' lines[i] += ' '+extra[i] # newline lines = [l+'\n' for l in lines] fp.writelines(lines) fp.close() def randomize_segmentation_labels(seg, random_seed=1, fill_value=np.nan): """ Randomize labels on a segmentation image for easier visualization Parameters ---------- seg : str or array Segmentation filename or integer array random_seed : int Random number seed for `numpy.random.seed` fill_value : scalar Value to insert where ``seg == 0`` Returns ------- rand_ids : array 1D array of the randomized labels with size `max(seg)+1` rand_seg : array 2D rray with randomized labels """ np.random.seed(random_seed) if isinstance(seg, str): seg_im = pyfits.open(seg) seg_data = seg_im[0].data else: seg_data = seg imax = seg_data.max() rand_ids = np.append(fill_value, np.argsort(np.random.rand(imax))+1) return rand_ids, rand_ids[seg_data] def get_ukidss_catalog(ra=165., dec=34.8, radius=3, database='UKIDSSDR9PLUS', programme_id='LAS'): """Query for objects in the UKIDSS catalogs Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin Returns ------- table : `~astropy.table.Table` Result of the query """ from astroquery.ukidss import Ukidss coo = coord.SkyCoord(ra*u.deg, dec*u.deg) table = Ukidss.query_region(coo, radius=radius*u.arcmin, database=database, programme_id=programme_id) return table def get_sdss_catalog(ra=165.86, dec=34.829694, radius=3): """Query for objects in the SDSS photometric catalog Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin Returns ------- table : `~astropy.table.Table` Result of the query """ from astroquery.sdss import SDSS coo = coord.SkyCoord(ra*u.deg, dec*u.deg) fields = ['ra', 'dec', 'raErr', 'decErr', 'petroMag_r', 'petroMagErr_r'] # print fields fields = None table = SDSS.query_region(coo, radius=radius*u.arcmin, spectro=False, photoobj_fields=fields) return table def get_twomass_catalog(ra=165.86, dec=34.829694, radius=3, catalog='allwise_p3as_psd'): return get_irsa_catalog(ra=ra, dec=dec, radius=radius, catalog='fp_psc', wise=False, twomass=True) def get_irsa_catalog(ra=165.86, dec=34.829694, tab=None, radius=3, catalog='allwise_p3as_psd', wise=False, twomass=False, ROW_LIMIT=500000, TIMEOUT=3600): """Query for objects in the `AllWISE <http://wise2.ipac.caltech.edu/docs/release/allwise/>`_ source catalog Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin Returns ------- table : `~astropy.table.Table` Result of the query """ from astroquery.irsa import Irsa Irsa.ROW_LIMIT = ROW_LIMIT Irsa.TIMEOUT = TIMEOUT #all_wise = 'wise_allwise_p3as_psd' #all_wise = 'allwise_p3as_psd' if wise: catalog = 'allwise_p3as_psd' elif twomass: catalog = 'fp_psc' coo = coord.SkyCoord(ra*u.deg, dec*u.deg) table = Irsa.query_region(coo, catalog=catalog, spatial="Cone", radius=radius*u.arcmin, get_query_payload=False) return table # def get_gaia_radec_at_time(gaia_tbl, date=2015.5, format='decimalyear'): """ Use `~astropy.coordinates.SkyCoord.apply_space_motion` to compute GAIA positions at a specific observation date Parameters ---------- gaia_tbl : `~astropy.table.Table` GAIA table query, e.g., provided by `get_gaia_DR2_catalog`. date : e.g., float Observation date that can be parsed with `~astropy.time.Time` format : str Date format, see `~astropy.time.Time.FORMATS`. Returns ------- coords : `~astropy.coordinates.SkyCoord` Projected sky coordinates. """ from astropy.time import Time from astropy.coordinates import SkyCoord # Distance and radial_velocity are dummy numbers needed # to get the space motion correct try: # Try to use pyia import pyia g = pyia.GaiaData(gaia_tbl) coord = g.get_skycoord(distance=1*u.kpc, radial_velocity=0.*u.km/u.second) except: # From table itself if 'ref_epoch' in gaia_tbl.colnames: ref_epoch = Time(gaia_tbl['ref_epoch'].data, format='decimalyear') else: ref_epoch = Time(2015.5, format='decimalyear') coord = SkyCoord(ra=gaia_tbl['ra'], dec=gaia_tbl['dec'], pm_ra_cosdec=gaia_tbl['pmra'], pm_dec=gaia_tbl['pmdec'], obstime=ref_epoch, distance=1*u.kpc, radial_velocity=0.*u.km/u.second) new_obstime = Time(date, format=format) coord_at_time = coord.apply_space_motion(new_obstime=new_obstime) return(coord_at_time) #GAIA_DR2_COLUMNS = None GAIA_DR2_COLUMNS = ['RA_ICRS','DE_ICRS','Epoch','e_RA_ICRS','e_DE_ICRS', 'pmRA','e_pmRA','pmDE','e_pmDE', 'NAL','NAC','Solved','APF','WAL'] def get_gaia_DR2_vizier_columns(): """ Get translation of Vizier GAIA DR2 columns. The subset of desired output columns can be specified in the GAIA_DR2_COLUMNS global variable, which, if `None`, will be all available columns. """ file = os.path.join(os.path.dirname(__file__), 'data/gaia_dr2_vizier_columns.txt') lines = open(file).readlines()[1:] gdict = OrderedDict() for line in lines: viz_col = line.split()[0] gaia_col = line.split()[1][1:-1] if GAIA_DR2_COLUMNS is not None: if viz_col in GAIA_DR2_COLUMNS: gdict[viz_col] = gaia_col else: gdict[viz_col] = gaia_col return gdict def get_gaia_DR2_vizier(ra=165.86, dec=34.829694, radius=3., max=100000, catalog="I/350/gaiaedr3", server='vizier.u-strasbg.fr', use_mirror=False, keys=None): """ Query GAIA catalog from Vizier DR2: ``catalog="I/345/gaia2"`` DR3: ``catalog="I/350/gaiaedr3"`` """ from astroquery.vizier import Vizier import astropy.units as u import astropy.coordinates as coord coo = coord.SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg), frame='icrs') gdict = get_gaia_DR2_vizier_columns() if keys is None: keys = list(gdict.keys()) try: # Hack, Vizier object doesn't seem to allow getting all keys # simultaneously (astroquery v0.3.7) N = 9 for i in range(len(keys)//N+1): v = Vizier(catalog=catalog, columns=['+_r']+keys[i*N:(i+1)*N]) v.VIZIER_SERVER = server v.ROW_LIMIT = max tab = v.query_region(coo, radius="{0}m".format(radius), catalog=catalog)[0] if i == 0: result = tab else: for k in tab.colnames: #print(i, k) result[k] = tab[k] for k in gdict: if k in result.colnames: result.rename_column(k, gdict[k]) except: utils.log_exception(utils.LOGFILE, traceback) return False return result def gaia_dr2_conesearch_query(ra=165.86, dec=34.829694, radius=3., max=100000): """ Generate a query string for the TAP servers TBD Parameters ---------- ra, dec : float RA, Dec in decimal degrees radius : float Search radius, in arc-minutes. Returns ------- query : str Query string """ query = "SELECT TOP {3} * FROM gaiadr2.gaia_source WHERE CONTAINS(POINT('ICRS',gaiadr2.gaia_source.ra,gaiadr2.gaia_source.dec),CIRCLE('ICRS',{0},{1},{2:.2f}))=1".format(ra, dec, radius/60., max) return query def get_gaia_DR2_catalog(ra=165.86, dec=34.829694, radius=3., use_mirror=True, max_wait=20, max=100000, output_file='gaia.fits'): """Query GAIA DR2 astrometric catalog Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin use_mirror : bool If True, use the mirror at `gaia.ari.uni-heidelberg.de`. Otherwise use `gea.esac.esa.int`. Returns ------- table : `~astropy.table.Table` Result of the query """ try: import httplib from urllib import urlencode except: # python 3 import http.client as httplib from urllib.parse import urlencode # import http.client in Python 3 # import urllib.parse in Python 3 import time from xml.dom.minidom import parseString host = "gea.esac.esa.int" port = 80 pathinfo = "/tap-server/tap/async" if use_mirror: host = "gaia.ari.uni-heidelberg.de" pathinfo = "/tap/async" # ------------------------------------- # Create job query = gaia_dr2_conesearch_query(ra=ra, dec=dec, radius=radius, max=max) # "SELECT TOP 100000 * FROM gaiadr2.gaia_source WHERE CONTAINS(POINT('ICRS',gaiadr2.gaia_source.ra,gaiadr2.gaia_source.dec),CIRCLE('ICRS',{0},{1},{2:.2f}))=1".format(ra, dec, radius/60.) print(query) params = urlencode({ "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "fits", "PHASE": "RUN", "QUERY": query }) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } connection = httplib.HTTPConnection(host, port) connection.request("POST", pathinfo, params, headers) # Status response = connection.getresponse() print("Status: " + str(response.status), "Reason: " + str(response.reason)) # Server job location (URL) location = response.getheader("location") print("Location: " + location) # Jobid jobid = location[location.rfind('/')+1:] print("Job id: " + jobid) connection.close() # ------------------------------------- # Check job status, wait until finished tcount = 0 while True: connection = httplib.HTTPConnection(host, port) connection.request("GET", pathinfo+"/"+jobid) response = connection.getresponse() data = response.read() # XML response: parse it to obtain the current status dom = parseString(data) if use_mirror: phaseElement = dom.getElementsByTagName('phase')[0] else: phaseElement = dom.getElementsByTagName('uws:phase')[0] phaseValueElement = phaseElement.firstChild phase = phaseValueElement.toxml() print("Status: " + phase) # Check finished if phase == 'COMPLETED': break #wait and repeat time.sleep(0.2) tcount += 0.2 if (phase == 'ERROR') | (tcount > max_wait): return False # print "Data:" # print data connection.close() # ------------------------------------- # Get results connection = httplib.HTTPConnection(host, port) connection.request("GET", pathinfo+"/"+jobid+"/results/result") response = connection.getresponse() data = response.read() outputFileName = output_file + (not use_mirror)*".gz" try: outputFile = open(outputFileName, "w") outputFile.write(data) except: # Python 3 outputFile = open(outputFileName, "wb") outputFile.write(data) outputFile.close() connection.close() print("Data saved in: " + outputFileName) if not use_mirror: # ESA archive returns gzipped try: os.remove(output_file) except: pass os.system('gunzip {output_file}.gz'.format(output_file=output_file)) table = Table.read(output_file, format='fits') return table def gen_tap_box_query(ra=165.86, dec=34.829694, radius=3., corners=None, max=100000, db='ls_dr7.tractor_primary', columns=['*'], rd_colnames=['ra', 'dec'], wcs_pad=0.5): """ Generate a query string for the NOAO Legacy Survey TAP server Parameters ---------- ra, dec : float RA, Dec in decimal degrees radius : float Search radius, in arc-minutes. corners : 4-tuple, `~astropy.wcs.WCS` or None ra_min, ra_max, dec_min, dec_max of a query box to use instead of `radius`. Or if a `~astropy.wcs.WCS` object, get limits from the `~astropy.wcs.WCS.calc_footprint` method Returns ------- query : str Query string """ rmi = radius/60/2 cosd = np.cos(dec/180*np.pi) if max is not None: maxsel = 'TOP {0}'.format(max) else: maxsel = '' if corners is not None: if hasattr(corners, 'calc_footprint'): foot = corners.calc_footprint() left = foot[:,0].min() right = foot[:,0].max() bottom = foot[:,1].min() top = foot[:,1].max() dx = (right-left) dy = (top-bottom) left -= wcs_pad*dx right += wcs_pad*dx bottom -= wcs_pad*dy top += wcs_pad*dy elif len(corners) != 4: msg = 'corners needs 4 values (ra_min, ra_max, dec_min, dec_max)' raise ValueError(msg) else: left, right, bottom, top = corners else: left = ra - rmi / cosd right = ra + rmi / cosd bottom = dec - rmi top = dec + rmi fmt = dict(rc=rd_colnames[0], dc=rd_colnames[1], left=left, right=right, top=top, bottom=bottom, maxsel=maxsel, db=db, output_columns=', '.join(columns)) if not np.isfinite(ra+dec): query = "SELECT {maxsel} {output_columns} FROM {db} " else: query = ("SELECT {maxsel} {output_columns} FROM {db} WHERE " + "{rc} > {left} AND {rc} < {right} AND " + "{dc} > {bottom} AND {dc} < {top} ") return query.format(**fmt) def query_tap_catalog(ra=165.86, dec=34.829694, radius=3., corners=None, max_wait=20, db='ls_dr9.tractor', columns=['*'], extra='', rd_colnames=['ra', 'dec'], tap_url='https://datalab.noirlab.edu/tap', max=1000000, clean_xml=True, verbose=True, des=False, gaia=False, nsc=False, vizier=False, skymapper=False, hubble_source_catalog=False, tap_kwargs={}, **kwargs): """Query NOAO Catalog holdings Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin corners : 4-tuple, `~astropy.wcs.WCS` or None ra_min, ra_max, dec_min, dec_max of a query box to use instead of `radius`. Or if a `WCS` object, get limits from the `~astropy.wcs.WCS.calc_footprint` method db : str Parent database (https://datalab.noirlab.edu/query.php). columns : list of str List of columns to output. Default ['*'] returns all columns. extra : str String to add to the end of the positional box query, e.g., 'AND mag_auto_i > 16 AND mag_auto_i < 16.5'. rd_colnames : str, str Column names in `db` corresponding to ra/dec (degrees). tap_url : str TAP hostname des : bool Query `des_dr1.main` from NOAO. gaia : bool Query `gaiadr2.gaia_source` from http://gea.esac.esa.int. nsc : bool Query the NOAO Source Catalog (Nidever et al. 2018), `nsc_dr1.object`. vizier : bool Use the VizieR TAP server at http://tapvizier.u-strasbg.fr/TAPVizieR/tap, see http://tapvizier.u-strasbg.fr/adql/about.html. hubble_source_catalog : bool Query the Hubble Source Catalog (v3). If no 'NumImages' criteria is found in `extra`, then add an additional requirement: >>> extra += 'AND NumImages > 1' Returns ------- table : `~astropy.table.Table` Result of the query """ from astroquery.utils.tap.core import TapPlus # DES DR1 if des: if verbose: print('Query DES DR1 from NOAO') db = 'des_dr1.main' tap_url = 'https://datalab.noirlab.edu/tap' # NOAO source catalog, seems to have some junk if nsc: if verbose: print('Query NOAO source catalog') db = 'nsc_dr1.object' tap_url = 'https://datalab.noirlab.edu/tap' extra += ' AND nsc_dr1.object.flags = 0' # GAIA DR2 if gaia: if verbose: print('Query GAIA DR2 from ESA') db = 'gaiadr2.gaia_source' tap_url = 'http://gea.esac.esa.int/tap-server/tap' # VizieR TAP server if vizier: if verbose: print('Query {0} from VizieR TAP server'.format(db)) tap_url = 'http://tapvizier.u-strasbg.fr/TAPVizieR/tap' rd_colnames = ['RAJ2000', 'DEJ2000'] if skymapper: if verbose: print('Query {0} from VizieR TAP server'.format(db)) tap_url = 'http://tapvizier.u-strasbg.fr/TAPVizieR/tap' rd_colnames = ['RAICRS', 'DEICRS'] if hubble_source_catalog: if db is None: db = 'dbo.SumPropMagAutoCat' elif 'dbo' not in db: db = 'dbo.SumPropMagAutoCat' tap_url = 'http://vao.stsci.edu/HSCTAP/tapservice.aspx' rd_colnames = ['MatchRA', 'MatchDec'] if 'NumImages' not in extra: extra += 'AND NumImages > 1' tap = TapPlus(url=tap_url, **tap_kwargs) query = gen_tap_box_query(ra=ra, dec=dec, radius=radius, max=max, db=db, columns=columns, rd_colnames=rd_colnames, corners=corners) job = tap.launch_job(query+extra, dump_to_file=True, verbose=verbose) try: table = job.get_results() if clean_xml: if hasattr(job, 'outputFile'): jobFile = job.outputFile else: jobFile = job.get_output_file() os.remove(jobFile) # Provide ra/dec columns for c, cc in zip(rd_colnames, ['ra', 'dec']): if (c in table.colnames) & (cc not in table.colnames): table[cc] = table[c] table.meta['TAPURL'] = tap_url, 'TAP URL' table.meta['TAPDB'] = db, 'TAP database name' table.meta['TAPQUERY'] = query+extra, 'TAP query' table.meta['RAQUERY'] = ra, 'Query central RA' table.meta['DECQUERY'] = dec, 'Query central Dec' table.meta['RQUERY'] = radius, 'Query radius, arcmin' if hubble_source_catalog: for col in table.colnames: if table[col].dtype == 'object': print('Reformat column: {0}'.format(col)) strcol = list(table[col]) table[col] = strcol except: if hasattr(job, 'outputFile'): jobFile = job.outputFile else: jobFile = job.get_output_file() print('Query failed, check {0} for error messages'.format(jobFile)) table = None return table # Limit Hubble Source Catalog query to brighter sources in limited bands HSCv3_FILTER_LIMITS = {'W3_F160W': 23.5, 'W3_F140W': 23.5, 'W3_F125W': 23.5, 'W3_F110W': 23.5, 'W3_F098M': 23.5, 'W3_F105W': 23.5, 'A_F814W': 23.5, 'W3_F814W': 23.5, 'A_F606W': 23.5, 'W3_F606W': 23.5, 'A_F850LP': 23.5, 'W3_F850LP': 23.5, 'A_F775W': 23.5, 'W3_F775W': 23.5} HSCv3_COLUMNS = ['MatchRA', 'MatchDec', 'CI', 'CI_Sigma', 'KronRadius', 'KronRadius_Sigma', 'Extinction', 'TargetName', 'NumImages', 'NumFilters', 'NumVisits', 'DSigma'] def get_hubble_source_catalog(ra=0., dec=0., radius=3, corners=None, max=int(1e7), extra=' AND NumImages > 0', kron_max=0.45, dsigma_max=100, clip_singles=10*u.arcsec, verbose=True, columns=HSCv3_COLUMNS, filter_limits=HSCv3_FILTER_LIMITS): """ Query NOAO Source Catalog, which is aligned to GAIA DR1. The default `extra` query returns well-detected sources in red bands. filter_limits : query on individual HSC filter magnitudes """ import astropy.table msg = 'Query NOAO Source Catalog ({ra:.5f},{dec:.5f},{radius:.1f}\')' print(msg.format(ra=ra, dec=dec, radius=radius)) if kron_max is not None: extra += ' AND KronRadius < {0}'.format(kron_max) if dsigma_max is not None: extra += ' AND DSigma < {0}'.format(dsigma_max) if filter_limits is not None: limit_list = ['{0} < {1}'.format(f, filter_limits[f]) for f in filter_limits] filter_selection = ' AND ({0})'.format(' OR '.join(limit_list)) extra += filter_selection columns += [f for f in filter_limits] db = 'dbo.SumPropMagAutoCat p join dbo.SumMagAutoCat m on p.MatchID = m.MatchID' else: db = 'dbo.SumPropMagAutoCat' tab = query_tap_catalog(ra=ra, dec=dec, radius=radius, corners=corners, max=max, extra=extra, hubble_source_catalog=True, verbose=verbose, db=db, columns=columns) if clip_singles not in [None, False]: rr = tab['NumImages'] > 1 if (rr.sum() > 0) & ((~rr).sum() > 0): r0, r1 = tab[rr], tab[~rr] idx, dr = utils.GTable(r0).match_to_catalog_sky(r1) new = dr > clip_singles xtab = astropy.table.vstack([r0, r1[new]]) if verbose: msg = ('HSCv3: Remove {0} NumImages == 1 sources ' + 'with tolerance {1}') print(msg.format((~new).sum(), clip_singles)) return tab def get_nsc_catalog(ra=0., dec=0., radius=3, corners=None, max=100000, extra=' AND (rerr < 0.08 OR ierr < 0.08 OR zerr < 0.08) AND raerr < 0.2 AND decerr < 0.2', verbose=True): """ Query NOAO Source Catalog, which is aligned to GAIA DR1. The default `extra` query returns well-detected sources in red bands. """ msg = 'Query NOAO Source Catalog ({ra:.5f},{dec:.5f},{radius:.1f}\')' print(msg.format(ra=ra, dec=dec, radius=radius)) tab = query_tap_catalog(ra=ra, dec=dec, radius=radius, corners=corners, extra=extra, nsc=True, verbose=verbose, max=max) return tab def get_desdr1_catalog(ra=0., dec=0., radius=3, corners=None, max=100000, extra=' AND (e_rmag < 0.15 OR e_imag < 0.15)', verbose=True): """ Query DES DR1 Catalog from Vizier The default `extra` query returns well-detected sources in one or more red bands. """ msg = 'Query DES Source Catalog ({ra:.5f},{dec:.5f},{radius:.1f}\')' print(msg.format(ra=ra, dec=dec, radius=radius)) tab = query_tap_catalog(ra=ra, dec=dec, radius=radius, corners=corners, extra=extra, db='"II/357/des_dr1"', vizier=True, verbose=verbose, max=max) return tab def get_desdr1_catalog_old(ra=0., dec=0., radius=3, corners=None, max=100000, extra=' AND (magerr_auto_r < 0.15 OR magerr_auto_i < 0.15)', verbose=True): """ Query DES DR1 Catalog. The default `extra` query returns well-detected sources in one or more red bands. """ msg = 'Query DES Source Catalog ({ra:.5f},{dec:.5f},{radius:.1f}\')' print(msg.format(ra=ra, dec=dec, radius=radius)) tab = query_tap_catalog(ra=ra, dec=dec, radius=radius, corners=corners, extra=extra, des=True, verbose=verbose, max=max) return tab def get_skymapper_catalog(ra=0., dec=0., radius=3., corners=None, max_records=500000, verbose=True, extra=''): """ Get Skymapper DR1 from Vizier """ msg = 'Query Skymapper DR1 catalog ({ra},{dec},{radius})' print(msg.format(ra=ra, dec=dec, radius=radius)) tab = query_tap_catalog(ra=ra, dec=dec, radius=radius*2, corners=corners, extra=extra, skymapper=True, db='"II/358/smss"', verbose=verbose, max=max_records) return tab def get_legacysurveys_catalog(ra=0., dec=0., radius=3., verbose=True, db='ls_dr9.tractor', sn_lim=('r',10), **kwargs): """ Query LegacySurveys TAP catalog """ if verbose: msg = 'Query LegacySurveys ({db}) catalog ({ra},{dec},{radius:.2f})' print(msg.format(ra=ra, dec=dec, radius=radius, db=db)) if (sn_lim is not None): if len(sn_lim) >= 2: b = sn_lim[0] extra = f' AND flux_{b}*SQRT(flux_ivar_{b}) > {sn_lim[1]}' if 'extra' in kwargs: kwargs['extra'] += extra else: kwargs['extra'] = extra tab = query_tap_catalog(ra=ra, dec=dec, radius=radius, db=db, **kwargs) # if (sn_lim is not None) & (len(tab) > 1): # if len(sn_lim) >= 2: # sn = tab[f'flux_{sn_lim[0]}'] # sn *= np.sqrt(tab[f'flux_ivar_{sn_lim[0]}']) # # valid = sn > sn_lim[1] # return tab[valid] return tab def get_panstarrs_catalog(ra=0., dec=0., radius=3., corners=None, max_records=500000, verbose=True, extra='AND "II/349/ps1".e_imag < 0.2 AND "II/349/ps1".e_RAJ2000 < 0.15 AND "II/349/ps1".e_DEJ2000 < 0.15'): """ Get PS1 from Vizier """ msg = 'Query PanSTARRS catalog ({ra},{dec},{radius})' print(msg.format(ra=ra, dec=dec, radius=radius)) tab = query_tap_catalog(ra=ra, dec=dec, radius=radius*2, corners=corners, extra=extra, vizier=True, db='"II/349/ps1"', verbose=verbose, max=max_records) return tab def get_radec_catalog(ra=0., dec=0., radius=3., product='cat', verbose=True, reference_catalogs=['GAIA', 'LS_DR9', 'PS1', 'Hubble', 'NSC', 'SDSS', 'WISE', 'DES'], use_self_catalog=False, **kwargs): """Decide what reference astrometric catalog to use First search SDSS, then WISE looking for nearby matches. Parameters ---------- ra, dec : float Center of the query region, decimal degrees radius : float Radius of the query, in arcmin product : str Basename of the drizzled product. If a locally-created catalog with filename that startswith `product` is found, use that one instead of the external (low precision) catalogs so that you're matching HST-to-HST astrometry. reference_catalogs : list Order in which to query reference catalogs. Options are 'GAIA', 'PS1' (STScI PanSTARRS), 'SDSS', 'WISE', 'NSC' (NOAO Source Catalog), 'DES' (Dark Energy Survey DR1), 'Hubble' (Hubble Source Catalog v3), 'LS_DR9' (LegacySurveys DR9). Returns ------- radec : str Filename of the RA/Dec list derived from the parent catalog ref_catalog : str, {'SDSS', 'WISE', 'VISIT'} Provenance of the `radec` list. """ query_functions = {'SDSS': get_sdss_catalog, 'GAIA_TAP': get_gaia_DR2_catalog, 'PS1': get_panstarrs_catalog, 'WISE': get_irsa_catalog, '2MASS': get_twomass_catalog, 'GAIA_Vizier': get_gaia_DR2_vizier, 'GAIA': get_gaia_DR2_vizier, 'NSC': get_nsc_catalog, 'DES': get_desdr1_catalog, 'Hubble': get_hubble_source_catalog, 'Skymapper': get_skymapper_catalog, 'LS_DR9': get_legacysurveys_catalog} # Try queries has_catalog = False ref_catalog = 'None' ref_cat = [] for ref_src in reference_catalogs: try: if ref_src == 'GAIA': try: ref_cat = query_functions[ref_src](ra=ra, dec=dec, radius=radius, use_mirror=False) except: try: ref_cat = query_functions[ref_src](ra=ra, dec=dec, radius=radius) except: ref_cat = False # Try GAIA mirror at Heidelberg if ref_cat is False: ref_cat = query_functions[ref_src](ra=ra, dec=dec, radius=radius, use_mirror=True) else: ref_cat = query_functions[ref_src](ra=ra, dec=dec, radius=radius) # # # ref_cat = query_functions[ref_src](ra=ra, dec=dec, # radius=radius) valid = np.isfinite(ref_cat['ra']+ref_cat['dec']) ref_cat = ref_cat[valid] if len(ref_cat) < 2: raise ValueError table_to_regions(ref_cat, output='{0}_{1}.reg'.format(product, ref_src.lower())) ref_cat['ra', 'dec'].write('{0}_{1}.radec'.format(product, ref_src.lower()), format='ascii.commented_header', overwrite=True) radec = '{0}_{1}.radec'.format(product, ref_src.lower()) ref_catalog = ref_src has_catalog = True if len(ref_cat) > 0: break except: print('{0} query failed'.format(ref_src)) has_catalog = False if (ref_src.startswith('GAIA')) & ('date' in kwargs) & has_catalog: if kwargs['date'] is not None: if 'date_format' in kwargs: date_format = kwargs['date_format'] else: date_format = 'mjd' gaia_tbl = ref_cat # utils.GTable.gread('gaia.fits') coo = get_gaia_radec_at_time(gaia_tbl, date=kwargs['date'], format=date_format) coo_tbl = utils.GTable() coo_tbl['ra'] = coo.ra coo_tbl['dec'] = coo.dec ok = np.isfinite(coo_tbl['ra']) & np.isfinite(coo_tbl['dec']) coo_tbl.meta['date'] = kwargs['date'] coo_tbl.meta['datefmt'] = date_format msg = 'Apply observation ({0},{1}) to GAIA catalog' print(msg.format(kwargs['date'], date_format)) table_to_regions(coo_tbl[ok], output='{0}_{1}.reg'.format(product, ref_src.lower())) coo_tbl['ra', 'dec'][ok].write('{0}_{1}.radec'.format(product, ref_src.lower()), format='ascii.commented_header', overwrite=True) if not has_catalog: return False # WISP, check if a catalog already exists for a given rootname and use # that if so. cat_files = glob.glob('-f1'.join(product.split('-f1')[:-1]) + '-f*.cat*') if (len(cat_files) > 0) & (use_self_catalog): ref_cat = utils.GTable.gread(cat_files[0]) root = cat_files[0].split('.cat')[0] ref_cat['X_WORLD', 'Y_WORLD'].write('{0}.radec'.format(root), format='ascii.commented_header', overwrite=True) radec = '{0}.radec'.format(root) ref_catalog = 'VISIT' if verbose: msg = '{0} - Reference RADEC: {1} [{2}] N={3}' print(msg.format(product, radec, ref_catalog, len(ref_cat))) return radec, ref_catalog
# Author: Vlad Niculae # Licence: BSD 3 clause import numpy as np from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_warns from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import check_skip_travis from sklearn.linear_model import (orthogonal_mp, orthogonal_mp_gram, OrthogonalMatchingPursuit, OrthogonalMatchingPursuitCV, LinearRegression) from sklearn.utils import check_random_state from sklearn.datasets import make_sparse_coded_signal n_samples, n_features, n_nonzero_coefs, n_targets = 20, 30, 5, 3 y, X, gamma = make_sparse_coded_signal(n_targets, n_features, n_samples, n_nonzero_coefs, random_state=0) G, Xy = np.dot(X.T, X), np.dot(X.T, y) # this makes X (n_samples, n_features) # and y (n_samples, 3) def test_correct_shapes(): assert_equal(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5).shape, (n_features,)) assert_equal(orthogonal_mp(X, y, n_nonzero_coefs=5).shape, (n_features, 3)) def test_correct_shapes_gram(): assert_equal(orthogonal_mp_gram(G, Xy[:, 0], n_nonzero_coefs=5).shape, (n_features,)) assert_equal(orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5).shape, (n_features, 3)) def test_n_nonzero_coefs(): assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5)) <= 5) assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5, precompute=True)) <= 5) def test_tol(): tol = 0.5 gamma = orthogonal_mp(X, y[:, 0], tol=tol) gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute=True) assert_true(np.sum((y[:, 0] - np.dot(X, gamma)) ** 2) <= tol) assert_true(np.sum((y[:, 0] - np.dot(X, gamma_gram)) ** 2) <= tol) def test_with_without_gram(): assert_array_almost_equal( orthogonal_mp(X, y, n_nonzero_coefs=5), orthogonal_mp(X, y, n_nonzero_coefs=5, precompute=True)) def test_with_without_gram_tol(): assert_array_almost_equal( orthogonal_mp(X, y, tol=1.), orthogonal_mp(X, y, tol=1., precompute=True)) def test_unreachable_accuracy(): assert_array_almost_equal( orthogonal_mp(X, y, tol=0), orthogonal_mp(X, y, n_nonzero_coefs=n_features)) assert_array_almost_equal( assert_warns(RuntimeWarning, orthogonal_mp, X, y, tol=0, precompute=True), orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_features)) def test_bad_input(): assert_raises(ValueError, orthogonal_mp, X, y, tol=-1) assert_raises(ValueError, orthogonal_mp, X, y, n_nonzero_coefs=-1) assert_raises(ValueError, orthogonal_mp, X, y, n_nonzero_coefs=n_features + 1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, tol=-1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, n_nonzero_coefs=-1) assert_raises(ValueError, orthogonal_mp_gram, G, Xy, n_nonzero_coefs=n_features + 1) def test_perfect_signal_recovery(): idx, = gamma[:, 0].nonzero() gamma_rec = orthogonal_mp(X, y[:, 0], 5) gamma_gram = orthogonal_mp_gram(G, Xy[:, 0], 5) assert_array_equal(idx, np.flatnonzero(gamma_rec)) assert_array_equal(idx, np.flatnonzero(gamma_gram)) assert_array_almost_equal(gamma[:, 0], gamma_rec, decimal=2) assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2) def test_estimator(): omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs) omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_.shape, ()) assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_.shape, (n_targets,)) assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) omp.set_params(fit_intercept=False, normalize=False) omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_, 0) assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_, 0) assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) def test_identical_regressors(): newX = X.copy() newX[:, 1] = newX[:, 0] gamma = np.zeros(n_features) gamma[0] = gamma[1] = 1. newy = np.dot(newX, gamma) assert_warns(RuntimeWarning, orthogonal_mp, newX, newy, 2) def test_swapped_regressors(): gamma = np.zeros(n_features) # X[:, 21] should be selected first, then X[:, 0] selected second, # which will take X[:, 21]'s place in case the algorithm does # column swapping for optimization (which is the case at the moment) gamma[21] = 1.0 gamma[0] = 0.5 new_y = np.dot(X, gamma) new_Xy = np.dot(X.T, new_y) gamma_hat = orthogonal_mp(X, new_y, 2) gamma_hat_gram = orthogonal_mp_gram(G, new_Xy, 2) assert_array_equal(np.flatnonzero(gamma_hat), [0, 21]) assert_array_equal(np.flatnonzero(gamma_hat_gram), [0, 21]) def test_no_atoms(): y_empty = np.zeros_like(y) Xy_empty = np.dot(X.T, y_empty) gamma_empty = ignore_warnings(orthogonal_mp)(X, y_empty, 1) gamma_empty_gram = ignore_warnings(orthogonal_mp)(G, Xy_empty, 1) assert_equal(np.all(gamma_empty == 0), True) assert_equal(np.all(gamma_empty_gram == 0), True) def test_omp_path(): path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True) last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False) assert_equal(path.shape, (n_features, n_targets, 5)) assert_array_almost_equal(path[:, :, -1], last) path = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=True) last = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=False) assert_equal(path.shape, (n_features, n_targets, 5)) assert_array_almost_equal(path[:, :, -1], last) def test_omp_cv(): # FIXME: This test is unstable on Travis, see issue #3190 for more detail. check_skip_travis() y_ = y[:, 0] gamma_ = gamma[:, 0] ompcv = OrthogonalMatchingPursuitCV(normalize=True, fit_intercept=False, max_iter=10, cv=5) ompcv.fit(X, y_) assert_equal(ompcv.n_nonzero_coefs_, n_nonzero_coefs) assert_array_almost_equal(ompcv.coef_, gamma_) omp = OrthogonalMatchingPursuit(normalize=True, fit_intercept=False, n_nonzero_coefs=ompcv.n_nonzero_coefs_) omp.fit(X, y_) assert_array_almost_equal(ompcv.coef_, omp.coef_) def test_omp_reaches_least_squares(): # Use small simple data; it's a sanity check but OMP can stop early rng = check_random_state(0) n_samples, n_features = (10, 8) n_targets = 3 X = rng.randn(n_samples, n_features) Y = rng.randn(n_samples, n_targets) omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_features) lstsq = LinearRegression() omp.fit(X, Y) lstsq.fit(X, Y) assert_array_almost_equal(omp.coef_, lstsq.coef_)
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2022, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import io import os import tempfile import unittest import biom import numpy as np import pandas.testing as pdt import qiime2 import skbio import pandas as pd from qiime2.plugin.util import transform from q2_types.tree import NewickFormat from q2_diversity import alpha_rarefaction from q2_diversity._alpha._visualizer import ( _compute_rarefaction_data, _compute_summary, _reindex_with_metadata, _alpha_rarefaction_jsonp) class AlphaRarefactionTests(unittest.TestCase): @staticmethod def _to_newick(tree: skbio.TreeNode): return transform(tree, from_type=skbio.TreeNode, to_type=NewickFormat) def test_alpha_rarefaction_without_metadata(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) def test_alpha_rarefaction_with_metadata(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) md = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'peanut']}, index=pd.Index(['S1', 'S2', 'S3'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) def test_alpha_rarefaction_with_superset_metadata(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) md = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'peanut', 'summer']}, index=pd.Index(['S1', 'S2', 'S3', 'S4'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) metric_fp = os.path.join(output_dir, 'shannon-pet.jsonp') with open(metric_fp) as metric_fh: self.assertTrue('summer' not in metric_fh.read()) def test_alpha_rarefaction_with_filtered_metadata_columns(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) # Empty column and numeric column should both be filtered. md = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'peanut', 'summer'], 'foo': [np.nan, np.nan, np.nan, 'bar'], 'bar': [42, 4.2, 99.9, 100.0]}, index=pd.Index(['S1', 'S2', 'S3', 'S4'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp, 'r') as fh: contents = fh.read() self.assertTrue('observed_features' in contents) self.assertTrue('shannon' in contents) self.assertTrue('didn\'t contain categorical data' in contents) self.assertTrue('consisted only of missing values:' in contents) self.assertTrue('<strong>bar, foo' in contents) metric_fp = os.path.join(output_dir, 'shannon-pet.jsonp') with open(metric_fp) as metric_fh: self.assertTrue('summer' not in metric_fh.read()) self.assertFalse( os.path.exists(os.path.join(output_dir, 'shannon_entropy-foo.jsonp'))) self.assertFalse( os.path.exists(os.path.join(output_dir, 'shannon_entropy-bar.jsonp'))) def test_alpha_rarefaction_with_depth_column_in_metadata(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) md = qiime2.Metadata( pd.DataFrame({'depth': ['1', '2', '3']}, index=pd.Index(['S1', 'S2', 'S3'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) def test_alpha_rarefaction_with_phylogeny(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) p = self._to_newick(skbio.TreeNode.read(io.StringIO( '((O1:0.25, O2:0.50):0.25, O3:0.75)root;'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, phylogeny=p) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) self.assertTrue('faith_pd' in index_content) def test_alpha_rarefaction_with_phylogeny_and_metadata(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) p = self._to_newick(skbio.TreeNode.read(io.StringIO( '((O1:0.25, O2:0.50):0.25, O3:0.75)root;'))) md = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'peanut']}, index=pd.Index(['S1', 'S2', 'S3'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, phylogeny=p, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) self.assertTrue('faith_pd' in index_content) def test_invalid_invocations(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) md = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'peanut']}, index=pd.Index(['S1', 'S2', 'S3'], name='id'))) empty_table = biom.Table(np.array([]), [], []) bad_metadata = qiime2.Metadata( pd.DataFrame({'pet': ['russ', 'milo', 'summer']}, index=pd.Index(['S1', 'S2', 'S4'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: with self.assertRaisesRegex(ValueError, 'must be greater'): alpha_rarefaction(output_dir, t, min_depth=200, max_depth=1, metadata=md) with self.assertRaisesRegex(ValueError, 'phylogeny was not'): alpha_rarefaction(output_dir, t, max_depth=200, metadata=md, metrics=set(['faith_pd'])) with self.assertRaisesRegex(TypeError, 'pole.*incompatible'): alpha_rarefaction(output_dir, t, max_depth=200, metadata=md, metrics=set(['pole-position'])) with self.assertRaisesRegex(ValueError, 'max_depth'): alpha_rarefaction(output_dir, t, max_depth=1000) with self.assertRaisesRegex(ValueError, 'steps'): alpha_rarefaction(output_dir, t, max_depth=2) with self.assertRaisesRegex(ValueError, 'empty'): alpha_rarefaction(output_dir, empty_table, max_depth=200) with self.assertRaisesRegex(ValueError, 'not present.*S3'): alpha_rarefaction(output_dir, t, metadata=bad_metadata, max_depth=200) with self.assertRaisesRegex(ValueError, 'empty set'): alpha_rarefaction(output_dir, t, max_depth=200, metadata=md, metrics=set()) def test_alpha_rarefaction_with_metric_set(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) metrics = set(['observed_features', 'shannon', 'pielou_e']) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, metrics=metrics, max_depth=200) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: index_content = index_fh.read() self.assertTrue('observed_features' in index_content) self.assertTrue('shannon' in index_content) self.assertTrue('pielou_e' in index_content) def test_alpha_rarefaction_with_metadata_column_with_spaces(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) md = qiime2.Metadata( pd.DataFrame({'pet name': ['russ', 'milo', 'peanut']}, index=pd.Index(['S1', 'S2', 'S3'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) index_fp = os.path.join(output_dir, 'index.html') self.assertTrue(os.path.exists(index_fp)) with open(index_fp) as index_fh: self.assertTrue('pet%2520name' in index_fh.read()) jsonp_fp = os.path.join(output_dir, 'shannon-pet%20name.jsonp') self.assertTrue(os.path.exists(jsonp_fp)) with open(jsonp_fp) as jsonp_fh: self.assertTrue('pet name' in jsonp_fh.read()) def test_alpha_rarefaction_with_fully_filtered_metadata_columns(self): t = biom.Table(np.array([[100, 111, 113], [111, 111, 112]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) # All columns should both be filtered and raise an error md = qiime2.Metadata( pd.DataFrame({'foo': [np.nan, np.nan, np.nan, 'bar'], 'bar': [42, 4.2, 99.9, 100.0]}, index=pd.Index(['S1', 'S2', 'S3', 'S4'], name='id'))) with tempfile.TemporaryDirectory() as output_dir: with self.assertRaisesRegex(ValueError, "non-categorical"): alpha_rarefaction(output_dir, t, max_depth=200, metadata=md) class ComputeRarefactionDataTests(unittest.TestCase): def setUp(self): np.random.seed(0) @staticmethod def _to_newick(tree: skbio.TreeNode): return transform(tree, from_type=skbio.TreeNode, to_type=NewickFormat) def test_observed_features(self): t = biom.Table(np.array([[150, 100, 100], [50, 100, 100]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) obs = _compute_rarefaction_data(feature_table=t, min_depth=1, max_depth=200, steps=2, iterations=1, phylogeny=None, metrics=['observed_features']) exp_ind = pd.MultiIndex.from_product( [[1, 200], [1]], names=['_alpha_rarefaction_depth_column_', 'iter']) exp = pd.DataFrame(data=[[1, 2], [1, 2], [1, 2]], columns=exp_ind, index=['S1', 'S2', 'S3']) pdt.assert_frame_equal(obs['observed_features'], exp) def test_faith_pd(self): t = biom.Table(np.array([[150, 100, 100], [50, 100, 100]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) p = self._to_newick(skbio.TreeNode.read(io.StringIO( '((O1:0.25, O2:0.50):0.25, O3:0.75)root;'))) obs = _compute_rarefaction_data(feature_table=t, min_depth=1, max_depth=200, steps=2, iterations=1, phylogeny=p, metrics=['faith_pd']) self.assertTrue('faith_pd' in obs) def test_multiple_metrics(self): t = biom.Table(np.array([[150, 100, 100], [50, 100, 100]]), ['O1', 'O2'], ['S1', 'S2', 'S3']) obs = _compute_rarefaction_data(feature_table=t, min_depth=1, max_depth=200, steps=2, iterations=1, phylogeny=None, metrics=['observed_features', 'shannon']) exp_ind = pd.MultiIndex.from_product( [[1, 200], [1]], names=['_alpha_rarefaction_depth_column_', 'iter']) exp = pd.DataFrame(data=[[1, 2], [1, 2], [1, 2]], columns=exp_ind, index=['S1', 'S2', 'S3']) pdt.assert_frame_equal(obs['observed_features'], exp) exp = pd.DataFrame(data=[[0., 0.811278124459], [0., 1.], [0., 1.]], columns=exp_ind, index=['S1', 'S2', 'S3']) pdt.assert_frame_equal(obs['shannon'], exp) class ComputeSummaryTests(unittest.TestCase): def test_one_iteration_no_metadata(self): columns = pd.MultiIndex.from_product([[1, 200], [1]], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2], [1, 2], [1, 2]], columns=columns, index=['S1', 'S2', 'S3']) # No counts provided because no metadata obs = _compute_summary(data, 'sample-id') d = [['S1', 1, 1, 1., 1., 1., 1., 1., 1., 1., 1., 1.], ['S1', 200, 1, 2., 2., 2., 2., 2., 2., 2., 2., 2.], ['S2', 1, 1, 1., 1., 1., 1., 1., 1., 1., 1., 1.], ['S2', 200, 1, 2., 2., 2., 2., 2., 2., 2., 2., 2.], ['S3', 1, 1, 1., 1., 1., 1., 1., 1., 1., 1., 1.], ['S3', 200, 1, 2., 2., 2., 2., 2., 2., 2., 2., 2.]] exp = pd.DataFrame(data=d, columns=['sample-id', 'depth', 'count', 'min', '2%', '9%', '25%', '50%', '75%', '91%', '98%', 'max']) pdt.assert_frame_equal(exp, obs) def test_two_iterations_no_metadata(self): columns = pd.MultiIndex.from_product([[1, 200], [1, 2]], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], columns=columns, index=['S1', 'S2', 'S3']) # No counts provided because no metadata obs = _compute_summary(data, 'sample-id') d = [['S1', 1, 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2.], ['S1', 200, 1, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4.], ['S2', 1, 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2.], ['S2', 200, 1, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4.], ['S3', 1, 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2.], ['S3', 200, 1, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4.]] exp = pd.DataFrame(data=d, columns=['sample-id', 'depth', 'count', 'min', '2%', '9%', '25%', '50%', '75%', '91%', '98%', 'max']) pdt.assert_frame_equal(exp, obs) def test_three_iterations_no_metadata(self): columns = pd.MultiIndex.from_product([[1, 200], [1, 2, 3]], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], columns=columns, index=['S1', 'S2', 'S3']) # No counts provided because no metadata obs = _compute_summary(data, 'sample-id') d = [['S1', 1, 1, 1., 1.04, 1.18, 1.5, 2., 2.5, 2.82, 2.96, 3.], ['S1', 200, 1, 4., 4.04, 4.18, 4.5, 5., 5.5, 5.82, 5.96, 6.], ['S2', 1, 1, 1., 1.04, 1.18, 1.5, 2., 2.5, 2.82, 2.96, 3.], ['S2', 200, 1, 4., 4.04, 4.18, 4.5, 5., 5.5, 5.82, 5.96, 6.], ['S3', 1, 1, 1., 1.04, 1.18, 1.5, 2., 2.5, 2.82, 2.96, 3.], ['S3', 200, 1, 4., 4.04, 4.18, 4.5, 5., 5.5, 5.82, 5.96, 6.]] exp = pd.DataFrame(data=d, columns=['sample-id', 'depth', 'count', 'min', '2%', '9%', '25%', '50%', '75%', '91%', '98%', 'max']) pdt.assert_frame_equal(exp, obs) def test_two_iterations_with_metadata_were_values_are_unique(self): # This should be identical to test_without_metadata_df_two_iterations, # with just the `sample-id` replaced with `pet`. columns = pd.MultiIndex.from_product([[1, 200], [1, 2]], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], columns=columns, index=['russ', 'milo', 'pea']) counts = pd.DataFrame(data=[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], columns=columns, index=['russ', 'milo', 'pea']) obs = _compute_summary(data, 'pet', counts=counts) d = [ ['russ', 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2., 1], ['russ', 200, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4., 1], ['milo', 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2., 1], ['milo', 200, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4., 1], ['pea', 1, 1., 1.02, 1.09, 1.25, 1.5, 1.75, 1.91, 1.98, 2., 1], ['pea', 200, 3., 3.02, 3.09, 3.25, 3.5, 3.75, 3.91, 3.98, 4., 1], ] exp = pd.DataFrame(data=d, columns=['pet', 'depth', 'min', '2%', '9%', '25%', '50%', '75%', '91%', '98%', 'max', 'count']) pdt.assert_frame_equal(exp, obs) def test_two_iterations_with_metadata_were_values_are_identical(self): columns = pd.MultiIndex.from_product([[1, 200], [1, 2]], names=['depth', 'iter']) data = pd.DataFrame(data=[[3, 6, 9, 9]], columns=columns, index=['milo']) counts = pd.DataFrame(data=[[3, 3, 3, 3]], columns=columns, index=['milo']) obs = _compute_summary(data, 'pet', counts=counts) d = [ ['milo', 1, 3., 3.06, 3.27, 3.75, 4.5, 5.25, 5.73, 5.94, 6., 3], ['milo', 200, 9., 9., 9., 9., 9., 9., 9., 9., 9., 3], ] exp = pd.DataFrame(data=d, columns=['pet', 'depth', 'min', '2%', '9%', '25%', '50%', '75%', '91%', '98%', 'max', 'count']) pdt.assert_frame_equal(exp, obs) class ReindexWithMetadataTests(unittest.TestCase): def test_unique_metadata_groups(self): columns = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (200, 1), (200, 2), ('pet', '')], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4, 'russ'], [5, 6, 7, 8, 'milo'], [9, 10, 11, 12, 'peanut']], columns=columns, index=['S1', 'S2', 'S3']) median, counts = _reindex_with_metadata('pet', ['pet'], data) exp_col = pd.MultiIndex(levels=[[1, 200, 'pet'], [1, 2, '']], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=['depth', 'iter']) exp_ind = pd.Index(['milo', 'peanut', 'russ'], name='pet') exp = pd.DataFrame(data=[[5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, median) exp = pd.DataFrame(data=[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, counts) def test_some_duplicates_in_column(self): columns = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (200, 1), (200, 2), ('pet', '')], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4, 'russ'], [5, 6, 7, 8, 'milo'], [9, 10, 11, 12, 'russ']], columns=columns, index=['S1', 'S2', 'S3']) median, counts = _reindex_with_metadata('pet', ['pet'], data) exp_col = pd.MultiIndex(levels=[[1, 200, 'pet'], [1, 2, '']], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=['depth', 'iter']) exp_ind = pd.Index(['milo', 'russ'], name='pet') exp = pd.DataFrame(data=[[5, 6, 7, 8], [5, 6, 7, 8]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, median) exp = pd.DataFrame(data=[[1, 1, 1, 1], [2, 2, 2, 2]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, counts) def test_all_identical(self): columns = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (200, 1), (200, 2), ('pet', '')], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4, 'russ'], [5, 6, 7, 8, 'russ'], [9, 10, 11, 12, 'russ']], columns=columns, index=['S1', 'S2', 'S3']) median, counts = _reindex_with_metadata('pet', ['pet'], data) exp_col = pd.MultiIndex(levels=[[1, 200, 'pet'], [1, 2, '']], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=['depth', 'iter']) exp_ind = pd.Index(['russ'], name='pet') exp = pd.DataFrame(data=[[5, 6, 7, 8]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, median) exp = pd.DataFrame(data=[[3, 3, 3, 3]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, counts) def test_multiple_columns(self): columns = pd.MultiIndex.from_tuples([(1, 1), (1, 2), (200, 1), (200, 2), ('pet', ''), ('toy', '')], names=['depth', 'iter']) data = pd.DataFrame(data=[[1, 2, 3, 4, 'russ', 'stick'], [5, 6, 7, 8, 'milo', 'yeti'], [9, 10, 11, 12, 'peanut', 'stick']], columns=columns, index=['S1', 'S2', 'S3']) median, counts = _reindex_with_metadata('pet', ['pet', 'toy'], data) exp_col = pd.MultiIndex(levels=[[1, 200, 'pet', 'toy'], [1, 2, '']], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=['depth', 'iter']) exp_ind = pd.Index(['milo', 'peanut', 'russ'], name='pet') exp = pd.DataFrame(data=[[5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, median) exp = pd.DataFrame(data=[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, counts) median, counts = _reindex_with_metadata('toy', ['pet', 'toy'], data) exp_ind = pd.Index(['stick', 'yeti'], name='toy') exp = pd.DataFrame(data=[[5, 6, 7, 8], [5, 6, 7, 8]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, median) exp = pd.DataFrame(data=[[2, 2, 2, 2], [1, 1, 1, 1]], columns=exp_col, index=exp_ind) pdt.assert_frame_equal(exp, counts) class AlphaRarefactionJSONPTests(unittest.TestCase): def test_simple(self): d = [[1.04, 1.5, 2., 2.5, 1.18, 2.82, 2.96, 3., 1, 3., 1., 'S1'], [1.04, 1.5, 2., 2.5, 1.18, 2.82, 2.96, 3., 1, 3., 1., 'S2'], [1.04, 1.5, 2., 2.5, 1.18, 2.82, 2.96, 3., 1, 3., 1., 'S3']] data = pd.DataFrame(data=d, columns=['2%', '25%', '50%', '75%', '9%', '91%', '98%', 'count', 'depth', 'max', 'min', 'sample-id']) with tempfile.TemporaryDirectory() as output_dir: _alpha_rarefaction_jsonp(output_dir, 'peanut.jsonp', 'shannon', data, '') jsonp_fp = os.path.join(output_dir, 'peanut.jsonp') self.assertTrue(os.path.exists(jsonp_fp)) with open(jsonp_fp) as jsonp_fh: jsonp_content = jsonp_fh.read() self.assertTrue('load_data' in jsonp_content) self.assertTrue('columns' in jsonp_content) self.assertTrue('index' in jsonp_content) self.assertTrue('data' in jsonp_content) self.assertTrue('sample-id' in jsonp_content) self.assertTrue('shannon' in jsonp_content) if __name__ == '__main__': unittest.main()
# (C) Datadog, Inc. 2010-2017 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) """kubernetes check Collects metrics from cAdvisor instance """ # stdlib from collections import defaultdict from fnmatch import fnmatch import numbers import re import time import calendar # 3p from requests.exceptions import ConnectionError # project from checks import AgentCheck from config import _is_affirmative from utils.kubernetes import KubeUtil from utils.service_discovery.sd_backend import get_sd_backend NAMESPACE = "kubernetes" DEFAULT_MAX_DEPTH = 10 LEADER_CANDIDATE = 'leader_candidate' DEFAULT_USE_HISTOGRAM = False DEFAULT_PUBLISH_ALIASES = False DEFAULT_ENABLED_RATES = [ 'diskio.io_service_bytes.stats.total', 'network.??_bytes', 'cpu.*.total'] DEFAULT_COLLECT_EVENTS = False DEFAULT_NAMESPACES = ['default'] DEFAULT_SERVICE_EVENT_FREQ = 5 * 60 # seconds NET_ERRORS = ['rx_errors', 'tx_errors', 'rx_dropped', 'tx_dropped'] DEFAULT_ENABLED_GAUGES = [ 'memory.usage', 'filesystem.usage'] GAUGE = AgentCheck.gauge RATE = AgentCheck.rate HISTORATE = AgentCheck.generate_historate_func(["container_name"]) HISTO = AgentCheck.generate_histogram_func(["container_name"]) FUNC_MAP = { GAUGE: {True: HISTO, False: GAUGE}, RATE: {True: HISTORATE, False: RATE} } EVENT_TYPE = 'kubernetes' # Mapping between k8s events and ddog alert types per # https://github.com/kubernetes/kubernetes/blob/adb75e1fd17b11e6a0256a4984ef9b18957d94ce/staging/src/k8s.io/client-go/1.4/tools/record/event.go#L59 K8S_ALERT_MAP = { 'Warning': 'warning', 'Normal': 'info' } # Suffixes per # https://github.com/kubernetes/kubernetes/blob/8fd414537b5143ab039cb910590237cabf4af783/pkg/api/resource/suffix.go#L108 FACTORS = { 'n': float(1)/(1000*1000*1000), 'u': float(1)/(1000*1000), 'm': float(1)/1000, 'k': 1000, 'M': 1000*1000, 'G': 1000*1000*1000, 'T': 1000*1000*1000*1000, 'P': 1000*1000*1000*1000*1000, 'E': 1000*1000*1000*1000*1000*1000, 'Ki': 1024, 'Mi': 1024*1024, 'Gi': 1024*1024*1024, 'Ti': 1024*1024*1024*1024, 'Pi': 1024*1024*1024*1024*1024, 'Ei': 1024*1024*1024*1024*1024*1024, } QUANTITY_EXP = re.compile(r'[-+]?\d+[\.]?\d*[numkMGTPE]?i?') class Kubernetes(AgentCheck): """ Collect metrics and events from kubelet """ pod_names_by_container = {} def __init__(self, name, init_config, agentConfig, instances=None): if instances is not None and len(instances) > 1: raise Exception('Kubernetes check only supports one configured instance.') AgentCheck.__init__(self, name, init_config, agentConfig, instances) inst = instances[0] if instances is not None else None self.kubeutil = KubeUtil(init_config=init_config, instance=inst) if not self.kubeutil.init_success: if self.kubeutil.left_init_retries > 0: self.log.warning("Kubelet client failed to initialized for now, pausing the Kubernetes check.") else: raise Exception('Unable to initialize Kubelet client. Try setting the host parameter. The Kubernetes check failed permanently.') if agentConfig.get('service_discovery') and \ agentConfig.get('service_discovery_backend') == 'docker': self._sd_backend = get_sd_backend(agentConfig) else: self._sd_backend = None self.leader_candidate = inst.get(LEADER_CANDIDATE) if self.leader_candidate: self.kubeutil.refresh_leader() self.k8s_namespace_regexp = None if inst: regexp = inst.get('namespace_name_regexp', None) if regexp: try: self.k8s_namespace_regexp = re.compile(regexp) except re.error as e: self.log.warning('Invalid regexp for "namespace_name_regexp" in configuration (ignoring regexp): %s' % str(e)) self.event_retriever = None self._configure_event_collection(inst) def _perform_kubelet_checks(self, url, instance): service_check_base = NAMESPACE + '.kubelet.check' is_ok = True try: req = self.kubeutil.perform_kubelet_query(url) for line in req.iter_lines(): # avoid noise; this check is expected to fail since we override the container hostname if line.find('hostname') != -1: continue matches = re.match('\[(.)\]([^\s]+) (.*)?', line) if not matches or len(matches.groups()) < 2: continue service_check_name = service_check_base + '.' + matches.group(2) status = matches.group(1) if status == '+': self.service_check(service_check_name, AgentCheck.OK, tags=instance.get('tags', [])) else: self.service_check(service_check_name, AgentCheck.CRITICAL, tags=instance.get('tags', [])) is_ok = False except Exception as e: self.log.warning('kubelet check %s failed: %s' % (url, str(e))) self.service_check(service_check_base, AgentCheck.CRITICAL, message='Kubelet check %s failed: %s' % (url, str(e)), tags=instance.get('tags', [])) else: if is_ok: self.service_check(service_check_base, AgentCheck.OK, tags=instance.get('tags', [])) else: self.service_check(service_check_base, AgentCheck.CRITICAL, tags=instance.get('tags', [])) def _configure_event_collection(self, instance): self._collect_events = self.kubeutil.is_leader or _is_affirmative(instance.get('collect_events', DEFAULT_COLLECT_EVENTS)) if self._collect_events: if self.event_retriever: self.event_retriever.set_kinds(None) self.event_retriever.set_delay(None) else: self.event_retriever = self.kubeutil.get_event_retriever() elif self.kubeutil.collect_service_tag: # Only fetch service and pod events for service mapping event_delay = instance.get('service_tag_update_freq', DEFAULT_SERVICE_EVENT_FREQ) if self.event_retriever: self.event_retriever.set_kinds(['Service', 'Pod']) self.event_retriever.set_delay(event_delay) else: self.event_retriever = self.kubeutil.get_event_retriever(kinds=['Service', 'Pod'], delay=event_delay) else: self.event_retriever = None def check(self, instance): if not self.kubeutil.init_success: if self.kubeutil.left_init_retries > 0: self.kubeutil.init_kubelet(instance) self.log.warning("Kubelet client is not initialized, Kubernetes check is paused.") return else: raise Exception("Unable to initialize Kubelet client. Try setting the host parameter. The Kubernetes check failed permanently.") # Leader election self.refresh_leader_status(instance) self.max_depth = instance.get('max_depth', DEFAULT_MAX_DEPTH) enabled_gauges = instance.get('enabled_gauges', DEFAULT_ENABLED_GAUGES) self.enabled_gauges = ["{0}.{1}".format(NAMESPACE, x) for x in enabled_gauges] enabled_rates = instance.get('enabled_rates', DEFAULT_ENABLED_RATES) self.enabled_rates = ["{0}.{1}".format(NAMESPACE, x) for x in enabled_rates] self.publish_aliases = _is_affirmative(instance.get('publish_aliases', DEFAULT_PUBLISH_ALIASES)) self.use_histogram = _is_affirmative(instance.get('use_histogram', DEFAULT_USE_HISTOGRAM)) self.publish_rate = FUNC_MAP[RATE][self.use_histogram] self.publish_gauge = FUNC_MAP[GAUGE][self.use_histogram] # initialized by _filter_containers self._filtered_containers = set() try: pods_list = self.kubeutil.retrieve_pods_list() except: pods_list = None # kubelet health checks self._perform_kubelet_checks(self.kubeutil.kube_health_url, instance) if pods_list is not None: # Will not fail if cAdvisor is not available self._update_pods_metrics(instance, pods_list) # cAdvisor & kubelet metrics, will fail if port 4194 is not open try: if int(instance.get('port', KubeUtil.DEFAULT_CADVISOR_PORT)) > 0: self._update_metrics(instance, pods_list) except ConnectionError: self.warning('''Can't access the cAdvisor metrics, performance metrics and''' ''' limits/requests will not be collected. Please setup''' ''' your kubelet with the --cadvisor-port=4194 option, or set port to 0''' ''' in this check's configuration to disable cAdvisor lookup.''') except Exception as err: self.log.warning("Error while getting performance metrics: %s" % str(err)) # kubelet events if self.event_retriever is not None: try: events = self.event_retriever.get_event_array() changed_cids = self.kubeutil.process_events(events, podlist=pods_list) if (changed_cids and self._sd_backend): self._sd_backend.update_checks(changed_cids) if events and self._collect_events: self._update_kube_events(instance, pods_list, events) except Exception as ex: self.log.error("Event collection failed: %s" % str(ex)) def _publish_raw_metrics(self, metric, dat, tags, depth=0): if depth >= self.max_depth: self.log.warning('Reached max depth on metric=%s' % metric) return if isinstance(dat, numbers.Number): if self.enabled_rates and any([fnmatch(metric, pat) for pat in self.enabled_rates]): self.publish_rate(self, metric, float(dat), tags) elif self.enabled_gauges and any([fnmatch(metric, pat) for pat in self.enabled_gauges]): self.publish_gauge(self, metric, float(dat), tags) elif isinstance(dat, dict): for k, v in dat.iteritems(): self._publish_raw_metrics(metric + '.%s' % k.lower(), v, tags, depth + 1) elif isinstance(dat, list): self._publish_raw_metrics(metric, dat[-1], tags, depth + 1) @staticmethod def _shorten_name(name): # shorten docker image id return re.sub('([0-9a-fA-F]{64,})', lambda x: x.group(1)[0:12], name) def _get_post_1_2_tags(self, cont_labels, subcontainer, kube_labels): tags = [] pod_name = cont_labels[KubeUtil.POD_NAME_LABEL] pod_namespace = cont_labels[KubeUtil.NAMESPACE_LABEL] # kube_container_name is the name of the Kubernetes container resource, # not the name of the docker container (that's tagged as container_name) kube_container_name = cont_labels[KubeUtil.CONTAINER_NAME_LABEL] tags.append(u"pod_name:{0}".format(pod_name)) tags.append(u"kube_namespace:{0}".format(pod_namespace)) tags.append(u"kube_container_name:{0}".format(kube_container_name)) kube_labels_key = "{0}/{1}".format(pod_namespace, pod_name) pod_labels = kube_labels.get(kube_labels_key) if pod_labels: tags += list(pod_labels) if "-" in pod_name: replication_controller = "-".join(pod_name.split("-")[:-1]) tags.append("kube_replication_controller:%s" % replication_controller) if self.publish_aliases and subcontainer.get("aliases"): for alias in subcontainer['aliases'][1:]: # we don't add the first alias as it will be the container_name tags.append('container_alias:%s' % (self._shorten_name(alias))) return tags def _get_pre_1_2_tags(self, cont_labels, subcontainer, kube_labels): tags = [] pod_name = cont_labels[KubeUtil.POD_NAME_LABEL] tags.append(u"pod_name:{0}".format(pod_name)) pod_labels = kube_labels.get(pod_name) if pod_labels: tags.extend(list(pod_labels)) if "-" in pod_name: replication_controller = "-".join(pod_name.split("-")[:-1]) if "/" in replication_controller: namespace, replication_controller = replication_controller.split("/", 1) tags.append(u"kube_namespace:%s" % namespace) tags.append(u"kube_replication_controller:%s" % replication_controller) if self.publish_aliases and subcontainer.get("aliases"): for alias in subcontainer['aliases'][1:]: # we don't add the first alias as it will be the container_name tags.append(u"container_alias:%s" % (self._shorten_name(alias))) return tags def _update_container_metrics(self, instance, subcontainer, kube_labels): """Publish metrics for a subcontainer and handle filtering on tags""" tags = list(instance.get('tags', [])) # add support for custom tags if len(subcontainer.get('aliases', [])) >= 1: # The first alias seems to always match the docker container name container_name = subcontainer['aliases'][0] else: self.log.debug("Subcontainer doesn't have a name, skipping.") return tags.append('container_name:%s' % container_name) container_image = self.kubeutil.image_name_resolver(subcontainer['spec'].get('image')) if container_image: tags.append('container_image:%s' % container_image) split = container_image.split(":") if len(split) > 2: # if the repo is in the image name and has the form 'docker.clearbit:5000' # the split will be like [repo_url, repo_port/image_name, image_tag]. Let's avoid that split = [':'.join(split[:-1]), split[-1]] tags.append('image_name:%s' % split[0]) if len(split) == 2: tags.append('image_tag:%s' % split[1]) try: cont_labels = subcontainer['spec']['labels'] except KeyError: self.log.debug("Subcontainer, doesn't have any labels") cont_labels = {} # Collect pod names, namespaces, rc... if KubeUtil.NAMESPACE_LABEL in cont_labels and KubeUtil.POD_NAME_LABEL in cont_labels: # Kubernetes >= 1.2 tags += self._get_post_1_2_tags(cont_labels, subcontainer, kube_labels) elif KubeUtil.POD_NAME_LABEL in cont_labels: # Kubernetes <= 1.1 tags += self._get_pre_1_2_tags(cont_labels, subcontainer, kube_labels) else: # Those are containers that are not part of a pod. # They are top aggregate views and don't have the previous metadata. tags.append("pod_name:no_pod") # if the container should be filtered we return its tags without publishing its metrics is_filtered = self.kubeutil.are_tags_filtered(tags) if is_filtered: self._filtered_containers.add(subcontainer['id']) return tags stats = subcontainer['stats'][-1] # take the latest self._publish_raw_metrics(NAMESPACE, stats, tags) if subcontainer.get("spec", {}).get("has_filesystem") and stats.get('filesystem', []) != []: fs = stats['filesystem'][-1] fs_utilization = float(fs['usage'])/float(fs['capacity']) self.publish_gauge(self, NAMESPACE + '.filesystem.usage_pct', fs_utilization, tags) if subcontainer.get("spec", {}).get("has_network"): net = stats['network'] self.publish_rate(self, NAMESPACE + '.network_errors', sum(float(net[x]) for x in NET_ERRORS), tags) return tags def _update_metrics(self, instance, pods_list): def parse_quantity(s): number = '' unit = '' for c in s: if c.isdigit() or c == '.': number += c else: unit += c return float(number) * FACTORS.get(unit, 1) metrics = self.kubeutil.retrieve_metrics() excluded_labels = instance.get('excluded_labels') kube_labels = self.kubeutil.extract_kube_pod_tags(pods_list, excluded_keys=excluded_labels) if not metrics: raise Exception('No metrics retrieved cmd=%s' % self.metrics_cmd) # container metrics from Cadvisor container_tags = {} for subcontainer in metrics: c_id = subcontainer.get('id') if 'aliases' not in subcontainer: # it means the subcontainer is about a higher-level entity than a container continue try: tags = self._update_container_metrics(instance, subcontainer, kube_labels) if c_id: container_tags[c_id] = tags # also store tags for aliases for alias in subcontainer.get('aliases', []): container_tags[alias] = tags except Exception as e: self.log.error("Unable to collect metrics for container: {0} ({1})".format(c_id, e)) # container metrics from kubernetes API: limits and requests for pod in pods_list['items']: try: containers = pod['spec']['containers'] name2id = {} for cs in pod['status'].get('containerStatuses', []): c_id = cs.get('containerID', '').split('//')[-1] name = cs.get('name') if name: name2id[name] = c_id except KeyError: self.log.debug("Pod %s does not have containers specs, skipping...", pod['metadata'].get('name')) continue for container in containers: c_name = container.get('name') c_id = name2id.get(c_name) if c_id in self._filtered_containers: self.log.debug('Container {} is excluded'.format(c_name)) continue _tags = container_tags.get(c_id, []) # limits try: for limit, value_str in container['resources']['limits'].iteritems(): values = [parse_quantity(s) for s in QUANTITY_EXP.findall(value_str)] if len(values) != 1: self.log.warning("Error parsing limits value string: %s", value_str) continue self.publish_gauge(self, '{}.{}.limits'.format(NAMESPACE, limit), values[0], _tags) except (KeyError, AttributeError) as e: self.log.debug("Unable to retrieve container limits for %s: %s", c_name, e) # requests try: for request, value_str in container['resources']['requests'].iteritems(): values = [parse_quantity(s) for s in QUANTITY_EXP.findall(value_str)] if len(values) != 1: self.log.warning("Error parsing requests value string: %s", value_str) continue self.publish_gauge(self, '{}.{}.requests'.format(NAMESPACE, request), values[0], _tags) except (KeyError, AttributeError) as e: self.log.debug("Unable to retrieve container requests for %s: %s", c_name, e) self._update_node(instance) def _update_node(self, instance): machine_info = self.kubeutil.retrieve_machine_info() num_cores = machine_info.get('num_cores', 0) memory_capacity = machine_info.get('memory_capacity', 0) tags = instance.get('tags', []) self.publish_gauge(self, NAMESPACE + '.cpu.capacity', float(num_cores), tags) self.publish_gauge(self, NAMESPACE + '.memory.capacity', float(memory_capacity), tags) # TODO(markine): Report 'allocatable' which is capacity minus capacity # reserved for system/Kubernetes. def _update_pods_metrics(self, instance, pods): """ Reports the number of running pods, tagged by service and creator We go though all the pods, extract tags then count them by tag list, sorted and serialized in a pipe-separated string (it is an illegar character for tags) """ tags_map = defaultdict(int) for pod in pods['items']: pod_meta = pod.get('metadata', {}) pod_tags = self.kubeutil.get_pod_creator_tags(pod_meta, legacy_rep_controller_tag=True) services = self.kubeutil.match_services_for_pod(pod_meta) if isinstance(services, list): for service in services: pod_tags.append('kube_service:%s' % service) if 'namespace' in pod_meta: pod_tags.append('kube_namespace:%s' % pod_meta['namespace']) tags_map[frozenset(pod_tags)] += 1 commmon_tags = instance.get('tags', []) for pod_tags, pod_count in tags_map.iteritems(): tags = list(pod_tags) tags.extend(commmon_tags) self.publish_gauge(self, NAMESPACE + '.pods.running', pod_count, tags) def _update_kube_events(self, instance, pods_list, event_items): """ Process kube events and send ddog events The namespace filtering is done here instead of KubeEventRetriever to avoid interfering with service discovery """ node_ip, node_name = self.kubeutil.get_node_info() self.log.debug('Processing events on {} [{}]'.format(node_name, node_ip)) k8s_namespaces = instance.get('namespaces', DEFAULT_NAMESPACES) if not isinstance(k8s_namespaces, list): self.log.warning('Configuration key "namespaces" is not a list: fallback to the default value') k8s_namespaces = DEFAULT_NAMESPACES # handle old config value if 'namespace' in instance and instance.get('namespace') not in (None, 'default'): self.log.warning('''The 'namespace' parameter is deprecated and will stop being supported starting ''' '''from 5.13. Please use 'namespaces' and/or 'namespace_name_regexp' instead.''') k8s_namespaces.append(instance.get('namespace')) if self.k8s_namespace_regexp: namespaces_endpoint = '{}/namespaces'.format(self.kubeutil.kubernetes_api_url) self.log.debug('Kubernetes API endpoint to query namespaces: %s' % namespaces_endpoint) namespaces = self.kubeutil.retrieve_json_auth(namespaces_endpoint).json() for namespace in namespaces.get('items', []): name = namespace.get('metadata', {}).get('name', None) if name and self.k8s_namespace_regexp.match(name): k8s_namespaces.append(name) k8s_namespaces = set(k8s_namespaces) for event in event_items: event_ts = calendar.timegm(time.strptime(event.get('lastTimestamp'), '%Y-%m-%dT%H:%M:%SZ')) involved_obj = event.get('involvedObject', {}) # filter events by white listed namespaces (empty namespace belong to the 'default' one) if involved_obj.get('namespace', 'default') not in k8s_namespaces: continue tags = self.kubeutil.extract_event_tags(event) tags.extend(instance.get('tags', [])) title = '{} {} on {}'.format(involved_obj.get('name'), event.get('reason'), node_name) message = event.get('message') source = event.get('source') k8s_event_type = event.get('type') alert_type = K8S_ALERT_MAP.get(k8s_event_type, 'info') if source: message += '\nSource: {} {}\n'.format(source.get('component', ''), source.get('host', '')) msg_body = "%%%\n{}\n```\n{}\n```\n%%%".format(title, message) dd_event = { 'timestamp': event_ts, 'host': node_ip, 'event_type': EVENT_TYPE, 'msg_title': title, 'msg_text': msg_body, 'source_type_name': EVENT_TYPE, 'alert_type': alert_type, 'event_object': 'kubernetes:{}'.format(involved_obj.get('name')), 'tags': tags, } self.event(dd_event) def refresh_leader_status(self, instance): """ calls kubeutil.refresh_leader and compares the resulting leader status with the previous one. If it changed, update the event collection logic """ if not self.leader_candidate: return leader_status = self.kubeutil.is_leader self.kubeutil.refresh_leader() # nothing changed, no-op if leader_status == self.kubeutil.is_leader: return # else, reset the event collection config else: self.log.info("Leader status changed, updating event collection config...") self._configure_event_collection(instance)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Models declaration for application ``django_mailbox``. """ from email.encoders import encode_base64 from email.message import Message as EmailMessage from email.utils import formatdate, parseaddr, parsedate_to_datetime from quopri import encode as encode_quopri import base64 import email import logging import mimetypes import os.path import sys import uuid import six from six.moves.urllib.parse import parse_qs, unquote, urlparse from django.conf import settings from django.core.files.base import ContentFile from django.core.mail.message import make_msgid from django.db import models from django.utils.translation import ugettext as _ from .utils import convert_header_to_unicode, get_body_from_message from django_mailbox.signals import message_received from django_mailbox.transports import Pop3Transport, ImapTransport, \ MaildirTransport, MboxTransport, BabylTransport, MHTransport, \ MMDFTransport, GmailImapTransport logger = logging.getLogger(__name__) STRIP_UNALLOWED_MIMETYPES = getattr( settings, 'DJANGO_MAILBOX_STRIP_UNALLOWED_MIMETYPES', False ) ALLOWED_MIMETYPES = getattr( settings, 'DJANGO_MAILBOX_ALLOWED_MIMETYPES', [ 'text/plain', 'text/html' ] ) TEXT_STORED_MIMETYPES = getattr( settings, 'DJANGO_MAILBOX_TEXT_STORED_MIMETYPES', [ 'text/plain', 'text/html' ] ) ALTERED_MESSAGE_HEADER = getattr( settings, 'DJANGO_MAILBOX_ALTERED_MESSAGE_HEADER', 'X-Django-Mailbox-Altered-Message' ) ATTACHMENT_INTERPOLATION_HEADER = getattr( settings, 'DJANGO_MAILBOX_ATTACHMENT_INTERPOLATION_HEADER', 'X-Django-Mailbox-Interpolate-Attachment' ) class ActiveMailboxManager(models.Manager): def get_queryset(self): return super(ActiveMailboxManager, self).get_queryset().filter( active=True, ) class Mailbox(models.Model): name = models.CharField( _(u'Name'), max_length=255, ) uri = models.CharField( _(u'URI'), max_length=255, help_text=(_( "Example: imap+ssl://myusername:mypassword@someserver <br />" "<br />" "Internet transports include 'imap' and 'pop3'; " "common local file transports include 'maildir', 'mbox', " "and less commonly 'babyl', 'mh', and 'mmdf'. <br />" "<br />" "Be sure to urlencode your username and password should they " "contain illegal characters (like @, :, etc)." )), blank=True, null=True, default=None, ) from_email = models.CharField( _(u'From email'), max_length=255, help_text=(_( "Example: MailBot &lt;mailbot@yourdomain.com&gt;<br />" "'From' header to set for outgoing email.<br />" "<br />" "If you do not use this e-mail inbox for outgoing mail, this " "setting is unnecessary.<br />" "If you send e-mail without setting this, your 'From' header will'" "be set to match the setting `DEFAULT_FROM_EMAIL`." )), blank=True, null=True, default=None, ) active = models.BooleanField( _(u'Active'), help_text=(_( "Check this e-mail inbox for new e-mail messages during polling " "cycles. This checkbox does not have an effect upon whether " "mail is collected here when this mailbox receives mail from a " "pipe, and does not affect whether e-mail messages can be " "dispatched from this mailbox. " )), blank=True, default=True, ) objects = models.Manager() active_mailboxes = ActiveMailboxManager() @property def _protocol_info(self): return urlparse(self.uri) @property def _query_string(self): return parse_qs(self._protocol_info.query) @property def _domain(self): return self._protocol_info.hostname @property def port(self): return self._protocol_info.port @property def username(self): return unquote(self._protocol_info.username) @property def password(self): return unquote(self._protocol_info.password) @property def location(self): return self._domain if self._domain else '' + self._protocol_info.path @property def type(self): scheme = self._protocol_info.scheme.lower() if '+' in scheme: return scheme.split('+')[0] return scheme @property def use_ssl(self): return '+ssl' in self._protocol_info.scheme.lower() @property def archive(self): archive_folder = self._query_string.get('archive', None) if not archive_folder: return None return archive_folder[0] def get_connection(self): if not self.uri: return None elif self.type == 'imap': conn = ImapTransport( self.location, port=self.port if self.port else None, ssl=self.use_ssl, archive=self.archive ) conn.connect(self.username, self.password) elif self.type == 'gmail': conn = GmailImapTransport( self.location, port=self.port if self.port else None, ssl=True, archive=self.archive ) conn.connect(self.username, self.password) elif self.type == 'pop3': conn = Pop3Transport( self.location, port=self.port if self.port else None, ssl=self.use_ssl ) conn.connect(self.username, self.password) elif self.type == 'maildir': conn = MaildirTransport(self.location) elif self.type == 'mbox': conn = MboxTransport(self.location) elif self.type == 'babyl': conn = BabylTransport(self.location) elif self.type == 'mh': conn = MHTransport(self.location) elif self.type == 'mmdf': conn = MMDFTransport(self.location) return conn def process_incoming_message(self, message): msg = self._process_message(message) msg.outgoing = False msg.save() try: message_received.send(sender=self, message=msg) except: pass return msg def record_outgoing_message(self, message): msg = self._process_message(message) msg.outgoing = True msg.save() return msg def _get_dehydrated_message(self, msg, record): new = EmailMessage() if msg.is_multipart(): for header, value in msg.items(): new[header] = value for part in msg.get_payload(): new.attach( self._get_dehydrated_message(part, record) ) elif ( STRIP_UNALLOWED_MIMETYPES and not msg.get_content_type() in ALLOWED_MIMETYPES ): for header, value in msg.items(): new[header] = value # Delete header, otherwise when attempting to deserialize the # payload, it will be expecting a body for this. del new['Content-Transfer-Encoding'] new[ALTERED_MESSAGE_HEADER] = ( 'Stripped; Content type %s not allowed' % ( msg.get_content_type() ) ) new.set_payload('') elif msg.get_content_type() not in TEXT_STORED_MIMETYPES: filename = msg.get_filename() if not filename: extension = mimetypes.guess_extension(msg.get_content_type()) else: _, extension = os.path.splitext(filename) if not extension: extension = '.bin' attachment = MessageAttachment() attachment.document.save( uuid.uuid4().hex + extension, ContentFile( six.BytesIO( msg.get_payload(decode=True) ).getvalue() ) ) attachment.message = record for key, value in msg.items(): attachment[key] = value attachment.save() placeholder = EmailMessage() placeholder[ATTACHMENT_INTERPOLATION_HEADER] = str(attachment.pk) new = placeholder else: content_charset = msg.get_content_charset() if not content_charset: content_charset = 'ascii' try: # Make sure that the payload can be properly decoded in the # defined charset, if it can't, let's mash some things # inside the payload :-\ msg.get_payload(decode=True).decode(content_charset) except LookupError: logger.warning( "Unknown encoding %s; interpreting as ASCII!", content_charset ) msg.set_payload( msg.get_payload(decode=True).decode( 'ascii', 'ignore' ) ) except ValueError: logger.warning( "Decoding error encountered; interpreting as ASCII!", content_charset ) msg.set_payload( msg.get_payload(decode=True).decode( content_charset, 'ignore' ) ) new = msg return new def _process_message(self, message): msg = Message() msg.mailbox = self if 'subject' in message: msg.subject = convert_header_to_unicode(message['subject'])[0:255] if 'message-id' in message: msg.message_id = message['message-id'][0:255] if 'from' in message: msg.from_header = convert_header_to_unicode(message['from']) if 'to' in message: msg.to_header = convert_header_to_unicode(message['to']) if 'date' in message: sent_time_str = convert_header_to_unicode(message['date']) msg.sent_time = parsedate_to_datetime(sent_time_str) elif 'Delivered-To' in message: msg.to_header = convert_header_to_unicode(message['Delivered-To']) msg.save() message = self._get_dehydrated_message(message, msg) msg.set_body(message.as_string()) if message['in-reply-to']: try: msg.in_reply_to = Message.objects.filter( message_id=message['in-reply-to'] )[0] except IndexError: pass msg.save() return msg def get_new_mail(self): new_mail = [] connection = self.get_connection() if not connection: return new_mail for message in connection.get_message(): msg = self.process_incoming_message(message) new_mail.append(msg) return new_mail def __unicode__(self): return self.name class Meta: verbose_name_plural = "Mailboxes" class IncomingMessageManager(models.Manager): def get_queryset(self): return super(IncomingMessageManager, self).get_queryset().filter( outgoing=False, ) class OutgoingMessageManager(models.Manager): def get_queryset(self): return super(OutgoingMessageManager, self).get_queryset().filter( outgoing=True, ) class UnreadMessageManager(models.Manager): def get_queryset(self): return super(UnreadMessageManager, self).get_queryset().filter( read=None ) class Message(models.Model): mailbox = models.ForeignKey( Mailbox, related_name='messages', verbose_name=_(u'Mailbox'), ) subject = models.CharField( _(u'Subject'), max_length=255 ) message_id = models.CharField( _(u'Message ID'), max_length=255 ) sent_time = models.DateTimeField( _('Sent Time'), ) in_reply_to = models.ForeignKey( 'django_mailbox.Message', related_name='replies', blank=True, null=True, verbose_name=_(u'In reply to'), ) from_header = models.CharField( _('From header'), max_length=255, ) to_header = models.TextField( _(u'To header'), ) outgoing = models.BooleanField( _(u'Outgoing'), default=False, blank=True, ) body = models.TextField( _(u'Body'), ) encoded = models.BooleanField( _(u'Encoded'), default=False, help_text=_('True if the e-mail body is Base64 encoded'), ) processed = models.DateTimeField( _('Processed'), auto_now_add=True ) read = models.DateTimeField( _(u'Read'), default=None, blank=True, null=True, ) matched_batch_apps = models.BooleanField( _('Matched by BA'), default=False, ) processed_batch_apps = models.BooleanField( _('Processed by BA'), default=False, ) objects = models.Manager() unread_messages = UnreadMessageManager() incoming_messages = IncomingMessageManager() outgoing_messages = OutgoingMessageManager() @property def address(self): """Property allowing one to get the relevant address(es). In earlier versions of this library, the model had an `address` field storing the e-mail address from which a message was received. During later refactorings, it became clear that perhaps storing sent messages would also be useful, so the address field was replaced with two separate fields. """ addresses = [] addresses = self.to_addresses + self.from_address return addresses @property def from_address(self): if self.from_header: return [parseaddr(self.from_header)[1].lower()] else: return [] @property def to_addresses(self): addresses = [] for address in self.to_header.split(','): if address: addresses.append( parseaddr( address )[1].lower() ) return addresses def reply(self, message): """Sends a message as a reply to this message instance. Although Django's e-mail processing will set both Message-ID and Date upon generating the e-mail message, we will not be able to retrieve that information through normal channels, so we must pre-set it. """ if self.mailbox.from_email: message.from_email = self.mailbox.from_email else: message.from_email = settings.DEFAULT_FROM_EMAIL message.extra_headers['Message-ID'] = make_msgid() message.extra_headers['Date'] = formatdate() message.extra_headers['In-Reply-To'] = self.message_id message.send() return self.mailbox.record_outgoing_message( email.message_from_string( message.message().as_string() ) ) @property def text(self): """ Returns the message body matching content type 'text/plain'. """ return get_body_from_message( self.get_email_object(), 'text', 'plain' ).replace('=\n', '').strip() @property def html(self): """ Returns the message body matching content type 'text/html'. """ return get_body_from_message( self.get_email_object(), 'text', 'html' ).replace('\n', '').strip() def _rehydrate(self, msg): new = EmailMessage() if msg.is_multipart(): for header, value in msg.items(): new[header] = value for part in msg.get_payload(): new.attach( self._rehydrate(part) ) elif ATTACHMENT_INTERPOLATION_HEADER in msg.keys(): try: attachment = MessageAttachment.objects.get( pk=msg[ATTACHMENT_INTERPOLATION_HEADER] ) for header, value in attachment.items(): new[header] = value encoding = new['Content-Transfer-Encoding'] if encoding and encoding.lower() == 'quoted-printable': # Cannot use `email.encoders.encode_quopri due to # bug 14360: http://bugs.python.org/issue14360 output = six.BytesIO() encode_quopri( six.BytesIO( attachment.document.read() ), output, quotetabs=True, header=False, ) new.set_payload( output.getvalue().decode().replace(' ', '=20') ) del new['Content-Transfer-Encoding'] new['Content-Transfer-Encoding'] = 'quoted-printable' else: new.set_payload( attachment.document.read() ) del new['Content-Transfer-Encoding'] encode_base64(new) except MessageAttachment.DoesNotExist: new[ALTERED_MESSAGE_HEADER] = ( 'Missing; Attachment %s not found' % ( msg[ATTACHMENT_INTERPOLATION_HEADER] ) ) new.set_payload('') else: for header, value in msg.items(): new[header] = value new.set_payload( msg.get_payload() ) return new def get_body(self): if self.encoded: return base64.b64decode(self.body.encode('ascii')) return self.body.encode('utf-8') def set_body(self, body): if six.PY3: body = body.encode('utf-8') self.encoded = True self.body = base64.b64encode(body).decode('ascii') def get_email_object(self): """ Returns an `email.message.Message` instance for this message.""" body = self.get_body() if six.PY3: flat = email.message_from_bytes(body) else: flat = email.message_from_string(body) return self._rehydrate(flat) def delete(self, *args, **kwargs): for attachment in self.attachments.all(): # This attachment is attached only to this message. attachment.delete() return super(Message, self).delete(*args, **kwargs) def __unicode__(self): return self.subject class MessageAttachment(models.Model): message = models.ForeignKey( Message, related_name='attachments', null=True, blank=True, verbose_name=_('Message'), ) headers = models.TextField( _(u'Headers'), null=True, blank=True, ) document = models.FileField( _(u'Document'), upload_to='mailbox_attachments/%Y/%m/%d/' ) def delete(self, *args, **kwargs): self.document.delete() return super(MessageAttachment, self).delete(*args, **kwargs) def _get_rehydrated_headers(self): headers = self.headers if headers is None: return EmailMessage() if sys.version_info < (3, 0): headers = headers.encode('utf-8') return email.message_from_string(headers) def _set_dehydrated_headers(self, email_object): self.headers = email_object.as_string() def __delitem__(self, name): rehydrated = self._get_rehydrated_headers() del rehydrated[name] self._set_dehydrated_headers(rehydrated) def __setitem__(self, name, value): rehydrated = self._get_rehydrated_headers() rehydrated[name] = value self._set_dehydrated_headers(rehydrated) def get_filename(self): file_name = self._get_rehydrated_headers().get_filename() if file_name: return convert_header_to_unicode(file_name) else: return None def items(self): return self._get_rehydrated_headers().items() def __getitem__(self, name): value = self._get_rehydrated_headers()[name] if value is None: raise KeyError('Header %s does not exist' % name) return value def __unicode__(self): return self.document.url
# Copyright (C) 2021 Nippon Telegraph and Telephone 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. class SolException(Exception): """Exception for SOL ProblemDetails Generally status, title and message should be defined in derived class. detail is constructed from message and kwargs. Attributes in ProblemDetails can be specified in kwargs of object initialization. Use `sol_*` (ex. `sol_instance`) to avoid confliction with kwargs. """ status = 500 title = None message = 'Internal Server Error' def __init__(self, **kwargs): self.status = kwargs.pop('sol_status', self.status) self.title = kwargs.pop('sol_title', self.title) self.type = kwargs.pop('sol_type', None) self.instance = kwargs.pop('sol_instance', None) self.detail = kwargs.pop('sol_detail', self.message % kwargs) super().__init__(self.detail) def make_problem_details(self): res = {'status': self.status, 'detail': self.detail} if self.title is not None: res['title'] = self.title if self.type is not None: res['type'] = self.type if self.instance is not None: res['instance'] = self.instance return res class SolHttpError400(SolException): status = 400 title = 'Bad Request' class SolHttpError403(SolException): status = 403 title = 'Forbidden' class SolHttpError404(SolException): status = 404 title = 'Not Found' class SolHttpError405(SolException): status = 405 title = 'Method Not Allowed' class SolHttpError406(SolException): status = 406 title = 'Not Acceptable' class SolHttpError409(SolException): status = 409 title = 'Conflict' class SolHttpError422(SolException): status = 422 title = 'Unprocessable Entity' class MethodNotAllowed(SolHttpError405): message = _("Method %(method)s is not supported.") class SolValidationError(SolHttpError400): message = _("%(detail)s") class InvalidAPIVersionString(SolHttpError400): message = _("Version String %(version)s is of invalid format. Must " "be of format Major.Minor.Patch.") class APIVersionMissing(SolHttpError400): message = _("'Version' HTTP header missing.") class APIVersionNotSupported(SolHttpError406): message = _("Version %(version)s not supported.") class VnfdIdNotEnabled(SolHttpError422): message = _("VnfId %(vnfd_id)s not ENABLED.") class VnfInstanceNotFound(SolHttpError404): message = _("VnfInstance %(inst_id)s not found.") class VnfInstanceIsInstantiated(SolHttpError409): message = _("VnfInstance %(inst_id)s is instantiated.") class VnfInstanceIsNotInstantiated(SolHttpError409): message = _("VnfInstance %(inst_id)s isn't instantiated.") class LccnSubscriptionNotFound(SolHttpError404): message = _("LccnSubscription %(subsc_id)s not found.") class VnfLcmOpOccNotFound(SolHttpError404): message = _("VnfLcmOpOcc %(lcmocc_id)s not found.") class VnfdIdNotFound(SolHttpError422): message = _("VnfPackage of vnfdId %(vnfd_id)s is not found or " "not operational.") class FlavourIdNotFound(SolHttpError400): message = _("FlavourId %(flavour_id)s not found in the vnfd.") class NoVimConnectionInfo(SolHttpError422): message = _("No VimConnectionInfo set to the VnfInstance.") class InvalidVnfdFormat(SolHttpError400): message = _("Vnfd is unexpected format.") class StackOperationFailed(SolHttpError422): # title and detail are set in the code from stack_status_reason pass class MgmtDriverExecutionFailed(SolHttpError422): title = 'Mgmt driver execution failed' # detail set in the code class BaseHOTNotDefined(SolHttpError400): message = _("BaseHOT is not defined.") class UserdataMissing(SolHttpError400): message = _("'lcm-operation-user-data' or " "'lcm-operation-user-data-class' missing.") class UserdataExecutionFailed(SolHttpError422): title = 'Userdata execution failed' # detail set in the code class TestNotificationFailed(SolHttpError422): message = _("Can't get from notification callback Uri.") class VimNotFound(SolHttpError404): message = _("VIM %(vim_id)s not found.") class OtherOperationInProgress(SolHttpError409): message = _("Other LCM operation of vnfInstance %(inst_id)s " "is in progress.") class UserDataClassNotImplemented(SolHttpError400): message = _("Userdata class not implemented.") class InvalidAttributeFilter(SolHttpError400): message = _("Attribute filter expression is invalid.") class InvalidAttributeSelector(SolHttpError400): message = _("Attribute selector expression is invalid.") class InvalidSubscription(SolHttpError400): # detail set in the code pass class ResponseTooBig(SolHttpError400): title = 'Response too big' message = _("Content length of the response is larger " "than %(size)d bytes.") class LocalNfvoGrantFailed(SolHttpError403): title = 'Grant failed' # detail set in the code class LcmOpOccNotFailedTemp(SolHttpError409): message = _("LCM operation %(lcmocc_id)s not FAILED_TEMP.") class GrantRequestOrGrantNotFound(SolHttpError404): message = _("GrantRequest or Grant for LCM operation " "%(lcmocc_id)s not found.") class RollbackNotSupported(SolHttpError422): message = _("Rollback of %(op)s is not supported.") class UnexpectedParentResourceDefinition(SolHttpError422): message = _("Parent resource is necessary for VDU definition.") class InvalidScaleAspectId(SolHttpError400): message = _("Invalid aspectId '%(aspect_id)s'.") class InvalidScaleNumberOfSteps(SolHttpError400): message = _("Invalid numberOfSteps '%(num_steps)d'.") class DeltaMissingInVnfd(SolHttpError400): message = _("Delta '%(delta)s' is not defined in " "VduScalingAspectDeltas.") class ConductorProcessingError(SolException): title = 'Internal Server Error' message = _("Failure due to conductor processing error.")
# # 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. # """ Python package for feature in MLlib. """ import sys import warnings from py4j.protocol import Py4JJavaError from pyspark import since from pyspark.rdd import RDD from pyspark.mllib.common import callMLlibFunc, JavaModelWrapper from pyspark.mllib.linalg import Vectors, _convert_to_vector from pyspark.mllib.util import JavaLoader, JavaSaveable __all__ = ['Normalizer', 'StandardScalerModel', 'StandardScaler', 'HashingTF', 'IDFModel', 'IDF', 'Word2Vec', 'Word2VecModel', 'ChiSqSelector', 'ChiSqSelectorModel', 'ElementwiseProduct'] class VectorTransformer(object): """ Base class for transformation of a vector or RDD of vector """ def transform(self, vector): """ Applies transformation on a vector. Parameters ---------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` vector or convertible or RDD to be transformed. """ raise NotImplementedError class Normalizer(VectorTransformer): r""" Normalizes samples individually to unit L\ :sup:`p`\ norm For any 1 <= `p` < float('inf'), normalizes samples using sum(abs(vector) :sup:`p`) :sup:`(1/p)` as norm. For `p` = float('inf'), max(abs(vector)) will be used as norm for normalization. .. versionadded:: 1.2.0 Parameters ---------- p : float, optional Normalization in L^p^ space, p = 2 by default. Examples -------- >>> from pyspark.mllib.linalg import Vectors >>> v = Vectors.dense(range(3)) >>> nor = Normalizer(1) >>> nor.transform(v) DenseVector([0.0, 0.3333, 0.6667]) >>> rdd = sc.parallelize([v]) >>> nor.transform(rdd).collect() [DenseVector([0.0, 0.3333, 0.6667])] >>> nor2 = Normalizer(float("inf")) >>> nor2.transform(v) DenseVector([0.0, 0.5, 1.0]) """ def __init__(self, p=2.0): assert p >= 1.0, "p should be greater than 1.0" self.p = float(p) def transform(self, vector): """ Applies unit length normalization on a vector. .. versionadded:: 1.2.0 Parameters ---------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` vector or RDD of vector to be normalized. Returns ------- :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` normalized vector(s). If the norm of the input is zero, it will return the input vector. """ if isinstance(vector, RDD): vector = vector.map(_convert_to_vector) else: vector = _convert_to_vector(vector) return callMLlibFunc("normalizeVector", self.p, vector) class JavaVectorTransformer(JavaModelWrapper, VectorTransformer): """ Wrapper for the model in JVM """ def transform(self, vector): """ Applies transformation on a vector or an RDD[Vector]. Parameters ---------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` Input vector(s) to be transformed. Notes ----- In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. """ if isinstance(vector, RDD): vector = vector.map(_convert_to_vector) else: vector = _convert_to_vector(vector) return self.call("transform", vector) class StandardScalerModel(JavaVectorTransformer): """ Represents a StandardScaler model that can transform vectors. .. versionadded:: 1.2.0 """ def transform(self, vector): """ Applies standardization transformation on a vector. .. versionadded:: 1.2.0 Parameters ---------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` Input vector(s) to be standardized. Returns ------- :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` Standardized vector(s). If the variance of a column is zero, it will return default `0.0` for the column with zero variance. Notes ----- In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. """ return JavaVectorTransformer.transform(self, vector) @since('1.4.0') def setWithMean(self, withMean): """ Setter of the boolean which decides whether it uses mean or not """ self.call("setWithMean", withMean) return self @since('1.4.0') def setWithStd(self, withStd): """ Setter of the boolean which decides whether it uses std or not """ self.call("setWithStd", withStd) return self @property @since('2.0.0') def withStd(self): """ Returns if the model scales the data to unit standard deviation. """ return self.call("withStd") @property @since('2.0.0') def withMean(self): """ Returns if the model centers the data before scaling. """ return self.call("withMean") @property @since('2.0.0') def std(self): """ Return the column standard deviation values. """ return self.call("std") @property @since('2.0.0') def mean(self): """ Return the column mean values. """ return self.call("mean") class StandardScaler(object): """ Standardizes features by removing the mean and scaling to unit variance using column summary statistics on the samples in the training set. .. versionadded:: 1.2.0 Parameters ---------- withMean : bool, optional False by default. Centers the data with mean before scaling. It will build a dense output, so take care when applying to sparse input. withStd : bool, optional True by default. Scales the data to unit standard deviation. Examples -------- >>> vs = [Vectors.dense([-2.0, 2.3, 0]), Vectors.dense([3.8, 0.0, 1.9])] >>> dataset = sc.parallelize(vs) >>> standardizer = StandardScaler(True, True) >>> model = standardizer.fit(dataset) >>> result = model.transform(dataset) >>> for r in result.collect(): r DenseVector([-0.7071, 0.7071, -0.7071]) DenseVector([0.7071, -0.7071, 0.7071]) >>> int(model.std[0]) 4 >>> int(model.mean[0]*10) 9 >>> model.withStd True >>> model.withMean True """ def __init__(self, withMean=False, withStd=True): if not (withMean or withStd): warnings.warn("Both withMean and withStd are false. The model does nothing.") self.withMean = withMean self.withStd = withStd def fit(self, dataset): """ Computes the mean and variance and stores as a model to be used for later scaling. .. versionadded:: 1.2.0 Parameters ---------- dataset : :py:class:`pyspark.RDD` The data used to compute the mean and variance to build the transformation model. Returns ------- :py:class:`StandardScalerModel` """ dataset = dataset.map(_convert_to_vector) jmodel = callMLlibFunc("fitStandardScaler", self.withMean, self.withStd, dataset) return StandardScalerModel(jmodel) class ChiSqSelectorModel(JavaVectorTransformer): """ Represents a Chi Squared selector model. .. versionadded:: 1.4.0 """ def transform(self, vector): """ Applies transformation on a vector. .. versionadded:: 1.4.0 Examples -------- vector : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` Input vector(s) to be transformed. Returns ------- :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` transformed vector(s). """ return JavaVectorTransformer.transform(self, vector) class ChiSqSelector(object): """ Creates a ChiSquared feature selector. The selector supports different selection methods: `numTopFeatures`, `percentile`, `fpr`, `fdr`, `fwe`. * `numTopFeatures` chooses a fixed number of top features according to a chi-squared test. * `percentile` is similar but chooses a fraction of all features instead of a fixed number. * `fpr` chooses all features whose p-values are below a threshold, thus controlling the false positive rate of selection. * `fdr` uses the `Benjamini-Hochberg procedure <https://en.wikipedia.org/wiki/ False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure>`_ to choose all features whose false discovery rate is below a threshold. * `fwe` chooses all features whose p-values are below a threshold. The threshold is scaled by 1/numFeatures, thus controlling the family-wise error rate of selection. By default, the selection method is `numTopFeatures`, with the default number of top features set to 50. .. versionadded:: 1.4.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector, DenseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = sc.parallelize([ ... LabeledPoint(0.0, SparseVector(3, {0: 8.0, 1: 7.0})), ... LabeledPoint(1.0, SparseVector(3, {1: 9.0, 2: 6.0})), ... LabeledPoint(1.0, [0.0, 9.0, 8.0]), ... LabeledPoint(2.0, [7.0, 9.0, 5.0]), ... LabeledPoint(2.0, [8.0, 7.0, 3.0]) ... ]) >>> model = ChiSqSelector(numTopFeatures=1).fit(data) >>> model.transform(SparseVector(3, {1: 9.0, 2: 6.0})) SparseVector(1, {}) >>> model.transform(DenseVector([7.0, 9.0, 5.0])) DenseVector([7.0]) >>> model = ChiSqSelector(selectorType="fpr", fpr=0.2).fit(data) >>> model.transform(SparseVector(3, {1: 9.0, 2: 6.0})) SparseVector(1, {}) >>> model.transform(DenseVector([7.0, 9.0, 5.0])) DenseVector([7.0]) >>> model = ChiSqSelector(selectorType="percentile", percentile=0.34).fit(data) >>> model.transform(DenseVector([7.0, 9.0, 5.0])) DenseVector([7.0]) """ def __init__(self, numTopFeatures=50, selectorType="numTopFeatures", percentile=0.1, fpr=0.05, fdr=0.05, fwe=0.05): self.numTopFeatures = numTopFeatures self.selectorType = selectorType self.percentile = percentile self.fpr = fpr self.fdr = fdr self.fwe = fwe @since('2.1.0') def setNumTopFeatures(self, numTopFeatures): """ set numTopFeature for feature selection by number of top features. Only applicable when selectorType = "numTopFeatures". """ self.numTopFeatures = int(numTopFeatures) return self @since('2.1.0') def setPercentile(self, percentile): """ set percentile [0.0, 1.0] for feature selection by percentile. Only applicable when selectorType = "percentile". """ self.percentile = float(percentile) return self @since('2.1.0') def setFpr(self, fpr): """ set FPR [0.0, 1.0] for feature selection by FPR. Only applicable when selectorType = "fpr". """ self.fpr = float(fpr) return self @since('2.2.0') def setFdr(self, fdr): """ set FDR [0.0, 1.0] for feature selection by FDR. Only applicable when selectorType = "fdr". """ self.fdr = float(fdr) return self @since('2.2.0') def setFwe(self, fwe): """ set FWE [0.0, 1.0] for feature selection by FWE. Only applicable when selectorType = "fwe". """ self.fwe = float(fwe) return self @since('2.1.0') def setSelectorType(self, selectorType): """ set the selector type of the ChisqSelector. Supported options: "numTopFeatures" (default), "percentile", "fpr", "fdr", "fwe". """ self.selectorType = str(selectorType) return self def fit(self, data): """ Returns a ChiSquared feature selector. .. versionadded:: 1.4.0 Parameters ---------- data : :py:class:`pyspark.RDD` of :py:class:`pyspark.mllib.regression.LabeledPoint` containing the labeled dataset with categorical features. Real-valued features will be treated as categorical for each distinct value. Apply feature discretizer before using this function. """ jmodel = callMLlibFunc("fitChiSqSelector", self.selectorType, self.numTopFeatures, self.percentile, self.fpr, self.fdr, self.fwe, data) return ChiSqSelectorModel(jmodel) class PCAModel(JavaVectorTransformer): """ Model fitted by [[PCA]] that can project vectors to a low-dimensional space using PCA. .. versionadded:: 1.5.0 """ class PCA(object): """ A feature transformer that projects vectors to a low-dimensional space using PCA. .. versionadded:: 1.5.0 Examples -------- >>> data = [Vectors.sparse(5, [(1, 1.0), (3, 7.0)]), ... Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]), ... Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0])] >>> model = PCA(2).fit(sc.parallelize(data)) >>> pcArray = model.transform(Vectors.sparse(5, [(1, 1.0), (3, 7.0)])).toArray() >>> pcArray[0] 1.648... >>> pcArray[1] -4.013... """ def __init__(self, k): """ Parameters ---------- k : int number of principal components. """ self.k = int(k) def fit(self, data): """ Computes a [[PCAModel]] that contains the principal components of the input vectors. .. versionadded:: 1.5.0 Parameters ---------- data : :py:class:`pyspark.RDD` source vectors """ jmodel = callMLlibFunc("fitPCA", self.k, data) return PCAModel(jmodel) class HashingTF(object): """ Maps a sequence of terms to their term frequencies using the hashing trick. .. versionadded:: 1.2.0 Parameters ---------- numFeatures : int, optional number of features (default: 2^20) Notes ----- The terms must be hashable (can not be dict/set/list...). Examples -------- >>> htf = HashingTF(100) >>> doc = "a a b b c d".split(" ") >>> htf.transform(doc) SparseVector(100, {...}) """ def __init__(self, numFeatures=1 << 20): self.numFeatures = numFeatures self.binary = False @since("2.0.0") def setBinary(self, value): """ If True, term frequency vector will be binary such that non-zero term counts will be set to 1 (default: False) """ self.binary = value return self @since('1.2.0') def indexOf(self, term): """ Returns the index of the input term. """ return hash(term) % self.numFeatures @since('1.2.0') def transform(self, document): """ Transforms the input document (list of terms) to term frequency vectors, or transform the RDD of document to RDD of term frequency vectors. """ if isinstance(document, RDD): return document.map(self.transform) freq = {} for term in document: i = self.indexOf(term) freq[i] = 1.0 if self.binary else freq.get(i, 0) + 1.0 return Vectors.sparse(self.numFeatures, freq.items()) class IDFModel(JavaVectorTransformer): """ Represents an IDF model that can transform term frequency vectors. .. versionadded:: 1.2.0 """ def transform(self, x): """ Transforms term frequency (TF) vectors to TF-IDF vectors. If `minDocFreq` was set for the IDF calculation, the terms which occur in fewer than `minDocFreq` documents will have an entry of 0. .. versionadded:: 1.2.0 Parameters ---------- x : :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` an RDD of term frequency vectors or a term frequency vector Returns ------- :py:class:`pyspark.mllib.linalg.Vector` or :py:class:`pyspark.RDD` an RDD of TF-IDF vectors or a TF-IDF vector Notes ----- In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. """ return JavaVectorTransformer.transform(self, x) @since('1.4.0') def idf(self): """ Returns the current IDF vector. """ return self.call('idf') @since('3.0.0') def docFreq(self): """ Returns the document frequency. """ return self.call('docFreq') @since('3.0.0') def numDocs(self): """ Returns number of documents evaluated to compute idf """ return self.call('numDocs') class IDF(object): """ Inverse document frequency (IDF). The standard formulation is used: `idf = log((m + 1) / (d(t) + 1))`, where `m` is the total number of documents and `d(t)` is the number of documents that contain term `t`. This implementation supports filtering out terms which do not appear in a minimum number of documents (controlled by the variable `minDocFreq`). For terms that are not in at least `minDocFreq` documents, the IDF is found as 0, resulting in TF-IDFs of 0. .. versionadded:: 1.2.0 Parameters ---------- minDocFreq : int minimum of documents in which a term should appear for filtering Examples -------- >>> n = 4 >>> freqs = [Vectors.sparse(n, (1, 3), (1.0, 2.0)), ... Vectors.dense([0.0, 1.0, 2.0, 3.0]), ... Vectors.sparse(n, [1], [1.0])] >>> data = sc.parallelize(freqs) >>> idf = IDF() >>> model = idf.fit(data) >>> tfidf = model.transform(data) >>> for r in tfidf.collect(): r SparseVector(4, {1: 0.0, 3: 0.5754}) DenseVector([0.0, 0.0, 1.3863, 0.863]) SparseVector(4, {1: 0.0}) >>> model.transform(Vectors.dense([0.0, 1.0, 2.0, 3.0])) DenseVector([0.0, 0.0, 1.3863, 0.863]) >>> model.transform([0.0, 1.0, 2.0, 3.0]) DenseVector([0.0, 0.0, 1.3863, 0.863]) >>> model.transform(Vectors.sparse(n, (1, 3), (1.0, 2.0))) SparseVector(4, {1: 0.0, 3: 0.5754}) """ def __init__(self, minDocFreq=0): self.minDocFreq = minDocFreq def fit(self, dataset): """ Computes the inverse document frequency. .. versionadded:: 1.2.0 Parameters ---------- dataset : :py:class:`pyspark.RDD` an RDD of term frequency vectors """ if not isinstance(dataset, RDD): raise TypeError("dataset should be an RDD of term frequency vectors") jmodel = callMLlibFunc("fitIDF", self.minDocFreq, dataset.map(_convert_to_vector)) return IDFModel(jmodel) class Word2VecModel(JavaVectorTransformer, JavaSaveable, JavaLoader): """ class for Word2Vec model """ def transform(self, word): """ Transforms a word to its vector representation .. versionadded:: 1.2.0 Parameters ---------- word : str a word Returns ------- :py:class:`pyspark.mllib.linalg.Vector` vector representation of word(s) Notes ----- Local use only """ try: return self.call("transform", word) except Py4JJavaError: raise ValueError("%s not found" % word) def findSynonyms(self, word, num): """ Find synonyms of a word .. versionadded:: 1.2.0 Parameters ---------- word : str or :py:class:`pyspark.mllib.linalg.Vector` a word or a vector representation of word num : int number of synonyms to find Returns ------- :py:class:`collections.abc.Iterable` array of (word, cosineSimilarity) Notes ----- Local use only """ if not isinstance(word, str): word = _convert_to_vector(word) words, similarity = self.call("findSynonyms", word, num) return zip(words, similarity) @since('1.4.0') def getVectors(self): """ Returns a map of words to their vector representations. """ return self.call("getVectors") @classmethod @since('1.5.0') def load(cls, sc, path): """ Load a model from the given path. """ jmodel = sc._jvm.org.apache.spark.mllib.feature \ .Word2VecModel.load(sc._jsc.sc(), path) model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel) return Word2VecModel(model) class Word2Vec(object): """Word2Vec creates vector representation of words in a text corpus. The algorithm first constructs a vocabulary from the corpus and then learns vector representation of words in the vocabulary. The vector representation can be used as features in natural language processing and machine learning algorithms. We used skip-gram model in our implementation and hierarchical softmax method to train the model. The variable names in the implementation matches the original C implementation. For original C implementation, see https://code.google.com/p/word2vec/ For research papers, see Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality. .. versionadded:: 1.2.0 Examples -------- >>> sentence = "a b " * 100 + "a c " * 10 >>> localDoc = [sentence, sentence] >>> doc = sc.parallelize(localDoc).map(lambda line: line.split(" ")) >>> model = Word2Vec().setVectorSize(10).setSeed(42).fit(doc) Querying for synonyms of a word will not return that word: >>> syms = model.findSynonyms("a", 2) >>> [s[0] for s in syms] ['b', 'c'] But querying for synonyms of a vector may return the word whose representation is that vector: >>> vec = model.transform("a") >>> syms = model.findSynonyms(vec, 2) >>> [s[0] for s in syms] ['a', 'b'] >>> import os, tempfile >>> path = tempfile.mkdtemp() >>> model.save(sc, path) >>> sameModel = Word2VecModel.load(sc, path) >>> model.transform("a") == sameModel.transform("a") True >>> syms = sameModel.findSynonyms("a", 2) >>> [s[0] for s in syms] ['b', 'c'] >>> from shutil import rmtree >>> try: ... rmtree(path) ... except OSError: ... pass """ def __init__(self): """ Construct Word2Vec instance """ self.vectorSize = 100 self.learningRate = 0.025 self.numPartitions = 1 self.numIterations = 1 self.seed = None self.minCount = 5 self.windowSize = 5 @since('1.2.0') def setVectorSize(self, vectorSize): """ Sets vector size (default: 100). """ self.vectorSize = vectorSize return self @since('1.2.0') def setLearningRate(self, learningRate): """ Sets initial learning rate (default: 0.025). """ self.learningRate = learningRate return self @since('1.2.0') def setNumPartitions(self, numPartitions): """ Sets number of partitions (default: 1). Use a small number for accuracy. """ self.numPartitions = numPartitions return self @since('1.2.0') def setNumIterations(self, numIterations): """ Sets number of iterations (default: 1), which should be smaller than or equal to number of partitions. """ self.numIterations = numIterations return self @since('1.2.0') def setSeed(self, seed): """ Sets random seed. """ self.seed = seed return self @since('1.4.0') def setMinCount(self, minCount): """ Sets minCount, the minimum number of times a token must appear to be included in the word2vec model's vocabulary (default: 5). """ self.minCount = minCount return self @since('2.0.0') def setWindowSize(self, windowSize): """ Sets window size (default: 5). """ self.windowSize = windowSize return self def fit(self, data): """ Computes the vector representation of each word in vocabulary. .. versionadded:: 1.2.0 Parameters ---------- data : :py:class:`pyspark.RDD` training data. RDD of list of string Returns ------- :py:class:`Word2VecModel` """ if not isinstance(data, RDD): raise TypeError("data should be an RDD of list of string") jmodel = callMLlibFunc("trainWord2VecModel", data, int(self.vectorSize), float(self.learningRate), int(self.numPartitions), int(self.numIterations), self.seed, int(self.minCount), int(self.windowSize)) return Word2VecModel(jmodel) class ElementwiseProduct(VectorTransformer): """ Scales each column of the vector, with the supplied weight vector. i.e the elementwise product. .. versionadded:: 1.5.0 Examples -------- >>> weight = Vectors.dense([1.0, 2.0, 3.0]) >>> eprod = ElementwiseProduct(weight) >>> a = Vectors.dense([2.0, 1.0, 3.0]) >>> eprod.transform(a) DenseVector([2.0, 2.0, 9.0]) >>> b = Vectors.dense([9.0, 3.0, 4.0]) >>> rdd = sc.parallelize([a, b]) >>> eprod.transform(rdd).collect() [DenseVector([2.0, 2.0, 9.0]), DenseVector([9.0, 6.0, 12.0])] """ def __init__(self, scalingVector): self.scalingVector = _convert_to_vector(scalingVector) @since('1.5.0') def transform(self, vector): """ Computes the Hadamard product of the vector. """ if isinstance(vector, RDD): vector = vector.map(_convert_to_vector) else: vector = _convert_to_vector(vector) return callMLlibFunc("elementwiseProductVector", self.scalingVector, vector) def _test(): import doctest from pyspark.sql import SparkSession globs = globals().copy() spark = SparkSession.builder\ .master("local[4]")\ .appName("mllib.feature tests")\ .getOrCreate() globs['sc'] = spark.sparkContext (failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": sys.path.pop(0) _test()
"""This directory is setup with configurations to run the main functional test. It exercises a full analysis pipeline on a smaller subset of data. """ import os import subprocess import unittest import shutil import contextlib import collections import functools from nose import SkipTest from nose.plugins.attrib import attr import yaml from bcbio.pipeline.config_utils import load_system_config @contextlib.contextmanager def make_workdir(): remove_old_dir = True #remove_old_dir = False dirname = os.path.join(os.path.dirname(__file__), "test_automated_output") if remove_old_dir: if os.path.exists(dirname): shutil.rmtree(dirname) os.makedirs(dirname) orig_dir = os.getcwd() try: os.chdir(dirname) yield dirname finally: os.chdir(orig_dir) def expected_failure(test): """Small decorator to mark tests as expected failure. Useful for tests that are work-in-progress. """ @functools.wraps(test) def inner(*args, **kwargs): try: test(*args, **kwargs) except Exception: raise SkipTest else: raise AssertionError('Failure expected') return inner def get_post_process_yaml(data_dir, workdir): try: from bcbiovm.docker.defaults import get_datadir datadir = get_datadir() system = os.path.join(datadir, "galaxy", "bcbio_system.yaml") if datadir else None except ImportError: system = None if system is None or not os.path.exists(system): try: _, system = load_system_config("bcbio_system.yaml") except ValueError: system = None sample = os.path.join(data_dir, "post_process-sample.yaml") std = os.path.join(data_dir, "post_process.yaml") if os.path.exists(std): return std elif system and os.path.exists(system): # create local config pointing to reduced genomes test_system = os.path.join(workdir, os.path.basename(system)) with open(system) as in_handle: config = yaml.load(in_handle) config["galaxy_config"] = os.path.join(data_dir, "universe_wsgi.ini") with open(test_system, "w") as out_handle: yaml.dump(config, out_handle) return test_system else: return sample class AutomatedAnalysisTest(unittest.TestCase): """Setup a full automated analysis and run the pipeline. """ def setUp(self): self.data_dir = os.path.join(os.path.dirname(__file__), "data", "automated") def _install_test_files(self, data_dir): """Download required sequence and reference files. """ DlInfo = collections.namedtuple("DlInfo", "fname dirname version") download_data = [DlInfo("110106_FC70BUKAAXX.tar.gz", None, None), DlInfo("genomes_automated_test.tar.gz", "genomes", 23), DlInfo("110907_ERP000591.tar.gz", None, None), DlInfo("100326_FC6107FAAXX.tar.gz", None, 8), DlInfo("tcga_benchmark.tar.gz", None, 3)] for dl in download_data: url = "http://chapmanb.s3.amazonaws.com/{fname}".format(fname=dl.fname) dirname = os.path.join(data_dir, os.pardir, dl.fname.replace(".tar.gz", "") if dl.dirname is None else dl.dirname) if os.path.exists(dirname) and dl.version is not None: version_file = os.path.join(dirname, "VERSION") is_old = True if os.path.exists(version_file): with open(version_file) as in_handle: version = int(in_handle.read()) is_old = version < dl.version if is_old: shutil.rmtree(dirname) if not os.path.exists(dirname): self._download_to_dir(url, dirname) def _download_to_dir(self, url, dirname): print dirname cl = ["wget", url] subprocess.check_call(cl) cl = ["tar", "-xzvpf", os.path.basename(url)] subprocess.check_call(cl) os.rename(os.path.basename(dirname), dirname) os.remove(os.path.basename(url)) @attr(speed=3) def IGNOREtest_3_full_pipeline(self): """Run full automated analysis pipeline with multiplexing. XXX Multiplexing not supporting in latest versions. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110106_FC70BUKAAXX"), os.path.join(self.data_dir, "run_info.yaml")] subprocess.check_call(cl) @attr(speed=3) def IGNOREtest_4_empty_fastq(self): """Handle analysis of empty fastq inputs from failed runs. XXX Multiplexing not supporting in latest versions. """ with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110221_empty_FC12345AAXX"), os.path.join(self.data_dir, "run_info-empty.yaml")] subprocess.check_call(cl) @attr(stranded=True) @attr(rnaseq=True) def test_2_stranded(self): """Run an RNA-seq analysis with TopHat and generate gene-level counts. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "test_stranded"), os.path.join(self.data_dir, "run_info-stranded.yaml")] subprocess.check_call(cl) @attr(rnaseq=True) @attr(tophat=True) def test_2_rnaseq(self): """Run an RNA-seq analysis with TopHat and generate gene-level counts. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110907_ERP000591"), os.path.join(self.data_dir, "run_info-rnaseq.yaml")] subprocess.check_call(cl) @attr(rnaseq=True) @attr(sailfish=True) @unittest.skip('sailfish support is in progress, skipping the unit test.') def test_2_sailfish(self): """Run an RNA-seq analysis with Sailfish """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110907_ERP000591"), os.path.join(self.data_dir, "run_info-sailfish.yaml")] subprocess.check_call(cl) @attr(fusion=True) def test_2_fusion(self): """Run an RNA-seq analysis and test fusion genes """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "test_fusion"), os.path.join(self.data_dir, "run_info-fusion.yaml")] subprocess.check_call(cl) @attr(rnaseq=True) @attr(star=True) def test_2_star(self): """Run an RNA-seq analysis with STAR and generate gene-level counts. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110907_ERP000591"), os.path.join(self.data_dir, "run_info-star.yaml")] subprocess.check_call(cl) @attr(rnaseq=True) @attr(star=True) @attr(rnaseq_variantcall=True) def test_2_rnaseq_variant(self): """Run an RNA-seq analysis with STAR and generate gene-level counts. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "110907_ERP000591"), os.path.join(self.data_dir, "run_info-rnaseq-variantcall.yaml")] subprocess.check_call(cl) @attr(explant=True) @attr(singleend=True) @attr(rnaseq=True) def test_explant(self): """ Run an explant RNA-seq analysis with TopHat and generate gene-level counts. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "1_explant"), os.path.join(self.data_dir, "run_info-explant.yaml")] subprocess.check_call(cl) @attr(chipseq=True) def test_chipseq(self): """ Run a chip-seq alignment with Bowtie2 """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "test_chipseq"), os.path.join(self.data_dir, "run_info-chipseq.yaml")] subprocess.check_call(cl) @attr(speed=1) @attr(ensemble=True) def test_1_variantcall(self): """Test variant calling with GATK pipeline. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "100326_FC6107FAAXX"), os.path.join(self.data_dir, "run_info-variantcall.yaml")] subprocess.check_call(cl) @attr(speed=1) @attr(devel=True) def test_5_bam(self): """Allow BAM files as input to pipeline. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, "run_info-bam.yaml")] subprocess.check_call(cl) @attr(speed=2) def test_6_bamclean(self): """Clean problem BAM input files that do not require alignment. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, os.pardir, "100326_FC6107FAAXX"), os.path.join(self.data_dir, "run_info-bamclean.yaml")] subprocess.check_call(cl) @attr(speed=2) @attr(cancer=True) @attr(cancermulti=True) def test_7_cancer(self): """Test paired tumor-normal calling using multiple calling approaches: MuTect, VarScan, FreeBayes. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, "run_info-cancer.yaml")] subprocess.check_call(cl) @attr(cancer=True) @attr(cancerpanel=True) def test_7_cancer_nonormal(self): """Test cancer calling without normal samples or with normal VCF panels. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, "run_info-cancer2.yaml")] subprocess.check_call(cl) @attr(speed=1) @attr(template=True) def test_8_template(self): """Create a project template from input files and metadata configuration. """ self._install_test_files(self.data_dir) fc_dir = os.path.join(self.data_dir, os.pardir, "100326_FC6107FAAXX") with make_workdir() as workdir: cl = ["bcbio_nextgen.py", "-w", "template", "--only-metadata", "freebayes-variant", os.path.join(fc_dir, "100326.csv"), os.path.join(fc_dir, "7_100326_FC6107FAAXX_1_fastq.txt"), os.path.join(fc_dir, "7_100326_FC6107FAAXX_2_fastq.txt"), os.path.join(fc_dir, "8_100326_FC6107FAAXX.bam")] subprocess.check_call(cl) @attr(joint=True) def test_9_joint(self): """Perform joint calling/backfilling/squaring off following variant calling. """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_nextgen.py", get_post_process_yaml(self.data_dir, workdir), os.path.join(self.data_dir, "run_info-joint.yaml")] subprocess.check_call(cl) @attr(docker=True) def test_docker(self): """Run an analysis with code and tools inside a docker container. Requires https://github.com/chapmanb/bcbio-nextgen-vm """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_vm.py", "run", "--systemconfig=%s" % get_post_process_yaml(self.data_dir, workdir), "--fcdir=%s" % os.path.join(self.data_dir, os.pardir, "100326_FC6107FAAXX"), os.path.join(self.data_dir, "run_info-bam.yaml")] subprocess.check_call(cl) @attr(docker_ipython=True) def test_docker_ipython(self): """Run an analysis with code and tools inside a docker container, driven via IPython. Requires https://github.com/chapmanb/bcbio-nextgen-vm """ self._install_test_files(self.data_dir) with make_workdir() as workdir: cl = ["bcbio_vm.py", "ipython", "--systemconfig=%s" % get_post_process_yaml(self.data_dir, workdir), "--fcdir=%s" % os.path.join(self.data_dir, os.pardir, "100326_FC6107FAAXX"), os.path.join(self.data_dir, "run_info-bam.yaml"), "lsf", "localrun"] subprocess.check_call(cl)
#!/usr/bin/env python # encoding: utf-8 import os import shutil import sys import tempfile import unittest sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import gramfuzz from gramfuzz.fields import * import gramfuzz.utils as gutils class TestFuzzer(unittest.TestCase): def setUp(self): gramfuzz.GramFuzzer.__instance__ = None self.fuzzer = gramfuzz.GramFuzzer() def tearDown(self): pass def test_set_max_recursion(self): self.fuzzer.set_max_recursion(100) self.assertEqual(Ref.max_recursion, 100) def test_default_cat_for_cat_group(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * TOP_CAT = "other" # should get pruned since b isn't defined Def("a", UInt, Ref("b", cat="other"), cat="other") Def("c", UInt, cat="other") """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) cat_group = os.path.basename(named_tmp.name) named_tmp.close() self.assertIn(cat_group, self.fuzzer.cat_group_defaults) self.assertEqual(self.fuzzer.cat_group_defaults[cat_group], "other") def test_gen_cat_group(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * TOP_CAT = "other" # should get pruned since b isn't defined Def("a", "hello", cat="other") """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) cat_group = os.path.basename(named_tmp.name) named_tmp.close() res = self.fuzzer.gen(cat_group=cat_group, num=1)[0] self.assertEqual(res, b"hello") def test_prune_rules(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * # should get pruned since b isn't defined Def("a", UInt, Ref("b")) Def("c", UInt) """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) named_tmp.close() self.fuzzer.preprocess_rules() self.assertNotIn("a", self.fuzzer.defs["default"]) self.assertIn("c", self.fuzzer.defs["default"]) def test_no_prune_rules(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * # should get pruned since b isn't defined Def("a", UInt, Ref("b"), no_prune=True) Def("c", UInt) """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) named_tmp.close() self.fuzzer.preprocess_rules() self.assertIn("a", self.fuzzer.defs["default"]) self.assertIn("c", self.fuzzer.defs["default"]) def test_prune_rules_circular(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * # should get pruned since b isn't defined Def("a", Ref("b")) Def("b", Ref("c")) Def("c", Ref("a")) """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) named_tmp.close() self.fuzzer.preprocess_rules() self.assertNotIn("a", self.fuzzer.defs["default"]) self.assertNotIn("b", self.fuzzer.defs["default"]) self.assertNotIn("c", self.fuzzer.defs["default"]) # see #16 - __file__ needs to be set for grammar files that are being # loaded def test_file_set_during_grammar_load(self): """Ensure that __file__ is set when loading a new grammar file """ named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" from gramfuzz.fields import * Def("file_test", __file__, cat="default") """)) named_tmp.flush() # should not raise an exception self.fuzzer.load_grammar(named_tmp.name) output = self.fuzzer.gen(num=1, cat="default") self.assertEqual(output[0], gutils.binstr(named_tmp.name)) def test_load_grammar(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * Def("test_def", Join(Int, Int, Opt("hello"), sep="|")) Def("test_def", Join(Float, Float, Opt("hello"), sep="|")) Def("test_def_ref", "this.", String(min=1), "=", Q(Ref("test_def"))) """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) named_tmp.close() res = self.fuzzer.get_ref("default", "test_def_ref").build() def test_relative_grammar_import(self): tmpdir = tempfile.mkdtemp() try: file1 = os.path.join(tmpdir, "file1.py") file2 = os.path.join(tmpdir, "file2.py") with open(file1, "wb") as f: f.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * import file2 TOP_CAT = "file1" Def("file1def", Ref("file2def", cat=file2.TOP_CAT), cat="file1") """)) with open(file2, "wb") as f: f.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * TOP_CAT = "file2" Def("file2def", "hi from file2", cat="file2") """)) self.fuzzer.load_grammar(file1) res = self.fuzzer.gen(cat_group="file1", num=1)[0] self.assertEqual(res, b"hi from file2") # always clean up finally: shutil.rmtree(tmpdir) # see #4 - auto process during gen() def test_auto_process(self): named_tmp = tempfile.NamedTemporaryFile() named_tmp.write(gutils.binstr(r""" import gramfuzz from gramfuzz.fields import * Def("test", "hello") # should also get pruned Def("other_test", Ref("not_reachable", cat="other")) # should get pruned Def("not_reachable", Ref("doesnt_exist", cat="other"), cat="other") """)) named_tmp.flush() self.fuzzer.load_grammar(named_tmp.name) named_tmp.close() self.assertTrue(self.fuzzer._rules_processed == False) data = self.fuzzer.gen(cat="default", num=1)[0] self.assertTrue(self.fuzzer._rules_processed == True) with self.assertRaises(gramfuzz.errors.GramFuzzError) as ctx: self.fuzzer.get_ref("other", "not_reachable") self.assertEqual( str(ctx.exception), "referenced definition ('not_reachable') not defined" ) if __name__ == "__main__": unittest.main()
""" mfupw module. Contains the ModflowUpw class. Note that the user can access the ModflowUpw class as `flopy.modflow.ModflowUpw`. Additional information for this MODFLOW package can be found at the `Online MODFLOW Guide <http://water.usgs.gov/ogw/modflow-nwt/MODFLOW-NWT-Guide/upw_upstream_weighting_package.htm>`_. """ import sys import numpy as np from .mfpar import ModflowPar as mfpar from ..pakbase import Package from ..utils import Util2d, Util3d class ModflowUpw(Package): """ Upstream weighting package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget data should be saved. If ipakcb is non-zero cell-by-cell budget data will be saved. (default is 53) hdry : float Is the head that is assigned to cells that are converted to dry during a simulation. Although this value plays no role in the model calculations, it is useful as an indicator when looking at the resulting heads that are output from the model. HDRY is thus similar to HNOFLO in the Basic Package, which is the value assigned to cells that are no-flow cells at the start of a model simulation. (default is -1.e30). iphdry : int iphdry is a flag that indicates whether groundwater head will be set to hdry when the groundwater head is less than 0.0001 above the cell bottom (units defined by lenuni in the discretization package). If iphdry=0, then head will not be set to hdry. If iphdry>0, then head will be set to hdry. If the head solution from one simulation will be used as starting heads for a subsequent simulation, or if the Observation Process is used (Harbaugh and others, 2000), then hdry should not be printed to the output file for dry cells (that is, the upw package input variable should be set as iphdry=0). (default is 0) noparcheck : bool noparcheck turns off the checking that a value is defined for all cells when parameters are used to define layer data. laytyp : int or array of ints (nlay) Layer type (default is 0). layavg : int or array of ints (nlay) Layer average (default is 0). 0 is harmonic mean 1 is logarithmic mean 2 is arithmetic mean of saturated thickness and logarithmic mean of of hydraulic conductivity chani : float or array of floats (nlay) contains a value for each layer that is a flag or the horizontal anisotropy. If CHANI is less than or equal to 0, then variable HANI defines horizontal anisotropy. If CHANI is greater than 0, then CHANI is the horizontal anisotropy for the entire layer, and HANI is not read. If any HANI parameters are used, CHANI for all layers must be less than or equal to 0. Use as many records as needed to enter a value of CHANI for each layer. The horizontal anisotropy is the ratio of the hydraulic conductivity along columns (the Y direction) to the hydraulic conductivity along rows (the X direction). layvka : float or array of floats (nlay) a flag for each layer that indicates whether variable VKA is vertical hydraulic conductivity or the ratio of horizontal to vertical hydraulic conductivity. laywet : float or array of floats (nlay) contains a flag for each layer that indicates if wetting is active. laywet should always be zero for the UPW Package because all cells initially active are wettable. hk : float or array of floats (nlay, nrow, ncol) is the hydraulic conductivity along rows. HK is multiplied by horizontal anisotropy (see CHANI and HANI) to obtain hydraulic conductivity along columns. (default is 1.0). hani : float or array of floats (nlay, nrow, ncol) is the ratio of hydraulic conductivity along columns to hydraulic conductivity along rows, where HK of item 10 specifies the hydraulic conductivity along rows. Thus, the hydraulic conductivity along columns is the product of the values in HK and HANI. (default is 1.0). vka : float or array of floats (nlay, nrow, ncol) is either vertical hydraulic conductivity or the ratio of horizontal to vertical hydraulic conductivity depending on the value of LAYVKA. (default is 1.0). ss : float or array of floats (nlay, nrow, ncol) is specific storage unless the STORAGECOEFFICIENT option is used. When STORAGECOEFFICIENT is used, Ss is confined storage coefficient. (default is 1.e-5). sy : float or array of floats (nlay, nrow, ncol) is specific yield. (default is 0.15). vkcb : float or array of floats (nlay, nrow, ncol) is the vertical hydraulic conductivity of a Quasi-three-dimensional confining bed below a layer. (default is 0.0). extension : string Filename extension (default is 'upw') unitnumber : int File unit number (default is None). filenames : str or list of str Filenames to use for the package and the output files. If filenames=None the package name will be created using the model name and package extension and the cbc output name will be created using the model name and .cbc extension (for example, modflowtest.cbc), if ipakcbc is a number greater than zero. If a single string is passed the package will be set to the string and cbc output name will be created using the model name and .cbc extension, if ipakcbc is a number greater than zero. To define the names for all package files (input and output) the length of the list of strings should be 2. Default is None. Attributes ---------- Methods ------- See Also -------- Notes ----- Examples -------- >>> import flopy >>> m = flopy.modflow.Modflow() >>> lpf = flopy.modflow.ModflowLpf(m) """ def __init__(self, model, laytyp=0, layavg=0, chani=1.0, layvka=0, laywet=0, ipakcb=None, hdry=-1E+30, iphdry=0, hk=1.0, hani=1.0, vka=1.0, ss=1e-5, sy=0.15, vkcb=0.0, noparcheck=False, extension='upw', unitnumber=None, filenames=None): if model.version != 'mfnwt': err = 'Error: model version must be mfnwt to use ' + \ '{} package'.format(ModflowUpw.ftype()) raise Exception(err) # set default unit number of one is not specified if unitnumber is None: unitnumber = ModflowUpw.defaultunit() # set filenames if filenames is None: filenames = [None, None] elif isinstance(filenames, str): filenames = [filenames, None] elif isinstance(filenames, list): if len(filenames) < 2: filenames.append(None) # update external file information with cbc output, if necessary if ipakcb is not None: fname = filenames[1] model.add_output_file(ipakcb, fname=fname, package=ModflowUpw.ftype()) else: ipakcb = 0 # Fill namefile items name = [ModflowUpw.ftype()] units = [unitnumber] extra = [''] # set package name fname = [filenames[0]] # Call ancestor's init to set self.parent, extension, name and unit number Package.__init__(self, model, extension=extension, name=name, unit_number=units, extra=extra, filenames=fname) self.heading = '# {} package for '.format(self.name[0]) + \ ' {}, '.format(model.version_types[model.version]) + \ 'generated by Flopy.' self.url = 'upw_upstream_weighting_package.htm' nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper # item 1 self.ipakcb = ipakcb self.hdry = hdry # Head in cells that are converted to dry during a simulation self.npupw = 0 # number of UPW parameters self.iphdry = iphdry self.laytyp = Util2d(model, (nlay,), np.int, laytyp, name='laytyp') self.layavg = Util2d(model, (nlay,), np.int, layavg, name='layavg') self.chani = Util2d(model, (nlay,), np.int, chani, name='chani') self.layvka = Util2d(model, (nlay,), np.int, layvka, name='vka') self.laywet = Util2d(model, (nlay,), np.int, laywet, name='laywet') self.options = ' ' if noparcheck: self.options = self.options + 'NOPARCHECK ' self.hk = Util3d(model, (nlay, nrow, ncol), np.float32, hk, name='hk', locat=self.unit_number[0]) self.hani = Util3d(model, (nlay, nrow, ncol), np.float32, hani, name='hani', locat=self.unit_number[0]) keys = [] for k in range(nlay): key = 'vka' if self.layvka[k] != 0: key = 'vani' keys.append(key) self.vka = Util3d(model, (nlay, nrow, ncol), np.float32, vka, name=keys, locat=self.unit_number[0]) self.ss = Util3d(model, (nlay, nrow, ncol), np.float32, ss, name='ss', locat=self.unit_number[0]) self.sy = Util3d(model, (nlay, nrow, ncol), np.float32, sy, name='sy', locat=self.unit_number[0]) self.vkcb = Util3d(model, (nlay, nrow, ncol), np.float32, vkcb, name='vkcb', locat=self.unit_number[0]) self.parent.add_package(self) def write_file(self, check=True): """ Write the package file. Parameters ---------- check : boolean Check package data for common errors. (default True) Returns ------- None """ if check: # allows turning off package checks when writing files at model level self.check(f='{}.chk'.format(self.name[0]), verbose=self.parent.verbose, level=1) nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper # Open file for writing f_upw = open(self.fn_path, 'w') # Item 0: text f_upw.write('{}\n'.format(self.heading)) # Item 1: IBCFCB, HDRY, NPLPF f_upw.write('{0:10d}{1:10.3G}{2:10d}{3:10d}{4:s}\n'.format(self.ipakcb, self.hdry, self.npupw, self.iphdry, self.options)) # LAYTYP array f_upw.write(self.laytyp.string); # LAYAVG array f_upw.write(self.layavg.string); # CHANI array f_upw.write(self.chani.string); # LAYVKA array f_upw.write(self.layvka.string) # LAYWET array f_upw.write(self.laywet.string); # Item 7: WETFCT, IWETIT, IHDWET iwetdry = self.laywet.sum() if iwetdry > 0: raise Exception('LAYWET should be 0 for UPW') transient = not self.parent.get_package('DIS').steady.all() for k in range(nlay): f_upw.write(self.hk[k].get_file_entry()) if self.chani[k] < 1: f_upw.write(self.hani[k].get_file_entry()) f_upw.write(self.vka[k].get_file_entry()) if transient == True: f_upw.write(self.ss[k].get_file_entry()) if self.laytyp[k] != 0: f_upw.write(self.sy[k].get_file_entry()) if self.parent.get_package('DIS').laycbd[k] > 0: f_upw.write(self.vkcb[k].get_file_entry()) if (self.laywet[k] != 0 and self.laytyp[k] != 0): f_upw.write(self.laywet[k].get_file_entry()) f_upw.close() @staticmethod def load(f, model, ext_unit_dict=None, check=True): """ Load an existing package. Parameters ---------- f : filename or file handle File to load. model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ext_unit_dict : dictionary, optional If the arrays in the file are specified using EXTERNAL, or older style array control records, then `f` should be a file handle. In this case ext_unit_dict is required, which can be constructed using the function :class:`flopy.utils.mfreadnam.parsenamefile`. check : boolean Check package data for common errors. (default True) Returns ------- dis : ModflowUPW object ModflowLpf object. Examples -------- >>> import flopy >>> m = flopy.modflow.Modflow() >>> upw = flopy.modflow.ModflowUpw.load('test.upw', m) """ if model.verbose: sys.stdout.write('loading upw package file...\n') if model.version != 'mfnwt': msg = "Warning: model version was reset from " + \ "'{}' to 'mfnwt' in order to load a UPW file".format( model.version) print(msg) model.version = 'mfnwt' if not hasattr(f, 'read'): filename = f f = open(filename, 'r') # dataset 0 -- header while True: line = f.readline() if line[0] != '#': break # determine problem dimensions nrow, ncol, nlay, nper = model.get_nrow_ncol_nlay_nper() # Item 1: IBCFCB, HDRY, NPLPF - line already read above if model.verbose: print(' loading ipakcb, HDRY, NPUPW, IPHDRY...') t = line.strip().split() ipakcb, hdry, npupw, iphdry = int(t[0]), \ float(t[1]), \ int(t[2]), \ int(t[3]) # if ipakcb != 0: # model.add_pop_key_list(ipakcb) # ipakcb = 53 # options noparcheck = False if len(t) > 3: for k in range(3, len(t)): if 'NOPARCHECK' in t[k].upper(): noparcheck = True # LAYTYP array if model.verbose: print(' loading LAYTYP...') line = f.readline() t = line.strip().split() laytyp = np.array((t[0:nlay]), dtype=np.int) # LAYAVG array if model.verbose: print(' loading LAYAVG...') line = f.readline() t = line.strip().split() layavg = np.array((t[0:nlay]), dtype=np.int) # CHANI array if model.verbose: print(' loading CHANI...') line = f.readline() t = line.strip().split() chani = np.array((t[0:nlay]), dtype=np.float32) # LAYVKA array if model.verbose: print(' loading LAYVKA...') line = f.readline() t = line.strip().split() layvka = np.array((t[0:nlay]), dtype=np.int) # LAYWET array if model.verbose: print(' loading LAYWET...') line = f.readline() t = line.strip().split() laywet = np.array((t[0:nlay]), dtype=np.int) # Item 7: WETFCT, IWETIT, IHDWET wetfct, iwetit, ihdwet = None, None, None iwetdry = laywet.sum() if iwetdry > 0: raise Exception('LAYWET should be 0 for UPW') # get parameters par_types = [] if npupw > 0: par_types, parm_dict = mfpar.load(f, npupw, model.verbose) # get arrays transient = not model.get_package('DIS').steady.all() hk = [0] * nlay hani = [0] * nlay vka = [0] * nlay ss = [0] * nlay sy = [0] * nlay vkcb = [0] * nlay for k in range(nlay): if model.verbose: print(' loading hk layer {0:3d}...'.format(k + 1)) if 'hk' not in par_types: t = Util2d.load(f, model, (nrow, ncol), np.float32, 'hk', ext_unit_dict) else: line = f.readline() t = mfpar.parameter_fill(model, (nrow, ncol), 'hk', parm_dict, findlayer=k) hk[k] = t if chani[k] < 1: if model.verbose: print(' loading hani layer {0:3d}...'.format(k + 1)) if 'hani' not in par_types: t = Util2d.load(f, model, (nrow, ncol), np.float32, 'hani', ext_unit_dict) else: line = f.readline() t = mfpar.parameter_fill(model, (nrow, ncol), 'hani', parm_dict, findlayer=k) hani[k] = t if model.verbose: print(' loading vka layer {0:3d}...'.format(k + 1)) if 'vk' not in par_types and 'vani' not in par_types: key = 'vka' if layvka[k] != 0: key = 'vani' t = Util2d.load(f, model, (nrow, ncol), np.float32, key, ext_unit_dict) else: line = f.readline() key = 'vka' if 'vani' in par_types: key = 'vani' t = mfpar.parameter_fill(model, (nrow, ncol), key, parm_dict, findlayer=k) vka[k] = t if transient: if model.verbose: print(' loading ss layer {0:3d}...'.format(k + 1)) if 'ss' not in par_types: t = Util2d.load(f, model, (nrow, ncol), np.float32, 'ss', ext_unit_dict) else: line = f.readline() t = mfpar.parameter_fill(model, (nrow, ncol), 'ss', parm_dict, findlayer=k) ss[k] = t if laytyp[k] != 0: if model.verbose: print(' loading sy layer {0:3d}...'.format(k + 1)) if 'sy' not in par_types: t = Util2d.load(f, model, (nrow, ncol), np.float32, 'sy', ext_unit_dict) else: line = f.readline() t = mfpar.parameter_fill(model, (nrow, ncol), 'sy', parm_dict, findlayer=k) sy[k] = t if model.get_package('DIS').laycbd[k] > 0: if model.verbose: print(' loading vkcb layer {0:3d}...'.format(k + 1)) if 'vkcb' not in par_types: t = Util2d.load(f, model, (nrow, ncol), np.float32, 'vkcb', ext_unit_dict) else: line = f.readline() t = mfpar.parameter_fill(model, (nrow, ncol), 'vkcb', parm_dict, findlayer=k) vkcb[k] = t # determine specified unit number unitnumber = None filenames = [None, None] if ext_unit_dict is not None: unitnumber, filenames[0] = \ model.get_ext_dict_attr(ext_unit_dict, filetype=ModflowUpw.ftype()) if ipakcb > 0: iu, filenames[1] = \ model.get_ext_dict_attr(ext_unit_dict, unit=ipakcb) model.add_pop_key_list(ipakcb) # create upw object upw = ModflowUpw(model, ipakcb=ipakcb, iphdry=iphdry, hdry=hdry, noparcheck=noparcheck, laytyp=laytyp, layavg=layavg, chani=chani, layvka=layvka, laywet=laywet, hk=hk, hani=hani, vka=vka, ss=ss, sy=sy, vkcb=vkcb, unitnumber=unitnumber, filenames=filenames) if check: upw.check(f='{}.chk'.format(upw.name[0]), verbose=upw.parent.verbose, level=0) # return upw object return upw @staticmethod def ftype(): return 'UPW' @staticmethod def defaultunit(): return 31
""" MySensors platform that offers a Climate (MySensors-HVAC) component. For more details about this platform, please refer to the documentation https://home-assistant.io/components/climate.mysensors/ """ import logging from homeassistant.components import mysensors from homeassistant.components.climate import ( STATE_COOL, STATE_HEAT, STATE_OFF, STATE_AUTO, ClimateDevice, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW) from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE _LOGGER = logging.getLogger(__name__) DICT_HA_TO_MYS = { STATE_AUTO: 'AutoChangeOver', STATE_COOL: 'CoolOn', STATE_HEAT: 'HeatOn', STATE_OFF: 'Off', } DICT_MYS_TO_HA = { 'AutoChangeOver': STATE_AUTO, 'CoolOn': STATE_COOL, 'HeatOn': STATE_HEAT, 'Off': STATE_OFF, } def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the mysensors climate.""" if discovery_info is None: return gateways = hass.data.get(mysensors.MYSENSORS_GATEWAYS) if not gateways: return for gateway in gateways: if float(gateway.protocol_version) < 1.5: continue pres = gateway.const.Presentation set_req = gateway.const.SetReq map_sv_types = { pres.S_HVAC: [set_req.V_HVAC_FLOW_STATE], } devices = {} gateway.platform_callbacks.append(mysensors.pf_callback_factory( map_sv_types, devices, MySensorsHVAC, add_devices)) class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): """Representation of a MySensors HVAC.""" @property def assumed_state(self): """Return True if unable to access real state of entity.""" return self.gateway.optimistic @property def temperature_unit(self): """Return the unit of measurement.""" return (TEMP_CELSIUS if self.gateway.metric else TEMP_FAHRENHEIT) @property def current_temperature(self): """Return the current temperature.""" value = self._values.get(self.gateway.const.SetReq.V_TEMP) if value is not None: value = float(value) return value @property def target_temperature(self): """Return the temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_COOL in self._values and \ set_req.V_HVAC_SETPOINT_HEAT in self._values: return None temp = self._values.get(set_req.V_HVAC_SETPOINT_COOL) if temp is None: temp = self._values.get(set_req.V_HVAC_SETPOINT_HEAT) return float(temp) @property def target_temperature_high(self): """Return the highbound target temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_HEAT in self._values: return float(self._values.get(set_req.V_HVAC_SETPOINT_COOL)) @property def target_temperature_low(self): """Return the lowbound target temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_COOL in self._values: return float(self._values.get(set_req.V_HVAC_SETPOINT_HEAT)) @property def current_operation(self): """Return current operation ie. heat, cool, idle.""" return self._values.get(self.gateway.const.SetReq.V_HVAC_FLOW_STATE) @property def operation_list(self): """List of available operation modes.""" return [STATE_OFF, STATE_AUTO, STATE_COOL, STATE_HEAT] @property def current_fan_mode(self): """Return the fan setting.""" return self._values.get(self.gateway.const.SetReq.V_HVAC_SPEED) @property def fan_list(self): """List of available fan modes.""" return ['Auto', 'Min', 'Normal', 'Max'] def set_temperature(self, **kwargs): """Set new target temperature.""" set_req = self.gateway.const.SetReq temp = kwargs.get(ATTR_TEMPERATURE) low = kwargs.get(ATTR_TARGET_TEMP_LOW) high = kwargs.get(ATTR_TARGET_TEMP_HIGH) heat = self._values.get(set_req.V_HVAC_SETPOINT_HEAT) cool = self._values.get(set_req.V_HVAC_SETPOINT_COOL) updates = () if temp is not None: if heat is not None: # Set HEAT Target temperature value_type = set_req.V_HVAC_SETPOINT_HEAT elif cool is not None: # Set COOL Target temperature value_type = set_req.V_HVAC_SETPOINT_COOL if heat is not None or cool is not None: updates = [(value_type, temp)] elif all(val is not None for val in (low, high, heat, cool)): updates = [ (set_req.V_HVAC_SETPOINT_HEAT, low), (set_req.V_HVAC_SETPOINT_COOL, high)] for value_type, value in updates: self.gateway.set_child_value( self.node_id, self.child_id, value_type, value) if self.gateway.optimistic: # optimistically assume that switch has changed state self._values[value_type] = value self.schedule_update_ha_state() def set_fan_mode(self, fan): """Set new target temperature.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_HVAC_SPEED, fan) if self.gateway.optimistic: # optimistically assume that switch has changed state self._values[set_req.V_HVAC_SPEED] = fan self.schedule_update_ha_state() def set_operation_mode(self, operation_mode): """Set new target temperature.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_HVAC_FLOW_STATE, DICT_HA_TO_MYS[operation_mode]) if self.gateway.optimistic: # optimistically assume that switch has changed state self._values[set_req.V_HVAC_FLOW_STATE] = operation_mode self.schedule_update_ha_state() def update(self): """Update the controller with the latest value from a sensor.""" set_req = self.gateway.const.SetReq node = self.gateway.sensors[self.node_id] child = node.children[self.child_id] for value_type, value in child.values.items(): _LOGGER.debug( "%s: value_type %s, value = %s", self._name, value_type, value) if value_type == set_req.V_HVAC_FLOW_STATE: self._values[value_type] = DICT_MYS_TO_HA[value] else: self._values[value_type] = value def set_humidity(self, humidity): """Set new target humidity.""" _LOGGER.error("Service Not Implemented yet") def set_swing_mode(self, swing_mode): """Set new target swing operation.""" _LOGGER.error("Service Not Implemented yet") def turn_away_mode_on(self): """Turn away mode on.""" _LOGGER.error("Service Not Implemented yet") def turn_away_mode_off(self): """Turn away mode off.""" _LOGGER.error("Service Not Implemented yet") def turn_aux_heat_on(self): """Turn auxillary heater on.""" _LOGGER.error("Service Not Implemented yet") def turn_aux_heat_off(self): """Turn auxillary heater off.""" _LOGGER.error("Service Not Implemented yet")
# Common functions used throughout various parts of binwalk code. import io import os import re import sys import ast import hashlib import operator as op import binwalk.core.idb from binwalk.core.compat import * # This allows other modules/scripts to subclass BlockFile from a custom class. Defaults to io.FileIO. if has_key(__builtins__, 'BLOCK_FILE_PARENT_CLASS'): BLOCK_FILE_PARENT_CLASS = __builtins__['BLOCK_FILE_PARENT_CLASS'] else: BLOCK_FILE_PARENT_CLASS = io.FileIO # Special override for when we're running in IDA if binwalk.core.idb.LOADED_IN_IDA: BLOCK_FILE_PARENT_CLASS = binwalk.core.idb.IDBFileIO # The __debug__ value is a bit backwards; by default it is set to True, but # then set to False if the Python interpreter is run with the -O option. if not __debug__: DEBUG = True else: DEBUG = False def debug(msg): ''' Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag. ''' if DEBUG: sys.stderr.write("DEBUG: " + msg + "\n") sys.stderr.flush() def warning(msg): ''' Prints warning messages to stderr ''' sys.stderr.write("\nWARNING: " + msg + "\n") def error(msg): ''' Prints error messages to stderr ''' sys.stderr.write("\nERROR: " + msg + "\n") def get_module_path(): root = __file__ if os.path.islink(root): root = os.path.realpath(root) return os.path.dirname(os.path.dirname(os.path.abspath(root))) def get_libs_path(): return os.path.join(get_module_path(), "libs") def file_md5(file_name): ''' Generate an MD5 hash of the specified file. @file_name - The file to hash. Returns an MD5 hex digest string. ''' md5 = hashlib.md5() with open(file_name, 'rb') as f: for chunk in iter(lambda: f.read(128*md5.block_size), b''): md5.update(chunk) return md5.hexdigest() def file_size(filename): ''' Obtains the size of a given file. @filename - Path to the file. Returns the size of the file. ''' # Using open/lseek works on both regular files and block devices fd = os.open(filename, os.O_RDONLY) try: return os.lseek(fd, 0, os.SEEK_END) except KeyboardInterrupt as e: raise e except Exception as e: raise Exception("file_size failed to obtain the size of '%s': %s" % (filename, str(e))) finally: os.close(fd) def strip_quoted_strings(string): ''' Strips out data in between double quotes. @string - String to strip. Returns a sanitized string. ''' # This regex removes all quoted data from string. # Note that this removes everything in between the first and last double quote. # This is intentional, as printed (and quoted) strings from a target file may contain # double quotes, and this function should ignore those. However, it also means that any # data between two quoted strings (ex: '"quote 1" you won't see me "quote 2"') will also be stripped. return re.sub(r'\"(.*)\"', "", string) def get_quoted_strings(string): ''' Returns a string comprised of all data in between double quotes. @string - String to get quoted data from. Returns a string of quoted data on success. Returns a blank string if no quoted data is present. ''' try: # This regex grabs all quoted data from string. # Note that this gets everything in between the first and last double quote. # This is intentional, as printed (and quoted) strings from a target file may contain # double quotes, and this function should ignore those. However, it also means that any # data between two quoted strings (ex: '"quote 1" non-quoted data "quote 2"') will also be included. return re.findall(r'\"(.*)\"', string)[0] except KeyboardInterrupt as e: raise e except Exception: return '' def unique_file_name(base_name, extension=''): ''' Creates a unique file name based on the specified base name. @base_name - The base name to use for the unique file name. @extension - The file extension to use for the unique file name. Returns a unique file string. ''' idcount = 0 if extension and not extension.startswith('.'): extension = '.%s' % extension fname = base_name + extension while os.path.exists(fname): fname = "%s-%d%s" % (base_name, idcount, extension) idcount += 1 return fname def strings(filename, minimum=4): ''' A strings generator, similar to the Unix strings utility. @filename - The file to search for strings in. @minimum - The minimum string length to search for. Yeilds printable ASCII strings from filename. ''' result = "" with BlockFile(filename) as f: while True: (data, dlen) = f.read_block() if not data: break for c in data: if c in string.printable: result += c continue elif len(result) >= minimum: yield result result = "" else: result = "" class GenericContainer(object): def __init__(self, **kwargs): for (k,v) in iterator(kwargs): setattr(self, k, v) class MathExpression(object): ''' Class for safely evaluating mathematical expressions from a string. Stolen from: http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string ''' OPERATORS = { ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor } def __init__(self, expression): self.expression = expression self.value = None if expression: try: self.value = self.evaluate(self.expression) except KeyboardInterrupt as e: raise e except Exception: pass def evaluate(self, expr): return self._eval(ast.parse(expr).body[0].value) def _eval(self, node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.operator): # <operator> return self.OPERATORS[type(node)] elif isinstance(node, ast.BinOp): # <left> <operator> <right> return self._eval(node.op)(self._eval(node.left), self._eval(node.right)) else: raise TypeError(node) class BlockFile(BLOCK_FILE_PARENT_CLASS): ''' Abstraction class for accessing binary files. This class overrides io.FilIO's read and write methods. This guaruntees two things: 1. All requested data will be read/written via the read and write methods. 2. All reads return a str object and all writes can accept either a str or a bytes object, regardless of the Python interpreter version. However, the downside is that other io.FileIO methods won't work properly in Python 3, namely things that are wrappers around self.read (e.g., readline, readlines, etc). This class also provides a read_block method, which is used by binwalk to read in a block of data, plus some additional data (DEFAULT_BLOCK_PEEK_SIZE), but on the next block read pick up at the end of the previous data block (not the end of the additional data). This is necessary for scans where a signature may span a block boundary. The descision to force read to return a str object instead of a bytes object is questionable for Python 3, but it seemed the best way to abstract differences in Python 2/3 from the rest of the code (especially for people writing plugins) and to add Python 3 support with minimal code change. ''' # The DEFAULT_BLOCK_PEEK_SIZE limits the amount of data available to a signature. # While most headers/signatures are far less than this value, some may reference # pointers in the header structure which may point well beyond the header itself. # Passing the entire remaining buffer to libmagic is resource intensive and will # significantly slow the scan; this value represents a reasonable buffer size to # pass to libmagic which will not drastically affect scan time. DEFAULT_BLOCK_PEEK_SIZE = 8 * 1024 # Max number of bytes to process at one time. This needs to be large enough to # limit disk I/O, but small enough to limit the size of processed data blocks. DEFAULT_BLOCK_READ_SIZE = 1 * 1024 * 1024 def __init__(self, fname, mode='r', length=0, offset=0, block=DEFAULT_BLOCK_READ_SIZE, peek=DEFAULT_BLOCK_PEEK_SIZE, swap=0): ''' Class constructor. @fname - Path to the file to be opened. @mode - Mode to open the file in (default: 'r'). @length - Maximum number of bytes to read from the file via self.block_read(). @offset - Offset at which to start reading from the file. @block - Size of data block to read (excluding any trailing size), @peek - Size of trailing data to append to the end of each block. @swap - Swap every n bytes of data. Returns None. ''' self.total_read = 0 self.block_read_size = self.DEFAULT_BLOCK_READ_SIZE self.block_peek_size = self.DEFAULT_BLOCK_PEEK_SIZE # This is so that custom parent classes can access/modify arguments as necessary self.args = GenericContainer(fname=fname, mode=mode, length=length, offset=offset, block=block, peek=peek, swap=swap, size=0) # Python 2.6 doesn't like modes like 'rb' or 'wb' mode = self.args.mode.replace('b', '') super(self.__class__, self).__init__(fname, mode) self.swap_size = self.args.swap if self.args.size: self.size = self.args.size else: try: self.size = file_size(self.args.fname) except KeyboardInterrupt as e: raise e except Exception: self.size = 0 if self.args.offset < 0: self.offset = self.size + self.args.offset else: self.offset = self.args.offset if self.offset < 0: self.offset = 0 elif self.offset > self.size: self.offset = self.size if self.args.offset < 0: self.length = self.args.offset * -1 elif self.args.length: self.length = self.args.length else: self.length = self.size - self.args.offset if self.length < 0: self.length = 0 elif self.length > self.size: self.length = self.size if self.args.block is not None: self.block_read_size = self.args.block self.base_block_size = self.block_read_size if self.args.peek is not None: self.block_peek_size = self.args.peek self.base_peek_size = self.block_peek_size # Work around for python 2.6 where FileIO._name is not defined try: self.name except AttributeError: self._name = fname self.seek(self.offset) def _swap_data_block(self, block): ''' Reverses every self.swap_size bytes inside the specified data block. Size of data block must be a multiple of self.swap_size. @block - The data block to swap. Returns a swapped string. ''' i = 0 data = "" if self.swap_size > 0: while i < len(block): data += block[i:i+self.swap_size][::-1] i += self.swap_size else: data = block return data def reset(self): self.set_block_size(block=self.base_block_size, peek=self.base_peek_size) self.seek(self.offset) def set_block_size(self, block=None, peek=None): if block is not None: self.block_read_size = block if peek is not None: self.block_peek_size = peek def write(self, data): ''' Writes data to the opened file. io.FileIO.write does not guaruntee that all data will be written; this method overrides io.FileIO.write and does guaruntee that all data will be written. Returns the number of bytes written. ''' n = 0 l = len(data) data = str2bytes(data) while n < l: n += super(self.__class__, self).write(data[n:]) return n def read(self, n=-1): '''' Reads up to n bytes of data (or to EOF if n is not specified). Will not read more than self.length bytes. io.FileIO.read does not guaruntee that all requested data will be read; this method overrides io.FileIO.read and does guaruntee that all data will be read. Returns a str object containing the read data. ''' l = 0 data = b'' if self.total_read < self.length: # Don't read more than self.length bytes from the file if (self.total_read + n) > self.length: n = self.length - self.total_read while n < 0 or l < n: tmp = super(self.__class__, self).read(n-l) if tmp: data += tmp l += len(tmp) else: break self.total_read += len(data) return self._swap_data_block(bytes2str(data)) def peek(self, n=-1): ''' Peeks at data in file. ''' pos = self.tell() data = self.read(n) self.seek(pos) return data def seek(self, n, whence=os.SEEK_SET): if whence == os.SEEK_SET: self.total_read = n - self.offset elif whence == os.SEEK_CUR: self.total_read += n elif whence == os.SEEK_END: self.total_read = self.size + n super(self.__class__, self).seek(n, whence) def read_block(self): ''' Reads in a block of data from the target file. Returns a tuple of (str(file block data), block data length). ''' data = self.read(self.block_read_size) dlen = len(data) data += self.peek(self.block_peek_size) return (data, dlen) def dup(self): ''' Creates a new BlockFile instance with all the same initialization settings as this one. Returns new BlockFile object. ''' return BlockFile(self.name, length=self.length, offset=self.offset, block=self.base_block_read_size, peek=self.base_peek_size, swap=self.swap)
# # 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 base64 import urlparse import zlib from conary.lib import networking from conary.lib import util from conary.lib.compat import namedtuple class URL(namedtuple('URL', 'scheme userpass hostport path')): def __new__(cls, scheme, userpass=None, hostport=None, path=None): if userpass is None and hostport is None and path is None: return cls.parse(scheme) else: return tuple.__new__(cls, (scheme, userpass, hostport, path)) @classmethod def parse(cls, url, defaultScheme='http'): if '://' not in url and defaultScheme: url = '%s://%s' % (defaultScheme, url) (scheme, username, password, host, port, path, query, fragment, ) = util.urlSplit(url) if not port and port != 0: if scheme[-1] == 's': port = 443 else: port = 80 hostport = networking.HostPort(host, port) path = urlparse.urlunsplit(('', '', path, query, fragment)) return cls(scheme, (username, password), hostport, path) def unsplit(self): username, password = self.userpass host, port = self.hostport if (self.scheme == 'http' and port == 80) or ( self.scheme == 'https' and port == 443): port = None return util.urlUnsplit((self.scheme, username, password, str(host), port, self.path, None, None)) def __str__(self): rv = self.unsplit() if hasattr(rv, '__safe_str__'): rv = rv.__safe_str__() return rv class HTTPHeaders(object): __slots__ = ('_headers',) def __init__(self, headers=None): self._headers = {} if headers: if isinstance(headers, dict): headers = headers.iteritems() for key, value in headers: self[key] = value @staticmethod def canonical(key): return '-'.join(x.capitalize() for x in key.split('-')) def __getitem__(self, key): key = self.canonical(key) return self._headers[key] def __setitem__(self, key, value): key = self.canonical(key) self._headers[key] = value def __delitem__(self, key): key = self.canonical(key) del self._headers[key] def __contains__(self, key): key = self.canonical(key) return key in self._headers def get(self, key, default=None): key = self.canonical(key) return self._headers.get(key) def iteritems(self): return self._headers.iteritems() def setdefault(self, key, default): key = self.canonical(key) return self._headers.setdefault(key, default) class Request(object): def __init__(self, url, method='GET', headers=()): if isinstance(url, basestring): url = URL.parse(url) self.url = url self.method = method self.headers = HTTPHeaders(headers) # Params for sending request entity self.abortCheck = None self.data = None self.size = None self.chunked = False self.callback = None self.rateLimit = None def setData(self, data, size=None, compress=False, callback=None, chunked=False, rateLimit=None): if compress: data = zlib.compress(data, 9) size = len(data) self.headers['Accept-Encoding'] = 'deflate' self.headers['Content-Encoding'] = 'deflate' self.data = data self.callback = callback self.rateLimit = rateLimit if size is None: try: size = len(data) except TypeError: pass self.size = size self.headers['Content-Length'] = str(size) if chunked or size is None: self.chunked = True self.headers['Transfer-Encoding'] = 'chunked' else: self.chunked = False def setAbortCheck(self, abortCheck): self.abortCheck = abortCheck def sendRequest(self, conn, isProxied=False): if isProxied: cleanUrl = self.url._replace(userpass=(None,None)) path = str(cleanUrl) else: path = self.url.path conn.putrequest(self.method, path, skip_host=1, skip_accept_encoding=1) self.headers.setdefault('Accept-Encoding', 'identity') for key, value in self.headers.iteritems(): conn.putheader(key, value) if 'Host' not in self.headers: hostport = self.url.hostport if hostport.port in (80, 443): hostport = hostport._replace(port=None) host = str(hostport) if isinstance(host, unicode): host = host.encode('idna') conn.putheader("Host", host) if 'Authorization' not in self.headers and self.url.userpass[0]: conn.putheader("Authorization", "Basic " + base64.b64encode(":".join(self.url.userpass))) conn.endheaders() self._sendData(conn) def _sendData(self, conn): if self.data is None: return if not hasattr(self.data, 'read'): conn.send(self.data) return if self.chunked: # Use chunked coding output = wrapper = ChunkedSender(conn) elif self.size is not None: # Use identity coding output = conn wrapper = None else: raise RuntimeError("Request must use chunked transfer coding " "if size is not known.") util.copyfileobj(self.data, output, callback=self.callback, rateLimit=self.rateLimit, abortCheck=self.abortCheck, sizeLimit=self.size) if wrapper: wrapper.close() def reset(self): if hasattr(self.data, 'read'): self.data.seek(0) class ChunkedSender(object): """ Do HTTP chunked transfer coding by wrapping a socket-like object, intercepting send() calls and sending the correct leading and trailing metadata. """ def __init__(self, target): self.target = target def send(self, data): self.target.send("%x\r\n%s\r\n" % (len(data), data)) def close(self, trailer=''): self.target.send("0\r\n%s\r\n" % (trailer,))
#!/usr/bin/env python """ Copyright 2013 OpERA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import sys path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")) sys.path.insert(0, path) from gnuradio import gr from gnuradio import blocks from grc_gnuradio import blks2 as grc_blks2 from gnuradio import digital from gnuradio.eng_option import eng_option from optparse import OptionParser from struct import * from threading import Thread import time import copy import threading import random import yaml import math import numpy as np from abc import ABCMeta, abstractmethod #Project imports: from OpERAFlow import OpERAFlow from algorithm import KunstTimeFeedback from device import * from sensing import FeedbackSSArch from sensing import EnergyDecision, WaveformDecision, BayesLearningThreshold2 from sensing import EnergySSArch, WaveformSSArch, CycloSSArch from channels import AWGNChannel from gr_blocks.utils import UHDSourceDummy from utils import Logger TOTAL_IT = range(0, 11) class OpERAUtils(object): """ Class with useful methods from OpERA. """ @staticmethod def device_definition(options): """ Definition of the devices used in the program. @param options """ tb = OpERAFlow(name='US') bits_per_symbol = 2 modulator = grc_blks2.packet_mod_b(digital.ofdm_mod( options=grc_blks2.options( modulation="bpsk", fft_length=512, occupied_tones=200, cp_length=128, pad_for_usrp=True, log=None, verbose=None, ), ), payload_length=0, ) uhd_source = UHDSourceDummy(modulator=modulator) uhd_source.pre_connect(tb) # Gambi the_source = AWGNChannel(component=uhd_source) arch1 = EnergySSArch(fft_size=1024, mavg_size=1) algo1 = BayesLearningThreshold2(in_th = 5.0, min_th = 0.0, max_th = 12.0, delta_th = 0.1, k = 1) if options.sensing == "wfd": arch2 = WaveformSSArch(fft_size=1024) algo2 = WaveformDecision(options.th['wfd']) elif options.sensing == 'cfd': arch2 = CycloSSArch(64, 16, 4) from sensing import CycloDecision algo2 = CycloDecision(64, 16, 4, options.th['cfd']) else: raise AttributeError ata = FeedbackSSArch( input_len = 1024, algo1=algo1, algo2=algo2, feedback_algorithm=KunstTimeFeedback(), ) radio = RadioDevice(name="radio") radio.add_arch(source=the_source, arch=arch1, sink=(ata, 0), uhd_device=uhd_source, name='ed') radio.add_arch(source=the_source, arch=arch2, sink=(ata, 1), uhd_device=uhd_source, name='sensing') tb.add_radio(radio, "radio") return tb, radio, algo1, algo2 if __name__ == "__main__": parser = OptionParser() parser.add_option("", "--ph1", type="float", default=0.5) parser.add_option("", "--sensing", type="string", default="cfd") (options, args) = parser.parse_args() options.ph0 = 1.0 - options.ph1 print "Loading YAML %s" % options.sensing thresholds = {} with open('lambda_%s.txt' % options.sensing, 'r') as fd: import yaml thresholds[options.sensing] = yaml.load(fd) print "Lading YAML ED" with open('lambda_ed.txt', 'r') as fd: import yaml thresholds['ed'] = yaml.load(fd) Logger._enable = True options.th = {} options.thresholds = thresholds for pfa in (0, 50, 100): #for ebn0 in (-20, -15, -10, -5, 0, 5): for ebn0 in (10, ): options.th = {} options.th[options.sensing] = thresholds[options.sensing][ebn0][ int(math.ceil(1999 * (1-(pfa/100.0)))) ] for options.it in TOTAL_IT: print "PFA: %f, EBN0: %d, IT: %d" % (pfa, ebn0, options.it) tb, radio, algo1, algo2 = OpERAUtils.device_definition(options) radio.ed._component.set_active_freqs([1, ]) radio.ed._component.set_center_freq(0) radio.ed.set_ebn0(ebn0) algo2._threshold = options.th[options.sensing] tin = time.clock() ################################################################################ options.ph = {0: options.ph0, 1: options.ph1 } t_tot = 0.0 status = random.choice([0, 1]) while True: x = random.random() t_next = math.fabs(random.expovariate(1.0/3.0)) if x < options.ph1: status = 1 else: status = 0 if t_tot + t_next > 10.0: t_next = 10.0 - t_tot if status == 1: radio.ed._component.set_center_freq(1) print "--- Setting ch_status to 1" Logger._ch_status = 1 else: radio.ed._component.set_center_freq(0) print "--- Setting ch_status to 0" Logger._ch_status = 0 if t_tot == 0: tb.start() time.sleep(t_next) t_tot += t_next if t_tot >= 10.0: break; ################################################################################ tb.stop() tb.wait() tfin = time.clock() enable = False Logger.register('global', ['clock', ]) Logger.set('global', 'clock', tfin - tin) _sdir = '/ata_%s_%02d_%02d/' % (options.sensing, options.ph1 * 10, pfa) _dir = "single/ebn0_{ebn0}".format(ebn0=ebn0) Logger.dump(_dir, _sdir, options.it) Logger.clear_all() # wait for thread model_channel finish #t_mc.join() with open("log.txt", "a+") as log: log.write(_dir + _sdir )
#$Id$# from books.model.ProjectList import ProjectList from books.model.Project import Project from books.model.PageContext import PageContext from books.model.TaskList import TaskList from books.model.Task import Task from books.model.User import User from books.model.TimeEntryList import TimeEntryList from books.model.TimeEntry import TimeEntry from books.model.Comment import Comment from books.model.InvoiceList import InvoiceList from books.model.Invoice import Invoice from books.model.UserList import UserList from books.model.CommentList import CommentList class ProjectsParser: """This class is used to parse the json object for Projects.""" def get_projects_list(self, resp): """This method parses the given response and returns projects list object. Args: resp(dict): Response containing json object for projects. Returns: instance: Projects list object. """ projects_list = ProjectList() for value in resp['projects']: project = Project() project.set_project_id(value['project_id']) project.set_project_name(value['project_name']) project.set_customer_id(value['customer_id']) project.set_customer_name(value['customer_name']) project.set_description(value['description']) project.set_status(value['status']) project.set_billing_type(value['billing_type']) #project.set_rate(value['rate']) project.set_created_time(value['created_time']) projects_list.set_projects(project) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) projects_list.set_page_context(page_context_obj) return projects_list def get_project(self, resp): """This method parses the given response and returns projects object. Args: resp(dict): Dictionary containing json object for projects. Returns: instance: Projects object. """ project_obj = Project() project = resp['project'] project_obj.set_project_id(project['project_id']) project_obj.set_project_name(project['project_name']) project_obj.set_customer_id(project['customer_id']) project_obj.set_customer_name(project['customer_name']) project_obj.set_currency_code(project['currency_code']) project_obj.set_description(project['description']) project_obj.set_status(project['status']) project_obj.set_billing_type(project['billing_type']) project_obj.set_budget_type(project['budget_type']) project_obj.set_total_hours(project['total_hours']) project_obj.set_billed_hours(project['billed_hours']) project_obj.set_un_billed_hours(project['un_billed_hours']) project_obj.set_created_time(project['created_time']) for value in project['tasks']: task = Task() task.set_task_id(value['task_id']) task.set_task_name(value['task_name']) task.set_description(value['description']) task.set_rate(value['rate']) task.set_budget_hours(value['budget_hours']) task.set_total_hours(value['total_hours']) task.set_billed_hours(value['billed_hours']) task.set_un_billed_hours(value['un_billed_hours']) project_obj.set_tasks(task) for value in project['users']: user = User() user.set_user_id(value['user_id']) user.set_is_current_user(value['is_current_user']) user.set_user_name(value['user_name']) user.set_email(value['email']) user.set_user_role(value['user_role']) user.set_status(value['status']) user.set_rate(value['rate']) user.set_budget_hours(value['budget_hours']) user.set_total_hours(value['total_hours']) user.set_billed_hours(value['billed_hours']) user.set_un_billed_hours(value['un_billed_hours']) project_obj.set_users(user) return project_obj def get_message(self, resp): """This method parses the given response and returns string message. Args: resp(dict): Response containing json object for string message. Returns: str: Success message. """ return resp['message'] def get_tasks_list(self, resp): """This method parses the given response and returns tasks list object. Args: resp(dict): Response containing json object for tasks list. Returns: instance: Task list object. """ task_list = TaskList() for value in resp['task']: task = Task() task.set_project_id(value['project_id']) task.set_task_id(value['task_id']) task.set_currency_id(value['currency_id']) task.set_customer_id(value['customer_id']) task.set_task_name(value['task_name']) task.set_project_name(value['project_name']) task.set_customer_name(value['customer_name']) task.set_billed_hours(value['billed_hours']) task.set_log_time(value['log_time']) task.set_un_billed_hours(value['un_billed_hours']) task_list.set_tasks(task) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) task_list.set_page_context(page_context_obj) return task_list def get_task(self, resp): """This method parses the given response and returns task object. Args: resp(dict): Response containing json object for task. Returns: instance: Task object. """ task_obj = Task() task = resp['task'] task_obj.set_project_id(task['project_id']) task_obj.set_project_name(task['project_name']) task_obj.set_task_id(task['task_id']) task_obj.set_task_name(task['task_name']) task_obj.set_description(task['description']) task_obj.set_rate(task['rate']) return task_obj def get_users(self, resp): """This method parses the given response and returns list of users object. Args: resp(dict): Response containing json object for users list object. Returns: instance: Users list object. """ users = UserList() for value in resp['users']: user = User() user.set_user_id(value['user_id']) user.set_is_current_user(value['is_current_user']) user.set_user_name(value['user_name']) user.set_email(value['email']) user.set_user_role(value['user_role']) user.set_status(value['status']) user.set_rate(value['rate']) user.set_budget_hours(value['budget_hours']) users.set_users(user) return users def get_user(self, resp): """This method parses the given response and returns user object. Args: resp(dict): Response containing json object for user. Returns: instance: User object. """ user_obj = User() user = resp['user'] user_obj.set_project_id(user['project_id']) user_obj.set_user_id(user['user_id']) user_obj.set_is_current_user(user['is_current_user']) user_obj.set_user_name(user['user_name']) user_obj.set_email(user['email']) user_obj.set_user_role(user['user_role']) return user_obj def get_time_entries_list(self, resp): """This method parses the given response and returns time entries list object. Args: resp(dict): Response containing json object for time entries. Returns: instance: Time entries list object. """ time_entries_list = TimeEntryList() for value in resp['time_entries']: time_entry = TimeEntry() time_entry.set_time_entry_id(value['time_entry_id']) time_entry.set_project_id(value['project_id']) time_entry.set_project_name(value['project_name']) time_entry.set_customer_id(value['customer_id']) time_entry.set_customer_name(value['customer_name']) time_entry.set_task_id(value['task_id']) time_entry.set_task_name(value['task_name']) time_entry.set_user_id(value['user_id']) time_entry.set_is_current_user(value['is_current_user']) time_entry.set_user_name(value['user_name']) time_entry.set_log_date(value['log_date']) time_entry.set_begin_time(value['begin_time']) time_entry.set_end_time(value['end_time']) time_entry.set_log_time(value['log_time']) time_entry.set_billed_status(value['billed_status']) time_entry.set_notes(value['notes']) time_entry.set_timer_started_at(value['timer_started_at']) time_entry.set_timer_duration_in_minutes(value[\ 'timer_duration_in_minutes']) time_entry.set_created_time(value['created_time']) time_entries_list.set_time_entries(time_entry) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) time_entries_list.set_page_context(page_context_obj) return time_entries_list def get_time_entry(self, resp): """This method parses the given response and returns time entry object. Args: resp(dict):Response containing json object for time entry. Returns: instance: Time entry object """ time_entry = resp['time_entry'] time_entry_obj = TimeEntry() time_entry_obj.set_time_entry_id(time_entry['time_entry_id']) time_entry_obj.set_project_id(time_entry['project_id']) time_entry_obj.set_project_name(time_entry['project_name']) time_entry_obj.set_task_id(time_entry['task_id']) time_entry_obj.set_task_name(time_entry['task_name']) time_entry_obj.set_user_id(time_entry['user_id']) time_entry_obj.set_user_name(time_entry['user_name']) time_entry_obj.set_is_current_user(time_entry['is_current_user']) time_entry_obj.set_log_date(time_entry['log_date']) time_entry_obj.set_begin_time(time_entry['begin_time']) time_entry_obj.set_end_time(time_entry['end_time']) time_entry_obj.set_log_time(time_entry['log_time']) time_entry_obj.set_billed_status(time_entry['billed_status']) time_entry_obj.set_notes(time_entry['notes']) time_entry_obj.set_timer_started_at(time_entry['timer_started_at']) time_entry_obj.set_timer_duration_in_minutes(time_entry[\ 'timer_duration_in_minutes']) time_entry_obj.set_created_time(time_entry['created_time']) return time_entry_obj def get_comments(self, resp): """This method parses the given response and returns comments list object. Args: resp(dict): Response containing json object for comments list. Returns: list of instance: Comments list object. """ comments = CommentList() for value in resp['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_project_id(value['project_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_is_current_user(value['is_current_user']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comments.set_comments(comment) return comments def get_comment(self, resp): """This method parses the given response and returns comment object. Args: resp(dict): Response containing json object for comment object. Returns: instance: Comment object. """ comment = resp['comment'] comment_obj = Comment() comment_obj.set_comment_id(comment['comment_id']) comment_obj.set_project_id(comment['project_id']) comment_obj.set_description(comment['description']) comment_obj.set_commented_by_id(comment['commented_by_id']) comment_obj.set_commented_by(comment['commented_by']) comment_obj.set_date(comment['date']) comment_obj.set_date_description(comment['date_description']) comment_obj.set_time(comment['time']) return comment_obj def get_invoice_list(self, resp): """This method parses the given response and returns invoice list object. Args: resp(dict): Response containing json object for invoice list object. Returns: instance: Invoice list object. """ invoices = InvoiceList() for value in resp['invoices']: invoice = Invoice() invoice.set_invoice_id(value['invoice_id']) invoice.set_customer_name(value['customer_name']) invoice.set_customer_id(value['customer_id']) invoice.set_status(value['status']) invoice.set_invoice_number(value['invoice_number']) invoice.set_reference_number(value['reference_number']) invoice.set_date(value['date']) invoice.set_due_date(value['due_date']) invoice.set_total(value['total']) invoice.set_balance(value['balance']) invoice.set_created_time(value['created_time']) invoices.set_invoices(invoice) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) invoices.set_page_context(page_context) return invoices
# Copyright 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. import contextlib import json import mock import netaddr from neutron.api.v2 import attributes as neutron_attrs from neutron.common import exceptions from oslo_config import cfg from quark.db import models from quark.drivers import registry from quark import exceptions as q_exc from quark import network_strategy from quark.plugin_modules import ports as quark_ports from quark import plugin_views from quark import tags from quark.tests import test_quark_plugin class TestQuarkGetPorts(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, ports=None, addrs=None): port_models = [] addr_models = None if addrs: addr_models = [] for address in addrs: a = models.IPAddress(**address) addr_models.append(a) if isinstance(ports, list): for port in ports: port_model = models.Port(**port) if addr_models: port_model.ip_addresses = addr_models port_models.append(port_model) elif ports is None: port_models = None else: port_model = models.Port(**ports) if addr_models: port_model.ip_addresses = addr_models port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_find") ) as (port_find,): port_find.return_value = port_models yield def test_port_list_no_ports(self): with self._stubs(ports=[]): ports = self.plugin.get_ports(self.context, filters=None, fields=None) self.assertEqual(ports, []) def test_port_list_with_device_owner_dhcp(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100").value, address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) filters = {'network_id': ip['network_id'], 'device_owner': 'network:dhcp'} port = dict(mac_address="AA:BB:CC:DD:EE:FF", network_id=1, tenant_id=self.context.tenant_id, device_id=2, bridge="xenbr0", device_owner='network:dhcp') with self._stubs(ports=[port], addrs=[ip]): ports = self.plugin.get_ports(self.context, filters=filters, fields=None) self.assertEqual(len(ports), 1) self.assertEqual(ports[0]["device_owner"], "network:dhcp") def test_port_list_with_ports(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100").value, address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) port = dict(mac_address="AA:BB:CC:DD:EE:FF", network_id=1, tenant_id=self.context.tenant_id, device_id=2, bridge="xenbr0") expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': 1, 'bridge': "xenbr0", 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'device_id': 2} with self._stubs(ports=[port], addrs=[ip]): ports = self.plugin.get_ports(self.context, filters=None, fields=None) self.assertEqual(len(ports), 1) fixed_ips = ports[0].pop("fixed_ips") for key in expected.keys(): self.assertEqual(ports[0][key], expected[key]) self.assertEqual(fixed_ips[0]["subnet_id"], ip["subnet_id"]) self.assertEqual(fixed_ips[0]["ip_address"], ip["address_readable"]) def test_port_show_with_int_mac(self): port = dict(mac_address=int('AABBCCDDEEFF', 16), network_id=1, tenant_id=self.context.tenant_id, device_id=2) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': 1, 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2} with self._stubs(ports=port): result = self.plugin.get_port(self.context, 1) for key in expected.keys(): self.assertEqual(result[key], expected[key]) def test_port_show_not_found(self): with self._stubs(ports=None): with self.assertRaises(exceptions.PortNotFound): self.plugin.get_port(self.context, 1) def test_port_show_vlan_id(self): """Prove VLAN IDs are included in port information when available.""" port_tags = [tags.VlanTag().serialize(5)] port = dict(mac_address=int('AABBCCDDEEFF', 16), network_id=1, tenant_id=self.context.tenant_id, device_id=2, tags=port_tags) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': 1, 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2, 'vlan_id': '5'} with self._stubs(ports=port): result = self.plugin.get_port(self.context, 1) for key in expected.keys(): self.assertEqual(result[key], expected[key]) def test_port_show_invalid_vlan_id(self): """Prove VLAN IDs are included in port information when available.""" port_tags = [tags.VlanTag().serialize('invalid')] port = dict(mac_address=int('AABBCCDDEEFF', 16), network_id=1, tenant_id=self.context.tenant_id, device_id=2, tags=port_tags) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': 1, 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2} with self._stubs(ports=port): result = self.plugin.get_port(self.context, 1) for key in expected.keys(): self.assertEqual(result[key], expected[key]) class TestQuarkGetPortsProviderSubnetIds(test_quark_plugin.TestQuarkPlugin): def setUp(self): super(TestQuarkGetPortsProviderSubnetIds, self).setUp() self.strategy = { "1": { "bridge": "publicnet", "subnets": { "4": "v4-provider-subnet-id", "6": "v6-provider-subnet-id" } } } self.strategy_json = json.dumps(self.strategy) self.old = plugin_views.STRATEGY plugin_views.STRATEGY = network_strategy.JSONStrategy( self.strategy_json) cfg.CONF.set_override("default_net_strategy", self.strategy_json, "QUARK") def tearDown(self): plugin_views.STRATEGY = self.old def _port_associate_stub(self, ports, address, **kwargs): if not isinstance(ports, list): ports = [ports] for port in ports: assoc = models.PortIpAssociation() assoc.port_id = port.id assoc.ip_address_id = address.id assoc.port = port assoc.ip_address = address assoc.enabled = address.address_type == "fixed" return address @contextlib.contextmanager def _stubs(self, ports=None, addrs=None): port_models = [] addr_models = None if addrs: addr_models = [] for address in addrs: a = models.IPAddress(**address) addr_models.append(a) if isinstance(ports, list): for port in ports: port_model = models.Port(**port) if addr_models: port_model.ip_addresses = addr_models for addr_model in addr_models: self._port_associate_stub( port_model, addr_model) port_models.append(port_model) elif ports is None: port_models = None else: port_model = models.Port(**ports) if addr_models: port_model.ip_addresses = addr_models for addr_model in addr_models: self._port_associate_stub( port_model, addr_model) port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_find") ) as (port_find,): port_find.return_value = port_models yield def test_port_show_with_provider_subnet_ids(self): """Prove provider subnets ids are shown on the port object.""" ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100").value, address_readable="192.168.1.100", subnet_id="1", network_id="1", version=4, address_type="fixed") port = dict(mac_address=int('AABBCCDDEEFF', 16), network_id="1", tenant_id=self.context.tenant_id, device_id=2) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': "1", 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [ {'subnet_id': 'v4-provider-subnet-id', 'enabled': True, 'ip_address': '192.168.1.100'} ], 'device_id': 2} with self._stubs(ports=port, addrs=[ip]): result = self.plugin.get_port(self.context, 1) for key in expected.keys(): self.assertEqual(result[key], expected[key]) def test_port_show_without_provider_subnet_ids(self): """Prove provider subnets ids are shown on the port object.""" cfg.CONF.set_override('show_provider_subnet_ids', False, 'QUARK') self.addCleanup( cfg.CONF.clear_override, 'show_provider_subnet_ids', 'QUARK') ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100").value, address_readable="192.168.1.100", subnet_id="1", network_id="1", version=4, address_type="fixed") port = dict(mac_address=int('AABBCCDDEEFF', 16), network_id="1", tenant_id=self.context.tenant_id, device_id=2) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': 'AA:BB:CC:DD:EE:FF', 'network_id': "1", 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [ {'subnet_id': '1', 'enabled': True, 'ip_address': '192.168.1.100'} ], 'device_id': 2} with self._stubs(ports=port, addrs=[ip]): result = self.plugin.get_port(self.context, 1) for key in expected.keys(): self.assertEqual(result[key], expected[key]) class TestQuarkGetPortsByIPAddress(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, ports=None, addr=None): addr_models = [] for port in ports: ip_mod = models.IPAddress() ip_mod.update(addr) port_model = models.Port() port_model.update(port) ip_mod.ports = [port_model] addr_models.append(ip_mod) with contextlib.nested( mock.patch("quark.db.api.port_find_by_ip_address") ) as (port_find_by_addr,): port_find_by_addr.return_value = addr_models yield def test_port_list_by_ip_address(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100").value, address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) port = dict(mac_address="AA:BB:CC:DD:EE:FF", network_id=1, tenant_id=self.context.tenant_id, device_id=2, bridge="xenbr0", device_owner='network:dhcp') with self._stubs(ports=[port], addr=ip): admin_ctx = self.context.elevated() filters = {"ip_address": ["192.168.0.1"]} ports = self.plugin.get_ports(admin_ctx, filters=filters, fields=None) self.assertEqual(len(ports), 1) self.assertEqual(ports[0]["device_owner"], "network:dhcp") def test_port_list_by_ip_not_admin_raises(self): with self._stubs(ports=[]): filters = {"ip_address": ["192.168.0.1"]} with self.assertRaises(exceptions.NotAuthorized): self.plugin.get_ports(self.context, filters=filters, fields=None) def test_port_list_malformed_address_bad_request(self): with self._stubs(ports=[]): filters = {"ip_address": ["malformed-address-here"]} admin_ctx = self.context.elevated() with self.assertRaises(exceptions.BadRequest): self.plugin.get_ports(admin_ctx, filters=filters, fields=None) class TestQuarkCreatePortFailure(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None): if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port) port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("quark.db.api.port_find"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.allocate_mac_address"), mock.patch("quark.db.api.port_count_all"), ) as (port_create, net_find, port_find, alloc_ip, alloc_mac, port_count): port_create.return_value = port_models net_find.return_value = network port_find.return_value = models.Port() alloc_ip.return_value = addr alloc_mac.return_value = mac port_count.return_value = 0 yield port_create def test_create_multiple_ports_on_same_net_and_device_id_bad_request(self): network = dict(id=1, tenant_id=self.context.tenant_id) ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=1, tenant_id=self.context.tenant_id, device_id=1, name="Fake")) port_2 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:11", network_id=1, tenant_id=self.context.tenant_id, device_id=1, name="Faker")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.BadRequest): self.plugin.create_port(self.context, port_1) self.plugin.create_port(self.context, port_2) class TestQuarkCreatePortRM9305(test_quark_plugin.TestQuarkPlugin): def setUp(self): super(TestQuarkCreatePortRM9305, self).setUp() strategy = {"00000000-0000-0000-0000-000000000000": {"bridge": "publicnet", "subnets": {"4": "public_v4", "6": "public_v6"}}, "11111111-1111-1111-1111-111111111111": {"bridge": "servicenet", "subnets": {"4": "private_v4", "6": "private_v6"}}} strategy_json = json.dumps(strategy) quark_ports.STRATEGY = network_strategy.JSONStrategy(strategy_json) @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None): if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port) port_models = port_model db_mod = "quark.db.api" ipam = "quark.ipam.QuarkIpam" with contextlib.nested( mock.patch("%s.port_create" % db_mod), mock.patch("%s.network_find" % db_mod), mock.patch("%s.port_find" % db_mod), mock.patch("%s.allocate_ip_address" % ipam), mock.patch("%s.allocate_mac_address" % ipam), mock.patch("%s.port_count_all" % db_mod), ) as (port_create, net_find, port_find, alloc_ip, alloc_mac, port_count): port_create.return_value = port_models net_find.return_value = network port_find.return_value = None alloc_ip.return_value = addr alloc_mac.return_value = mac port_count.return_value = 0 yield port_create def test_RM9305_tenant_create_servicenet_port(self): network_id = "11111111-1111-1111-1111-111111111111" network = dict(id=network_id, tenant_id="rackspace") ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=self.context.tenant_id, device_id=2, segment_id="bar", name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): self.plugin.create_port(self.context, port_1) def test_RM9305_tenant_create_publicnet_port(self): network_id = "00000000-0000-0000-0000-000000000000" network = dict(id=network_id, tenant_id="rackspace") ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=self.context.tenant_id, device_id=3, segment_id="bar", name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): self.plugin.create_port(self.context, port_1) def test_RM9305_tenant_create_tenants_port(self): network_id = "foobar" network = dict(id=network_id, tenant_id=self.context.tenant_id) ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=self.context.tenant_id, device_id=4, name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): self.plugin.create_port(self.context, port_1) def test_RM9305_tenant_create_other_tenants_port(self): network_id = "foobar" network = dict(id=network_id, tenant_id="other_tenant") ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=self.context.tenant_id, device_id=5, name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.NotAuthorized): self.plugin.create_port(self.context, port_1) class TestQuarkCreatePortsSameDevBadRequest(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None, limit_checks=None, subnet=None): subnet_model = None if subnet: subnet_model = models.Subnet() subnet_model.update(subnet) if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" def _create_db_port(context, **kwargs): port_model = models.Port() port_model.update(kwargs) return port_model def _alloc_ip(context, new_ips, *args, **kwargs): ip_mod = models.IPAddress() ip_mod.update(addr) ip_mod.enabled_for_port = lambda x: True new_ips.extend([ip_mod]) return mock.DEFAULT with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.allocate_mac_address"), mock.patch("quark.db.api.port_count_all"), mock.patch("neutron.quota.QuotaEngine.limit_check"), mock.patch("quark.db.api.subnet_find"), ) as (port_create, net_find, alloc_ip, alloc_mac, port_count, limit_check, subnet_find): port_create.side_effect = _create_db_port net_find.return_value = network alloc_ip.side_effect = _alloc_ip alloc_mac.return_value = mac if subnet: subnet_find.return_value = [subnet_model] port_count.return_value = 0 if limit_checks: limit_check.side_effect = limit_checks yield port_create def test_create_port(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name)) expected = {'status': "ACTIVE", 'name': port_name, 'device_owner': None, 'mac_address': mac["address"], 'network_id': network["id"], 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2} with self._stubs(port=port["port"], network=network, addr=ip, mac=mac) as port_create: result = self.plugin.create_port(self.context, port) self.assertTrue(port_create.called) for key in expected.keys(): self.assertEqual(result[key], expected[key]) def test_create_port_segment_id_on_unshared_net_ignored(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, segment_id="cell01", name=port_name)) expected = {'status': "ACTIVE", 'name': port_name, 'device_owner': None, 'mac_address': mac["address"], 'network_id': network["id"], 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2} with self._stubs(port=port["port"], network=network, addr=ip, mac=mac) as port_create: result = self.plugin.create_port(self.context, port) self.assertTrue(port_create.called) for key in expected.keys(): self.assertEqual(result[key], expected[key]) def test_create_port_mac_address_not_specified(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2)) expected = {'status': "ACTIVE", 'device_owner': None, 'mac_address': mac["address"], 'network_id': network["id"], 'tenant_id': self.context.tenant_id, 'admin_state_up': None, 'fixed_ips': [], 'device_id': 2} with self._stubs(port=port["port"], network=network, addr=ip, mac=mac) as port_create: port["port"]["mac_address"] = neutron_attrs.ATTR_NOT_SPECIFIED result = self.plugin.create_port(self.context, port) self.assertTrue(port_create.called) for key in expected.keys(): self.assertEqual(result[key], expected[key]) @mock.patch("quark.network_strategy.JSONStrategy.is_provider_network") def test_create_providernet_port_fixed_ip_not_authorized(self, is_parent): is_parent.return_value = True network = dict(id='1', tenant_id=self.context.tenant_id) subnet = dict(id=1, network_id=network["id"]) mac = dict(address="AA:BB:CC:DD:EE:FF") ip = mock.MagicMock() ip.get = lambda x, *y: 1 if x == "subnet_id" else None ip.formatted = lambda: "192.168.10.45" ip.enabled_for_port = lambda x: True fixed_ips = [dict(subnet_id=1, enabled=True, ip_address="192.168.10.45")] port = dict(port=dict(mac_address=mac["address"], network_id='1', tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips, ip_addresses=[ip], segment_id="provider_segment")) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac, subnet=subnet): with self.assertRaises(exceptions.NotAuthorized): self.plugin.create_port(self.context, port) @mock.patch("quark.network_strategy.JSONStrategy.is_provider_network") def test_create_providernet_port_fixed_ip_wrong_segment(self, is_parent): is_parent.return_value = True network = dict(id='1', tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") subnet = dict(id=1, network_id=network["id"]) ip = mock.MagicMock() ip.get = lambda x, *y: 1 if x == "subnet_id" else None ip.formatted = lambda: "192.168.10.45" ip.enabled_for_port = lambda x: True fixed_ips = [dict(subnet_id=1, enabled=True, ip_address="192.168.10.45")] port = dict(port=dict(mac_address=mac["address"], network_id='1', tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips, ip_addresses=[ip], segment_id="provider_segment")) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac, subnet=subnet): with self.assertRaises(q_exc.AmbiguousNetworkId): self.plugin.create_port(self.context.elevated(), port) def test_create_port_fixed_ip_subnet_not_found(self): network = dict(id='1', tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") ip = mock.MagicMock() ip.get = lambda x, *y: 1 if x == "subnet_id" else None ip.formatted = lambda: "192.168.10.45" ip.enabled_for_port = lambda x: True fixed_ips = [dict(subnet_id=1, enabled=True, ip_address="192.168.10.45")] port = dict(port=dict(mac_address=mac["address"], network_id='1', tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips, ip_addresses=[ip], segment_id="provider_segment")) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.NotFound): self.plugin.create_port(self.context.elevated(), port) def test_create_port_fixed_ip_subnet_not_in_network(self): network = dict(id='1', tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") subnet = dict(id=1, network_id='2') ip = mock.MagicMock() ip.get = lambda x, *y: 1 if x == "subnet_id" else None ip.formatted = lambda: "192.168.10.45" ip.enabled_for_port = lambda x: True fixed_ips = [dict(subnet_id=1, enabled=True, ip_address="192.168.10.45")] port = dict(port=dict(mac_address=mac["address"], network_id='1', tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips, ip_addresses=[ip], segment_id="provider_segment")) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac, subnet=subnet): with self.assertRaises(exceptions.InvalidInput): self.plugin.create_port(self.context.elevated(), port) def test_create_port_fixed_ips_bad_request(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") ip = mock.MagicMock() ip.get = lambda x: 1 if x == "subnet_id" else None ip.formatted = lambda: "192.168.10.45" fixed_ips = [dict()] port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips, ip_addresses=[ip])) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.BadRequest): self.plugin.create_port(self.context, port) def test_create_port_no_network_found(self): port = dict(port=dict(network_id=1, tenant_id=self.context.tenant_id, device_id=2)) with self._stubs(network=None, port=port["port"]): with self.assertRaises(exceptions.NetworkNotFound): self.plugin.create_port(self.context, port) def test_create_port_security_groups_raises(self, groups=[1]): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() group = models.SecurityGroup() group.update({'id': 1, 'tenant_id': self.context.tenant_id, 'name': 'foo', 'description': 'bar'}) port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, security_groups=[group])) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): with mock.patch("quark.db.api.security_group_find"): with self.assertRaises(q_exc.SecurityGroupsNotImplemented): self.plugin.create_port(self.context, port) class TestQuarkPortCreateQuota(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None): if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port) port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.allocate_mac_address"), mock.patch("quark.db.api.port_count_all"), mock.patch("neutron.quota.QuotaEngine.limit_check") ) as (port_create, net_find, alloc_ip, alloc_mac, port_count, limit_check): port_create.return_value = port_models net_find.return_value = network alloc_ip.return_value = addr alloc_mac.return_value = mac port_count.return_value = len(network["ports"]) limit_check.side_effect = exceptions.OverQuota yield port_create def test_create_port_net_at_max(self): network = dict(id=1, ports=[models.Port()], tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name)) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.OverQuota): self.plugin.create_port(self.context, port) class TestQuarkPortCreateFixedIpsQuota(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, network): network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" with mock.patch("quark.db.api.network_find") as net_find: net_find.return_value = network yield def test_create_port_fixed_ips_over_quota(self): network = {"id": 1, "tenant_id": self.context.tenant_id} fixed_ips = [{"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}] port = {"port": {"network_id": 1, "tenant_id": self.context.tenant_id, "device_id": 2, "fixed_ips": fixed_ips}} with self._stubs(network=network): with self.assertRaises(exceptions.OverQuota): self.plugin.create_port(self.context, port) class TestQuarkUpdatePort(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port, new_ips=None, parent_net=False): port_model = None if port: net_model = models.Network() net_model["network_plugin"] = "BASE" port_model = models.Port() port_model.network = net_model port_model.update(port) with contextlib.nested( mock.patch("quark.db.api.port_find"), mock.patch("quark.db.api.port_update"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.deallocate_ips_by_port"), ) as (port_find, port_update, alloc_ip, dealloc_ip): port_find.return_value = port_model port_update.return_value = port_model if new_ips: alloc_ip.return_value = new_ips yield port_find, port_update, alloc_ip, dealloc_ip def test_update_port_not_found(self): with self._stubs(port=None): with self.assertRaises(exceptions.PortNotFound): self.plugin.update_port(self.context, 1, {}) def test_update_port(self): with self._stubs( port=dict(id=1, name="myport") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict(name="ourport")) self.plugin.update_port(self.context, 1, new_port) self.assertEqual(port_find.call_count, 2) port_update.assert_called_once_with( self.context, port_find(), name="ourport", security_groups=[]) def test_update_port_fixed_ip_bad_request(self): with self._stubs( port=dict(id=1, name="myport") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=None, ip_address=None)])) with self.assertRaises(exceptions.BadRequest): self.plugin.update_port(self.context, 1, new_port) def test_update_port_fixed_ip_bad_request_malformed_address(self): with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=1, ip_address="malformed-address-here")])) with self.assertRaises(exceptions.BadRequest): self.plugin.update_port(self.context, 1, new_port) def test_update_port_fixed_ip(self): with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=1, ip_address="1.1.1.1")])) self.plugin.update_port(self.context, 1, new_port) self.assertEqual(alloc_ip.call_count, 1) def test_update_port_fixed_ip_no_subnet_raises(self): with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(ip_address="1.1.1.1")])) with self.assertRaises(exceptions.BadRequest): self.plugin.update_port(self.context, 1, new_port) def test_update_port_fixed_ip_subnet_only_allocates_ip(self): with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=1)])) self.plugin.update_port(self.context, 1, new_port) self.assertEqual(alloc_ip.call_count, 1) def test_update_port_fixed_ip_allocs_new_deallocs_existing(self): addr_dict = {"address": 0, "address_readable": "0.0.0.0"} addr = models.IPAddress() addr.update(addr_dict) new_addr_dict = {"address": netaddr.IPAddress("1.1.1.1"), "address_readable": "1.1.1.1"} new_addr = models.IPAddress() new_addr.update(new_addr_dict) with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1", ip_addresses=[addr]), new_ips=[new_addr] ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=1, ip_address=new_addr["address_readable"])])) self.plugin.update_port(self.context, 1, new_port) self.assertEqual(alloc_ip.call_count, 1) def test_update_port_goes_over_quota(self): fixed_ips = {"fixed_ips": [{"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}, {"subnet_id": 1}]} with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1") ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = {"port": fixed_ips} with self.assertRaises(exceptions.OverQuota): self.plugin.update_port(self.context, 1, new_port) class TestQuarkUpdatePortSecurityGroups(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port, new_ips=None, parent_net=False): port_model = None sg_mod = models.SecurityGroup() if port: net_model = models.Network() net_model["network_plugin"] = "BASE" port_model = models.Port() port_model.network = net_model port_model.update(port) port_model["security_groups"].append(sg_mod) with contextlib.nested( mock.patch("quark.db.api.port_find"), mock.patch("quark.db.api.port_update"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.deallocate_ips_by_port"), mock.patch("neutron.quota.QuotaEngine.limit_check"), mock.patch("quark.plugin_modules.ports.STRATEGY" ".is_provider_network"), mock.patch("quark.db.api.security_group_find"), mock.patch("quark.drivers.base.BaseDriver.update_port") ) as (port_find, port_update, alloc_ip, dealloc_ip, limit_check, net_strat, sg_find, driver_port_update): port_find.return_value = port_model def _port_update(context, port_db, **kwargs): return port_db.update(kwargs) port_update.side_effect = _port_update if new_ips: alloc_ip.return_value = new_ips net_strat.return_value = parent_net sg_find.return_value = sg_mod yield (port_find, port_update, alloc_ip, dealloc_ip, sg_find, driver_port_update) def test_update_port_security_groups(self): with self._stubs( port=dict(id=1, device_id="device"), parent_net=True ) as (port_find, port_update, alloc_ip, dealloc_ip, sg_find, driver_port_update): new_port = dict(port=dict(name="ourport", security_groups=[1])) port = self.plugin.update_port(self.context, 1, new_port) port_update.assert_called_once_with( self.context, port_find(), name="ourport", security_groups=[sg_find()]) self.assertEqual(sg_find()["id"], port["security_groups"][0]) def test_update_port_empty_list_security_groups(self): port_dict = {"id": 1, "mac_address": "AA:BB:CC:DD:EE:FF", "device_id": 2, "backend_key": 3} with self._stubs( port=port_dict, parent_net=True ) as (port_find, port_update, alloc_ip, dealloc_ip, sg_find, driver_port_update): new_port = dict(port=dict(name="ourport", security_groups=[])) port = self.plugin.update_port(self.context, 1, new_port) self.assertEqual(port["security_groups"], []) port_update.assert_called_once_with( self.context, port_find(), name="ourport", security_groups=[]) driver_port_update.assert_called_once_with( self.context, port_id=port_dict["backend_key"], mac_address=port_dict["mac_address"], device_id=port_dict["device_id"], security_groups=[], base_net_driver=registry.DRIVER_REGISTRY.get_driver('BASE')) def test_update_port_no_security_groups(self): port_dict = {"id": 1, "mac_address": "AA:BB:CC:DD:EE:FF", "device_id": 2, "backend_key": 3} with self._stubs( port=port_dict, parent_net=True ) as (port_find, port_update, alloc_ip, dealloc_ip, sg_find, driver_port_update): new_port = dict(port=dict(name="ourport")) self.plugin.update_port(self.context, 1, new_port) driver_port_update.assert_called_once_with( self.context, port_id=port_dict["backend_key"], mac_address=port_dict["mac_address"], device_id=port_dict["device_id"], base_net_driver=registry.DRIVER_REGISTRY.get_driver('BASE')) def test_update_port_security_groups_no_device_id_raises(self): with self._stubs( port=dict(id=1), parent_net=True ) as (port_find, port_update, alloc_ip, dealloc_ip, sg_find, driver_port_update): new_port = dict(port=dict(name="ourport", security_groups=[1])) with self.assertRaises(q_exc.SecurityGroupsRequireDevice): self.plugin.update_port(self.context, 1, new_port) class TestQuarkUpdatePortSetsIps(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port, new_ips=None): def alloc_mock(kls, context, addresses, *args, **kwargs): addresses.extend(new_ips) self.called = True port_model = None if port: net_model = models.Network() net_model["network_plugin"] = "BASE" port_model = models.Port() port_model['network'] = net_model port_model.update(port) with contextlib.nested( mock.patch("quark.db.api.port_find"), mock.patch("quark.db.api.port_update"), mock.patch("quark.ipam.QuarkIpam.deallocate_ips_by_port"), mock.patch("neutron.quota.QuotaEngine.limit_check") ) as (port_find, port_update, dealloc_ip, limit_check): port_find.return_value = port_model port_update.return_value = port_model alloc_ip = mock.patch("quark.ipam.QuarkIpam.allocate_ip_address", new=alloc_mock) alloc_ip.start() yield port_find, port_update, alloc_ip, dealloc_ip alloc_ip.stop() def test_update_port_fixed_ip_subnet_only_allocates_ip(self): self.called = False new_addr_dict = {"address": netaddr.IPAddress('1.1.1.1'), "address_readable": "1.1.1.1"} new_addr = models.IPAddress() new_addr.update(new_addr_dict) with self._stubs( port=dict(id=1, name="myport", mac_address="0:0:0:0:0:1"), new_ips=[new_addr] ) as (port_find, port_update, alloc_ip, dealloc_ip): new_port = dict(port=dict( fixed_ips=[dict(subnet_id=1)])) self.plugin.update_port(self.context, 1, new_port) self.assertTrue(self.called) class TestQuarkCreatePortOnSharedNetworks(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None): self.strategy = {"public_network": {"bridge": "xenbr0", "subnets": {"4": "public_v4", "6": "public_v6"}}} strategy_json = json.dumps(self.strategy) quark_ports.STRATEGY = network_strategy.JSONStrategy(strategy_json) if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port) port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.allocate_mac_address"), mock.patch("neutron.quota.QuotaEngine.limit_check") ) as (port_create, net_find, alloc_ip, alloc_mac, limit_check): port_create.return_value = port_models net_find.return_value = network alloc_ip.return_value = addr alloc_mac.return_value = mac yield port_create def test_create_port_shared_net_no_quota_check(self): network = dict(id=1, ports=[models.Port()], tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id="public_network", tenant_id=self.context.tenant_id, device_id=2, segment_id="cell01", name=port_name)) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): try: self.plugin.create_port(self.context, port) except Exception: self.fail("create_port raised OverQuota") def test_create_port_shared_net_no_segment_id_fails(self): network = dict(id=1, ports=[models.Port()], tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id="public_network", tenant_id=self.context.tenant_id, device_id=2, name=port_name)) with self._stubs(port=port["port"], network=network, addr=ip, mac=mac): with self.assertRaises(q_exc.AmbiguousNetworkId): self.plugin.create_port(self.context, port) class TestQuarkGetPortCount(test_quark_plugin.TestQuarkPlugin): def test_get_port_count(self): """This isn't really testable.""" with mock.patch("quark.db.api.port_count_all"): self.plugin.get_ports_count(self.context, {}) class TestQuarkDeletePort(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, addr=None, mac=None): port_models = None if port: net_model = models.Network() net_model["network_plugin"] = "BASE" net_model["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port) port_model.network = net_model port_models = port_model with contextlib.nested( mock.patch("quark.db.api.port_find"), mock.patch("quark.ipam.QuarkIpam.deallocate_ips_by_port"), mock.patch("quark.ipam.QuarkIpam.deallocate_mac_address"), mock.patch("quark.db.api.port_delete"), mock.patch("quark.drivers.base.BaseDriver.delete_port") ) as (port_find, dealloc_ip, dealloc_mac, db_port_del, driver_port_del): port_find.return_value = port_models dealloc_ip.return_value = addr dealloc_mac.return_value = mac yield db_port_del, driver_port_del def test_port_delete(self): port = dict(port=dict(network_id=1, tenant_id=self.context.tenant_id, device_id=2, mac_address="AA:BB:CC:DD:EE:FF", backend_key="foo")) with self._stubs(port=port["port"]) as (db_port_del, driver_port_del): self.plugin.delete_port(self.context, 1) self.assertTrue(db_port_del.called) driver_port_del.assert_called_with( self.context, "foo", mac_address=port["port"]["mac_address"], device_id=port["port"]["device_id"], base_net_driver=registry.DRIVER_REGISTRY.get_driver("BASE")) def test_port_delete_port_not_found_fails(self): with self._stubs(port=None) as (db_port_del, driver_port_del): with self.assertRaises(exceptions.PortNotFound): self.plugin.delete_port(self.context, 1) class TestPortDiagnose(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port, list_format=False): port_res = None if port: network_mod = models.Network() port_mod = models.Port() port_mod.update(port) network_mod["network_plugin"] = "UNMANAGED" port_mod.network = network_mod port_res = port_mod if list_format: ports = mock.MagicMock() ports.all.return_value = [port_mod] port_res = ports with mock.patch("quark.db.api.port_find") as port_find: port_find.return_value = port_res yield def test_port_diagnose(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100"), address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) fixed_ips = [{"subnet_id": ip["subnet_id"], "ip_address": ip["address_readable"]}] port = dict(port=dict(network_id=1, tenant_id=self.context.tenant_id, device_id=2, mac_address="AA:BB:CC:DD:EE:FF", backend_key="foo", fixed_ips=fixed_ips, network_plugin="UNMANAGED")) with self._stubs(port=port): diag = self.plugin.diagnose_port(self.context.elevated(), 1, []) ports = diag["ports"] # All none because we're using the unmanaged driver, which # doesn't do anything with these self.assertEqual(ports["status"], "ACTIVE") self.assertEqual(ports["device_owner"], None) self.assertEqual(ports["fixed_ips"], []) self.assertEqual(ports["security_groups"], []) self.assertEqual(ports["device_id"], None) self.assertEqual(ports["admin_state_up"], None) self.assertEqual(ports["network_id"], None) self.assertEqual(ports["tenant_id"], None) self.assertEqual(ports["mac_address"], None) def test_port_diagnose_with_wildcard(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100"), address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) fixed_ips = [{"subnet_id": ip["subnet_id"], "ip_address": ip["address_readable"]}] port = dict(port=dict(network_id=1, tenant_id=self.context.tenant_id, device_id=2, mac_address="AA:BB:CC:DD:EE:FF", backend_key="foo", fixed_ips=fixed_ips, network_plugin="UNMANAGED")) with self._stubs(port=port, list_format=True): diag = self.plugin.diagnose_port(self.context.elevated(), '*', []) ports = diag["ports"] # All none because we're using the unmanaged driver, which # doesn't do anything with these self.assertEqual(ports[0]["status"], "ACTIVE") self.assertEqual(ports[0]["device_owner"], None) self.assertEqual(ports[0]["fixed_ips"], []) self.assertEqual(ports[0]["security_groups"], []) self.assertEqual(ports[0]["device_id"], None) self.assertEqual(ports[0]["admin_state_up"], None) self.assertEqual(ports[0]["network_id"], None) self.assertEqual(ports[0]["tenant_id"], None) self.assertEqual(ports[0]["mac_address"], None) def test_port_diagnose_with_config_field(self): ip = dict(id=1, address=netaddr.IPAddress("192.168.1.100"), address_readable="192.168.1.100", subnet_id=1, network_id=2, version=4) fixed_ips = [{"subnet_id": ip["subnet_id"], "ip_address": ip["address_readable"]}] port = dict(port=dict(network_id=1, tenant_id=self.context.tenant_id, device_id=2, mac_address="AA:BB:CC:DD:EE:FF", backend_key="foo", fixed_ips=fixed_ips, network_plugin="UNMANAGED")) with self._stubs(port=port, list_format=True): diag = self.plugin.diagnose_port(self.context.elevated(), '*', ["config"]) ports = diag["ports"] # All none because we're using the unmanaged driver, which # doesn't do anything with these self.assertEqual(ports[0]["status"], "ACTIVE") self.assertEqual(ports[0]["device_owner"], None) self.assertEqual(ports[0]["fixed_ips"], []) self.assertEqual(ports[0]["security_groups"], []) self.assertEqual(ports[0]["device_id"], None) self.assertEqual(ports[0]["admin_state_up"], None) self.assertEqual(ports[0]["network_id"], None) self.assertEqual(ports[0]["tenant_id"], None) self.assertEqual(ports[0]["mac_address"], None) def test_port_diagnose_no_port_raises(self): with self._stubs(port=None): with self.assertRaises(exceptions.PortNotFound): self.plugin.diagnose_port(self.context.elevated(), 1, []) def test_port_diagnose_not_authorized(self): with self._stubs(port=None): with self.assertRaises(exceptions.NotAuthorized): self.plugin.diagnose_port(self.context, 1, []) class TestPortDriverSelection(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, network=None, addr=None, mac=None, compat_map=None, driver_res=None, ipam="FOO"): network["ipam_strategy"] = "FOO" # Response from the backend driver self.expected_bridge = "backend-drivers-bridge" if driver_res is None: driver_res = {"uuid": 1, "bridge": self.expected_bridge} # Mock out the driver registry foo_driver = mock.Mock() foo_driver.create_port.return_value = driver_res foo_driver.select_ipam_strategy.return_value = "FOO" bar_driver = mock.Mock() bar_driver.create_port.return_value = driver_res bar_driver.select_ipam_strategy.return_value = "BAR" drivers = {"FOO": foo_driver, "BAR": bar_driver} compat_map = compat_map or {} # Mock out the IPAM registry foo_ipam = mock.Mock() foo_ipam.allocate_ip_address.return_value = addr foo_ipam.allocate_mac_address.return_value = mac bar_ipam = mock.Mock() bar_ipam.allocate_ip_address.return_value = addr bar_ipam.allocate_mac_address.return_value = mac ipam = {"FOO": foo_ipam, "BAR": bar_ipam} with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("oslo_utils.uuidutils.generate_uuid"), mock.patch("quark.plugin_views._make_port_dict"), mock.patch("quark.db.api.port_count_all"), mock.patch("neutron.quota.QuotaEngine.limit_check"), mock.patch("quark.plugin_modules.ports.registry." "DRIVER_REGISTRY.drivers", new_callable=mock.PropertyMock(return_value=drivers)), mock.patch("quark.plugin_modules.ports.registry." "DRIVER_REGISTRY.port_driver_compat_map", new_callable=mock.PropertyMock( return_value=compat_map)), mock.patch("quark.plugin_modules.ports.ipam." "IPAM_REGISTRY.strategies", new_callable=mock.PropertyMock(return_value=ipam)) ) as (port_create, net_find, gen_uuid, make_port, port_count, limit_check, _, _, _): net_find.return_value = network gen_uuid.return_value = 1 port_count.return_value = 0 yield (port_create, ipam, net_find) def test_create_port_with_bad_network_plugin_fails(self): network_dict = dict(id=1, tenant_id=self.context.tenant_id) port_name = "foobar" mac = dict(address="AA:BB:CC:DD:EE:FF") ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name)) network = models.Network() network.update(network_dict) network["network_plugin"] = "FAIL" port_model = models.Port() port_model.update(port) port_models = port_model with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): port_create.return_value = port_models exc = "Driver FAIL is not registered." with self.assertRaisesRegexp(exceptions.BadRequest, exc): self.plugin.create_port(self.context, port) def test_create_port_with_bad_port_network_plugin_fails(self): network_dict = dict(id=1, tenant_id=self.context.tenant_id) port_name = "foobar" mac = dict(address="AA:BB:CC:DD:EE:FF") ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, network_plugin="FAIL")) network = models.Network() network.update(network_dict) network["network_plugin"] = "FOO" port_model = models.Port() port_model.update(port) port_models = port_model with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): port_create.return_value = port_models exc = "Driver FAIL is not registered." admin_ctx = self.context.elevated() with self.assertRaisesRegexp(exceptions.BadRequest, exc): self.plugin.create_port(admin_ctx, port) def test_create_port_with_incompatable_port_network_plugin_fails(self): network_dict = dict(id=1, tenant_id=self.context.tenant_id) port_name = "foobar" mac = dict(address="AA:BB:CC:DD:EE:FF") ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, network_plugin="BAR")) network = models.Network() network.update(network_dict) network["network_plugin"] = "FOO" port_model = models.Port() port_model.update(port) port_models = port_model with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): port_create.return_value = port_models exc = ("Port driver BAR not allowed for underlying network " "driver FOO.") admin_ctx = self.context.elevated() with self.assertRaisesRegexp(exceptions.BadRequest, exc): self.plugin.create_port(admin_ctx, port) def test_create_port_with_no_port_network_plugin(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="FOO") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["BAR"].allocate_mac_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["FOO"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=self.expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], instance_node_id='', network_plugin="FOO") def test_create_port_with_port_network_plugin(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="FOO") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" expected_network_plugin = "FOO" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state port_create_dict["port"]["network_plugin"] = expected_network_plugin admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["BAR"].allocate_mac_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["FOO"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=self.expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], instance_node_id='', network_plugin=expected_network_plugin) def test_create_port_with_compatible_port_network_plugin(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="FOO") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" expected_network_plugin = "BAR" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state port_create_dict["port"]["network_plugin"] = expected_network_plugin compat_map = {"BAR": ["FOO"]} admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac, compat_map=compat_map) as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["FOO"].allocate_mac_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["BAR"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=self.expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], instance_node_id='', network_plugin=expected_network_plugin) def test_create_port_ipam_selection(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="FOO") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac) as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["BAR"].allocate_mac_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["FOO"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=self.expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], instance_node_id='', network_plugin="FOO") def test_create_port_ipam_selection_override_by_driver(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="BAR") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac, ipam="BAR") as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["FOO"].allocate_mac_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["BAR"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=self.expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], instance_node_id='', network_plugin="BAR") def test_create_port_network_plugin_response_no_uuid_raises(self): network_dict = dict(id=1, tenant_id=self.context.tenant_id) port_name = "foobar" mac = dict(address="AA:BB:CC:DD:EE:FF") ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name)) network = models.Network() network.update(network_dict) network["network_plugin"] = "FOO" port_model = models.Port() port_model.update(port) port_models = port_model with self._stubs(network=network, addr=ip, mac=mac, driver_res={}) as (port_create, alloc_mac, net_find): port_create.return_value = port_models exc = "uuid" with self.assertRaisesRegexp(KeyError, exc): self.plugin.create_port(self.context, port) def test_create_port_network_plugin_response_is_filtered(self): network = dict(id=1, tenant_id=self.context.tenant_id, network_plugin="FOO") mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state driver_res = { "uuid": 5, "vlan_id": 50, "tags": [123, {"foo": "bar"}], "id": "fail", "randomkey": None } admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac, driver_res=driver_res) as (port_create, ipam, net_find): self.plugin.create_port(admin_ctx, port_create_dict) ipam["BAR"].allocate_mac_address.assert_not_called() ipam["BAR"].allocate_ip_address.assert_not_called() ipam["FOO"].allocate_ip_address.assert_called_once_with( admin_ctx, [], network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, segment_id=None, mac_address=mac) ipam["FOO"].allocate_mac_address.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=expected_bridge, uuid=5, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=5, security_groups=[], addresses=[], vlan_id=50, network_plugin=network["network_plugin"], instance_node_id='') class TestQuarkPortCreateFiltering(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, network=None, addr=None, mac=None): network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" with contextlib.nested( mock.patch("quark.db.api.port_create"), mock.patch("quark.db.api.network_find"), mock.patch("quark.ipam.QuarkIpam.allocate_ip_address"), mock.patch("quark.ipam.QuarkIpam.allocate_mac_address"), mock.patch("oslo_utils.uuidutils.generate_uuid"), mock.patch("quark.plugin_views._make_port_dict"), mock.patch("quark.db.api.port_count_all"), mock.patch("neutron.quota.QuotaEngine.limit_check") ) as (port_create, net_find, alloc_ip, alloc_mac, gen_uuid, make_port, port_count, limit_check): net_find.return_value = network alloc_ip.return_value = addr alloc_mac.return_value = mac gen_uuid.return_value = 1 port_count.return_value = 0 yield port_create, alloc_mac, net_find def test_create_port_attribute_filtering(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = "DE:AD:BE:EF:00:00" port_create_dict["port"]["device_owner"] = "ignored" port_create_dict["port"]["bridge"] = "ignored" port_create_dict["port"]["admin_state_up"] = "ignored" port_create_dict["port"]["network_plugin"] = "ignored" with self._stubs(network=network, addr=ip, mac=mac) as (port_create, alloc_mac, net_find): self.plugin.create_port(self.context, port_create_dict) alloc_mac.assert_called_once_with( self.context, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=None, use_forbidden_mac_range=False) port_create.assert_called_once_with( self.context, addresses=[], network_id=network["id"], tenant_id="fake", uuid=1, name="foobar", mac_address=alloc_mac()["address"], backend_key=1, id=1, security_groups=[], network_plugin='BASE', device_id=2, instance_node_id='') def test_create_port_attribute_filtering_admin(self): network = dict(id=1, tenant_id=self.context.tenant_id) mac = dict(address="AA:BB:CC:DD:EE:FF") port_name = "foobar" ip = dict() port = dict(port=dict(mac_address=mac["address"], network_id=1, tenant_id=self.context.tenant_id, device_id=2, name=port_name, device_owner="quark_tests", bridge="quark_bridge", admin_state_up=False)) expected_mac = "DE:AD:BE:EF:00:00" expected_bridge = "new_bridge" expected_device_owner = "new_device_owner" expected_admin_state = "new_state" expected_network_plugin = "BASE" port_create_dict = {} port_create_dict["port"] = port["port"].copy() port_create_dict["port"]["mac_address"] = expected_mac port_create_dict["port"]["device_owner"] = expected_device_owner port_create_dict["port"]["bridge"] = expected_bridge port_create_dict["port"]["admin_state_up"] = expected_admin_state port_create_dict["port"]["network_plugin"] = expected_network_plugin admin_ctx = self.context.elevated() with self._stubs(network=network, addr=ip, mac=mac) as (port_create, alloc_mac, net_find): self.plugin.create_port(admin_ctx, port_create_dict) alloc_mac.assert_called_once_with( admin_ctx, network["id"], 1, cfg.CONF.QUARK.ipam_reuse_after, mac_address=expected_mac, use_forbidden_mac_range=False) port_create.assert_called_once_with( admin_ctx, bridge=expected_bridge, uuid=1, name="foobar", admin_state_up=expected_admin_state, network_id=1, tenant_id="fake", id=1, device_owner=expected_device_owner, mac_address=mac["address"], device_id=2, backend_key=1, security_groups=[], addresses=[], network_plugin=expected_network_plugin, instance_node_id='') class TestQuarkPortUpdateFiltering(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self): with contextlib.nested( mock.patch("quark.db.api.port_find"), mock.patch("quark.db.api.port_update"), mock.patch("quark.drivers.registry.DriverRegistry.get_driver"), mock.patch("quark.plugin_views._make_port_dict"), mock.patch("neutron.quota.QuotaEngine.limit_check") ) as (port_find, port_update, get_driver, make_port, limit_check): yield port_find, port_update def test_update_port_attribute_filtering(self): new_port = {} new_port["port"] = { "mac_address": "DD:EE:FF:00:00:00", "device_owner": "new_owner", "bridge": "new_bridge", "admin_state_up": False, "device_id": 3, "network_id": 10, "backend_key": 1234, "name": "new_name", "network_plugin": "BASE"} with self._stubs() as (port_find, port_update): self.plugin.update_port(self.context, 1, new_port) port_update.assert_called_once_with( self.context, port_find(), name="new_name", security_groups=[]) def test_update_port_attribute_filtering_admin(self): new_port = {} new_port["port"] = { "mac_address": "DD:EE:FF:00:00:00", "device_owner": "new_owner", "bridge": "new_bridge", "admin_state_up": False, "device_id": 3, "network_id": 10, "backend_key": 1234, "name": "new_name", "network_plugin": "BASE"} admin_ctx = self.context.elevated() with self._stubs() as (port_find, port_update): self.plugin.update_port(admin_ctx, 1, new_port) port_update.assert_called_once_with( admin_ctx, port_find(), name="new_name", bridge=new_port["port"]["bridge"], admin_state_up=new_port["port"]["admin_state_up"], device_owner=new_port["port"]["device_owner"], mac_address=new_port["port"]["mac_address"], device_id=new_port["port"]["device_id"], security_groups=[]) class TestQuarkPortCreateAsAdvancedService(test_quark_plugin.TestQuarkPlugin): @contextlib.contextmanager def _stubs(self, port=None, network=None, addr=None, mac=None): if network: network["network_plugin"] = "BASE" network["ipam_strategy"] = "ANY" port_model = models.Port() port_model.update(port['port']) port_models = port_model db_mod = "quark.db.api" ipam = "quark.ipam.QuarkIpam" with contextlib.nested( mock.patch("%s.port_create" % db_mod), mock.patch("%s.network_find" % db_mod), mock.patch("%s.port_find" % db_mod), mock.patch("%s.allocate_ip_address" % ipam), mock.patch("%s.allocate_mac_address" % ipam), mock.patch("%s.port_count_all" % db_mod), ) as (port_create, net_find, port_find, alloc_ip, alloc_mac, port_count): port_create.return_value = port_models net_find.return_value = network port_find.return_value = None alloc_ip.return_value = addr alloc_mac.return_value = mac port_count.return_value = 0 yield port_create def test_advanced_service_create_port_other_tenant_network(self): """NCP-1819 - Advanced service can create port on any network Tests when an advanced service creating a port on another tenant's network does not fail AND the tenant_id is that of the context's. """ self.context.is_advsvc = True network_id = "foobar" network = dict(id=network_id, tenant_id="other_tenant") ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=self.context.tenant_id, device_id=5, name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): port = self.plugin.create_port(self.context, port_1) self.assertEqual(self.context.tenant_id, port['tenant_id']) def test_advsvc_can_create_port_with_another_tenant_id(self): """NCP-1819 - Advanced Service can create port on another tenant's net Tests that an advanced service can create a port on another tenant's network. """ another_tenant_id = 'im-another-tenant' self.context.is_advsvc = True network_id = "foobar" network = dict(id=network_id, tenant_id="other_tenant") ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=another_tenant_id, device_id=5, name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): port = self.plugin.create_port(self.context, port_1) self.assertEqual(another_tenant_id, port['tenant_id']) def test_non_advsvc_cannot_create_port_another_network(self): """NCP-1819 - Normal tenant port create should fail another's network Tests that a normal tenant creating a port on another tenant's network should not be allowed and throws an exception. """ normal_tenant_id = "other_tenant" network_id = "foobar" network = dict(id=network_id, tenant_id=normal_tenant_id) ip = dict() mac = dict(address="AA:BB:CC:DD:EE:FF") port_1 = dict(port=dict(mac_address="AA:BB:CC:DD:EE:00", network_id=network_id, tenant_id=normal_tenant_id, device_id=5, name="Fake")) with self._stubs(port=port_1, network=network, addr=ip, mac=mac): with self.assertRaises(exceptions.NotAuthorized): self.plugin.create_port(self.context, port_1)
from unittest import TestCase from domino_puzzle import Domino from queued_board import QueuedBoard from test_domino_puzzle import DummyRandom class QueuedBoardTest(TestCase): def test_create(self): state = """\ 0 1|2 - 1 0|0 === 4 5 - - 5 6 """ expected_queue = [Domino(4, 5), Domino(5, 6)] board = QueuedBoard.create(state) self.assertEqual(1, board[0][0].pips) self.assertEqual(2, board[2][1].pips) self.assertEqual(expected_queue, board.queue) def test_create_without_queue(self): state = """\ 0 1|2 - 1 0|0 """ expected_queue = [] board = QueuedBoard.create(state) self.assertEqual(expected_queue, board.queue) def test_equal(self): board1 = QueuedBoard.create("""\ 0 1|2 - 1 0|0 === 4 5 - - 5 6 """) # no change board2 = QueuedBoard.create("""\ 0 1|2 - 1 0|0 === 4 5 - - 5 6 """) # change a domino on the board board3 = QueuedBoard.create("""\ 0 2|1 - 1 0|0 === 4 5 - - 5 6 """) # change a domino in the queue board4 = QueuedBoard.create("""\ 0 1|2 - 1 0|0 === 4 6 - - 5 5 """) self.assertNotEqual(board1, board4) self.assertEqual(board1, board2) self.assertNotEqual(board1, board3) def test_extra_dominoes(self): state = """\ 0 1|2 - 1 0|0 === 0 1 - - 2 1 """ expected_extras = [Domino(2, 2)] board = QueuedBoard.create(state, max_pips=2) self.assertEqual(expected_extras, board.extra_dominoes) def test_get_from_queue(self): state = """\ 0 1|2 - 1 0|0 === 0 1 - - 2 1 """ board = QueuedBoard.create(state) expected_from_queue = Domino(0, 2) expected_queue = [Domino(1, 1)] from_queue = board.get_from_queue() self.assertEqual(expected_from_queue, from_queue) self.assertEqual(expected_queue, board.queue) def test_display(self): state = """\ 0 1|2 - 1 0|0 === 4 5 - - 5 6 """ board = QueuedBoard.create(state) display = board.display() self.assertEqual(state, display) def test_display_empty_queue(self): state = """\ 0 1|2 - 1 0|0 """ board = QueuedBoard.create(state) display = board.display() self.assertEqual(state, display) def test_fill(self): dummy_random = DummyRandom(samples=[[Domino(0, 1), Domino(1, 2), Domino(2, 3), Domino(3, 4), Domino(4, 5), Domino(6, 6)]], randints={(0, 1): [0, 1, 0, 0, 0, 0]}) board = QueuedBoard(4, 3, max_pips=6) expected_state = """\ === 0 2 2 3 4 6 - - - - - - 1 1 3 4 5 6 """ board.fill(dummy_random) state = board.display(cropped=True) self.assertEqual(expected_state, state) def test_mutate(self): dummy_random = DummyRandom(samples=[[Domino(5, 5)]], randints={(1, 21): [1], # mutation count (0, 5): [2, 4]}) # to remove or add board = QueuedBoard.create("""\ === 0 2 2 3 4 6 - - - - - - 1 1 3 4 5 6 """, max_pips=6) expected_state = """\ === 0 2 3 4 5 6 - - - - - - 1 1 4 5 5 6 """ new_board = board.mutate(dummy_random, QueuedBoard) state = new_board.display(cropped=True) self.assertEqual(expected_state, state) def test_mutate_last(self): dummy_random = DummyRandom(samples=[[Domino(5, 1)]], randints={(1, 21): [1], # mutation count (0, 5): [2, 5], # to remove or add (0, 1): [1]}) # to flip? start_state = """\ === 0 2 2 3 4 6 - - - - - - 1 1 3 4 5 6 """ board = QueuedBoard.create(start_state, max_pips=6) expected_state = """\ === 0 2 3 4 6 1 - - - - - - 1 1 4 5 6 5 """ new_board = board.mutate(dummy_random, QueuedBoard) state = board.display(cropped=True) self.assertEqual(start_state, state) new_state = new_board.display(cropped=True) self.assertEqual(expected_state, new_state)
import braintree import warnings from braintree.resource import Resource from braintree.address import Address from braintree.configuration import Configuration from braintree.credit_card_verification import CreditCardVerification class CreditCard(Resource): """ A class representing Braintree CreditCard objects. An example of creating an credit card with all available fields:: result = braintree.CreditCard.create({ "cardholder_name": "John Doe", "cvv": "123", "expiration_date": "12/2012", "number": "4111111111111111", "token": "my_token", "billing_address": { "first_name": "John", "last_name": "Doe", "company": "Braintree", "street_address": "111 First Street", "extended_address": "Unit 1", "locality": "Chicago", "postal_code": "60606", "region": "IL", "country_name": "United States of America" }, "options": { "verify_card": True, "verification_amount": "2.00" } }) print(result.credit_card.token) print(result.credit_card.masked_number) For more information on CreditCards, see https://developers.braintreepayments.com/reference/request/credit-card/create/python """ class CardType(object): """ Contants representing the type of the credit card. Available types are: * Braintree.CreditCard.AmEx * Braintree.CreditCard.CarteBlanche * Braintree.CreditCard.ChinaUnionPay * Braintree.CreditCard.DinersClubInternational * Braintree.CreditCard.Discover * Braintree.CreditCard.Electron * Braintree.CreditCard.Elo * Braintree.CreditCard.Hiper * Braintree.CreditCard.Hipercard * Braintree.CreditCard.JCB * Braintree.CreditCard.Laser * Braintree.CreditCard.UK_Maestro * Braintree.CreditCard.Maestro * Braintree.CreditCard.MasterCard * Braintree.CreditCard.Solo * Braintree.CreditCard.Switch * Braintree.CreditCard.Visa * Braintree.CreditCard.Unknown """ AmEx = "American Express" CarteBlanche = "Carte Blanche" ChinaUnionPay = "China UnionPay" DinersClubInternational = "Diners Club" Discover = "Discover" Electron = "Electron" Elo = "Elo" Hiper = "Hiper" Hipercard = "Hipercard" JCB = "JCB" Laser = "Laser" UK_Maestro = "UK Maestro" Maestro = "Maestro" MasterCard = "MasterCard" Solo = "Solo" Switch = "Switch" Visa = "Visa" Unknown = "Unknown" class CustomerLocation(object): """ Contants representing the issuer location of the credit card. Available locations are: * braintree.CreditCard.CustomerLocation.International * braintree.CreditCard.CustomerLocation.US """ International = "international" US = "us" # NEXT_MAJOR_VERSION this can be an enum! they were added as of python 3.4 and we support 3.5+ class CardTypeIndicator(object): """ Constants representing the three states for the card type indicator attributes * braintree.CreditCard.CardTypeIndicator.Yes * braintree.CreditCard.CardTypeIndicator.No * braintree.CreditCard.CardTypeIndicator.Unknown """ Yes = "Yes" No = "No" Unknown = "Unknown" Commercial = DurbinRegulated = Debit = Healthcare = \ CountryOfIssuance = IssuingBank = Payroll = Prepaid = ProductId = CardTypeIndicator @staticmethod def create(params=None): """ Create a CreditCard. A number and expiration_date are required. :: result = braintree.CreditCard.create({ "number": "4111111111111111", "expiration_date": "12/2012" }) """ if params is None: params = {} return Configuration.gateway().credit_card.create(params) @staticmethod def update(credit_card_token, params=None): """ Update an existing CreditCard By credit_card_id. The params are similar to create:: result = braintree.CreditCard.update("my_credit_card_id", { "cardholder_name": "John Doe" }) """ if params is None: params = {} return Configuration.gateway().credit_card.update(credit_card_token, params) @staticmethod def delete(credit_card_token): """ Delete a credit card Given a credit_card_id:: result = braintree.CreditCard.delete("my_credit_card_id") """ return Configuration.gateway().credit_card.delete(credit_card_token) @staticmethod def expired(): """ Return a collection of expired credit cards. """ return Configuration.gateway().credit_card.expired() @staticmethod def expiring_between(start_date, end_date): """ Return a collection of credit cards expiring between the given dates. """ return Configuration.gateway().credit_card.expiring_between(start_date, end_date) @staticmethod def find(credit_card_token): """ Find a credit card, given a credit_card_id. This does not return a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided credit_card_id is not found. :: credit_card = braintree.CreditCard.find("my_credit_card_token") """ return Configuration.gateway().credit_card.find(credit_card_token) @staticmethod def from_nonce(nonce): """ Convert a payment method nonce into a CreditCard. This does not return a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided credit_card_id is not found. :: credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce") """ return Configuration.gateway().credit_card.from_nonce(nonce) @staticmethod def create_signature(): return CreditCard.signature("create") @staticmethod def update_signature(): return CreditCard.signature("update") @staticmethod def signature(type): billing_address_params = [ "company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name", "extended_address", "first_name", "last_name", "locality", "postal_code", "region", "street_address" ] options = [ "fail_on_duplicate_payment_method", "make_default", "skip_advanced_fraud_checking", "venmo_sdk_session", "verification_account_type", "verification_amount", "verification_merchant_account_id", "verify_card", { "adyen":[ "overwrite_brand", "selected_brand" ] } ] three_d_secure_pass_thru = [ "cavv", "ds_transaction_id", "eci_flag", "three_d_secure_version", "xid" ] signature = [ "billing_address_id", "cardholder_name", "cvv", "expiration_date", "expiration_month", "expiration_year", "number", "token", "venmo_sdk_payment_method_code", "device_data", "payment_method_nonce", "device_session_id", "fraud_merchant_id", # NEXT_MAJOR_VERSION remove device_session_id and fraud_merchant_id { "billing_address": billing_address_params }, { "options": options }, { "three_d_secure_pass_thru": three_d_secure_pass_thru } ] if type == "create": signature.append("customer_id") elif type == "update": billing_address_params.append({"options": ["update_existing"]}) elif type == "update_via_customer": options.append("update_existing_token") billing_address_params.append({"options": ["update_existing"]}) else: raise AttributeError return signature def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes) self.is_expired = self.expired if "billing_address" in attributes: self.billing_address = Address(gateway, self.billing_address) else: self.billing_address = None if "subscriptions" in attributes: self.subscriptions = [braintree.subscription.Subscription(gateway, subscription) for subscription in self.subscriptions] if "verifications" in attributes: sorted_verifications = sorted(attributes["verifications"], key=lambda verification: verification["created_at"], reverse=True) if len(sorted_verifications) > 0: self.verification = CreditCardVerification(gateway, sorted_verifications[0]) @property def expiration_date(self): return self.expiration_month + "/" + self.expiration_year @property def masked_number(self): """ Returns the masked number of the CreditCard. """ return self.bin + "******" + self.last_4
#!/usr/bin/env python ######################################################################################## # Davi Frossard, 2016 # # VGG16 implementation in TensorFlow # # Details: # # http://www.cs.toronto.edu/~frossard/post/vgg16/ # # # # Model from https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md # # Weights from Caffe converted using https://github.com/ethereon/caffe-tensorflow # ######################################################################################## # Kent Sommer, 2016 # # Modified for Image retrieval on the UKBenchmark image set using fc2 features # ######################################################################################## import rospy import tensorflow as tf import numpy as np import scipy.spatial.distance import errno from os import listdir from os.path import join from os.path import basename from shutil import copyfile from scipy.misc import imread, imresize from math import* import heapq import time import cv2 import csv class vgg16: def __init__(self, imgs, weights=None, sess=None): self.imgs = imgs self.convlayers() self.fc_layers() self.probs = tf.nn.softmax(self.fc3l) if weights is not None and sess is not None: self.load_weights(weights, sess) def convlayers(self): self.parameters = [] # zero-mean input with tf.name_scope('preprocess') as scope: mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[1, 1, 1, 3], name='img_mean') images = self.imgs-mean # conv1_1 with tf.name_scope('conv1_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv1_1 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv1_2 with tf.name_scope('conv1_2') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 64], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv1_1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv1_2 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # pool1 self.pool1 = tf.nn.max_pool(self.conv1_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool1') # conv2_1 with tf.name_scope('conv2_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.pool1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv2_1 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv2_2 with tf.name_scope('conv2_2') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 128], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv2_1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv2_2 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # pool2 self.pool2 = tf.nn.max_pool(self.conv2_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool2') # conv3_1 with tf.name_scope('conv3_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 256], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.pool2, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv3_1 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv3_2 with tf.name_scope('conv3_2') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv3_1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv3_2 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv3_3 with tf.name_scope('conv3_3') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv3_2, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv3_3 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # pool3 self.pool3 = tf.nn.max_pool(self.conv3_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool3') # conv4_1 with tf.name_scope('conv4_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.pool3, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv4_1 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv4_2 with tf.name_scope('conv4_2') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv4_1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv4_2 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv4_3 with tf.name_scope('conv4_3') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv4_2, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv4_3 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # pool4 self.pool4 = tf.nn.max_pool(self.conv4_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool4') # conv5_1 with tf.name_scope('conv5_1') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.pool4, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv5_1 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv5_2 with tf.name_scope('conv5_2') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv5_1, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv5_2 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # conv5_3 with tf.name_scope('conv5_3') as scope: kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights') conv = tf.nn.conv2d(self.conv5_2, kernel, [1, 1, 1, 1], padding='SAME') biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases') out = tf.nn.bias_add(conv, biases) self.conv5_3 = tf.nn.relu(out, name=scope) self.parameters += [kernel, biases] # pool5 self.pool5 = tf.nn.max_pool(self.conv5_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool4') def fc_layers(self): # fc1 with tf.name_scope('fc1') as scope: shape = int(np.prod(self.pool5.get_shape()[1:])) fc1w = tf.Variable(tf.truncated_normal([shape, 4096], dtype=tf.float32, stddev=1e-1), name='weights') fc1b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32), trainable=True, name='biases') pool5_flat = tf.reshape(self.pool5, [-1, shape]) fc1l = tf.nn.bias_add(tf.matmul(pool5_flat, fc1w), fc1b) self.fc1 = tf.nn.relu(fc1l) self.parameters += [fc1w, fc1b] # fc2 with tf.name_scope('fc2') as scope: fc2w = tf.Variable(tf.truncated_normal([4096, 4096], dtype=tf.float32, stddev=1e-1), name='weights') fc2b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32), trainable=True, name='biases') fc2l = tf.nn.bias_add(tf.matmul(self.fc1, fc2w), fc2b) self.fc2 = tf.nn.relu(fc2l) self.parameters += [fc2w, fc2b] # fc3 with tf.name_scope('fc3') as scope: fc3w = tf.Variable(tf.truncated_normal([4096, 1000], dtype=tf.float32, stddev=1e-1), name='weights') fc3b = tf.Variable(tf.constant(1.0, shape=[1000], dtype=tf.float32), trainable=True, name='biases') self.fc3l = tf.nn.bias_add(tf.matmul(self.fc2, fc3w), fc3b) self.parameters += [fc3w, fc3b] def load_weights(self, weight_file, sess): weights = np.load(weight_file) keys = sorted(weights.keys()) print ('Load weights...') for i, k in enumerate(keys): sess.run(self.parameters[i].assign(weights[k])) print ('Load complete.') def square_rooted(x): return round(sqrt(sum([a*a for a in x])),3) def cosine_similarity(x,y): numerator = sum(a*b for a,b in zip(x,y)) denominator = square_rooted(x)*square_rooted(y) return round(numerator/float(denominator),3) def retrieve_nsmallest_dist(query_image, test_dirs, out_dir, n, dist_type, weights_path, log_dir): """This function will compare a query image against all images provided in the test_dir, and save/log the smallest n images to the out_dir Args: query_path (str): Query image object test_dirs (str): List of directories containing the test images out_dir (str): Location to the save the retrieved images n (int): Number of images to retrieve dist_type (str): The distance algorithm (euc, cos, chev) weights_path (str): CNN weights path log_path (str): Path of the logs directory to save the logs in """ # Setup Session sess = tf.Session() imgs = tf.placeholder(tf.float32, [None, 224, 224, 3]) vgg = vgg16(imgs, weights_path, sess) # Get number of images to match (default 4) #dist_type = raw_input("Enter distance algorithm (euc, cos, chev): \n") or "euc" #print("distance type selected: " + dist_type) #dist_type="euc" #################### ###Perform Search### #################### #Timer and precision count total + open file for saving data t0 = time.time() feat_dict = {} #fp = open("Last_Run.txt", 'w') #fp.truncate() # Retrieve feature vector for query image #Setup Dict and precision tracking img_dict = {} #img_query = imread(query_path) img_query = imresize(query_image, (224, 224)) # Extract image descriptor in layer fc2/Relu. If you want, change fc2 to fc1 layer_query = sess.graph.get_tensor_by_name('fc2/Relu:0') # layer_query = sess.graph.get_tensor_by_name('fc1/Relu:0') # Run the session for feature extract at 'fc2/Relu' layer _feature_query = sess.run(layer_query, feed_dict={vgg.imgs: [img_query]}) # Convert tensor variable into numpy array # It is 4096 dimension vector feature_query = np.array(_feature_query) print (test_dirs) for test_dir in test_dirs: print (test_dir) # Set dataset directory path data_dir_test = test_dir datalist_test = [join(data_dir_test, f) for f in listdir(data_dir_test)] # Retrieve feature vector for test image for j in datalist_test: try: img_test = imread(j) img_test = cv2.cvtColor(img_test, cv2.COLOR_BGRA2BGR) img_test = imresize(img_test, (224, 224)) except: print("Error with file:\t"+j) continue # Extract image descriptor in layer fc2/Relu. If you want, change fc2 to fc1 layer_test = sess.graph.get_tensor_by_name('fc2/Relu:0') # layer_test = sess.graph.get_tensor_by_name('fc1/Relu:0') # Run the session for feature extract at 'fc2/Relu' layer _feature_test = sess.run(layer_test, feed_dict={vgg.imgs: [img_test]}) # Convert tensor variable into numpy array # It is 4096 dimension vector feature_test = np.array(_feature_test) feat_dict[j] = feature_test # Calculate Euclidean distance between two feature vectors if dist_type == "euc": curr_dist = scipy.spatial.distance.euclidean(feature_query, feature_test) # Calculate Cosine distance between two feature vectors if dist_type == "cos": curr_dist = scipy.spatial.distance.cosine(feature_query, feature_test) # Calculate Chevyshev distance between two feature vectors if dist_type == "chev": curr_dist = scipy.spatial.distance.chebyshev(feature_query, feature_test) # Add to dictionary img_dict[curr_dist] = str(j) fp = open(log_dir+"/"+ "retrieval_log.csv", 'w') fp.truncate() fpWriter = csv.writer(fp, delimiter='\t') fpWriter.writerow(["File", "Distance"]) # Get Results for Query keys_sorted = heapq.nsmallest(n, img_dict) for y in range(0,min(n, len(keys_sorted))): print(str(y+1) + ":\t" + "Distance: " + str(keys_sorted[y]) + ", FileName: " + basename(img_dict[keys_sorted[y]])) #fp.write(str(y+1) + ":\t" + "Distance: " + str(keys_sorted[y]) + ", FileName: " + basename(img_dict[keys_sorted[y]]) +"\n") fpWriter.writerow([basename(img_dict[keys_sorted[y]]), str(keys_sorted[y])]) #basename(img_dict[keys_sorted[y]]) copyfile(img_dict[keys_sorted[y]], out_dir + "/" + basename(img_dict[keys_sorted[y]])) t1 = time.time() total = t1-t0 #print("\nTime taken: " + str(total)) #fpWriter.writerow([]) #fp.write("\n\nTime taken: " + str(total) + "\n") fp.close() def retrieve_dist(query_image, test_path, dist_type, weights_path): """This function will compare a query image against all images provided in the test_dir, and save/log the smallest n images to the out_dir Args: query_image (np.darray): Query image path test_dir (str): Location of the test images dist_type (str): The distance algorithm (euc, cos, chev) vgg (class vgg16): Object of the vgg16 class sess(tf Session): Object of the tensorflow session """ # Setup Session sess = tf.Session() imgs = tf.placeholder(tf.float32, [None, 224, 224, 3]) vgg = vgg16(imgs, weights_path, sess) # Get number of images to match (default 4) #dist_type = raw_input("Enter distance algorithm (euc, cos, chev): \n") or "euc" #print("distance type selected: " + dist_type) #dist_type="euc" #################### ###Perform Search### #################### #Timer and precision count total + open file for saving data t0 = time.time() feat_dict = {} #fp = open("Last_Run.txt", 'w') #fp.truncate() # Retrieve feature vector for query image #Setup Dict and precision tracking img_dict = {} #img_query = imread(query_path) img_query = imresize(query_image, (224, 224)) img_test = imread(test_path) img_test = imresize(img_test, (224, 224)) # Extract image descriptor in layer fc2/Relu. If you want, change fc2 to fc1 layer_query = sess.graph.get_tensor_by_name('fc2/Relu:0') # layer_query = sess.graph.get_tensor_by_name('fc1/Relu:0') # Run the session for feature extract at 'fc2/Relu' layer _feature_query = sess.run(layer_query, feed_dict={vgg.imgs: [img_query]}) # Convert tensor variable into numpy array # It is 4096 dimension vector feature_query = np.array(_feature_query) # Extract image descriptor in layer fc2/Relu. If you want, change fc2 to fc1 layer_test = sess.graph.get_tensor_by_name('fc2/Relu:0') # layer_test = sess.graph.get_tensor_by_name('fc1/Relu:0') # Run the session for feature extract at 'fc2/Relu' layer _feature_test = sess.run(layer_test, feed_dict={vgg.imgs: [img_test]}) # Convert tensor variable into numpy array # It is 4096 dimension vector feature_test = np.array(_feature_test) # Calculate Euclidean distance between two feature vectors if dist_type == "euc": curr_dist = scipy.spatial.distance.euclidean(feature_query, feature_test) # Calculate Cosine distance between two feature vectors if dist_type == "cos": curr_dist = scipy.spatial.distance.cosine(feature_query, feature_test) # Calculate Chevyshev distance between two feature vectors if dist_type == "chev": curr_dist = scipy.spatial.distance.chebyshev(feature_query, feature_test) return curr_dist
# # 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. # """Code snippets used in webdocs. The examples here are written specifically to read well with the accompanying web docs. Do not rewrite them until you make sure the webdocs still read well and the rewritten code supports the concept being described. For example, there are snippets that could be shorter but they are written like this to make a specific point in the docs. The code snippets are all organized as self contained functions. Parts of the function body delimited by [START tag] and [END tag] will be included automatically in the web docs. The naming convention for the tags is to have as prefix the PATH_TO_HTML where they are included followed by a descriptive string. The tags can contain only letters, digits and _. """ import apache_beam as beam from apache_beam.io import iobase from apache_beam.io.range_trackers import OffsetRangeTracker from apache_beam.metrics import Metrics from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to from apache_beam.transforms.core import PTransform # Quiet some pylint warnings that happen because of the somewhat special # format for the code snippets. # pylint:disable=invalid-name # pylint:disable=expression-not-assigned # pylint:disable=redefined-outer-name # pylint:disable=reimported # pylint:disable=unused-variable # pylint:disable=wrong-import-order, wrong-import-position class SnippetUtils(object): from apache_beam.pipeline import PipelineVisitor class RenameFiles(PipelineVisitor): """RenameFiles will rewire read/write paths for unit testing. RenameFiles will replace the GCS files specified in the read and write transforms to local files so the pipeline can be run as a unit test. This assumes that read and write transforms defined in snippets have already been replaced by transforms 'DummyReadForTesting' and 'DummyReadForTesting' (see snippets_test.py). This is as close as we can get to have code snippets that are executed and are also ready to presented in webdocs. """ def __init__(self, renames): self.renames = renames def visit_transform(self, transform_node): if transform_node.full_label.find('DummyReadForTesting') >= 0: transform_node.transform.fn.file_to_read = self.renames['read'] elif transform_node.full_label.find('DummyWriteForTesting') >= 0: transform_node.transform.fn.file_to_write = self.renames['write'] def construct_pipeline(renames): """A reverse words snippet as an example for constructing a pipeline.""" import re # This is duplicate of the import statement in # pipelines_constructing_creating tag below, but required to avoid # Unresolved reference in ReverseWords class import apache_beam as beam class ReverseWords(beam.PTransform): """A PTransform that reverses individual elements in a PCollection.""" def expand(self, pcoll): return pcoll | beam.Map(lambda e: e[::-1]) def filter_words(unused_x): """Pass through filter to select everything.""" return True # [START pipelines_constructing_creating] import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions p = beam.Pipeline(options=PipelineOptions()) # [END pipelines_constructing_creating] p = TestPipeline() # Use TestPipeline for testing. # [START pipelines_constructing_reading] lines = p | 'ReadMyFile' >> beam.io.ReadFromText('gs://some/inputData.txt') # [END pipelines_constructing_reading] # [START pipelines_constructing_applying] words = lines | beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x)) reversed_words = words | ReverseWords() # [END pipelines_constructing_applying] # [START pipelines_constructing_writing] filtered_words = reversed_words | 'FilterWords' >> beam.Filter(filter_words) filtered_words | 'WriteMyFile' >> beam.io.WriteToText( 'gs://some/outputData.txt') # [END pipelines_constructing_writing] p.visit(SnippetUtils.RenameFiles(renames)) # [START pipelines_constructing_running] p.run() # [END pipelines_constructing_running] def model_pipelines(argv): """A wordcount snippet as a simple pipeline example.""" # [START model_pipelines] import re import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions class MyOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--input', dest='input', default='gs://dataflow-samples/shakespeare/kinglear' '.txt', help='Input file to process.') parser.add_argument('--output', dest='output', required=True, help='Output file to write results to.') pipeline_options = PipelineOptions(argv) my_options = pipeline_options.view_as(MyOptions) with beam.Pipeline(options=pipeline_options) as p: (p | beam.io.ReadFromText(my_options.input) | beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x)) | beam.Map(lambda x: (x, 1)) | beam.combiners.Count.PerKey() | beam.io.WriteToText(my_options.output)) # [END model_pipelines] def model_pcollection(argv): """Creating a PCollection from data in local memory.""" from apache_beam.options.pipeline_options import PipelineOptions class MyOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--output', dest='output', required=True, help='Output file to write results to.') pipeline_options = PipelineOptions(argv) my_options = pipeline_options.view_as(MyOptions) # [START model_pcollection] with beam.Pipeline(options=pipeline_options) as p: lines = (p | beam.Create([ 'To be, or not to be: that is the question: ', 'Whether \'tis nobler in the mind to suffer ', 'The slings and arrows of outrageous fortune, ', 'Or to take arms against a sea of troubles, '])) # [END model_pcollection] (lines | beam.io.WriteToText(my_options.output)) def pipeline_options_remote(argv): """Creating a Pipeline using a PipelineOptions object for remote execution.""" from apache_beam import Pipeline from apache_beam.options.pipeline_options import PipelineOptions # [START pipeline_options_create] options = PipelineOptions(flags=argv) # [END pipeline_options_create] # [START pipeline_options_define_custom] class MyOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--input') parser.add_argument('--output') # [END pipeline_options_define_custom] from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import StandardOptions # [START pipeline_options_dataflow_service] # Create and set your PipelineOptions. options = PipelineOptions(flags=argv) # For Cloud execution, set the Cloud Platform project, job_name, # staging location, temp_location and specify DataflowRunner. google_cloud_options = options.view_as(GoogleCloudOptions) google_cloud_options.project = 'my-project-id' google_cloud_options.job_name = 'myjob' google_cloud_options.staging_location = 'gs://my-bucket/binaries' google_cloud_options.temp_location = 'gs://my-bucket/temp' options.view_as(StandardOptions).runner = 'DataflowRunner' # Create the Pipeline with the specified options. p = Pipeline(options=options) # [END pipeline_options_dataflow_service] my_options = options.view_as(MyOptions) my_input = my_options.input my_output = my_options.output p = TestPipeline() # Use TestPipeline for testing. lines = p | beam.io.ReadFromText(my_input) lines | beam.io.WriteToText(my_output) p.run() def pipeline_options_local(argv): """Creating a Pipeline using a PipelineOptions object for local execution.""" from apache_beam import Pipeline from apache_beam.options.pipeline_options import PipelineOptions options = PipelineOptions(flags=argv) # [START pipeline_options_define_custom_with_help_and_default] class MyOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--input', help='Input for the pipeline', default='gs://my-bucket/input') parser.add_argument('--output', help='Output for the pipeline', default='gs://my-bucket/output') # [END pipeline_options_define_custom_with_help_and_default] my_options = options.view_as(MyOptions) my_input = my_options.input my_output = my_options.output # [START pipeline_options_local] # Create and set your Pipeline Options. options = PipelineOptions() p = Pipeline(options=options) # [END pipeline_options_local] p = TestPipeline() # Use TestPipeline for testing. lines = p | beam.io.ReadFromText(my_input) lines | beam.io.WriteToText(my_output) p.run() def pipeline_options_command_line(argv): """Creating a Pipeline by passing a list of arguments.""" # [START pipeline_options_command_line] # Use Python argparse module to parse custom arguments import argparse parser = argparse.ArgumentParser() parser.add_argument('--input') parser.add_argument('--output') known_args, pipeline_args = parser.parse_known_args(argv) # Create the Pipeline with remaining arguments. with beam.Pipeline(argv=pipeline_args) as p: lines = p | 'ReadFromText' >> beam.io.ReadFromText(known_args.input) lines | 'WriteToText' >> beam.io.WriteToText(known_args.output) # [END pipeline_options_command_line] def pipeline_logging(lines, output): """Logging Pipeline Messages.""" import re import apache_beam as beam # [START pipeline_logging] # import Python logging module. import logging class ExtractWordsFn(beam.DoFn): def process(self, element): words = re.findall(r'[A-Za-z\']+', element) for word in words: yield word if word.lower() == 'love': # Log using the root logger at info or higher levels logging.info('Found : %s', word.lower()) # Remaining WordCount example code ... # [END pipeline_logging] with TestPipeline() as p: # Use TestPipeline for testing. (p | beam.Create(lines) | beam.ParDo(ExtractWordsFn()) | beam.io.WriteToText(output)) def pipeline_monitoring(renames): """Using monitoring interface snippets.""" import re import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions class WordCountOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--input', help='Input for the pipeline', default='gs://my-bucket/input') parser.add_argument('--output', help='output for the pipeline', default='gs://my-bucket/output') class ExtractWordsFn(beam.DoFn): def process(self, element): words = re.findall(r'[A-Za-z\']+', element) for word in words: yield word class FormatCountsFn(beam.DoFn): def process(self, element): word, count = element yield '%s: %s' % (word, count) # [START pipeline_monitoring_composite] # The CountWords Composite Transform inside the WordCount pipeline. class CountWords(beam.PTransform): def expand(self, pcoll): return (pcoll # Convert lines of text into individual words. | 'ExtractWords' >> beam.ParDo(ExtractWordsFn()) # Count the number of times each word occurs. | beam.combiners.Count.PerElement() # Format each word and count into a printable string. | 'FormatCounts' >> beam.ParDo(FormatCountsFn())) # [END pipeline_monitoring_composite] pipeline_options = PipelineOptions() options = pipeline_options.view_as(WordCountOptions) with TestPipeline() as p: # Use TestPipeline for testing. # [START pipeline_monitoring_execution] (p # Read the lines of the input text. | 'ReadLines' >> beam.io.ReadFromText(options.input) # Count the words. | CountWords() # Write the formatted word counts to output. | 'WriteCounts' >> beam.io.WriteToText(options.output)) # [END pipeline_monitoring_execution] p.visit(SnippetUtils.RenameFiles(renames)) def examples_wordcount_minimal(renames): """MinimalWordCount example snippets.""" import re import apache_beam as beam from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.pipeline_options import PipelineOptions # [START examples_wordcount_minimal_options] options = PipelineOptions() google_cloud_options = options.view_as(GoogleCloudOptions) google_cloud_options.project = 'my-project-id' google_cloud_options.job_name = 'myjob' google_cloud_options.staging_location = 'gs://your-bucket-name-here/staging' google_cloud_options.temp_location = 'gs://your-bucket-name-here/temp' options.view_as(StandardOptions).runner = 'DataflowRunner' # [END examples_wordcount_minimal_options] # Run it locally for testing. options = PipelineOptions() # [START examples_wordcount_minimal_create] p = beam.Pipeline(options=options) # [END examples_wordcount_minimal_create] ( # [START examples_wordcount_minimal_read] p | beam.io.ReadFromText( 'gs://dataflow-samples/shakespeare/kinglear.txt') # [END examples_wordcount_minimal_read] # [START examples_wordcount_minimal_pardo] | 'ExtractWords' >> beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x)) # [END examples_wordcount_minimal_pardo] # [START examples_wordcount_minimal_count] | beam.combiners.Count.PerElement() # [END examples_wordcount_minimal_count] # [START examples_wordcount_minimal_map] | beam.Map(lambda word_count: '%s: %s' % (word_count[0], word_count[1])) # [END examples_wordcount_minimal_map] # [START examples_wordcount_minimal_write] | beam.io.WriteToText('gs://my-bucket/counts.txt') # [END examples_wordcount_minimal_write] ) p.visit(SnippetUtils.RenameFiles(renames)) # [START examples_wordcount_minimal_run] result = p.run() # [END examples_wordcount_minimal_run] result.wait_until_finish() def examples_wordcount_wordcount(renames): """WordCount example snippets.""" import re import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions argv = [] # [START examples_wordcount_wordcount_options] class WordCountOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument('--input', help='Input for the pipeline', default='gs://my-bucket/input') options = PipelineOptions(argv) with beam.Pipeline(options=options) as p: # [END examples_wordcount_wordcount_options] lines = p | beam.io.ReadFromText( 'gs://dataflow-samples/shakespeare/kinglear.txt') # [START examples_wordcount_wordcount_composite] class CountWords(beam.PTransform): def expand(self, pcoll): return (pcoll # Convert lines of text into individual words. | 'ExtractWords' >> beam.FlatMap( lambda x: re.findall(r'[A-Za-z\']+', x)) # Count the number of times each word occurs. | beam.combiners.Count.PerElement()) counts = lines | CountWords() # [END examples_wordcount_wordcount_composite] # [START examples_wordcount_wordcount_dofn] class FormatAsTextFn(beam.DoFn): def process(self, element): word, count = element yield '%s: %s' % (word, count) formatted = counts | beam.ParDo(FormatAsTextFn()) # [END examples_wordcount_wordcount_dofn] formatted | beam.io.WriteToText('gs://my-bucket/counts.txt') p.visit(SnippetUtils.RenameFiles(renames)) def examples_wordcount_templated(renames): """Templated WordCount example snippet.""" import re import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_beam.options.pipeline_options import PipelineOptions # [START example_wordcount_templated] class WordcountTemplatedOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): # Use add_value_provider_argument for arguments to be templatable # Use add_argument as usual for non-templatable arguments parser.add_value_provider_argument( '--input', help='Path of the file to read from') parser.add_argument( '--output', required=True, help='Output file to write results to.') pipeline_options = PipelineOptions(['--output', 'some/output_path']) p = beam.Pipeline(options=pipeline_options) wordcount_options = pipeline_options.view_as(WordcountTemplatedOptions) lines = p | 'Read' >> ReadFromText(wordcount_options.input) # [END example_wordcount_templated] def format_result(word_count): (word, count) = word_count return '%s: %s' % (word, count) ( lines | 'ExtractWords' >> beam.FlatMap( lambda x: re.findall(r'[A-Za-z\']+', x)) | 'PairWithOnes' >> beam.Map(lambda x: (x, 1)) | 'Group' >> beam.GroupByKey() | 'Sum' >> beam.Map(lambda word_ones: (word_ones[0], sum(word_ones[1]))) | 'Format' >> beam.Map(format_result) | 'Write' >> WriteToText(wordcount_options.output) ) p.visit(SnippetUtils.RenameFiles(renames)) result = p.run() result.wait_until_finish() def examples_wordcount_debugging(renames): """DebuggingWordCount example snippets.""" import re import apache_beam as beam # [START example_wordcount_debugging_logging] # [START example_wordcount_debugging_aggregators] import logging class FilterTextFn(beam.DoFn): """A DoFn that filters for a specific key based on a regular expression.""" def __init__(self, pattern): self.pattern = pattern # A custom metric can track values in your pipeline as it runs. Create # custom metrics matched_word and unmatched_words. self.matched_words = Metrics.counter(self.__class__, 'matched_words') self.umatched_words = Metrics.counter(self.__class__, 'umatched_words') def process(self, element): word, _ = element if re.match(self.pattern, word): # Log at INFO level each element we match. When executing this pipeline # using the Dataflow service, these log lines will appear in the Cloud # Logging UI. logging.info('Matched %s', word) # Add 1 to the custom metric counter matched_words self.matched_words.inc() yield element else: # Log at the "DEBUG" level each element that is not matched. Different # log levels can be used to control the verbosity of logging providing # an effective mechanism to filter less important information. Note # currently only "INFO" and higher level logs are emitted to the Cloud # Logger. This log message will not be visible in the Cloud Logger. logging.debug('Did not match %s', word) # Add 1 to the custom metric counter umatched_words self.umatched_words.inc() # [END example_wordcount_debugging_logging] # [END example_wordcount_debugging_aggregators] with TestPipeline() as p: # Use TestPipeline for testing. filtered_words = ( p | beam.io.ReadFromText( 'gs://dataflow-samples/shakespeare/kinglear.txt') | 'ExtractWords' >> beam.FlatMap( lambda x: re.findall(r'[A-Za-z\']+', x)) | beam.combiners.Count.PerElement() | 'FilterText' >> beam.ParDo(FilterTextFn('Flourish|stomach'))) # [START example_wordcount_debugging_assert] beam.testing.util.assert_that( filtered_words, beam.testing.util.equal_to( [('Flourish', 3), ('stomach', 1)])) # [END example_wordcount_debugging_assert] def format_result(word_count): (word, count) = word_count return '%s: %s' % (word, count) output = (filtered_words | 'format' >> beam.Map(format_result) | 'Write' >> beam.io.WriteToText('gs://my-bucket/counts.txt')) p.visit(SnippetUtils.RenameFiles(renames)) def examples_ptransforms_templated(renames): # [START examples_ptransforms_templated] import apache_beam as beam from apache_beam.io import WriteToText from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.value_provider import StaticValueProvider class TemplatedUserOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_value_provider_argument('--templated_int', type=int) class MySumFn(beam.DoFn): def __init__(self, templated_int): self.templated_int = templated_int def process(self, an_int): yield self.templated_int.get() + an_int pipeline_options = PipelineOptions() p = beam.Pipeline(options=pipeline_options) user_options = pipeline_options.view_as(TemplatedUserOptions) my_sum_fn = MySumFn(user_options.templated_int) sum = (p | 'ReadCollection' >> beam.io.ReadFromText( 'gs://some/integer_collection') | 'StringToInt' >> beam.Map(lambda w: int(w)) | 'AddGivenInt' >> beam.ParDo(my_sum_fn) | 'WriteResultingCollection' >> WriteToText('some/output_path')) # [END examples_ptransforms_templated] # Templates are not supported by DirectRunner (only by DataflowRunner) # so a value must be provided at graph-construction time my_sum_fn.templated_int = StaticValueProvider(int, 10) p.visit(SnippetUtils.RenameFiles(renames)) result = p.run() result.wait_until_finish() # Defining a new source. # [START model_custom_source_new_source] class CountingSource(iobase.BoundedSource): def __init__(self, count): self.records_read = Metrics.counter(self.__class__, 'recordsRead') self._count = count def estimate_size(self): return self._count def get_range_tracker(self, start_position, stop_position): if start_position is None: start_position = 0 if stop_position is None: stop_position = self._count return OffsetRangeTracker(start_position, stop_position) def read(self, range_tracker): for i in range(self._count): if not range_tracker.try_claim(i): return self.records_read.inc() yield i def split(self, desired_bundle_size, start_position=None, stop_position=None): if start_position is None: start_position = 0 if stop_position is None: stop_position = self._count bundle_start = start_position while bundle_start < self._count: bundle_stop = max(self._count, bundle_start + desired_bundle_size) yield iobase.SourceBundle(weight=(bundle_stop - bundle_start), source=self, start_position=bundle_start, stop_position=bundle_stop) bundle_start = bundle_stop # [END model_custom_source_new_source] def model_custom_source(count): """Demonstrates creating a new custom source and using it in a pipeline. Defines a new source ``CountingSource`` that produces integers starting from 0 up to a given size. Uses the new source in an example pipeline. Additionally demonstrates how a source should be implemented using a ``PTransform``. This is the recommended way to develop sources that are to distributed to a large number of end users. This method runs two pipelines. (1) A pipeline that uses ``CountingSource`` directly using the ``df.Read`` transform. (2) A pipeline that uses a custom ``PTransform`` that wraps ``CountingSource``. Args: count: the size of the counting source to be used in the pipeline demonstrated in this method. """ # Using the source in an example pipeline. # [START model_custom_source_use_new_source] with beam.Pipeline(options=PipelineOptions()) as p: numbers = p | 'ProduceNumbers' >> beam.io.Read(CountingSource(count)) # [END model_custom_source_use_new_source] lines = numbers | beam.core.Map(lambda number: 'line %d' % number) assert_that( lines, equal_to( ['line ' + str(number) for number in range(0, count)])) # We recommend users to start Source classes with an underscore to discourage # using the Source class directly when a PTransform for the source is # available. We simulate that here by simply extending the previous Source # class. class _CountingSource(CountingSource): pass # [START model_custom_source_new_ptransform] class ReadFromCountingSource(PTransform): def __init__(self, count, **kwargs): super(ReadFromCountingSource, self).__init__(**kwargs) self._count = count def expand(self, pcoll): return pcoll | iobase.Read(_CountingSource(count)) # [END model_custom_source_new_ptransform] # [START model_custom_source_use_ptransform] p = beam.Pipeline(options=PipelineOptions()) numbers = p | 'ProduceNumbers' >> ReadFromCountingSource(count) # [END model_custom_source_use_ptransform] lines = numbers | beam.core.Map(lambda number: 'line %d' % number) assert_that( lines, equal_to( ['line ' + str(number) for number in range(0, count)])) # Don't test runner api due to pickling errors. p.run(test_runner_api=False).wait_until_finish() def model_custom_sink(simplekv, KVs, final_table_name_no_ptransform, final_table_name_with_ptransform): """Demonstrates creating a new custom sink and using it in a pipeline. Defines a new sink ``SimpleKVSink`` that demonstrates writing to a simple key-value based storage system which has following API. simplekv.connect(url) - connects to the storage system and returns an access token which can be used to perform further operations simplekv.open_table(access_token, table_name) - creates a table named 'table_name'. Returns a table object. simplekv.write_to_table(access_token, table, key, value) - writes a key-value pair to the given table. simplekv.rename_table(access_token, old_name, new_name) - renames the table named 'old_name' to 'new_name'. Uses the new sink in an example pipeline. Additionally demonstrates how a sink should be implemented using a ``PTransform``. This is the recommended way to develop sinks that are to be distributed to a large number of end users. This method runs two pipelines. (1) A pipeline that uses ``SimpleKVSink`` directly using the ``df.Write`` transform. (2) A pipeline that uses a custom ``PTransform`` that wraps ``SimpleKVSink``. Args: simplekv: an object that mocks the key-value storage. KVs: the set of key-value pairs to be written in the example pipeline. final_table_name_no_ptransform: the prefix of final set of tables to be created by the example pipeline that uses ``SimpleKVSink`` directly. final_table_name_with_ptransform: the prefix of final set of tables to be created by the example pipeline that uses a ``PTransform`` that wraps ``SimpleKVSink``. """ import apache_beam as beam from apache_beam.io import iobase from apache_beam.transforms.core import PTransform from apache_beam.options.pipeline_options import PipelineOptions # Defining the new sink. # [START model_custom_sink_new_sink] class SimpleKVSink(iobase.Sink): def __init__(self, url, final_table_name): self._url = url self._final_table_name = final_table_name def initialize_write(self): access_token = simplekv.connect(self._url) return access_token def open_writer(self, access_token, uid): table_name = 'table' + uid return SimpleKVWriter(access_token, table_name) def finalize_write(self, access_token, table_names): for i, table_name in enumerate(table_names): simplekv.rename_table( access_token, table_name, self._final_table_name + str(i)) # [END model_custom_sink_new_sink] # Defining a writer for the new sink. # [START model_custom_sink_new_writer] class SimpleKVWriter(iobase.Writer): def __init__(self, access_token, table_name): self._access_token = access_token self._table_name = table_name self._table = simplekv.open_table(access_token, table_name) def write(self, record): key, value = record simplekv.write_to_table(self._access_token, self._table, key, value) def close(self): return self._table_name # [END model_custom_sink_new_writer] final_table_name = final_table_name_no_ptransform # Using the new sink in an example pipeline. # [START model_custom_sink_use_new_sink] with beam.Pipeline(options=PipelineOptions()) as p: kvs = p | 'CreateKVs' >> beam.Create(KVs) kvs | 'WriteToSimpleKV' >> beam.io.Write( SimpleKVSink('http://url_to_simple_kv/', final_table_name)) # [END model_custom_sink_use_new_sink] # We recommend users to start Sink class names with an underscore to # discourage using the Sink class directly when a PTransform for the sink is # available. We simulate that here by simply extending the previous Sink # class. class _SimpleKVSink(SimpleKVSink): pass # [START model_custom_sink_new_ptransform] class WriteToKVSink(PTransform): def __init__(self, url, final_table_name, **kwargs): super(WriteToKVSink, self).__init__(**kwargs) self._url = url self._final_table_name = final_table_name def expand(self, pcoll): return pcoll | iobase.Write(_SimpleKVSink(self._url, self._final_table_name)) # [END model_custom_sink_new_ptransform] final_table_name = final_table_name_with_ptransform # [START model_custom_sink_use_ptransform] with beam.Pipeline(options=PipelineOptions()) as p: kvs = p | 'CreateKVs' >> beam.core.Create(KVs) kvs | 'WriteToSimpleKV' >> WriteToKVSink( 'http://url_to_simple_kv/', final_table_name) # [END model_custom_sink_use_ptransform] def model_textio(renames): """Using a Read and Write transform to read/write text files.""" def filter_words(x): import re return re.findall(r'[A-Za-z\']+', x) import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions # [START model_textio_read] with beam.Pipeline(options=PipelineOptions()) as p: # [START model_pipelineio_read] lines = p | 'ReadFromText' >> beam.io.ReadFromText('path/to/input-*.csv') # [END model_pipelineio_read] # [END model_textio_read] # [START model_textio_write] filtered_words = lines | 'FilterWords' >> beam.FlatMap(filter_words) # [START model_pipelineio_write] filtered_words | 'WriteToText' >> beam.io.WriteToText( '/path/to/numbers', file_name_suffix='.csv') # [END model_pipelineio_write] # [END model_textio_write] p.visit(SnippetUtils.RenameFiles(renames)) def model_textio_compressed(renames, expected): """Using a Read Transform to read compressed text files.""" with TestPipeline() as p: # [START model_textio_write_compressed] lines = p | 'ReadFromText' >> beam.io.ReadFromText( '/path/to/input-*.csv.gz', compression_type=beam.io.filesystem.CompressionTypes.GZIP) # [END model_textio_write_compressed] assert_that(lines, equal_to(expected)) p.visit(SnippetUtils.RenameFiles(renames)) def model_datastoreio(): """Using a Read and Write transform to read/write to Cloud Datastore.""" import uuid from google.cloud.proto.datastore.v1 import entity_pb2 from google.cloud.proto.datastore.v1 import query_pb2 import googledatastore import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore project = 'my_project' kind = 'my_kind' query = query_pb2.Query() query.kind.add().name = kind # [START model_datastoreio_read] p = beam.Pipeline(options=PipelineOptions()) entities = p | 'Read From Datastore' >> ReadFromDatastore(project, query) # [END model_datastoreio_read] # [START model_datastoreio_write] p = beam.Pipeline(options=PipelineOptions()) musicians = p | 'Musicians' >> beam.Create( ['Mozart', 'Chopin', 'Beethoven', 'Vivaldi']) def to_entity(content): entity = entity_pb2.Entity() googledatastore.helper.add_key_path(entity.key, kind, str(uuid.uuid4())) googledatastore.helper.add_properties(entity, {'content': unicode(content)}) return entity entities = musicians | 'To Entity' >> beam.Map(to_entity) entities | 'Write To Datastore' >> WriteToDatastore(project) # [END model_datastoreio_write] def model_bigqueryio(): """Using a Read and Write transform to read/write to BigQuery.""" import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions # [START model_bigqueryio_read] p = beam.Pipeline(options=PipelineOptions()) weather_data = p | 'ReadWeatherStations' >> beam.io.Read( beam.io.BigQuerySource( 'clouddataflow-readonly:samples.weather_stations')) # [END model_bigqueryio_read] # [START model_bigqueryio_query] p = beam.Pipeline(options=PipelineOptions()) weather_data = p | 'ReadYearAndTemp' >> beam.io.Read( beam.io.BigQuerySource( query='SELECT year, mean_temp FROM samples.weather_stations')) # [END model_bigqueryio_query] # [START model_bigqueryio_query_standard_sql] p = beam.Pipeline(options=PipelineOptions()) weather_data = p | 'ReadYearAndTemp' >> beam.io.Read( beam.io.BigQuerySource( query='SELECT year, mean_temp FROM `samples.weather_stations`', use_standard_sql=True)) # [END model_bigqueryio_query_standard_sql] # [START model_bigqueryio_schema] schema = 'source:STRING, quote:STRING' # [END model_bigqueryio_schema] # [START model_bigqueryio_write] quotes = p | beam.Create( [{'source': 'Mahatma Ghandi', 'quote': 'My life is my message.'}]) quotes | 'Write' >> beam.io.Write( beam.io.BigQuerySink( 'my-project:output.output_table', schema=schema, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED)) # [END model_bigqueryio_write] def model_composite_transform_example(contents, output_path): """Example of a composite transform. To declare a composite transform, define a subclass of PTransform. To override the apply method, define a method "apply" that takes a PCollection as its only parameter and returns a PCollection. """ import re import apache_beam as beam # [START composite_transform_example] # [START composite_ptransform_apply_method] # [START composite_ptransform_declare] class CountWords(beam.PTransform): # [END composite_ptransform_declare] def expand(self, pcoll): return (pcoll | beam.FlatMap(lambda x: re.findall(r'\w+', x)) | beam.combiners.Count.PerElement() | beam.Map(lambda word_c: '%s: %s' % (word_c[0], word_c[1]))) # [END composite_ptransform_apply_method] # [END composite_transform_example] with TestPipeline() as p: # Use TestPipeline for testing. (p | beam.Create(contents) | CountWords() | beam.io.WriteToText(output_path)) def model_multiple_pcollections_flatten(contents, output_path): """Merging a PCollection with Flatten.""" some_hash_fn = lambda s: ord(s[0]) partition_fn = lambda element, partitions: some_hash_fn(element) % partitions import apache_beam as beam with TestPipeline() as p: # Use TestPipeline for testing. # Partition into deciles partitioned = p | beam.Create(contents) | beam.Partition(partition_fn, 3) pcoll1 = partitioned[0] pcoll2 = partitioned[1] pcoll3 = partitioned[2] # Flatten them back into 1 # A collection of PCollection objects can be represented simply # as a tuple (or list) of PCollections. # (The SDK for Python has no separate type to store multiple # PCollection objects, whether containing the same or different # types.) # [START model_multiple_pcollections_flatten] merged = ( (pcoll1, pcoll2, pcoll3) # A list of tuples can be "piped" directly into a Flatten transform. | beam.Flatten()) # [END model_multiple_pcollections_flatten] merged | beam.io.WriteToText(output_path) def model_multiple_pcollections_partition(contents, output_path): """Splitting a PCollection with Partition.""" some_hash_fn = lambda s: ord(s[0]) def get_percentile(i): """Assume i in [0,100).""" return i import apache_beam as beam with TestPipeline() as p: # Use TestPipeline for testing. students = p | beam.Create(contents) # [START model_multiple_pcollections_partition] def partition_fn(student, num_partitions): return int(get_percentile(student) * num_partitions / 100) by_decile = students | beam.Partition(partition_fn, 10) # [END model_multiple_pcollections_partition] # [START model_multiple_pcollections_partition_40th] fortieth_percentile = by_decile[4] # [END model_multiple_pcollections_partition_40th] ([by_decile[d] for d in xrange(10) if d != 4] + [fortieth_percentile] | beam.Flatten() | beam.io.WriteToText(output_path)) def model_group_by_key(contents, output_path): """Applying a GroupByKey Transform.""" import re import apache_beam as beam with TestPipeline() as p: # Use TestPipeline for testing. def count_ones(word_ones): (word, ones) = word_ones return (word, sum(ones)) words_and_counts = ( p | beam.Create(contents) | beam.FlatMap(lambda x: re.findall(r'\w+', x)) | 'one word' >> beam.Map(lambda w: (w, 1))) # GroupByKey accepts a PCollection of (w, 1) and # outputs a PCollection of (w, (1, 1, ...)). # (A key/value pair is just a tuple in Python.) # This is a somewhat forced example, since one could # simply use beam.combiners.Count.PerElement here. # [START model_group_by_key_transform] grouped_words = words_and_counts | beam.GroupByKey() # [END model_group_by_key_transform] (grouped_words | 'count words' >> beam.Map(count_ones) | beam.io.WriteToText(output_path)) def model_co_group_by_key_tuple(emails, phones, output_path): """Applying a CoGroupByKey Transform to a tuple.""" import apache_beam as beam # [START model_group_by_key_cogroupbykey_tuple] # The result PCollection contains one key-value element for each key in the # input PCollections. The key of the pair will be the key from the input and # the value will be a dictionary with two entries: 'emails' - an iterable of # all values for the current key in the emails PCollection and 'phones': an # iterable of all values for the current key in the phones PCollection. results = ({'emails': emails, 'phones': phones} | beam.CoGroupByKey()) def join_info(name_info): (name, info) = name_info return '%s; %s; %s' %\ (name, sorted(info['emails']), sorted(info['phones'])) contact_lines = results | beam.Map(join_info) # [END model_group_by_key_cogroupbykey_tuple] contact_lines | beam.io.WriteToText(output_path) def model_join_using_side_inputs( name_list, email_list, phone_list, output_path): """Joining PCollections using side inputs.""" import apache_beam as beam from apache_beam.pvalue import AsIter with TestPipeline() as p: # Use TestPipeline for testing. # [START model_join_using_side_inputs] # This code performs a join by receiving the set of names as an input and # passing PCollections that contain emails and phone numbers as side inputs # instead of using CoGroupByKey. names = p | 'names' >> beam.Create(name_list) emails = p | 'email' >> beam.Create(email_list) phones = p | 'phone' >> beam.Create(phone_list) def join_info(name, emails, phone_numbers): filtered_emails = [] for name_in_list, email in emails: if name_in_list == name: filtered_emails.append(email) filtered_phone_numbers = [] for name_in_list, phone_number in phone_numbers: if name_in_list == name: filtered_phone_numbers.append(phone_number) return '; '.join(['%s' % name, '%s' % ','.join(filtered_emails), '%s' % ','.join(filtered_phone_numbers)]) contact_lines = names | 'CreateContacts' >> beam.core.Map( join_info, AsIter(emails), AsIter(phones)) # [END model_join_using_side_inputs] contact_lines | beam.io.WriteToText(output_path) # [START model_library_transforms_keys] class Keys(beam.PTransform): def expand(self, pcoll): return pcoll | 'Keys' >> beam.Map(lambda k_v: k_v[0]) # [END model_library_transforms_keys] # pylint: enable=invalid-name # [START model_library_transforms_count] class Count(beam.PTransform): def expand(self, pcoll): return ( pcoll | 'PairWithOne' >> beam.Map(lambda v: (v, 1)) | beam.CombinePerKey(sum)) # [END model_library_transforms_count]
# -*- coding: utf-8 -*- # File: batch_norm.py import tensorflow as tf from tensorflow.python.training import moving_averages import re import six from ..utils import logger from ..utils.argtools import get_data_format from ..tfutils.tower import get_current_tower_context from ..tfutils.common import get_tf_version_tuple from ..tfutils.collection import backup_collection, restore_collection from .common import layer_register, VariableHolder from .tflayer import convert_to_tflayer_args, rename_get_variable __all__ = ['BatchNorm', 'BatchRenorm'] # decay: being too close to 1 leads to slow start-up. torch use 0.9. # eps: torch: 1e-5. Lasagne: 1e-4 def get_bn_variables(n_out, use_scale, use_bias, beta_init, gamma_init): if use_bias: beta = tf.get_variable('beta', [n_out], initializer=beta_init) else: beta = tf.zeros([n_out], name='beta') if use_scale: gamma = tf.get_variable('gamma', [n_out], initializer=gamma_init) else: gamma = tf.ones([n_out], name='gamma') # x * gamma + beta moving_mean = tf.get_variable('mean/EMA', [n_out], initializer=tf.constant_initializer(), trainable=False) moving_var = tf.get_variable('variance/EMA', [n_out], initializer=tf.constant_initializer(1.0), trainable=False) return beta, gamma, moving_mean, moving_var def update_bn_ema(xn, batch_mean, batch_var, moving_mean, moving_var, decay, internal_update): update_op1 = moving_averages.assign_moving_average( moving_mean, batch_mean, decay, zero_debias=False, name='mean_ema_op') update_op2 = moving_averages.assign_moving_average( moving_var, batch_var, decay, zero_debias=False, name='var_ema_op') if internal_update: with tf.control_dependencies([update_op1, update_op2]): return tf.identity(xn, name='output') else: tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_op1) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_op2) return tf.identity(xn, name='output') @layer_register() @convert_to_tflayer_args( args_names=[], name_mapping={ 'use_bias': 'center', 'use_scale': 'scale', 'gamma_init': 'gamma_initializer', 'decay': 'momentum', 'use_local_stat': 'training' }) def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, data_format='channels_last', internal_update=False, sync_statistics=None): """ Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful) in the following: 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from tensorpack's `TowerContext`, but can be overwritten. 4. Support the `internal_update` option, which enables the use of BatchNorm layer inside conditionals. 5. Support the `sync_statistics` option, which is very useful in small-batch models. Args: internal_update (bool): if False, add EMA update ops to `tf.GraphKeys.UPDATE_OPS`. If True, update EMA inside the layer by control dependencies. They are very similar in speed, but `internal_update=True` can be used when you have conditionals in your model, or when you have multiple networks to train. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/14699 sync_statistics (str or None): one of None, "nccl", or "horovod". By default (None), it uses statistics of the input tensor to normalize. This is the standard way BatchNorm was done in most frameworks. When set to "nccl", this layer must be used under tensorpack's multi-GPU trainers. It uses the aggregated statistics of the whole batch (across all GPUs) to normalize. When set to "horovod", this layer must be used under tensorpack's :class:`HorovodTrainer`. It uses the aggregated statistics of the whole batch (across all MPI ranks) to normalize. Note that on single machine this is significantly slower than the "nccl" implementation. This implementation averages the per-GPU E[x] and E[x^2] among GPUs to compute global mean & variance. Therefore each GPU needs to have the same batch size. This option has no effect when not training. This option is also known as "Cross-GPU BatchNorm" as mentioned in: `MegDet: A Large Mini-Batch Object Detector <https://arxiv.org/abs/1711.07240>`_. Corresponding TF issue: https://github.com/tensorflow/tensorflow/issues/18222. Variable Names: * ``beta``: the bias term. Will be zero-inited by default. * ``gamma``: the scale term. Will be one-inited by default. * ``mean/EMA``: the moving average of mean. * ``variance/EMA``: the moving average of variance. Note: Combinations of ``training`` and ``ctx.is_training``: * ``training == ctx.is_training``: standard BN, EMA are maintained during training and used during inference. This is the default. * ``training and not ctx.is_training``: still use batch statistics in inference. * ``not training and ctx.is_training``: use EMA to normalize in training. This is useful when you load a pre-trained BN and don't want to fine tune the EMA. EMA will not be updated in this case. """ # parse shapes data_format = get_data_format(data_format, tfmode=False) shape = inputs.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4], ndims if sync_statistics is not None: sync_statistics = sync_statistics.lower() assert sync_statistics in [None, 'nccl', 'horovod'], sync_statistics if axis is None: if ndims == 2: data_format = 'NHWC' axis = 1 else: axis = 1 if data_format == 'NCHW' else 3 else: data_format = 'NCHW' if axis == 1 else 'NHWC' num_chan = shape[axis] # parse training/ctx ctx = get_current_tower_context() if training is None: training = ctx.is_training training = bool(training) TF_version = get_tf_version_tuple() freeze_bn_backward = not training and ctx.is_training if freeze_bn_backward: assert TF_version >= (1, 4), \ "Fine tuning a BatchNorm model with fixed statistics needs TF>=1.4!" if ctx.is_main_training_tower: # only warn in first tower logger.warn("[BatchNorm] Using moving_mean/moving_variance in training.") # Using moving_mean/moving_variance in training, which means we # loaded a pre-trained BN and only fine-tuning the affine part. if sync_statistics is None or not (training and ctx.is_training): coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) with rename_get_variable( {'moving_mean': 'mean/EMA', 'moving_variance': 'variance/EMA'}): tf_args = dict( axis=axis, momentum=momentum, epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, # https://github.com/tensorflow/tensorflow/issues/10857#issuecomment-410185429 fused=(ndims == 4 and axis in [1, 3] and not freeze_bn_backward), _reuse=tf.get_variable_scope().reuse) if TF_version >= (1, 5): tf_args['virtual_batch_size'] = virtual_batch_size else: assert virtual_batch_size is None, "Feature not supported in this version of TF!" layer = tf.layers.BatchNormalization(**tf_args) xn = layer.apply(inputs, training=training, scope=tf.get_variable_scope()) # maintain EMA only on one GPU is OK, even in replicated mode. # because during training, EMA isn't used if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) if not ctx.is_main_training_tower or internal_update: restore_collection(coll_bk) if training and internal_update: assert layer.updates with tf.control_dependencies(layer.updates): ret = tf.identity(xn, name='output') else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=layer.moving_mean, mean=layer.moving_mean, # for backward-compatibility moving_variance=layer.moving_variance, variance=layer.moving_variance) # for backward-compatibility if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta else: red_axis = [0] if ndims == 2 else ([0, 2, 3] if axis == 1 else [0, 1, 2]) new_shape = None # don't need to reshape unless ... if ndims == 4 and axis == 1: new_shape = [1, num_chan, 1, 1] batch_mean = tf.reduce_mean(inputs, axis=red_axis) batch_mean_square = tf.reduce_mean(tf.square(inputs), axis=red_axis) if sync_statistics == 'nccl': num_dev = ctx.total if num_dev == 1: logger.warn("BatchNorm(sync_statistics='nccl') is used with only one tower!") else: assert six.PY2 or TF_version >= (1, 10), \ "Cross-GPU BatchNorm is only supported in TF>=1.10 ." \ "Upgrade TF or apply this patch manually: https://github.com/tensorflow/tensorflow/pull/20360" from tensorflow.contrib.nccl.ops import gen_nccl_ops shared_name = re.sub('tower[0-9]+/', '', tf.get_variable_scope().name) batch_mean = gen_nccl_ops.nccl_all_reduce( input=batch_mean, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean') * (1.0 / num_dev) batch_mean_square = gen_nccl_ops.nccl_all_reduce( input=batch_mean_square, reduction='sum', num_devices=num_dev, shared_name=shared_name + '_NCCL_mean_square') * (1.0 / num_dev) elif sync_statistics == 'horovod': # Require https://github.com/uber/horovod/pull/331 import horovod.tensorflow as hvd if hvd.size() == 1: logger.warn("BatchNorm(sync_statistics='horovod') is used with only one process!") else: import horovod hvd_version = tuple(map(int, horovod.__version__.split('.'))) assert hvd_version >= (0, 13, 6), "sync_statistics=horovod needs horovod>=0.13.6 !" batch_mean = hvd.allreduce(batch_mean, average=True) batch_mean_square = hvd.allreduce(batch_mean_square, average=True) batch_var = batch_mean_square - tf.square(batch_mean) batch_mean_vec = batch_mean batch_var_vec = batch_var beta, gamma, moving_mean, moving_var = get_bn_variables( num_chan, scale, center, beta_initializer, gamma_initializer) if new_shape is not None: batch_mean = tf.reshape(batch_mean, new_shape) batch_var = tf.reshape(batch_var, new_shape) # Using fused_batch_norm(is_training=False) is actually slightly faster, # but hopefully this call will be JITed in the future. xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, tf.reshape(beta, new_shape), tf.reshape(gamma, new_shape), epsilon) else: xn = tf.nn.batch_normalization( inputs, batch_mean, batch_var, beta, gamma, epsilon) if ctx.is_main_training_tower: ret = update_bn_ema( xn, batch_mean_vec, batch_var_vec, moving_mean, moving_var, momentum, internal_update) else: ret = tf.identity(xn, name='output') vh = ret.variables = VariableHolder( moving_mean=moving_mean, mean=moving_mean, # for backward-compatibility moving_variance=moving_var, variance=moving_var) # for backward-compatibility if scale: vh.gamma = gamma if center: vh.beta = beta return ret @layer_register() @convert_to_tflayer_args( args_names=[], name_mapping={ 'use_bias': 'center', 'use_scale': 'scale', 'gamma_init': 'gamma_initializer', 'decay': 'momentum' }) def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): """ Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models <https://arxiv.org/abs/1702.03275>`_. This implementation is a wrapper around `tf.layers.batch_normalization`. Args: x (tf.Tensor): a NHWC or NC tensor. rmax, dmax (tf.Tensor): a scalar tensor, the maximum allowed corrections. decay (float): decay rate of moving average. epsilon (float): epsilon to avoid divide-by-zero. use_scale, use_bias (bool): whether to use the extra affine transformation or not. Returns: tf.Tensor: a tensor named ``output`` with the same shape of x. Variable Names: * ``beta``: the bias term. * ``gamma``: the scale term. Input will be transformed by ``x * gamma + beta``. * ``moving_mean, renorm_mean, renorm_mean_weight``: See TF documentation. * ``moving_variance, renorm_stddev, renorm_stddev_weight``: See TF documentation. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims == 2: data_format = 'channels_first' ctx = get_current_tower_context() coll_bk = backup_collection([tf.GraphKeys.UPDATE_OPS]) layer = tf.layers.BatchNormalization( axis=1 if data_format == 'channels_first' else 3, momentum=momentum, epsilon=epsilon, center=center, scale=scale, renorm=True, renorm_clipping={ 'rmin': 1.0 / rmax, 'rmax': rmax, 'dmax': dmax}, renorm_momentum=0.99, gamma_initializer=gamma_initializer, fused=False, _reuse=tf.get_variable_scope().reuse) xn = layer.apply(x, training=ctx.is_training, scope=tf.get_variable_scope()) if ctx.is_main_training_tower: for v in layer.non_trainable_variables: if isinstance(v, tf.Variable): tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v) else: # only run UPDATE_OPS in the first tower restore_collection(coll_bk) if ndims == 2: xn = tf.squeeze(xn, [1, 2]) ret = tf.identity(xn, name='output') # TODO not sure whether to add moving_mean/moving_var to VH now vh = ret.variables = VariableHolder() if scale: vh.gamma = layer.gamma if center: vh.beta = layer.beta return ret
# Copyright (c) 2018 European Organization for Nuclear Research. # 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 copy import testtools from testtools import matchers from magnumclient import exceptions from magnumclient.tests import utils from magnumclient.v1 import nodegroups NODEGROUP1 = { 'id': 123, 'uuid': '66666666-7777-8888-9999-000000000001', 'cluster_id': '66666666-7777-8888-9999-000000000000', 'name': 'test-worker', 'node_addresses': ['172.17.2.3'], 'node_count': 2, 'project_id': 'fake_project', 'labels': {}, 'flavor_id': 'fake_flavor_1', 'image_id': 'fake_image', 'is_default': True, 'role': 'worker', 'max_node_count': 10, 'min_node_count': 0 } NODEGROUP2 = { 'id': 124, 'uuid': '66666666-7777-8888-9999-000000000002', 'cluster_id': '66666666-7777-8888-9999-000000000000', 'name': 'test-master', 'node_addresses': ['172.17.2.4'], 'node_count': 2, 'project_id': 'fake_project', 'labels': {}, 'flavor_id': 'fake_flavor_1', 'image_id': 'fake_image', 'is_default': True, 'role': 'master', 'max_node_count': 10, 'min_node_count': 0 } CREATE_NODEGROUP = copy.deepcopy(NODEGROUP1) del CREATE_NODEGROUP['id'] del CREATE_NODEGROUP['uuid'] del CREATE_NODEGROUP['node_addresses'] del CREATE_NODEGROUP['is_default'] del CREATE_NODEGROUP['cluster_id'] UPDATED_NODEGROUP = copy.deepcopy(NODEGROUP1) NEW_NODE_COUNT = 9 UPDATED_NODEGROUP['node_count'] = NEW_NODE_COUNT fake_responses = { '/v1/clusters/test/nodegroups/': { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), 'POST': ( {}, CREATE_NODEGROUP, ), }, '/v1/clusters/test/nodegroups/%s' % NODEGROUP1['id']: { 'GET': ( {}, NODEGROUP1 ), 'DELETE': ( {}, None, ), 'PATCH': ( {}, UPDATED_NODEGROUP, ), }, '/v1/clusters/test/nodegroups/%s/?rollback=True' % NODEGROUP1['id']: { 'PATCH': ( {}, UPDATED_NODEGROUP, ), }, '/v1/clusters/test/nodegroups/%s' % NODEGROUP1['name']: { 'GET': ( {}, NODEGROUP1 ), 'DELETE': ( {}, None, ), 'PATCH': ( {}, UPDATED_NODEGROUP, ), }, '/v1/clusters/test/nodegroups/?limit=2': { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), }, '/v1/clusters/test/nodegroups/?marker=%s' % NODEGROUP2['uuid']: { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), }, '/v1/clusters/test/nodegroups/?limit=2&marker=%s' % NODEGROUP2['uuid']: { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), }, '/v1/clusters/test/nodegroups/?sort_dir=asc': { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), }, '/v1/clusters/test/nodegroups/?sort_key=uuid': { 'GET': ( {}, {'nodegroups': [NODEGROUP1, NODEGROUP2]}, ), }, '/v1/clusters/test/nodegroups/?sort_key=uuid&sort_dir=desc': { 'GET': ( {}, {'nodegroups': [NODEGROUP2, NODEGROUP1]}, ), }, } class NodeGroupManagerTest(testtools.TestCase): def setUp(self): super(NodeGroupManagerTest, self).setUp() self.api = utils.FakeAPI(fake_responses) self.mgr = nodegroups.NodeGroupManager(self.api) self.cluster_id = 'test' self.base_path = '/v1/clusters/test/nodegroups/' def test_nodegroup_list(self): clusters = self.mgr.list(self.cluster_id) expect = [ ('GET', self.base_path, {}, None), ] self.assertEqual(expect, self.api.calls) self.assertThat(clusters, matchers.HasLength(2)) def _test_nodegroup_list_with_filters(self, cluster_id, limit=None, marker=None, sort_key=None, sort_dir=None, detail=False, expect=[]): nodegroup_filter = self.mgr.list(cluster_id, limit=limit, marker=marker, sort_key=sort_key, sort_dir=sort_dir, detail=detail) self.assertEqual(expect, self.api.calls) self.assertThat(nodegroup_filter, matchers.HasLength(2)) def test_nodegroup_list_with_limit(self): expect = [ ('GET', self.base_path + '?limit=2', {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, limit=2, expect=expect) def test_nodegroup_list_with_marker(self): filter_ = '?marker=%s' % NODEGROUP2['uuid'] expect = [ ('GET', self.base_path + filter_, {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, marker=NODEGROUP2['uuid'], expect=expect) def test_nodegroup_list_with_marker_limit(self): filter_ = '?limit=2&marker=%s' % NODEGROUP2['uuid'] expect = [ ('GET', self.base_path + filter_, {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, limit=2, marker=NODEGROUP2['uuid'], expect=expect) def test_nodegroup_list_with_sort_dir(self): expect = [ ('GET', '/v1/clusters/test/nodegroups/?sort_dir=asc', {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, sort_dir='asc', expect=expect) def test_nodegroup_list_with_sort_key(self): expect = [ ('GET', '/v1/clusters/test/nodegroups/?sort_key=uuid', {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, sort_key='uuid', expect=expect) def test_nodegroup_list_with_sort_key_dir(self): expect = [ ('GET', self.base_path + '?sort_key=uuid&sort_dir=desc', {}, None), ] self._test_nodegroup_list_with_filters( self.cluster_id, sort_key='uuid', sort_dir='desc', expect=expect) def test_nodegroup_show_by_name(self): nodegroup = self.mgr.get(self.cluster_id, NODEGROUP1['name']) expect = [ ('GET', self.base_path + '%s' % NODEGROUP1['name'], {}, None) ] self.assertEqual(expect, self.api.calls) self.assertEqual(NODEGROUP1['name'], nodegroup.name) def test_nodegroup_show_by_id(self): nodegroup = self.mgr.get(self.cluster_id, NODEGROUP1['id']) expect = [ ('GET', self.base_path + '%s' % NODEGROUP1['id'], {}, None) ] self.assertEqual(expect, self.api.calls) self.assertEqual(NODEGROUP1['name'], nodegroup.name) def test_nodegroup_delete_by_id(self): nodegroup = self.mgr.delete(self.cluster_id, NODEGROUP1['id']) expect = [ ('DELETE', self.base_path + '%s' % NODEGROUP1['id'], {}, None), ] self.assertEqual(expect, self.api.calls) self.assertIsNone(nodegroup) def test_nodegroup_delete_by_name(self): nodegroup = self.mgr.delete(self.cluster_id, NODEGROUP1['name']) expect = [ ('DELETE', self.base_path + '%s' % NODEGROUP1['name'], {}, None), ] self.assertEqual(expect, self.api.calls) self.assertIsNone(nodegroup) def test_nodegroup_update(self): patch = {'op': 'replace', 'value': NEW_NODE_COUNT, 'path': '/node_count'} nodegroup = self.mgr.update(self.cluster_id, id=NODEGROUP1['id'], patch=patch) expect = [ ('PATCH', self.base_path + '%s' % NODEGROUP1['id'], {}, patch), ] self.assertEqual(expect, self.api.calls) self.assertEqual(NEW_NODE_COUNT, nodegroup.node_count) def test_nodegroup_create(self): nodegroup = self.mgr.create(self.cluster_id, **CREATE_NODEGROUP) expect = [ ('POST', self.base_path, {}, CREATE_NODEGROUP), ] self.assertEqual(expect, self.api.calls) self.assertTrue(nodegroup) def test_nodegroup_create_with_docker_volume_size(self): ng_with_volume_size = dict() ng_with_volume_size.update(CREATE_NODEGROUP) ng_with_volume_size['docker_volume_size'] = 20 nodegroup = self.mgr.create(self.cluster_id, **ng_with_volume_size) expect = [ ('POST', self.base_path, {}, ng_with_volume_size), ] self.assertEqual(expect, self.api.calls) self.assertTrue(nodegroup) def test_nodegroup_create_with_labels(self): ng_with_labels = dict() ng_with_labels.update(CREATE_NODEGROUP) ng_with_labels['labels'] = "key=val" nodegroup = self.mgr.create(self.cluster_id, **ng_with_labels) expect = [ ('POST', self.base_path, {}, ng_with_labels), ] self.assertEqual(expect, self.api.calls) self.assertTrue(nodegroup) def test_nodegroup_create_fail(self): CREATE_NODEGROUP_FAIL = copy.deepcopy(CREATE_NODEGROUP) CREATE_NODEGROUP_FAIL["wrong_key"] = "wrong" self.assertRaisesRegex(exceptions.InvalidAttribute, ("Key must be in %s" % ','.join(nodegroups.CREATION_ATTRIBUTES)), self.mgr.create, self.cluster_id, **CREATE_NODEGROUP_FAIL) self.assertEqual([], self.api.calls)
# Copyright 2012 Cloudbase Solutions Srl # 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. """ Management class for host operations. """ import datetime import platform import time from nova.compute import api from nova.compute import arch from nova.compute import hv_type from nova.compute import vm_mode from nova.compute import vm_states import nova.conf from nova import context from nova import exception from nova import objects from os_win import constants as os_win_const from os_win import utilsfactory from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import units from hyperv.i18n import _, _LE, _LI from hyperv.nova import constants from hyperv.nova import pathutils from hyperv.nova import vmops hyper_host_opts = [ cfg.IntOpt('evacuate_task_state_timeout', default=600, help='Number of seconds to wait for an instance to be ' 'evacuated during host maintenance.'), ] CONF = nova.conf.CONF CONF.register_opts(hyper_host_opts, 'hyperv') LOG = logging.getLogger(__name__) class HostOps(object): def __init__(self): self._diskutils = utilsfactory.get_diskutils() self._hostutils = utilsfactory.get_hostutils() self._pathutils = pathutils.PathUtils() self._vmutils = utilsfactory.get_vmutils() self._vmops = vmops.VMOps() self._api = api.API() def _get_cpu_info(self): """Get the CPU information. :returns: A dictionary containing the main properties of the central processor in the hypervisor. """ cpu_info = dict() processors = self._hostutils.get_cpus_info() w32_arch_dict = constants.WMI_WIN32_PROCESSOR_ARCHITECTURE cpu_info['arch'] = w32_arch_dict.get(processors[0]['Architecture'], 'Unknown') cpu_info['model'] = processors[0]['Name'] cpu_info['vendor'] = processors[0]['Manufacturer'] topology = dict() topology['sockets'] = len(processors) topology['cores'] = processors[0]['NumberOfCores'] topology['threads'] = (processors[0]['NumberOfLogicalProcessors'] // processors[0]['NumberOfCores']) cpu_info['topology'] = topology features = list() for fkey, fname in os_win_const.PROCESSOR_FEATURE.items(): if self._hostutils.is_cpu_feature_present(fkey): features.append(fname) cpu_info['features'] = features return cpu_info def _get_memory_info(self): (total_mem_kb, free_mem_kb) = self._hostutils.get_memory_info() total_mem_mb = total_mem_kb // 1024 free_mem_mb = free_mem_kb // 1024 return (total_mem_mb, free_mem_mb, total_mem_mb - free_mem_mb) def _get_storage_info_gb(self): instances_dir = self._pathutils.get_instances_dir() (size, free_space) = self._diskutils.get_disk_capacity( instances_dir) total_gb = size // units.Gi free_gb = free_space // units.Gi used_gb = total_gb - free_gb return (total_gb, free_gb, used_gb) def _get_hypervisor_version(self): """Get hypervisor version. :returns: hypervisor version (ex. 6003) """ # NOTE(claudiub): The hypervisor_version will be stored in the database # as an Integer and it will be used by the scheduler, if required by # the image property 'hypervisor_version_requires'. # The hypervisor_version will then be converted back to a version # by splitting the int in groups of 3 digits. # E.g.: hypervisor_version 6003 is converted to '6.3'. version = self._hostutils.get_windows_version().split('.') version = int(version[0]) * 1000 + int(version[1]) LOG.debug('Windows version: %s ', version) return version def _get_host_numa_topology(self): numa_nodes = self._hostutils.get_numa_nodes() cells = [] for numa_node in numa_nodes: numa_node['pinned_cpus'] = set([]) numa_node['mempages'] = [] numa_node['siblings'] = [] cell = objects.NUMACell(**numa_node) cells.append(cell) return objects.NUMATopology(cells=cells) def _get_remotefx_gpu_info(self): total_video_ram = 0 available_video_ram = 0 if CONF.hyperv.enable_remotefx: gpus = self._hostutils.get_remotefx_gpu_info() for gpu in gpus: total_video_ram += int(gpu['total_video_ram']) available_video_ram += int(gpu['available_video_ram']) else: gpus = [] return {'total_video_ram': total_video_ram, 'used_video_ram': total_video_ram - available_video_ram, 'gpu_info': jsonutils.dumps(gpus)} def get_available_resource(self): """Retrieve resource info. This method is called when nova-compute launches, and as part of a periodic task. :returns: dictionary describing resources """ LOG.debug('get_available_resource called') (total_mem_mb, free_mem_mb, used_mem_mb) = self._get_memory_info() (total_hdd_gb, free_hdd_gb, used_hdd_gb) = self._get_storage_info_gb() cpu_info = self._get_cpu_info() cpu_topology = cpu_info['topology'] vcpus = (cpu_topology['sockets'] * cpu_topology['cores'] * cpu_topology['threads']) dic = {'vcpus': vcpus, 'memory_mb': total_mem_mb, 'memory_mb_used': used_mem_mb, 'local_gb': total_hdd_gb, 'local_gb_used': used_hdd_gb, 'hypervisor_type': "hyperv", 'hypervisor_version': self._get_hypervisor_version(), 'hypervisor_hostname': platform.node(), 'vcpus_used': 0, 'cpu_info': jsonutils.dumps(cpu_info), 'supported_instances': [(arch.I686, hv_type.HYPERV, vm_mode.HVM), (arch.X86_64, hv_type.HYPERV, vm_mode.HVM)], } gpu_info = self._get_remotefx_gpu_info() dic.update(gpu_info) numa_topology = self._get_host_numa_topology() if numa_topology: dic['numa_topology'] = numa_topology._to_json() else: dic['numa_topology'] = None return dic def host_power_action(self, action): """Reboots, shuts down or powers up the host.""" if action in [constants.HOST_POWER_ACTION_SHUTDOWN, constants.HOST_POWER_ACTION_REBOOT]: self._hostutils.host_power_action(action) else: if action == constants.HOST_POWER_ACTION_STARTUP: raise NotImplementedError( _("Host PowerOn is not supported by the Hyper-V driver")) def get_host_ip_addr(self): host_ip = CONF.my_ip if not host_ip: # Return the first available address host_ip = self._hostutils.get_local_ips()[0] LOG.debug("Host IP address is: %s", host_ip) return host_ip def get_host_uptime(self): """Returns the host uptime.""" tick_count64 = self._hostutils.get_host_tick_count64() # format the string to match libvirt driver uptime # Libvirt uptime returns a combination of the following # - current host time # - time since host is up # - number of logged in users # - cpu load # Since the Windows function GetTickCount64 returns only # the time since the host is up, returning 0s for cpu load # and number of logged in users. # This is done to ensure the format of the returned # value is same as in libvirt return "%s up %s, 0 users, load average: 0, 0, 0" % ( str(time.strftime("%H:%M:%S")), str(datetime.timedelta(milliseconds=int(tick_count64)))) def host_maintenance_mode(self, host, mode): """Starts/Stops host maintenance. On start, it triggers guest VMs evacuation. """ ctxt = context.get_admin_context() if not mode: self._set_service_state(host=host, binary='nova-compute', is_disabled=False) LOG.info(_LI('Host is no longer under maintenance.')) return 'off_maintenance' self._set_service_state(host=host, binary='nova-compute', is_disabled=True) vms_uuids = self._vmops.list_instance_uuids() for vm_uuid in vms_uuids: self._wait_for_instance_pending_task(ctxt, vm_uuid) vm_names = self._vmutils.list_instances() for vm_name in vm_names: self._migrate_vm(ctxt, vm_name, host) vms_uuid_after_migration = self._vmops.list_instance_uuids() remaining_vms = len(vms_uuid_after_migration) if remaining_vms == 0: LOG.info(_LI('All vms have been migrated successfully.' 'Host is down for maintenance')) return 'on_maintenance' raise exception.MigrationError( reason=_('Not all vms have been migrated: %s remaining instances.') % remaining_vms) def _set_service_state(self, host, binary, is_disabled): "Enables/Disables service on host" ctxt = context.get_admin_context(read_deleted='no') service = objects.Service.get_by_args(ctxt, host, binary) service.disabled = is_disabled service.save() def _migrate_vm(self, ctxt, vm_name, host): try: instance_uuid = self._vmutils.get_instance_uuid(vm_name) if not instance_uuid: LOG.info(_LI('VM "%s" running on this host was not created by ' 'nova. Skip migrating this vm to a new host.'), vm_name) return instance = objects.Instance.get_by_uuid(ctxt, instance_uuid) if instance.vm_state == vm_states.ACTIVE: self._api.live_migrate(ctxt, instance, block_migration=False, disk_over_commit=False, host_name=None) else: self._api.resize(ctxt, instance, flavor_id=None, clean_shutdown=True) self._wait_for_instance_pending_task(ctxt, instance_uuid) except Exception as e: LOG.error(_LE('Migrating vm failed with error: %s '), e) raise exception.MigrationError(reason='Unable to migrate %s.' % vm_name) def _wait_for_instance_pending_task(self, context, vm_uuid): instance = objects.Instance.get_by_uuid(context, vm_uuid) task_state_timeout = CONF.hyperv.evacuate_task_state_timeout while instance.task_state: LOG.debug("Waiting to evacuate instance %(instance_id)s. Current " "task state: '%(task_state)s', Time remaining: " "%(timeout)s.", {'instance_id': instance.id, 'task_state': instance.task_state, 'timeout': task_state_timeout}) time.sleep(1) instance.refresh() task_state_timeout -= 1 if task_state_timeout <= 0: err = (_("Timeout error. Instance %(instance)s hasn't changed " "task_state %(task_state)s within %(timeout)s " "seconds.") % {'instance': instance.name, 'task_state': instance.task_state, 'timeout': CONF.hyperv.evacuate_task_state_timeout}) raise exception.InternalError(message=err)
import warnings import string import numpy as np import pandas.util.testing as tm from pandas import (DataFrame, Series, Panel, MultiIndex, date_range, concat, merge, merge_asof) try: from pandas import merge_ordered except ImportError: from pandas import ordered_merge as merge_ordered class Append(object): def setup(self): self.df1 = DataFrame(np.random.randn(10000, 4), columns=['A', 'B', 'C', 'D']) self.df2 = self.df1.copy() self.df2.index = np.arange(10000, 20000) self.mdf1 = self.df1.copy() self.mdf1['obj1'] = 'bar' self.mdf1['obj2'] = 'bar' self.mdf1['int1'] = 5 try: with warnings.catch_warnings(record=True): self.mdf1.consolidate(inplace=True) except (AttributeError, TypeError): pass self.mdf2 = self.mdf1.copy() self.mdf2.index = self.df2.index def time_append_homogenous(self): self.df1.append(self.df2) def time_append_mixed(self): self.mdf1.append(self.mdf2) class Concat(object): params = [0, 1] param_names = ['axis'] def setup(self, axis): N = 1000 s = Series(N, index=tm.makeStringIndex(N)) self.series = [s[i:- i] for i in range(1, 10)] * 50 self.small_frames = [DataFrame(np.random.randn(5, 4))] * 1000 df = DataFrame({'A': range(N)}, index=date_range('20130101', periods=N, freq='s')) self.empty_left = [DataFrame(), df] self.empty_right = [df, DataFrame()] def time_concat_series(self, axis): concat(self.series, axis=axis) def time_concat_small_frames(self, axis): concat(self.small_frames, axis=axis) def time_concat_empty_right(self, axis): concat(self.empty_right, axis=axis) def time_concat_empty_left(self, axis): concat(self.empty_left, axis=axis) class ConcatPanels(object): params = ([0, 1, 2], [True, False]) param_names = ['axis', 'ignore_index'] def setup(self, axis, ignore_index): with warnings.catch_warnings(record=True): panel_c = Panel(np.zeros((10000, 200, 2), dtype=np.float32, order='C')) self.panels_c = [panel_c] * 20 panel_f = Panel(np.zeros((10000, 200, 2), dtype=np.float32, order='F')) self.panels_f = [panel_f] * 20 def time_c_ordered(self, axis, ignore_index): with warnings.catch_warnings(record=True): concat(self.panels_c, axis=axis, ignore_index=ignore_index) def time_f_ordered(self, axis, ignore_index): with warnings.catch_warnings(record=True): concat(self.panels_f, axis=axis, ignore_index=ignore_index) class ConcatDataFrames(object): params = ([0, 1], [True, False]) param_names = ['axis', 'ignore_index'] def setup(self, axis, ignore_index): frame_c = DataFrame(np.zeros((10000, 200), dtype=np.float32, order='C')) self.frame_c = [frame_c] * 20 frame_f = DataFrame(np.zeros((10000, 200), dtype=np.float32, order='F')) self.frame_f = [frame_f] * 20 def time_c_ordered(self, axis, ignore_index): concat(self.frame_c, axis=axis, ignore_index=ignore_index) def time_f_ordered(self, axis, ignore_index): concat(self.frame_f, axis=axis, ignore_index=ignore_index) class Join(object): params = [True, False] param_names = ['sort'] def setup(self, sort): level1 = tm.makeStringIndex(10).values level2 = tm.makeStringIndex(1000).values label1 = np.arange(10).repeat(1000) label2 = np.tile(np.arange(1000), 10) index2 = MultiIndex(levels=[level1, level2], labels=[label1, label2]) self.df_multi = DataFrame(np.random.randn(len(index2), 4), index=index2, columns=['A', 'B', 'C', 'D']) self.key1 = np.tile(level1.take(label1), 10) self.key2 = np.tile(level2.take(label2), 10) self.df = DataFrame({'data1': np.random.randn(100000), 'data2': np.random.randn(100000), 'key1': self.key1, 'key2': self.key2}) self.df_key1 = DataFrame(np.random.randn(len(level1), 4), index=level1, columns=['A', 'B', 'C', 'D']) self.df_key2 = DataFrame(np.random.randn(len(level2), 4), index=level2, columns=['A', 'B', 'C', 'D']) shuf = np.arange(100000) np.random.shuffle(shuf) self.df_shuf = self.df.reindex(self.df.index[shuf]) def time_join_dataframe_index_multi(self, sort): self.df.join(self.df_multi, on=['key1', 'key2'], sort=sort) def time_join_dataframe_index_single_key_bigger(self, sort): self.df.join(self.df_key2, on='key2', sort=sort) def time_join_dataframe_index_single_key_small(self, sort): self.df.join(self.df_key1, on='key1', sort=sort) def time_join_dataframe_index_shuffle_key_bigger_sort(self, sort): self.df_shuf.join(self.df_key2, on='key2', sort=sort) class JoinIndex(object): def setup(self): N = 50000 self.left = DataFrame(np.random.randint(1, N / 500, (N, 2)), columns=['jim', 'joe']) self.right = DataFrame(np.random.randint(1, N / 500, (N, 2)), columns=['jolie', 'jolia']).set_index('jolie') def time_left_outer_join_index(self): self.left.join(self.right, on='jim') class JoinNonUnique(object): # outer join of non-unique # GH 6329 def setup(self): date_index = date_range('01-Jan-2013', '23-Jan-2013', freq='T') daily_dates = date_index.to_period('D').to_timestamp('S', 'S') self.fracofday = date_index.values - daily_dates.values self.fracofday = self.fracofday.astype('timedelta64[ns]') self.fracofday = self.fracofday.astype(np.float64) / 86400000000000.0 self.fracofday = Series(self.fracofday, daily_dates) index = date_range(date_index.min(), date_index.max(), freq='D') self.temp = Series(1.0, index)[self.fracofday.index] def time_join_non_unique_equal(self): self.fracofday * self.temp class Merge(object): params = [True, False] param_names = ['sort'] def setup(self, sort): N = 10000 indices = tm.makeStringIndex(N).values indices2 = tm.makeStringIndex(N).values key = np.tile(indices[:8000], 10) key2 = np.tile(indices2[:8000], 10) self.left = DataFrame({'key': key, 'key2': key2, 'value': np.random.randn(80000)}) self.right = DataFrame({'key': indices[2000:], 'key2': indices2[2000:], 'value2': np.random.randn(8000)}) self.df = DataFrame({'key1': np.tile(np.arange(500).repeat(10), 2), 'key2': np.tile(np.arange(250).repeat(10), 4), 'value': np.random.randn(10000)}) self.df2 = DataFrame({'key1': np.arange(500), 'value2': np.random.randn(500)}) self.df3 = self.df[:5000] def time_merge_2intkey(self, sort): merge(self.left, self.right, sort=sort) def time_merge_dataframe_integer_2key(self, sort): merge(self.df, self.df3, sort=sort) def time_merge_dataframe_integer_key(self, sort): merge(self.df, self.df2, on='key1', sort=sort) class I8Merge(object): params = ['inner', 'outer', 'left', 'right'] param_names = ['how'] def setup(self, how): low, high, n = -1000, 1000, 10**6 self.left = DataFrame(np.random.randint(low, high, (n, 7)), columns=list('ABCDEFG')) self.left['left'] = self.left.sum(axis=1) self.right = self.left.sample(frac=1).rename({'left': 'right'}, axis=1) self.right = self.right.reset_index(drop=True) self.right['right'] *= -1 def time_i8merge(self, how): merge(self.left, self.right, how=how) class MergeCategoricals(object): def setup(self): self.left_object = DataFrame( {'X': np.random.choice(range(0, 10), size=(10000,)), 'Y': np.random.choice(['one', 'two', 'three'], size=(10000,))}) self.right_object = DataFrame( {'X': np.random.choice(range(0, 10), size=(10000,)), 'Z': np.random.choice(['jjj', 'kkk', 'sss'], size=(10000,))}) self.left_cat = self.left_object.assign( Y=self.left_object['Y'].astype('category')) self.right_cat = self.right_object.assign( Z=self.right_object['Z'].astype('category')) def time_merge_object(self): merge(self.left_object, self.right_object, on='X') def time_merge_cat(self): merge(self.left_cat, self.right_cat, on='X') class MergeOrdered(object): def setup(self): groups = tm.makeStringIndex(10).values self.left = DataFrame({'group': groups.repeat(5000), 'key': np.tile(np.arange(0, 10000, 2), 10), 'lvalue': np.random.randn(50000)}) self.right = DataFrame({'key': np.arange(10000), 'rvalue': np.random.randn(10000)}) def time_merge_ordered(self): merge_ordered(self.left, self.right, on='key', left_by='group') class MergeAsof(object): def setup(self): one_count = 200000 two_count = 1000000 df1 = DataFrame( {'time': np.random.randint(0, one_count / 20, one_count), 'key': np.random.choice(list(string.ascii_uppercase), one_count), 'key2': np.random.randint(0, 25, one_count), 'value1': np.random.randn(one_count)}) df2 = DataFrame( {'time': np.random.randint(0, two_count / 20, two_count), 'key': np.random.choice(list(string.ascii_uppercase), two_count), 'key2': np.random.randint(0, 25, two_count), 'value2': np.random.randn(two_count)}) df1 = df1.sort_values('time') df2 = df2.sort_values('time') df1['time32'] = np.int32(df1.time) df2['time32'] = np.int32(df2.time) self.df1a = df1[['time', 'value1']] self.df2a = df2[['time', 'value2']] self.df1b = df1[['time', 'key', 'value1']] self.df2b = df2[['time', 'key', 'value2']] self.df1c = df1[['time', 'key2', 'value1']] self.df2c = df2[['time', 'key2', 'value2']] self.df1d = df1[['time32', 'value1']] self.df2d = df2[['time32', 'value2']] self.df1e = df1[['time', 'key', 'key2', 'value1']] self.df2e = df2[['time', 'key', 'key2', 'value2']] def time_on_int(self): merge_asof(self.df1a, self.df2a, on='time') def time_on_int32(self): merge_asof(self.df1d, self.df2d, on='time32') def time_by_object(self): merge_asof(self.df1b, self.df2b, on='time', by='key') def time_by_int(self): merge_asof(self.df1c, self.df2c, on='time', by='key2') def time_multiby(self): merge_asof(self.df1e, self.df2e, on='time', by=['key', 'key2']) class Align(object): def setup(self): size = 5 * 10**5 rng = np.arange(0, 10**13, 10**7) stamps = np.datetime64('now').view('i8') + rng idx1 = np.sort(np.random.choice(stamps, size, replace=False)) idx2 = np.sort(np.random.choice(stamps, size, replace=False)) self.ts1 = Series(np.random.randn(size), idx1) self.ts2 = Series(np.random.randn(size), idx2) def time_series_align_int64_index(self): self.ts1 + self.ts2 def time_series_align_left_monotonic(self): self.ts1.align(self.ts2, join='left') from .pandas_vb_common import setup # noqa: F401
import numpy as np import pandas as pd import pytest from ..choice import * from ..sampling import seeded_call def test_binary_choice(): p = pd.Series([0, 0.1, 0.9]) expected_result = pd.Series([False, False, True]) # 1st test with a provided threshold t = 0.5 c1 = binary_choice(p, t) assert (c1 == expected_result).all() # next test with randoms (the default) # note the randoms produced with this seed should be # [0.69646919, 0.28613933, 0.22685145] seed = 123 c2 = seeded_call(seed, binary_choice, p) assert (c2 == expected_result).all() def test_rate_based_binary_choice(): # expected randoms should be # [ 0.69646919 0.28613933 0.22685145 0.55131477] seed = 123 rates = pd.DataFrame({ 'grp1': ['a', 'a', 'b'], 'grp2': [1, 2, 1], 'rate': [0.1, 0.6, 0.3] }) agents = pd.DataFrame({ 'grp1': ['a', 'a', 'b', 'b'], 'grp2': [1, 2, 1, 3] }) expected_result = pd.Series([False, True, True, False]) c = seeded_call( seed, rate_based_binary_choice, rates, 'rate', agents, ['grp1', 'grp2'] ) assert (c == expected_result).all() def test_logit_binary_choice(): seed = 123 agents = pd.DataFrame({ 'do_it': [1, 1, 1, 1, 0, 0, 0], 'var1': [1, 1, 1, 0, 0, 0, 0], 'var2': np.arange(7, 0, -1), 'intercept': np.ones(7) }) coeff = pd.Series( [-2, 3, .5], index=pd.Index(['intercept', 'var1', 'var2']) ) u, p, c = seeded_call(seed, logit_binary_choice, coeff, agents) expected_u = pd.Series([ 90.0171313, 54.59815003, 33.11545196, 1., 0.60653066, 0.36787944, 0.22313016 ]) assert (u.round(5) == expected_u.round(5)).all() expected_p = pd.Series([ 0.98901306, 0.98201379, 0.97068777, 0.5, 0.37754067, 0.26894142, 0.18242552 ]) assert (p.round(5) == expected_p.round(5)).all() # expected randoms should be # [ 0.69646919 0.28613933 0.22685145 0.55131477 # 0.71946897 0.42310646 0.9807642 ] expected_c = pd.Series([ True, True, True, False, False, False, False ]) assert (c == expected_c).all() ########################## # WEIGHTED CHOICE ########################## @pytest.fixture() def agents(): return pd.DataFrame({'col': ['a', 'b', 'c']}) @pytest.fixture() def alts(): return pd.DataFrame({ 'w': [1, 5, 10], 'c': [3, 2, 1] }) def test_weighted_choice_noW_noCap(agents, alts): c = seeded_call( 123, weighted_choice, agents, alts ) expected_c = pd.Series([2, 1, 2]) assert (c == expected_c).all() def test_weighted_choice_noCap(agents, alts): c = seeded_call( 123, weighted_choice, agents, alts, 'w' ) expected_c = pd.Series([2, 1, 1]) assert (c == expected_c).all() def test_weighted_choice_noW(agents, alts): c = seeded_call( 123, weighted_choice, agents, alts, cap_col='c' ) expected_c = pd.Series([0, 1, 1]) assert (c == expected_c).all() def test_weighted_choice(agents, alts): c = seeded_call( 123, weighted_choice, agents, alts, w_col='w', cap_col='c' ) expected_c = pd.Series([2, 1, 1]) assert (c == expected_c).all() def test_weighted_choice_notEnoughCap(agents, alts): with pytest.raises(ValueError): weighted_choice(agents, alts.loc[2], w_col='w', cap_col='c') ######################################### # CHOICE WITH SAMPLING OF ALTERNATIVES ######################################### @pytest.fixture() def choosers(): return pd.DataFrame( { 'agent_col1': [10, 20, 30] }, index=pd.Index(list('cba')) ) @pytest.fixture() def alternatives(): return pd.DataFrame( { 'alt_col1': [100, 200, 300, 400, 500], 'cap': [2, 2, 0, 1, 1] }, index=pd.Index(np.arange(5, 0, -1,)) ) def test_get_interaction_data(choosers, alternatives): seed = 123 sample_size = 2 def check_results(data, num_choosers, size, expected_choosers, exepected_alts): for cc in choosers.columns: assert cc in data.columns for ac in alternatives.columns: assert ac in data.columns assert len(data) == num_choosers * size choosers_idx = data.index.get_level_values(0).values alts_idx = data.index.get_level_values(1).values assert (choosers_idx == expected_choosers).all() assert (alts_idx == expected_alts).all() # with replacement data, new_size = seeded_call( seed, get_interaction_data, choosers, alternatives, sample_size) expected_choosers = ['c', 'c', 'b', 'b', 'a', 'a'] expected_alts = [1, 3, 3, 4, 2, 3] assert new_size == sample_size check_results(data, len(choosers), new_size, expected_choosers, expected_alts) # without replacement -- note not enough alternative to satify sample size # so sample size will be adjusted to 1 per agent data, new_size = seeded_call( seed, get_interaction_data, choosers, alternatives, sample_size, False) expected_choosers = ['c', 'b', 'a'] expected_alts = [4, 2, 1] def prob_call(interaction_data, num_choosers, sample_size, factor): # simple probabilities function that just uses the alt column as a weight util = factor * interaction_data['alt_col1'].values.reshape(num_choosers, sample_size) return util / util.sum(axis=1, keepdims=True) def test_choice_with_sampling(choosers, alternatives): seed = 123 sample_size = 4 # 1st test w/out verbosity choices = seeded_call( seed, choice_with_sampling, choosers, alternatives, prob_call, factor=1.0, sample_size=sample_size ) assert (choices['alternative_id'] == [1, 4, 1]).all() # now test w/ samples as well choices, samples = seeded_call( seed, choice_with_sampling, choosers, alternatives, prob_call, factor=1.0, sample_size=sample_size, verbose=True ) assert (choices['alternative_id'] == [1, 4, 1]).all() assert len(samples) == len(choosers) * sample_size assert 'alternative_id' in samples.columns assert 'chooser_id' in samples.columns assert 'prob' in samples.columns # test without replacement choices, samples = seeded_call( seed, choice_with_sampling, choosers.head(2), alternatives, prob_call, sample_size=2, verbose=True, factor=2.0, sample_replace=False ) assert (choices['alternative_id'] == [2, 1]).all() assert len(samples) == 4 # test without replacement, without enough alts with pytest.raises(ValueError): choices = choice_with_sampling( choosers, alternatives.head(2), prob_call, sample_size=sample_size, factor=2.0, sample_replace=False ) def test_capacity_choice_with_sampling(choosers, alternatives): seed = 123 sample_size = 4 choices, capacities = seeded_call( seed, capacity_choice_with_sampling, choosers, alternatives, 'cap', prob_call, sample_size, factor=2.0 ) assert (choices == pd.Series([1, 5, 2], index=choosers.index)).all() assert (capacities == pd.Series([1, 2, 0, 0, 0], index=alternatives.index)).all() def test_capacity_choice_with_sampling_notEnoughCap(choosers, alternatives): seed = 123 sample_size = 4 choices, capacities = seeded_call( seed, capacity_choice_with_sampling, choosers, alternatives.head(1), 'cap', prob_call, sample_size, factor=2.0 ) print choices assert choices.loc['c'] == 5 assert choices.loc['b'] == 5 assert (choices.isnull().values == [False, False, True]).all() assert (capacities == pd.Series([0], index=pd.Index([5]))).all() def test_capacity_choice_with_sampling_finalI(choosers, alternatives): seed = 123 sample_size = 4 choices, capacities = seeded_call( seed, capacity_choice_with_sampling, choosers, alternatives, 'cap', prob_call, sample_size, max_iterations=1, factor=2.0 ) assert (choices == pd.Series([5, 1, 4], index=choosers.index)).all() assert (capacities == pd.Series([1, 1, 0, 1, 0], index=alternatives.index)).all() def test_get_mnl_probs(choosers, alternatives): # get some interaction data # note this chooses alt IDs [1, 3, 3, 4, 2, 3] # resulting alt_col1 values: [500, 300, 300, 200, 400, 300] # resulting agent_col1 values: [10, 10, 20, 20, 30, 30] sample_size = 2 data, new_size = seeded_call( 123, get_interaction_data, choosers, alternatives, sample_size) # define some coeeficients coeff = pd.Series([0.1, .01], index=pd.Index(['agent_col1', 'alt_col1'])) # expected results exp_p = np.round([0.8807, 0.1192, 0.7310, 0.26894, 0.7310, 0.2689], 2) # test w/out an expression p1 = get_mnl_probs(data, len(choosers), sample_size, coeff) assert (np.round(p1.ravel(), 2) == exp_p).all() # test w/ patsy expression expr = 'agent_col1 + alt_col1' p2 = get_mnl_probs(data, len(choosers), sample_size, coeff, expr) assert (np.round(p2.ravel(), 2) == exp_p).all() # test w/ an intercept in the coefficients coeff.loc['Intercept'] = 1 p3 = get_mnl_probs(data, len(choosers), sample_size, coeff) assert (np.round(p3.ravel(), 2) == exp_p).all def test_mnl_choice_with_sampling(choosers, alternatives): seed = 123 sample_size = 4 coeff = pd.Series( [0.5, .01], index=['agent_col1', 'alt_col1'] ) # test 1 - no capacity choices = seeded_call( seed, mnl_choice_with_sampling, choosers, alternatives, coeff ) assert (choices == pd.Series([1, 3, 1], index=choosers.index)).all() # test 2 - with capacities, use a patsy expression this time expr = 'agent_col1 + alt_col1' choices = seeded_call( seed, mnl_choice_with_sampling, choosers, alternatives, coeff, expr, sample_size=sample_size, cap_col='cap' ) assert (choices == pd.Series([4, 2, 1], index=choosers.index)).all()
import sys, os, getopt import string import numpy import re from difflib import SequenceMatcher import swalign import textwrap ''' for the swalign stuff, had to make some changes to the file to fix syntax like changing xrange to range and including print things in () ''' def aligned_query_filtering(original,query): y=query.split() lengths=[] for a in y: x=len(a) lengths.append(x) for i in range(len(y)): if y[i] not in original: if y[i][0] is '-': regex=re.compile('^-+') y[i]=regex.sub('',y[i]) y[i]=y[i].rjust(lengths[i]) if y[i][-1] is '-': regex=re.compile('-+$') y[i]=regex.sub('',y[i]) y[i]=y[i].ljust(lengths[i]) regex=re.compile('-*') y[i]=regex.sub('', y[i]) y[i]=y[i].ljust(lengths[i]) return list_to_string(y) def aligned_ref_filtering(original, ref): y=ref.split() lengths=[] for a in y: x=len(a) lengths.append(x) for i in range(len(y)): if y[i] not in original: if y[i][0] is '-': regex=re.compile('^-+') y[i]=regex.sub('',y[i]) y[i]=y[i].rjust(lengths[i]) if y[i][-1] is '-': regex=re.compile('-+$') y[i]=regex.sub('',y[i]) y[i]=y[i].ljust(lengths[i]) regex=re.compile('-*') y[i]=regex.sub('', y[i]) y[i]=y[i].ljust(lengths[i]) return list_to_string(y) def list_to_string(string_list): s='' for sr in string_list: s+=sr+' ' return s.lstrip().rstrip() ''' number of errors (deletion, insertion, substitution) ---- wer code below from https://martin-thoma.com/word-error-rate-calculation/ ''' def wer(r, h): #r and h are lists # initialisation d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint8) d = d.reshape((len(r)+1, len(h)+1)) for i in range(len(r)+1): for j in range(len(h)+1): if i == 0: d[0][j] = j elif j == 0: d[i][0] = i # computation for i in range(1, len(r)+1): for j in range(1, len(h)+1): if r[i-1] == h[j-1]: d[i][j] = d[i-1][j-1] else: substitution = d[i-1][j-1] + 1 insertion = d[i][j-1] + 1 deletion = d[i-1][j] + 1 d[i][j] = min(substitution, insertion, deletion) return d[len(r)][len(h)] def print_alignment(str1,str2, out, width=100): l1=len(str1) l2=len(str2) i = 0 while i < min(l1,l2): line1 = str1[i:min(i+width,l1)] line2 = str2[i:min(i+width,l2)] i += width if min(i,l1-1,l2-1) is not i: break while str1[i] is not ' ' or str2[i] is not ' ': line1 += str1[i] line2 += str2[i] i += 1 if min(i,l1-1,l2-1) is not i: break out.write(line1+'\n') out.write(line2+'\n\n') def print_alignment_withSymbol(str1,str2, symbol, out, width=100): reg = [' ','-'] l1=len(str1) l2=len(str2) l3=len(symbol) i = 0 while i < min(l1,l2): line1 = str1[i:min(i+width,l1)] line2 = symbol[i:min(i+width,l3)] line3 = str2[i:min(i+width,l2)] i += width if min(i,l1-1,l2-1) is not i: break while str1[i] not in reg or str2[i] not in reg: line1 += str1[i] line2 += symbol[i] line3 += str2[i] i += 1 if min(i,l1-1,l2-1) is not i: break out.write(line1+'\n') out.write(line2+'\n') out.write(line3+'\n\n') def remove_ref_punctuation(lines_list,grnd): #lines_list is list of transcript file lines reg123=['\'','\"','\.*','\,','\?','\!'] reg_list=[] for r in reg123: reg_list.append(re.compile(r)) paragraphs=lines_list filtered=[] for p in paragraphs: fil=p for regex in reg_list: fil=regex.sub('', fil) filtered.append(fil) t=[] prev='' count=0 for i in range(len(filtered)): f = filtered[i].lstrip().rstrip().rstrip('\n') if f == '': continue seq=SequenceMatcher(None,prev,f) a=seq.find_longest_match(0,len(prev),0,len(f)) x=a[0] y=a[1] size=a[2] str1=prev[x:x+size].lstrip().rstrip() str2=f[y:y+size].lstrip().rstrip() ## print(str1,' ||| ', str2) ## print(a) if y==0: if prev[x:x+size] == prev[-size:]: c=str1+' '+str2 ## print(prev[x:x+size]) ## print(prev[-size:]) ## print(c, c not in grnd) if c not in grnd: ## print(a) ## print(prev) ## print(f) ## print(c) t.append(prev[:-size-1]) else: t.append(prev) else: t.append(prev) else: t.append(prev) prev=f #not all repetition is removed the first time b/c longest match #isn't always the beginning/end #this below helps get some of the smaller beginnig/end repetitions in transcript #lines, but not all.. I'm not sure how to fix it prev='' s='' count=0 for i in range(len(t)): f = t[i].lstrip().rstrip() ## print('CURR:', f) ## print('PREV:',prev) if f == '': continue ps=prev.split() fs=f.split() j=0 w=fs[j] #print(w) w=fs.pop(0) while w in ps and len(fs) !=0: w+=' '+fs[0] a=prev.find(w.strip()) if a>=0: ## print(prev) ## print(f) ## print(prev[a:],' |||| ',w) ## print(a) c=prev[a:]+' '+w #print(c) if prev[a:].strip()==w.strip() and c not in grnd: #print(w,len(w)) #print(a) #print(prev[a:],' |||| ',w) #print('repeat') #print(s) s=s[:-len(w.strip())-1] #print(s) s+=f+' ' prev=f return s.lower().lstrip().rstrip() '----------------------------------------------------------------------' ''' names=[] grnd_names=[] with open('filename.txt') as f: filelist = f.readlines() #print(filelist) for name in filelist: x=name[-21:-1] names.append(x) grnd_names.append(x[:-14]+'groundtruth.txt') #print(grnd_names) #print(names) error_sum=0 file=open('child_speech_recognition_evaluation2.txt',"w") for i in range(len(names)): paragraphs=[] with open(names[i]) as f: paragraphs=f.readlines() filtered=[] regex=re.compile('\;\d*\.*\d*') #remove the ;numbers at the end of each line in transcrip files and save to new file for p in paragraphs: fil=regex.sub(' ', p) fil=re.compile('\n').sub('',fil) filtered.append(fil) a=remove_grnd_punctuation(grnd_names[i]) aa=a.split() aaa=list_to_string(aa) r=remove_ref_punctuation(filtered,aaa) rr=r.split() rrr=list_to_string(rr) x=get_alignment_WER(rrr,aaa) #x[0] total words, x[1] # errors, x[2] WER print(grnd_names[i][:-16]) print('*******************************************************') s=grnd_names[i][:-16] +','+str(x[0])+','+str(x[1])+','+str(x[2])+'\n' error_sum+=x[2] file.write(s) file.close() print('average WER: ',error_sum/65) ''' def trim_query_lines(dir, query_lines, align_parser): # create result and directory if not os.path.exists(dir): os.makedirs(dir) for i in range(len(query_lines)-1): alignment = align_parser.align(query_lines[i],query_lines[i+1]) alignment.dump() def main(argv): query_dir = '' # text to be aligned (e.g., result from speech api) ref_dir = '' # text to be aligned against (e.g., hand transcription) result_dir = 'result/' # punctuation regex = re.compile('[%s]' % re.escape(string.punctuation)) match = 3 mismatch = -1 scoring = swalign.NucleotideScoringMatrix(match, mismatch) sw = swalign.LocalAlignment(scoring,-1.5,-.4) # you can also choose gap penalties, etc... # can play around with values of match, mismatch, and the gaps parameters in localalignment try: opts, args = getopt.getopt(argv,"hq:r:",["queryDir=","refDir="]) except getopt.GetoptError: print ('text_alignment.py -q <query_dir> -r <ref_dir>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('text_alignment.py -q <query_dir> -r <ref_dir>') sys.exit() elif opt in ("-q", "--queryDir"): query_dir = arg elif opt in ("-r", "--refDir"): ref_dir = arg print ('Query Directory is ', query_dir) print ('Reference Directory is ', ref_dir) # create result and directory if not os.path.exists(result_dir): os.makedirs(result_dir) # for root, subdirs, files in os.walk(query_dir): for filename in files: if filename.endswith('txt'): query_file_path = os.path.join(root, filename) print (query_file_path) ref_file_path = os.path.join(ref_dir, filename.replace('transcript','groundtruth')) print (ref_file_path) rst_file_path = os.path.join(result_dir, filename.replace('transcript','result')) #query_lines=[] query_line='' ref_line='' with open(query_file_path, 'r') as query_file, open(ref_file_path, 'r') as ref_file, open(rst_file_path, 'w+') as rst_file: for line in query_file: line = re.split(';', line) line = regex.sub('', line[0]).rstrip().lower() query_line += line + ' ' #query_lines.append(line) #trim_query_lines('query_trimmed', query_lines, sw) for line in ref_file: line = regex.sub('', line).rstrip().lower() ref_line += line + ' ' #print query_line #print ref_line alignment=sw.align(query_line,ref_line) x=alignment.match() #x[0] corresponding with ref_line, x[1] corresponding with query_line print('****************************************************************') #print_alignment_withSymbol(x[0],x[1],x[2],sys.stdout) #print_alignment(x[0],x[1],sys.stdout) # changed a and aa to be ref_line_filtered and ref_line_filtered_split # changed b and bb to be query_line_filtered and query_line_filtered_split # changed aligned_act_filtering name to aligned_ref_filtering # changed aligned_rec_filtering name to aligned_query_filtering ref_line_filtered=aligned_ref_filtering(ref_line, x[0]) query_line_filtered=aligned_query_filtering(query_line, x[1]) print_alignment(ref_line_filtered,query_line_filtered,rst_file) query_line_filtered_split=query_line_filtered.split() ref_line_filtered_split=ref_line_filtered.split() errors=wer(query_line_filtered_split,ref_line_filtered_split) rst_file.write('\n\n\ntotal words: %d' % len(ref_line_filtered_split)) rst_file.write('\nERRORS: %d' % errors) rst_file.write('\nWER: %.4f\n' % (errors/float(len(ref_line_filtered_split)))) if __name__ == "__main__": main(sys.argv[1:])
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Counter' db.create_table( 'sentry_projectcounter', ( ( 'id', self.gf('sentry.db.models.fields.bounded.BoundedBigAutoField')( primary_key=True ) ), ( 'project', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')( to=orm['sentry.Project'], unique=True ) ), ('value', self.gf('sentry.db.models.fields.bounded.BoundedBigIntegerField')()), ) ) db.send_create_signal('sentry', ['Counter']) # Adding field 'Group.short_id' db.add_column( 'sentry_groupedmessage', 'short_id', self.gf('sentry.db.models.fields.bounded.BoundedBigIntegerField')(null=True), keep_default=False ) # Adding unique constraint on 'Group', fields ['project', 'short_id'] db.create_unique('sentry_groupedmessage', ['project_id', 'short_id']) def backwards(self, orm): # Removing unique constraint on 'Group', fields ['project', 'short_id'] db.delete_unique('sentry_groupedmessage', ['project_id', 'short_id']) # Deleting model 'Counter' db.delete_table('sentry_projectcounter') # Deleting field 'Group.short_id' db.delete_column('sentry_groupedmessage', 'short_id') models = { 'sentry.activity': { 'Meta': { 'object_name': 'Activity' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ) }, 'sentry.apikey': { 'Meta': { 'object_name': 'ApiKey' }, 'allowed_origins': ('django.db.models.fields.TextField', [], { 'null': 'True', 'blank': 'True' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '32' }), 'label': ( 'django.db.models.fields.CharField', [], { 'default': "'Default'", 'max_length': '64', 'blank': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Organization']" } ), 'scopes': ('django.db.models.fields.BigIntegerField', [], { 'default': 'None' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.auditlogentry': { 'Meta': { 'object_name': 'AuditLogEntry' }, 'actor': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'audit_actors'", 'null': 'True', 'to': "orm['sentry.User']" } ), 'actor_key': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.ApiKey']", 'null': 'True', 'blank': 'True' } ), 'actor_label': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True', 'blank': 'True' } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ip_address': ( 'django.db.models.fields.GenericIPAddressField', [], { 'max_length': '39', 'null': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'target_user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.authidentity': { 'Meta': { 'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity' }, 'auth_provider': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.AuthProvider']" } ), 'data': ('sentry.db.models.fields.jsonfield.JSONField', [], { 'default': '{}' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'last_synced': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'last_verified': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.authprovider': { 'Meta': { 'object_name': 'AuthProvider' }, 'config': ('sentry.db.models.fields.jsonfield.JSONField', [], { 'default': '{}' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'default_global_access': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'default_teams': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True' } ), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_sync': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']", 'unique': 'True' } ), 'provider': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }) }, 'sentry.broadcast': { 'Meta': { 'object_name': 'Broadcast' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'date_expires': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime(2016, 3, 11, 0, 0)', 'null': 'True', 'blank': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True', 'db_index': 'True' }), 'link': ( 'django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.CharField', [], { 'max_length': '256' }), 'title': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'upstream_id': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'blank': 'True' } ) }, 'sentry.broadcastseen': { 'Meta': { 'unique_together': "(('broadcast', 'user'),)", 'object_name': 'BroadcastSeen' }, 'broadcast': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Broadcast']" } ), 'date_seen': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.counter': { 'Meta': { 'object_name': 'Counter', 'db_table': "'sentry_projectcounter'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'unique': True } ), 'value': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}) }, 'sentry.event': { 'Meta': { 'unique_together': "(('project_id', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group_id', 'datetime'),)" }, 'data': ('sentry.db.models.fields.node.NodeField', [], { 'null': 'True', 'blank': 'True' }), 'datetime': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'event_id': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'db_column': "'message_id'" } ), 'group_id': ( 'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], { 'null': 'True', 'blank': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project_id': ( 'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], { 'null': 'True', 'blank': 'True' } ), 'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'null': 'True' }) }, 'sentry.eventmapping': { 'Meta': { 'unique_together': "(('project_id', 'event_id'),)", 'object_name': 'EventMapping' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event_id': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}) }, 'sentry.eventtag': { 'Meta': { 'unique_together': "(('event_id', 'key_id', 'value_id'),)", 'object_name': 'EventTag' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}), 'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}), 'value_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}) }, 'sentry.eventuser': { 'Meta': { 'unique_together': "(('project', 'ident'), ('project', 'hash'))", 'object_name': 'EventUser', 'index_together': "(('project', 'email'), ('project', 'username'), ('project', 'ip_address'))" }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75', 'null': 'True' }), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '128', 'null': 'True' }), 'ip_address': ( 'django.db.models.fields.GenericIPAddressField', [], { 'max_length': '39', 'null': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'username': ('django.db.models.fields.CharField', [], { 'max_length': '128', 'null': 'True' }) }, 'sentry.file': { 'Meta': { 'object_name': 'File' }, 'blob': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'legacy_blob'", 'null': 'True', 'to': "orm['sentry.FileBlob']" } ), 'blobs': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.FileBlob']", 'through': "orm['sentry.FileBlobIndex']", 'symmetrical': 'False' } ), 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '40', 'null': 'True' }), 'headers': ('sentry.db.models.fields.jsonfield.JSONField', [], { 'default': '{}' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'path': ('django.db.models.fields.TextField', [], { 'null': 'True' }), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'timestamp': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'type': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.fileblob': { 'Meta': { 'object_name': 'FileBlob' }, 'checksum': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '40' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'path': ('django.db.models.fields.TextField', [], { 'null': 'True' }), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'timestamp': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ) }, 'sentry.fileblobindex': { 'Meta': { 'unique_together': "(('file', 'blob', 'offset'),)", 'object_name': 'FileBlobIndex' }, 'blob': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.FileBlob']" } ), 'file': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.File']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'offset': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}) }, 'sentry.globaldsymfile': { 'Meta': { 'object_name': 'GlobalDSymFile' }, 'cpu_name': ('django.db.models.fields.CharField', [], { 'max_length': '40' }), 'file': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.File']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'object_name': ('django.db.models.fields.TextField', [], {}), 'uuid': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '36' }) }, 'sentry.group': { 'Meta': { 'unique_together': "(('project', 'short_id'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'", 'index_together': "(('project', 'first_release'),)" }, 'active_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'culprit': ( 'django.db.models.fields.CharField', [], { 'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True' } ), 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_release': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Release']", 'null': 'True', 'on_delete': 'models.PROTECT' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_public': ( 'django.db.models.fields.NullBooleanField', [], { 'default': 'False', 'null': 'True', 'blank': 'True' } ), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'level': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '40', 'db_index': 'True', 'blank': 'True' } ), 'logger': ( 'django.db.models.fields.CharField', [], { 'default': "''", 'max_length': '64', 'db_index': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'null': 'True' } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'resolved_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'short_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'times_seen': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '1', 'db_index': 'True' } ) }, 'sentry.groupassignee': { 'Meta': { 'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'" }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.groupbookmark': { 'Meta': { 'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.groupemailthread': { 'Meta': { 'unique_together': "(('email', 'group'), ('email', 'msgid'))", 'object_name': 'GroupEmailThread' }, 'date': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'groupemail_set'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'msgid': ('django.db.models.fields.CharField', [], { 'max_length': '100' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'groupemail_set'", 'to': "orm['sentry.Project']" } ) }, 'sentry.grouphash': { 'Meta': { 'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ) }, 'sentry.groupmeta': { 'Meta': { 'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.groupresolution': { 'Meta': { 'object_name': 'GroupResolution' }, 'datetime': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'unique': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'release': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Release']" } ), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.grouprulestatus': { 'Meta': { 'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_active': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'rule': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Rule']" } ), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], { 'default': '0' }) }, 'sentry.groupseen': { 'Meta': { 'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_seen': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'db_index': 'False' } ) }, 'sentry.groupsnooze': { 'Meta': { 'object_name': 'GroupSnooze' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'unique': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'until': ('django.db.models.fields.DateTimeField', [], {}) }, 'sentry.grouptagkey': { 'Meta': { 'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.grouptagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'" }, 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']" } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.helppage': { 'Meta': { 'object_name': 'HelpPage' }, 'content': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_visible': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'key': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'unique': 'True', 'null': 'True' } ), 'priority': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'title': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.lostpasswordhash': { 'Meta': { 'object_name': 'LostPasswordHash' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'unique': 'True' } ) }, 'sentry.option': { 'Meta': { 'object_name': 'Option' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '64' }), 'last_updated': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': { 'object_name': 'Organization' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'default_role': ('django.db.models.fields.CharField', [], { 'default': "'member'", 'max_length': '32' }), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '1' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'members': ( 'django.db.models.fields.related.ManyToManyField', [], { 'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']" } ), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'slug': ('django.db.models.fields.SlugField', [], { 'unique': 'True', 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.organizationaccessrequest': { 'Meta': { 'unique_together': "(('team', 'member'),)", 'object_name': 'OrganizationAccessRequest' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'member': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.OrganizationMember']" } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.organizationmember': { 'Meta': { 'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember' }, 'counter': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True', 'blank': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ( 'django.db.models.fields.EmailField', [], { 'max_length': '75', 'null': 'True', 'blank': 'True' } ), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'has_global_access': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'member_set'", 'to': "orm['sentry.Organization']" } ), 'role': ('django.db.models.fields.CharField', [], { 'default': "'member'", 'max_length': '32' }), 'teams': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Team']", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMemberTeam']", 'blank': 'True' } ), 'type': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50', 'blank': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.organizationmemberteam': { 'Meta': { 'unique_together': "(('team', 'organizationmember'),)", 'object_name': 'OrganizationMemberTeam', 'db_table': "'sentry_organizationmember_teams'" }, 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'organizationmember': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.OrganizationMember']" } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.organizationonboardingtask': { 'Meta': { 'unique_together': "(('organization', 'task'),)", 'object_name': 'OrganizationOnboardingTask' }, 'data': ('sentry.db.models.fields.jsonfield.JSONField', [], { 'default': '{}' }), 'date_completed': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'project_id': ( 'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], { 'null': 'True', 'blank': 'True' } ), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'task': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ) }, 'sentry.organizationoption': { 'Meta': { 'unique_together': "(('organization', 'key'),)", 'object_name': 'OrganizationOption', 'db_table': "'sentry_organizationoptions'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.project': { 'Meta': { 'unique_together': "(('team', 'slug'), ('organization', 'slug'), ('organization', 'callsign'))", 'object_name': 'Project' }, 'callsign': ('django.db.models.fields.CharField', [], { 'max_length': '40', 'null': 'True' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'first_event': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '200' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'public': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50', 'null': 'True' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.projectbookmark': { 'Meta': { 'unique_together': "(('project_id', 'user'),)", 'object_name': 'ProjectBookmark' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project_id': ( 'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], { 'null': 'True', 'blank': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.projectdsymfile': { 'Meta': { 'unique_together': "(('project', 'uuid'),)", 'object_name': 'ProjectDSymFile' }, 'cpu_name': ('django.db.models.fields.CharField', [], { 'max_length': '40' }), 'file': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.File']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'object_name': ('django.db.models.fields.TextField', [], {}), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'uuid': ('django.db.models.fields.CharField', [], { 'max_length': '36' }) }, 'sentry.projectkey': { 'Meta': { 'object_name': 'ProjectKey' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True', 'blank': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Project']" } ), 'public_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'roles': ('django.db.models.fields.BigIntegerField', [], { 'default': '1' }), 'secret_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.projectoption': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': { 'unique_together': "(('project', 'version'),)", 'object_name': 'Release' }, 'data': ('sentry.db.models.fields.jsonfield.JSONField', [], { 'default': '{}' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'date_released': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'blank': 'True' }), 'date_started': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'blank': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'new_groups': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True', 'blank': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'ref': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True', 'blank': 'True' } ), 'url': ( 'django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True', 'blank': 'True' } ), 'version': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.releasefile': { 'Meta': { 'unique_together': "(('release', 'ident'),)", 'object_name': 'ReleaseFile' }, 'file': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.File']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '40' }), 'name': ('django.db.models.fields.TextField', [], {}), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'release': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Release']" } ) }, 'sentry.rule': { 'Meta': { 'object_name': 'Rule' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) }, 'sentry.savedsearch': { 'Meta': { 'unique_together': "(('project', 'name'),)", 'object_name': 'SavedSearch' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_default': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'query': ('django.db.models.fields.TextField', [], {}) }, 'sentry.savedsearchuserdefault': { 'Meta': { 'unique_together': "(('project', 'user'),)", 'object_name': 'SavedSearchUserDefault', 'db_table': "'sentry_savedsearch_userdefault'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'savedsearch': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.SavedSearch']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.tagkey': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.tagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'" }, 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.team': { 'Meta': { 'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.user': { 'Meta': { 'object_name': 'User', 'db_table': "'auth_user'" }, 'date_joined': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75', 'blank': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'is_managed': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'is_staff': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'is_superuser': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'last_login': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'name': ( 'django.db.models.fields.CharField', [], { 'max_length': '200', 'db_column': "'first_name'", 'blank': 'True' } ), 'password': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'username': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '128' }) }, 'sentry.useroption': { 'Meta': { 'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.userreport': { 'Meta': { 'object_name': 'UserReport', 'index_together': "(('project', 'event_id'), ('project', 'date_added'))" }, 'comments': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75' }), 'event_id': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) } } complete_apps = ['sentry']
# -*- coding: utf-8 -*- import collections import mimetypes import os import random from django.conf import settings from django.utils.translation import activate from django.core.files.uploadedfile import SimpleUploadedFile from django.test.client import RequestFactory from fxa.constants import ENVIRONMENT_URLS from fxa.core import Client from fxa.tests.utils import TestEmailAccount from rest_framework import serializers import olympia.core.logger from olympia.amo.tests import user_factory, addon_factory, copy_file_to_temp from olympia import amo from olympia.addons.forms import icons from olympia.addons.models import AddonUser, Preview, Addon from olympia.addons.utils import generate_addon_guid from olympia.constants.applications import APPS, FIREFOX from olympia.constants.base import ( ADDON_EXTENSION, ADDON_PERSONA, STATUS_PUBLIC ) from olympia.landfill.collection import generate_collection from olympia.landfill.generators import generate_themes from olympia.landfill.user import generate_user from olympia.files.tests.test_file_viewer import get_file from olympia.ratings.models import Rating from olympia.users.models import UserProfile from olympia.devhub.tasks import create_version_for_upload log = olympia.core.logger.getLogger('z.users') class GenerateAddonsSerializer(serializers.Serializer): count = serializers.IntegerField(default=10) def __init__(self): self.fxa_email = os.environ['FXA_EMAIL'] self.fxa_password = os.environ['FXA_PASSWORD'] self.fxa_id = self._create_fxa_user() self.user = self._create_addon_user() def _create_fxa_user(self): """Create fxa user for logging in.""" fxa_client = Client(ENVIRONMENT_URLS['stable']['authentication']) account = TestEmailAccount(email=self.fxa_email) password = self.fxa_password FxAccount = collections.namedtuple('FxAccount', 'email password') fxa_account = FxAccount(email=account.email, password=password) session = fxa_client.create_account(fxa_account.email, fxa_account.password) account.fetch() message = account.wait_for_email( lambda m: 'x-verify-code' in m['headers'] and session.uid == m['headers']['x-uid'] ) session.verify_email_code(message['headers']['x-verify-code']) log.debug('fxa account created: {}'.format(fxa_account)) return session.uid def _create_addon_user(self): """Create addon user with fxa information assigned.""" try: return UserProfile.objects.create_user( username='uitest', email=self.fxa_email, fxa_id=self.fxa_id, display_name='uitest' ) except Exception as e: log.debug('There was a problem creating the user: {}.' ' Returning user from database'.format(e)) return UserProfile.objects.get(username='uitest') def create_generic_featured_addons(self): """Creates 10 addons. Creates exactly 10 random addons with users that are also randomly generated. """ for _ in range(10): AddonUser.objects.create( user=user_factory(), addon=addon_factory()) def create_named_addon_with_author(self, name, author=None): """Create a generic addon and a user. The user will be created if a user is not given. """ if author is None: author = user_factory() try: generate_user(author) except Exception: # django.db.utils.IntegrityError # If the user is already made, use that same user, # if not use created user addon = addon_factory( status=STATUS_PUBLIC, users=[UserProfile.objects.get(username=author)], name=u'{}'.format(name), slug=u'{}'.format(name), ) addon.save() else: addon = addon_factory( status=STATUS_PUBLIC, users=[UserProfile.objects.get(username=author.username)], name=u'{}'.format(name), slug=u'{}'.format(name), ) addon.save() return addon def create_featured_addon_with_version(self): """Creates a custom addon named 'Ui-Addon'. This addon will be a featured addon and will have a featured collecton attatched to it. It will belong to the user uitest. It has 1 preview, 5 reviews, and 2 authors. The second author is named 'ui-tester2'. It has a version number. """ default_icons = [x[0] for x in icons() if x[0].startswith('icon/')] addon = addon_factory( status=STATUS_PUBLIC, type=ADDON_EXTENSION, average_daily_users=5000, users=[self.user], average_rating=5, description=u'My Addon description', file_kw={ 'hash': 'fakehash', 'platform': amo.PLATFORM_ALL.id, 'size': 42, }, guid=generate_addon_guid(), icon_type=random.choice(default_icons), name=u'Ui-Addon', public_stats=True, slug='ui-test-2', summary=u'My Addon summary', tags=['some_tag', 'another_tag', 'ui-testing', 'selenium', 'python'], total_ratings=500, weekly_downloads=9999999, developer_comments='This is a testing addon.', ) Preview.objects.create(addon=addon, position=1) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) Rating.objects.create(addon=addon, rating=5, user=user_factory()) AddonUser.objects.create(user=user_factory(username='ui-tester2'), addon=addon, listed=True) addon.save() generate_collection(addon, app=FIREFOX) print( 'Created addon {0} for testing successfully' .format(addon.name)) def create_featured_addon_with_version_for_install(self): """Creates a custom addon named 'Ui-Addon'. This addon will be a featured addon and will have a featured collecton attatched to it. It will belong to the user uitest. It has 1 preview, 5 reviews, and 2 authors. The second author is named 'ui-tester2'. It has a version number. """ default_icons = [x[0] for x in icons() if x[0].startswith('icon/')] try: addon = Addon.objects.get(guid='@webextension-guid') except Addon.DoesNotExist: addon = addon_factory( status=STATUS_PUBLIC, type=ADDON_EXTENSION, file_kw=False, average_daily_users=5000, users=[self.user], average_rating=5, description=u'My Addon description', guid='@webextension-guid', icon_type=random.choice(default_icons), name=u'Ui-Addon-Install', public_stats=True, slug='ui-test-install', summary=u'My Addon summary', tags=['some_tag', 'another_tag', 'ui-testing', 'selenium', 'python'], weekly_downloads=9999999, developer_comments='This is a testing addon.', ) addon.save() generate_collection(addon, app=FIREFOX) print( 'Created addon {0} for testing successfully' .format(addon.name)) return addon def create_featured_theme(self): """Creates a custom theme named 'Ui-Test Theme'. This theme will be a featured theme and will belong to the uitest user. It has one author. """ addon = addon_factory( status=STATUS_PUBLIC, type=ADDON_PERSONA, average_daily_users=4242, users=[self.user], average_rating=5, description=u'My UI Theme description', file_kw={ 'hash': 'fakehash', 'platform': amo.PLATFORM_ALL.id, 'size': 42, }, guid=generate_addon_guid(), homepage=u'https://www.example.org/', name=u'Ui-Test Theme', public_stats=True, slug='ui-test', summary=u'My UI theme summary', support_email=u'support@example.org', support_url=u'https://support.example.org/support/ui-theme-addon/', tags=['some_tag', 'another_tag', 'ui-testing', 'selenium', 'python'], total_ratings=777, weekly_downloads=123456, developer_comments='This is a testing theme, used within pytest.', ) addon.save() generate_collection( addon, app=FIREFOX, type=amo.COLLECTION_FEATURED) print('Created Theme {0} for testing successfully'.format(addon.name)) def create_featured_collections(self): """Creates exactly 4 collections that are featured. This fixture uses the generate_collection function from olympia. """ for _ in range(4): addon = addon_factory(type=amo.ADDON_EXTENSION) generate_collection( addon, APPS['firefox'], type=amo.COLLECTION_FEATURED) def create_featured_themes(self): """Creates exactly 6 themes that will be not featured. These belong to the user uitest. It will also create 6 themes that are featured with random authors. """ generate_themes(6, 'uitest@mozilla.com') for _ in range(6): addon = addon_factory(status=STATUS_PUBLIC, type=ADDON_PERSONA) generate_collection(addon, app=FIREFOX) def create_a_named_collection_and_addon(self, name, author): """Creates a collection with a name and author.""" generate_collection( self.create_named_addon_with_author(name, author=author), app=FIREFOX, author=UserProfile.objects.get(username=author), type=amo.COLLECTION_FEATURED, name=name ) def create_installable_addon(self): activate('en-US') # using whatever add-on you already have should work imho, otherwise # fall back to a new one for test purposes addon = self.create_featured_addon_with_version_for_install() # the user the add-on gets created with user = UserProfile.objects.get(username='uitest') user, _ = UserProfile.objects.get_or_create( pk=settings.TASK_USER_ID, defaults={'email': 'admin@mozilla.com', 'username': 'admin'}) # generate a proper uploaded file that simulates what django requires # as request.POST file_to_upload = 'webextension_signed_already.xpi' file_path = get_file(file_to_upload) # make sure we are not using the file in the source-tree but a # temporary one to avoid the files get moved somewhere else and # deleted from source tree with copy_file_to_temp(file_path) as temporary_path: data = open(temporary_path).read() filedata = SimpleUploadedFile( file_to_upload, data, content_type=mimetypes.guess_type(file_to_upload)[0]) # now, lets upload the file into the system from olympia.devhub.views import handle_upload request = RequestFactory().get('/') request.user = user upload = handle_upload( filedata=filedata, request=request, channel=amo.RELEASE_CHANNEL_LISTED, addon=addon, ) # And let's create a new version for that upload. create_version_for_upload( upload.addon, upload, amo.RELEASE_CHANNEL_LISTED) # Change status to public addon.update(status=amo.STATUS_PUBLIC)
# coding=utf-8 # Copyright 2015 Foursquare Labs Inc. All Rights Reserved. from __future__ import absolute_import, division, print_function import json import logging import os import subprocess from argparse import ArgumentParser from fsqio.splitter.codebase.git_utils.filter_branch import git_filter_branch logger = logging.getLogger(__name__) def change_file_locations(commit_range=None, file_moves_map=None): """Rewrite the git history to have a file's location changed for every commit". The general idea is that you overwrite files that have hard-to-extract internal coupling with edited versions. :param dict file_moves_map: A dictionary of string:string mapping file paths from {source: dest}. """ command = [] for move in file_moves_map: # The existance check is shell because it is run filter branch and presumably the file doesn't exist ~always. command.extend([""" if [ -f {file_to_move} ]; then mkdir -p `dirname {new_location}` && mv -f {file_to_move} {new_location}; fi;""".format(file_to_move=move, new_location=file_moves_map[move])]) if file_moves_map and command: logger.info("Splitter: Moving file locations") git_filter_branch(filter_type='tree', shell_command=' '.join(command), commit_range=commit_range) else: logger.info("No file moves requested.") def anonymize_contributors( commit_range=None, default_author_name=None, default_email=None, contributor_file=None, contributor_ref=None, mailmap_file=None, mailmap_ref=None, ): """Anonymize the commit name and email credits not listed in the contributors file. The contributor file should have a list of emails, one per-line. The opt-in and mailmap locations are checked for every commit. You can set the '--backport-*' options to True if you want that check to always use HEAD, otherwise it will check those files as they were when each commit landed. """ command = """ OPTED_IN=$(git show {contributor_ref}:{contributor_file}) export MAILMAP="mailmap.blob={mailmap_ref}:{mailmap_file}" """.format( contributor_ref=contributor_ref, contributor_file=contributor_file, mailmap_ref=mailmap_ref, mailmap_file=mailmap_file, ) # Leaving the commented out debugging because this was a pain to get right and you never know. command += """ orig=$GIT_AUTHOR_EMAIL mapped=$(git -c $MAILMAP check-mailmap "<$GIT_AUTHOR_EMAIL>") if [[ ! $OPTED_IN =~ $mapped ]]; then GIT_AUTHOR_NAME="{default_author_name}"; GIT_AUTHOR_EMAIL="{default_email}"; GIT_COMMITTER_NAME="{default_author_name}"; GIT_COMMITTER_EMAIL="{default_email}"; else GIT_AUTHOR_EMAIL=$mapped; fi # echo -e Email: $orig set as: $GIT_AUTHOR_EMAIL. $orig was mapped as: $mapped\n """.format(default_author_name=default_author_name, default_email=default_email) logger.info("Redacting unknown contributors.") git_filter_branch(filter_type='tree', shell_command=command, commit_range=commit_range) def remove_patterns_from_commit_message(commit_range=None, match_patterns=None, line_patterns=None): """Delete any line of a commit message that contains a match with any pattern in "patterns". :param list[string] match_patterns: regex that can be understood by sed, removes only matches themselves. :param list[string] line_patterns: regex that can be understood by sed, removes any line containing a match. """ command = '' if line_patterns: command += "sed -n \"/{}/!p\"".format(line_patterns[0]) for pattern in line_patterns[1:]: # Don't try and redact newlines. if pattern: command += """ | sed -n \"/{}/!p\"""".format(pattern) if match_patterns: if command: command += " | " command += """sed "s/{}//g\"""".format(match_patterns[0]) for pattern in match_patterns[1:]: # Don't try and redact newlines. if pattern: command += """ | sed "s/{}//g\"""".format(pattern) if command: command += """ | cat -s""" logger.info("Redacting commit messages.") git_filter_branch(filter_type='msg', shell_command=command, commit_range=commit_range) else: logger.info("No redaction patterns found!") def permanently_transform_opensource_repo(): """ Filter and permanently edit the history of a git branch. This will catastrophically rewrite your git history, you should not run this function. This runs every transformation needed by Foursquare's opensource repo. :param string commit_range: Commit range ( e.g. 'master', 'release-1.4.0', 'HEAD~10..HEAD') """ head = subprocess.check_output('git log -1 --pretty=%H', shell=True).strip() parser = ArgumentParser('Rewrite git history with filter-branch to replace files and redact commit messages.') parser.add_argument( '--commit-range', default='_sapling_split_opensource_', help="Git range to process. Accepts rev-parse ranges (e.g. 'master', 'my_branch', 'HEAD~10..HEAD', etc)." "Default matches the branch created by sapling_util." ) # Default author details for any commits with an author that is not included in the contributor file. parser.add_argument( '--default-author-name', default="Opensource", help="Commits by authors not mentioned in the contributors list will rewritten to credit this name." ) parser.add_argument( '--default-email', default="opensource@foursquare.com", help="Commits by authors not mentioned in the contributors list will be recredited to this email." ) # Default refs speficy the revision to source the file from, even when operating over older commits. # # This is mostly intended to support one of the following methods: # * "HEAD" # - (aka as it existed at the time of each commit) # * None # - Passing None falls back to the default, reading the file from HEAD of the working (NOT target) branch. parser.add_argument( '--contributor-file', help="File path to contributor list, a text file with one email list per-line." "Commits authored by anyone not in this file will be credited to the default author." ) parser.add_argument( '--contributor-ref', default=head, help="Use the contributor file from this ref. Pass 'HEAD' to read the file as it existed when the commit landed." "NOTE: Anything other than HEAD allows updating the contibutor file to overwrite existing history.", ) parser.add_argument( '--mailmap-file', default='.mailmap', help="Mailmap file path." ) parser.add_argument( '--mailmap-ref', default=head, help="Use the mailmap file from this ref. Pass 'HEAD' to read the file as it existed when the commit landed." "NOTE: Anything other than HEAD allows updating the mailmap to overwrite existing history.", ) parser.add_argument( '--line-redactions-file', default=None, help="Commit message redaction. File path of text file, with a single sed regex on each line" "Removes the entire line from any commit message matching these patterns.", ) parser.add_argument( '--match-redactions-file', default=None, help="Commit message redaction. File path of text file, with a single sed regex on each line" "Removes only the matches themselves from commit messages.", ) parser.add_argument( '--file-moves-json-file', help="JSON file with every key/value being a mapping of file moves from { source: dest}." "When rewriting commits, the SRC file, if present at the time of the commit, overwrites the DEST at that sha.", ) def get_lines_from_text_file(file_path): if file_path is None: yield elif not os.path.isfile(file_path): raise ValueError("No file found: {}".format(file_path)) else: with open(file_path, 'rb') as file_path: for line in file_path.read().split('\n'): yield line args = parser.parse_args() git_commit_range = args.commit_range anonymize_contributors( commit_range=git_commit_range, default_author_name=args.default_author_name, default_email=args.default_email, contributor_file=args.contributor_file, contributor_ref=args.contributor_ref, mailmap_file=args.mailmap_file, mailmap_ref=args.mailmap_ref, ) line_redactions_file = args.line_redactions_file match_redactions_file = args.match_redactions_file line_patterns = list(get_lines_from_text_file(line_redactions_file)) if line_redactions_file else None match_patterns = list(get_lines_from_text_file(match_redactions_file)) if match_redactions_file else None remove_patterns_from_commit_message( commit_range=git_commit_range, match_patterns=match_patterns, line_patterns=line_patterns ) moves_json = args.file_moves_json_file if moves_json is not None: if not os.path.isfile(moves_json): raise ValueError("No file found: {}".format(moves_json)) with open(moves_json, 'rb') as moves: file_moves_dict = json.load(moves) change_file_locations(commit_range=git_commit_range, file_moves_map=file_moves_dict) if __name__ == '__main__': permanently_transform_opensource_repo()
#!/usr/bin/env python import os import xmltodict # sudo easy_install xmltodict import subprocess import zipfile class PackAndroid(object): def __init__(self, root, project_folder, project, input_apk, destination, keystore, keystore_alias, apk_name=None, zipalign=None, jarsigner=None, configuration='Release', keystore_password=None): self.name = project_folder self.proj_folder = project_folder self.project = project self.input_apk = input_apk self.destination = os.path.expanduser(destination) self.configuration = configuration self.keystore = keystore self.keystore_alias = keystore_alias self.keystore_password = keystore_password # Name of the final apk self.apk_name = apk_name if self.apk_name is None and self.keystore_alias is not None: self.apk_name = self.keystore_alias.lower() if self.apk_name is None: projf = os.path.basename(project) self.apk_name = projf.replace('.csproj', '') self.final_apk = os.path.join(self.destination, "%s-" % self.apk_name) self.signed_apk = os.path.join(self.destination, "%s-signed.apk" % self.apk_name) self.zipalign = zipalign if self.zipalign is None: self.zipalign = '/usr/bin/zipalign' self.jarsigner = jarsigner if self.jarsigner is None: self.jarsigner = "/usr/bin/jarsigner" self.keystore = os.path.join(root, self.keystore) self.project = os.path.join(root, self.project) self.proj_folder = os.path.join(root, self.proj_folder) self.input_apk = os.path.join(self.proj_folder, self.input_apk) if not os.path.exists(self.keystore): exit("Failed to locate keystore - " + self.keystore) if not os.path.exists(self.zipalign): exit("Failed to locate zipalign - " + self.zipalign) if not os.path.exists(self.jarsigner): exit("Failed to locate jarsigner - " + self.jarsigner) def clean(self): bin_folder = os.path.join(self.proj_folder, 'bin') obj_folder = os.path.join(self.proj_folder, 'obj') if os.path.exists(bin_folder): print 'Clearing away ' + bin_folder os.system('rm -fdr ' + bin_folder) if os.path.exists(obj_folder): print 'Clearing away ' + obj_folder os.system('rm -fdr ' + obj_folder) def get_manifest_dictionary(self): manifest = os.path.join(self.proj_folder, 'Properties/AndroidManifest.xml') if not os.path.exists(manifest): exit("Failed to locate AndroidManifest.xml - " + manifest) f = file(manifest) xml = f.read() f.close() doc = xmltodict.parse(xml) return doc def get_build_number(self): doc = self.get_manifest_dictionary() return doc['manifest']['@android:versionCode'] def get_version_number(self): doc = self.get_manifest_dictionary() return doc['manifest']['@android:versionName'] def set_build_number(self, build_num): doc = self.get_manifest_dictionary() doc['manifest']['@android:versionCode'] = build_num xml = xmltodict.unparse(doc, pretty=True) manifest = os.path.join(self.proj_folder, 'Properties/AndroidManifest.xml') if not os.path.exists(manifest): exit("Failed to locate AndroidManifest.xml - " + manifest) f = file(manifest, 'w') f.write(xml) f.close() def increment_build_number(self): build_number = self.get_build_number() if build_number is None: build_number = "1" else: build_number = str(int(build_number)+1) self.set_build_number(build_number) def decrement_build_number(self): build_number = self.get_build_number() if build_number is None: build_number = "1" else: build_number = str(int(build_number)-1) self.set_build_number(build_number) def set_version_number(self, version): doc = self.get_manifest_dictionary() doc['manifest']['@android:versionName'] = version xml = xmltodict.unparse(doc, pretty=True) manifest = os.path.join(self.proj_folder, 'Properties/AndroidManifest.xml') if not os.path.exists(manifest): exit("Failed to locate AndroidManifest.xml - " + manifest) f = file(manifest, 'w') f.write(xml) f.close() def build(self): cmd_update = "msbuild %s /t:UpdateAndroidResources /p:Configuration=%s" % (self.project, self.configuration) os.system(cmd_update) cmd = "msbuild %s /t:SignAndroidPackage /p:Configuration=%s" % (self.project, self.configuration) os.system(cmd) if not os.path.exists(self.input_apk): exit("Failed to build raw apk, i.e. its missing - " + self.input_apk) @staticmethod def convert_windows_path(any_path): chars = [] for i in range(len(any_path)): char = any_path[i] if char == '\\': chars.append('/') else: chars.append(char) return ''.join(chars) @staticmethod def update_solution_resources(solution,configuration): if not os.path.exists(solution): exit("Failed to locate %s - " % os.path.basename(solution)) f = file(solution) sln = f.read() f.close() projects = [] lines = sln.split('\n') for line in lines: if line.startswith("Project("): start = line.find(",") rest = line[start+3:len(line)] end = rest.find(",") projects.append(os.path.abspath(os.path.join(os.path.dirname(solution),PackAndroid.convert_windows_path(rest[0:end-1])))) # print projects for project in projects: cmd_update = "msbuild %s /t:UpdateAndroidResources /p:Configuration=%s" % (project, configuration) os.system(cmd_update) def sign(self): sign_cmd = [self.jarsigner, "-verbose", "-sigalg", "MD5withRSA", "-digestalg", "SHA1", "-keystore", self.keystore] if not self.keystore_password is None: sign_cmd.extend(["-storepass",self.keystore_password]) sign_cmd.extend(["-signedjar", self.signed_apk, self.input_apk, self.keystore_alias]) subprocess.call(sign_cmd) subprocess.call([self.zipalign, "-f", "-v", "4", self.signed_apk, self.final_apk]) if os.path.exists(self.final_apk): if os.path.exists(self.signed_apk): os.system('rm ' + self.signed_apk) def update_version(self): build_number = self.get_build_number() print build_number q = raw_input("Would you like to increment the build number for %s? y/n\n> " % self.apk_name) if q == "y": build_number = str(int(build_number)+1) self.set_build_number(build_number) version_number = self.get_version_number() print version_number q = raw_input("Would you like to change the version number for %s? y/n\n> " % self.apk_name) if q == "y": version_number = raw_input("What to?> ") self.set_version_number(version_number) def copy_symbols(self): artifacts_folder = os.path.join(self.proj_folder, 'bin', 'Release') stuff = os.listdir(artifacts_folder) msym_folder = None for name in stuff: if name.endswith(".mSYM"): msym_folder = os.path.join(artifacts_folder, name) break if msym_folder is not None: def zipdir(path, ziph): for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file),os.path.relpath(os.path.join(root, file), os.path.join(path, '..'))) msym_destination = os.path.join(os.path.expanduser("~/Desktop/"), os.path.basename(self.final_apk)) + ".mSYM.zip" zipf = zipfile.ZipFile(msym_destination, 'w', zipfile.ZIP_DEFLATED) zipdir(msym_folder, zipf) zipf.close() def run(self, update_versions=True, confirm_build=True): self.clean() self.final_apk = os.path.join(self.destination, "%s-" % self.apk_name) if update_versions: self.update_version() build_number = self.get_build_number() version_number = self.get_version_number() if confirm_build: print 'So thats version ' + version_number + " build " + build_number q = raw_input("Would you like to continue? y/n\n> ") if q != "y": print "Ok, not doing the build, suit yourself..." return None self.final_apk = self.final_apk + build_number + '-' + version_number + '.apk' print self.final_apk self.build() self.sign() self.copy_symbols() return self.final_apk
"""Support gathering system information of hosts which are running glances.""" from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from .const import DATA_UPDATED, DOMAIN, SENSOR_TYPES async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Glances sensors.""" client = hass.data[DOMAIN][config_entry.entry_id] name = config_entry.data[CONF_NAME] dev = [] for sensor_type, sensor_details in SENSOR_TYPES.items(): if not sensor_details[0] in client.api.data: continue if sensor_details[0] in client.api.data: if sensor_details[0] == "fs": # fs will provide a list of disks attached for disk in client.api.data[sensor_details[0]]: dev.append( GlancesSensor( client, name, disk["mnt_point"], SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) elif sensor_details[0] == "sensors": # sensors will provide temp for different devices for sensor in client.api.data[sensor_details[0]]: dev.append( GlancesSensor( client, name, sensor["label"], SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) elif client.api.data[sensor_details[0]]: dev.append( GlancesSensor( client, name, "", SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) async_add_entities(dev, True) class GlancesSensor(Entity): """Implementation of a Glances sensor.""" def __init__( self, glances_data, name, sensor_name_prefix, sensor_name_suffix, sensor_type, sensor_details, ): """Initialize the sensor.""" self.glances_data = glances_data self._sensor_name_prefix = sensor_name_prefix self._sensor_name_suffix = sensor_name_suffix self._name = name self.type = sensor_type self._state = None self.sensor_details = sensor_details self.unsub_update = None @property def name(self): """Return the name of the sensor.""" return f"{self._name} {self._sensor_name_prefix} {self._sensor_name_suffix}" @property def unique_id(self): """Set unique_id for sensor.""" return f"{self.glances_data.host}-{self.name}" @property def icon(self): """Icon to use in the frontend, if any.""" return self.sensor_details[3] @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self.sensor_details[2] @property def available(self): """Could the device be accessed during the last update call.""" return self.glances_data.available @property def state(self): """Return the state of the resources.""" return self._state @property def should_poll(self): """Return the polling requirement for this sensor.""" return False async def async_added_to_hass(self): """Handle entity which will be added.""" self.unsub_update = async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) @callback def _schedule_immediate_update(self): self.async_schedule_update_ha_state(True) async def will_remove_from_hass(self): """Unsubscribe from update dispatcher.""" if self.unsub_update: self.unsub_update() self.unsub_update = None async def async_update(self): """Get the latest data from REST API.""" value = self.glances_data.api.data if value is None: return if value is not None: if self.sensor_details[0] == "fs": for var in value["fs"]: if var["mnt_point"] == self._sensor_name_prefix: disk = var break if self.type == "disk_use_percent": self._state = disk["percent"] elif self.type == "disk_use": self._state = round(disk["used"] / 1024 ** 3, 1) elif self.type == "disk_free": try: self._state = round(disk["free"] / 1024 ** 3, 1) except KeyError: self._state = round( (disk["size"] - disk["used"]) / 1024 ** 3, 1, ) elif self.type == "sensor_temp": for sensor in value["sensors"]: if sensor["label"] == self._sensor_name_prefix: self._state = sensor["value"] break elif self.type == "memory_use_percent": self._state = value["mem"]["percent"] elif self.type == "memory_use": self._state = round(value["mem"]["used"] / 1024 ** 2, 1) elif self.type == "memory_free": self._state = round(value["mem"]["free"] / 1024 ** 2, 1) elif self.type == "swap_use_percent": self._state = value["memswap"]["percent"] elif self.type == "swap_use": self._state = round(value["memswap"]["used"] / 1024 ** 3, 1) elif self.type == "swap_free": self._state = round(value["memswap"]["free"] / 1024 ** 3, 1) elif self.type == "processor_load": # Windows systems don't provide load details try: self._state = value["load"]["min15"] except KeyError: self._state = value["cpu"]["total"] elif self.type == "process_running": self._state = value["processcount"]["running"] elif self.type == "process_total": self._state = value["processcount"]["total"] elif self.type == "process_thread": self._state = value["processcount"]["thread"] elif self.type == "process_sleeping": self._state = value["processcount"]["sleeping"] elif self.type == "cpu_use_percent": self._state = value["quicklook"]["cpu"] elif self.type == "docker_active": count = 0 try: for container in value["docker"]["containers"]: if ( container["Status"] == "running" or "Up" in container["Status"] ): count += 1 self._state = count except KeyError: self._state = count elif self.type == "docker_cpu_use": cpu_use = 0.0 try: for container in value["docker"]["containers"]: if ( container["Status"] == "running" or "Up" in container["Status"] ): cpu_use += container["cpu"]["total"] self._state = round(cpu_use, 1) except KeyError: self._state = STATE_UNAVAILABLE elif self.type == "docker_memory_use": mem_use = 0.0 try: for container in value["docker"]["containers"]: if ( container["Status"] == "running" or "Up" in container["Status"] ): mem_use += container["memory"]["usage"] self._state = round(mem_use / 1024 ** 2, 1) except KeyError: self._state = STATE_UNAVAILABLE
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of pywinauto 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. """Tests for classes in controls\common_controls.py""" from __future__ import print_function import sys #import ctypes import unittest import time from datetime import datetime #import pdb import os import win32api import six sys.path.append(".") from pywinauto.application import Application # noqa: E402 from pywinauto.win32structures import RECT # noqa: E402 from pywinauto import win32defines # noqa: E402 from pywinauto import findbestmatch # noqa: E402 from pywinauto.sysinfo import is_x64_Python # noqa: E402 from pywinauto.remote_memory_block import RemoteMemoryBlock # noqa: E402 from pywinauto.actionlogger import ActionLogger # noqa: E402 from pywinauto.timings import Timings # noqa: E402 from pywinauto.timings import wait_until # noqa: E402 from pywinauto import mouse # noqa: E402 controlspy_folder = os.path.join( os.path.dirname(__file__), r"..\..\apps\controlspy0998") controlspy_folder_32 = controlspy_folder mfc_samples_folder = os.path.join( os.path.dirname(__file__), r"..\..\apps\MFC_samples") mfc_samples_folder_32 = mfc_samples_folder winforms_folder = os.path.join( os.path.dirname(__file__), r"..\..\apps\WinForms_samples") winforms_folder_32 = winforms_folder if is_x64_Python(): controlspy_folder = os.path.join(controlspy_folder, 'x64') mfc_samples_folder = os.path.join(mfc_samples_folder, 'x64') winforms_folder = os.path.join(winforms_folder, 'x64') class RemoteMemoryBlockTestCases(unittest.TestCase): def test__init__fail(self): self.assertRaises(AttributeError, RemoteMemoryBlock, 0) class ListViewTestCases32(unittest.TestCase): """Unit tests for the ListViewWrapper class""" path = os.path.join(mfc_samples_folder_32, u"RowList.exe") def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() app = Application() app.start(self.path) self.texts = [ (u"Yellow", u"255", u"255", u"0", u"40", u"240", u"120", u"Neutral"), (u"Red", u"255", u"0", u"0", u"0", u"240", u"120", u"Warm"), (u"Green", u"0", u"255", u"0", u"80", u"240", u"120", u"Cool"), (u"Magenta", u"255", u"0", u"255", u"200", u"240", u"120", u"Warm"), (u"Cyan", u"0", u"255", u"255", u"120", u"240", u"120", u"Cool"), (u"Blue", u"0", u"0", u"255", u"160", u"240", u"120", u"Cool"), (u"Gray", u"192", u"192", u"192", u"160", u"0", u"181", u"Neutral") ] self.app = app self.dlg = app.RowListSampleApplication self.ctrl = app.RowListSampleApplication.ListView.WrapperObject() self.dlg.Toolbar.Button(0).Click() # switch to icon view self.dlg.Toolbar.Button(6).Click() # switch off states def tearDown(self): """Close the application after tests""" self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the ListView friendly class is set correctly""" self.assertEquals(self.ctrl.friendly_class_name(), u"ListView") def testColumnCount(self): """Test the ListView ColumnCount method""" self.assertEquals(self.ctrl.ColumnCount(), 8) def testItemCount(self): """Test the ListView ItemCount method""" self.assertEquals(self.ctrl.ItemCount(), 7) def testItemText(self): """Test the ListView item.Text property""" item = self.ctrl.GetItem(1) self.assertEquals(item['text'], u"Red") def testItems(self): """Test the ListView Items method""" flat_texts = [] for row in self.texts: flat_texts.extend(row) items = self.ctrl.Items() for i, item in enumerate(items): self.assertEquals(item['text'], flat_texts[i]) self.assertEquals(len(items), len(flat_texts)) def testTexts(self): """Test the ListView texts method""" flat_texts = [] for row in self.texts: flat_texts.extend(row) self.assertEquals(flat_texts, self.ctrl.texts()[1:]) def testGetItem(self): """Test the ListView GetItem method""" for row in range(self.ctrl.ItemCount()): for col in range(self.ctrl.ColumnCount()): self.assertEquals( self.ctrl.GetItem(row, col)['text'], self.texts[row][col]) def testGetItemText(self): """Test the ListView GetItem method - with text this time""" for text in [row[0] for row in self.texts]: self.assertEquals( self.ctrl.GetItem(text)['text'], text) self.assertRaises(ValueError, self.ctrl.GetItem, "Item not in this list") def testColumn(self): """Test the ListView Columns method""" cols = self.ctrl.Columns() self.assertEqual(len(cols), self.ctrl.ColumnCount()) # TODO: add more checking of column values #for col in cols: # print(col) def testGetSelectionCount(self): """Test the ListView GetSelectedCount method""" self.assertEquals(self.ctrl.GetSelectedCount(), 0) self.ctrl.Select(1) self.ctrl.Select(6) self.assertEquals(self.ctrl.GetSelectedCount(), 2) # def testGetSelectionCount(self): # "Test the ListView GetSelectedCount method" # # self.assertEquals(self.ctrl.GetSelectedCount(), 0) # # self.ctrl.Select(1) # self.ctrl.Select(7) # # self.assertEquals(self.ctrl.GetSelectedCount(), 2) def testIsSelected(self): """Test ListView IsSelected for some items""" # ensure that the item is not selected self.assertEquals(self.ctrl.IsSelected(1), False) # select an item self.ctrl.Select(1) # now ensure that the item is selected self.assertEquals(self.ctrl.IsSelected(1), True) def _testFocused(self): """Test checking the focus of some ListView items""" print("Select something quick!!") time.sleep(3) #self.ctrl.Select(1) print(self.ctrl.IsFocused(0)) print(self.ctrl.IsFocused(1)) print(self.ctrl.IsFocused(2)) print(self.ctrl.IsFocused(3)) print(self.ctrl.IsFocused(4)) print(self.ctrl.IsFocused(5)) #for col in cols: # print(col) def testSelect(self): """Test ListView Selecting some items""" self.ctrl.Select(1) self.ctrl.Select(3) self.ctrl.Select(4) self.assertRaises(IndexError, self.ctrl.Deselect, 23) self.assertEquals(self.ctrl.GetSelectedCount(), 3) def testSelectText(self): """Test ListView Selecting some items""" self.ctrl.Select(u"Green") self.ctrl.Select(u"Yellow") self.ctrl.Select(u"Gray") self.assertRaises(ValueError, self.ctrl.Deselect, u"Item not in list") self.assertEquals(self.ctrl.GetSelectedCount(), 3) def testDeselect(self): """Test ListView Selecting some items""" self.ctrl.Select(1) self.ctrl.Select(4) self.ctrl.Deselect(3) self.ctrl.Deselect(4) self.assertRaises(IndexError, self.ctrl.Deselect, 23) self.assertEquals(self.ctrl.GetSelectedCount(), 1) def testGetProperties(self): """Test getting the properties for the listview control""" props = self.ctrl.GetProperties() self.assertEquals( "ListView", props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props.keys(): self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) self.assertEquals(props['column_count'], 8) self.assertEquals(props['item_count'], 7) def testGetColumnTexts(self): """Test columns titles text""" self.assertEquals(self.ctrl.GetColumn(0)['text'], u"Color") self.assertEquals(self.ctrl.GetColumn(1)['text'], u"Red") self.assertEquals(self.ctrl.GetColumn(2)['text'], u"Green") self.assertEquals(self.ctrl.GetColumn(3)['text'], u"Blue") def testItemRectangles(self): """Test getting item rectangles""" yellow_rect = self.ctrl.GetItemRect('Yellow') gold_rect = RECT(13, 0, 61, 53) self.assertEquals(yellow_rect.left, gold_rect.left) self.assertEquals(yellow_rect.top, gold_rect.top) self.assertEquals(yellow_rect.right, gold_rect.right) if yellow_rect.bottom < 53 or yellow_rect.bottom > 55: self.assertEquals(yellow_rect.bottom, gold_rect.bottom) self.ctrl.GetItem('Green').Click(where='text') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.ctrl.GetItem('Magenta').Click(where='icon') self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), True) self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), False) self.ctrl.GetItem('Green').Click(where='all') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), False) def testItemCheck(self): """Test checking/unchecking item""" if not self.dlg.Toolbar.Button(6).IsChecked(): self.dlg.Toolbar.Button(6).Click() yellow = self.ctrl.GetItem('Yellow') yellow.Check() self.assertEquals(yellow.IsChecked(), True) yellow.UnCheck() self.assertEquals(yellow.IsChecked(), False) # test legacy deprecated methods (TODO: remove later) self.ctrl.Check('Yellow') self.assertEquals(self.ctrl.IsChecked('Yellow'), True) self.ctrl.UnCheck('Yellow') self.assertEquals(self.ctrl.IsChecked('Yellow'), False) def testItemClick(self): """Test clicking item rectangles by Click() method""" self.ctrl.GetItem('Green').Click(where='select') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.ctrl.GetItem('Magenta').Click(where='select') self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), True) self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), False) self.assertEquals(self.ctrl.GetItem('Green').IsFocused(), False) self.assertEquals(self.ctrl.GetItem('Green').State() & win32defines.LVIS_FOCUSED, 0) self.ctrl.GetItem('Green').Click(where='select') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.assertEquals(self.ctrl.IsSelected('Green'), True) # TODO: deprecated method self.assertEquals(self.ctrl.GetItem('Green').IsFocused(), True) self.assertEquals(self.ctrl.IsFocused('Green'), True) # TODO: deprecated method self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), False) # Test click on checkboxes if not self.dlg.Toolbar.Button(6).IsChecked(): # switch on states self.dlg.Toolbar.Button(6).Click() for i in range(1, 6): self.dlg.Toolbar.Button(i - 1).Click() self.ctrl.GetItem(i).Click(where='check') # check item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), True) self.assertEquals(self.ctrl.GetItem(i - 1).IsChecked(), False) self.ctrl.GetItem(i).Click(where='check') # uncheck item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), False) self.ctrl.GetItem(i).Click(where='check') # recheck item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), True) self.dlg.Toolbar.Button(6).Click() # switch off states self.assertRaises(RuntimeError, self.ctrl.GetItem(6).Click, where="check") def testItemClickInput(self): """Test clicking item rectangles by click_input() method""" Timings.Defaults() self.ctrl.GetItem('Green').click_input(where='select') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.ctrl.GetItem('Magenta').click_input(where='select') self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), True) self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), False) self.assertEquals(self.ctrl.GetItem('Green').IsFocused(), False) self.assertEquals(self.ctrl.GetItem('Green').State() & win32defines.LVIS_FOCUSED, 0) self.ctrl.GetItem('Green').click_input(where='select') self.assertEquals(self.ctrl.GetItem('Green').IsSelected(), True) self.assertEquals(self.ctrl.IsSelected('Green'), True) # TODO: deprecated method self.assertEquals(self.ctrl.GetItem('Green').IsFocused(), True) self.assertEquals(self.ctrl.IsFocused('Green'), True) # TODO: deprecated method self.assertEquals(self.ctrl.GetItem('Magenta').IsSelected(), False) # Test click on checkboxes if not self.dlg.Toolbar.Button(6).IsChecked(): # switch on states self.dlg.Toolbar.Button(6).Click() for i in range(1, 6): self.dlg.Toolbar.Button(i - 1).Click() self.ctrl.GetItem(i).click_input(where='check') # check item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), True) self.assertEquals(self.ctrl.GetItem(i - 1).IsChecked(), False) self.ctrl.GetItem(i).click_input(where='check') # uncheck item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), False) self.ctrl.GetItem(i).click_input(where='check') # recheck item time.sleep(0.5) self.assertEquals(self.ctrl.GetItem(i).IsChecked(), True) self.dlg.Toolbar.Button(6).Click() # switch off states self.assertRaises(RuntimeError, self.ctrl.GetItem(6).click_input, where="check") def testItemMethods(self): """Test short item methods like Text(), State() etc""" self.assertEquals(self.ctrl.GetItem('Green').Text(), 'Green') self.assertEquals(self.ctrl.GetItem('Green').Image(), 2) self.assertEquals(self.ctrl.GetItem('Green').Indent(), 0) def test_ensure_visible(self): self.dlg.MoveWindow(width=300) # Gray is selected by click because ensure_visible() is called inside self.ctrl.GetItem('Gray').Click() self.assertEquals(self.ctrl.GetItem('Gray').IsSelected(), True) self.dlg.set_focus() # just in case self.ctrl.GetItem('Green').EnsureVisible() self.ctrl.GetItem('Red').Click() self.assertEquals(self.ctrl.GetItem('Gray').IsSelected(), False) self.assertEquals(self.ctrl.GetItem('Red').IsSelected(), True) # # def testSubItems(self): # # for row in range(self.ctrl.ItemCount()) # # for i in self.ctrl.Items(): # # #self.assertEquals(item.Text, texts[i]) def testEqualsItems(self): """ Test __eq__ and __ne__ cases for _listview_item. """ item1 = self.ctrl.GetItem(0, 0) item1_copy = self.ctrl.GetItem(0, 0) item2 = self.ctrl.GetItem(1, 0) self.assertEqual(item1, item1_copy) self.assertNotEqual(item1, "Not _listview_item") self.assertNotEqual(item1, item2) def test_cells_rectangles(self): """Test the ListView get_item rectangle method for cells""" if not self.dlg.Toolbar.Button(4).is_checked(): self.dlg.Toolbar.Button(4).click() for row in range(self.ctrl.item_count() - 1): for col in range(self.ctrl.column_count() - 1): self.assertEqual( self.ctrl.get_item(row, col).rectangle(area="text").right, self.ctrl.get_item(row, col + 1).rectangle(area="text").left) self.assertEqual( self.ctrl.get_item(row, col).rectangle(area="text").bottom, self.ctrl.get_item(row + 1, col).rectangle(area="text").top) self.assertEqual(self.ctrl.get_item(1, 2).rectangle(area="text"), RECT(200, 36, 250, 53)) self.assertEqual(self.ctrl.get_item(3, 4).rectangle(area="text"), RECT(300, 70, 400, 87)) def test_inplace_control(self): """Test the ListView inplace_control method for item""" # Item is not editable so it will raise timeout error with self.assertRaises(Exception) as context: self.ctrl.get_item(0).inplace_control() self.assertTrue('In-place-edit control for item' in str(context.exception)) if is_x64_Python(): class ListViewTestCases64(ListViewTestCases32): """Unit tests for the 64-bit ListViewWrapper on a 32-bit sample""" path = os.path.join(mfc_samples_folder, u"RowList.exe") class ListViewWinFormTestCases32(unittest.TestCase): """Unit tests for the ListViewWrapper class with WinForm applications""" path = os.path.join(winforms_folder_32, u"ListView_TestApp.exe") def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Defaults() app = Application() app.start(self.path) self.dlg = app.ListViewEx self.ctrl = app.ListViewEx.ListView.wrapper_object() def tearDown(self): """Close the application after tests""" self.dlg.send_message(win32defines.WM_CLOSE) def test_cell_click_input(self): """Test the ListView get_item click_input method""" self.ctrl.get_item(0,2).click_input(double=True, where="text") self.dlg.type_keys("{ENTER}") # For make sure the input is finished, click to another place self.ctrl.get_item(0,3).click_input(double=False, where="text") self.assertEqual(str(self.ctrl.get_item(0,2).text()), u"Clicked!") def test_get_editor_of_datetimepicker(self): """Test the ListView inplace_control method using DateTimePicker""" dt_picker = self.ctrl.get_item(2,0).inplace_control("DateTimePicker") dt_picker.set_time(year=2017, month=5, day=23) cur_time = dt_picker.get_time(); self.assertEqual(cur_time.wYear, 2017) self.assertEqual(cur_time.wMonth, 5) self.assertEqual(cur_time.wDay, 23) def test_get_editor_of_combobox(self): """Test the ListView inplace_control method using ComboBox""" combo_box = self.ctrl.get_item(1,1).inplace_control("ComboBox") combo_box.select(combo_box.selected_index() - 1) self.assertEqual(combo_box.selected_index(), 2) def test_get_editor_of_editwrapper(self): """Test the ListView inplace_control method using EditWrapper""" dt_picker = self.ctrl.get_item(3,4).inplace_control("Edit") dt_picker.set_text("201") self.assertEqual(dt_picker.text_block(), u"201") def test_get_editor_wrong_args(self): """Test the ListView inplace_control case when used wrong friendly class name""" with self.assertRaises(Exception) as context: self.ctrl.get_item(1,1).inplace_control("Edit") self.assertTrue('In-place-edit control "Edit"' in str(context.exception)) if is_x64_Python(): class ListViewWinFormTestCases64(ListViewWinFormTestCases32): """Unit tests for the 64-bit ListViewWrapper on a 32-bit sample""" path = os.path.join(winforms_folder, u"ListView_TestApp.exe") class TreeViewTestCases32(unittest.TestCase): """Unit tests for the TreeViewWrapper class""" path = os.path.join(controlspy_folder_32, "Tree View.exe") def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.root_text = "The Planets" self.texts = [ ("Mercury", '57,910,000', '4,880', '3.30e23'), ("Venus", '108,200,000', '12,103.6', '4.869e24'), ("Earth", '149,600,000', '12,756.3', '5.9736e24'), ("Mars", '227,940,000', '6,794', '6.4219e23'), ("Jupiter", '778,330,000', '142,984', '1.900e27'), ("Saturn", '1,429,400,000', '120,536', '5.68e26'), ("Uranus", '2,870,990,000', '51,118', '8.683e25'), ("Neptune", '4,504,000,000', '49,532', '1.0247e26'), ("Pluto", '5,913,520,000', '2,274', '1.27e22'), ] self.app = Application() self.app.start(self.path) self.dlg = self.app.MicrosoftControlSpy self.ctrl = self.app.MicrosoftControlSpy.TreeView.WrapperObject() def tearDown(self): """Close the application after tests""" self.dlg.SendMessage(win32defines.WM_CLOSE) def test_friendly_class_name(self): """Make sure the friendly class name is set correctly (TreeView)""" self.assertEquals(self.ctrl.friendly_class_name(), "TreeView") def testItemCount(self): """Test the TreeView ItemCount method""" self.assertEquals(self.ctrl.ItemCount(), 37) def testGetItem(self): """Test the GetItem method""" self.assertRaises(RuntimeError, self.ctrl.GetItem, "test\here\please") self.assertRaises(IndexError, self.ctrl.GetItem, r"\test\here\please") self.assertEquals( self.ctrl.GetItem((0, 1, 2)).Text(), self.texts[1][3] + " kg") self.assertEquals( self.ctrl.GetItem(r"\The Planets\Venus\4.869e24 kg", exact=True).Text(), self.texts[1][3] + " kg") self.assertEquals( self.ctrl.GetItem(["The Planets", "Venus", "4.869"]).Text(), self.texts[1][3] + " kg" ) def testItemText(self): """Test the TreeView item Text() method""" self.assertEquals(self.ctrl.Root().Text(), self.root_text) self.assertEquals( self.ctrl.GetItem((0, 1, 2)).Text(), self.texts[1][3] + " kg") def testSelect(self): """Test selecting an item""" self.ctrl.Select((0, 1, 2)) self.ctrl.GetItem((0, 1, 2)).State() self.assertEquals(True, self.ctrl.IsSelected((0, 1, 2))) def testEnsureVisible(self): """make sure that the item is visible""" # TODO: note this is partially a fake test at the moment because # just by getting an item - we usually make it visible self.ctrl.EnsureVisible((0, 8, 2)) # make sure that the item is not hidden self.assertNotEqual(None, self.ctrl.GetItem((0, 8, 2)).client_rect()) def testGetProperties(self): """Test getting the properties for the treeview control""" props = self.ctrl.GetProperties() self.assertEquals( "TreeView", props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemsClick(self): """Test clicking of items and sub-items in the treeview control""" planets_item_path = (0, 0) mercury_diam_item_path = (0, 0, 1) mars_dist_item_path = (0, 3, 0) itm = self.ctrl.GetItem(planets_item_path) itm.EnsureVisible() time.sleep(1) itm.Click(button='left') self.assertEquals(True, self.ctrl.IsSelected(planets_item_path)) itm = self.ctrl.GetItem(mars_dist_item_path) itm.EnsureVisible() time.sleep(1) itm.Click(button='left') self.assertEquals(True, self.ctrl.IsSelected(mars_dist_item_path)) itm = self.ctrl.GetItem(mercury_diam_item_path) itm.EnsureVisible() time.sleep(1) itm.Click(button='left') self.assertEquals(True, self.ctrl.IsSelected(mercury_diam_item_path)) self.assertEquals(False, self.ctrl.IsSelected(mars_dist_item_path)) itm = self.ctrl.GetItem(planets_item_path) itm.EnsureVisible() time.sleep(1) itm.Click(button='left') self.assertEquals(True, self.ctrl.IsSelected(planets_item_path)) self.assertEquals(False, self.ctrl.IsSelected(mercury_diam_item_path)) if is_x64_Python(): class TreeViewTestCases64(TreeViewTestCases32): """Unit tests for the 64-bit TreeViewWrapper on a 32-bit sample""" path = os.path.join(controlspy_folder, "Tree View.exe") class TreeViewAdditionalTestCases(unittest.TestCase): """More unit tests for the TreeViewWrapper class (CmnCtrl1.exe)""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.app = Application().start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.dlg = self.app.CommonControlsSample self.ctrl = self.app.CommonControlsSample.TreeView.WrapperObject() self.app.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1) def tearDown(self): """Close the application after tests""" self.dlg.send_message(win32defines.WM_CLOSE) self.app.kill_() def testCheckBoxes(self): """Make sure tree view item method IsChecked() works as expected""" self.dlg.set_focus() self.dlg.TVS_CHECKBOXES.check_by_click() birds = self.ctrl.GetItem(r'\Birds') birds.Click(where='check') self.assertEqual(birds.IsChecked(), True) birds.click_input(where='check') wait_until(3, 0.4, birds.IsChecked, value=False) def testPrintItems(self): """Test TreeView method PrintItems()""" birds = self.ctrl.GetItem(r'\Birds') birds.Expand() items_str = self.ctrl.PrintItems() self.assertEquals(items_str, "Treeview1\nBirds\n Eagle\n Hummingbird\n Pigeon\n" + "Dogs\n Dalmatian\n German Shepherd\n Great Dane\n" + "Fish\n Salmon\n Snapper\n Sole\n") def testIsSelected(self): """Make sure tree view item method IsSelected() works as expected""" birds = self.ctrl.GetItem(r'\Birds') birds.Expand() eagle = self.ctrl.GetItem(r'\Birds\Eagle') eagle.Select() self.assertEquals(eagle.IsSelected(), True) def test_expand_collapse(self): """Make sure tree view item methods Expand() and Collapse() work as expected""" birds = self.ctrl.GetItem(r'\Birds') birds.Expand() self.assertEquals(birds.IsExpanded(), True) birds.Collapse() self.assertEquals(birds.IsExpanded(), False) def test_expand_collapse_buttons(self): """Make sure correct area is clicked""" self.dlg.TVS_HASBUTTONS.click_input() self.dlg.TVS_HASLINES.click_input() self.dlg.TVS_LINESATROOT.click_input() birds = self.ctrl.GetItem(r'\Birds') birds.Click(where='button') self.assertEquals(birds.IsExpanded(), True) birds.Click(double=True, where='icon') self.assertEquals(birds.IsExpanded(), False) birds.click_input(where='button') self.assertEquals(birds.IsExpanded(), True) birds.click_input(double=True, where='icon') self.assertEquals(birds.IsExpanded(), False) def testIncorrectAreas(self): """Make sure incorrect area raises an exception""" birds = self.ctrl.GetItem(r'\Birds') self.assertRaises(RuntimeError, birds.Click, where='radiob') self.assertRaises(RuntimeError, birds.click_input, where='radiob') def testStartDraggingAndDrop(self): """Make sure tree view item methods StartDragging() and Drop() work as expected""" birds = self.ctrl.GetItem(r'\Birds') birds.Expand() pigeon = self.ctrl.GetItem(r'\Birds\Pigeon') pigeon.StartDragging() eagle = self.ctrl.GetItem(r'\Birds\Eagle') eagle.Drop() self.assertRaises(IndexError, birds.GetChild, 'Pigeon') self.assertRaises(IndexError, self.ctrl.GetItem, r'\Birds\Pigeon') self.assertRaises(IndexError, self.ctrl.GetItem, [0, 2]) self.assertRaises(IndexError, self.ctrl.GetItem, r'\Bread', exact=True) new_pigeon = self.ctrl.GetItem(r'\Birds\Eagle\Pigeon') self.assertEquals(len(birds.children()), 2) self.assertEquals(new_pigeon.children(), []) class HeaderTestCases(unittest.TestCase): """Unit tests for the Header class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() app = Application() app.start(os.path.join(mfc_samples_folder, "RowList.exe"), timeout=20) self.texts = [u'Color', u'Red', u'Green', u'Blue', u'Hue', u'Sat', u'Lum', u'Type'] self.item_rects = [ RECT(000, 0, 150, 19), RECT(150, 0, 200, 19), RECT(200, 0, 250, 19), RECT(250, 0, 300, 19), RECT(300, 0, 400, 19), RECT(400, 0, 450, 19), RECT(450, 0, 500, 19), RECT(500, 0, 650, 19)] self.app = app self.dlg = app.RowListSampleApplication self.ctrl = app.RowListSampleApplication.Header.WrapperObject() def tearDown(self): """Close the application after tests""" # close the application self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the friendly class is set correctly (Header)""" self.assertEquals(self.ctrl.friendly_class_name(), "Header") def testTexts(self): """Make sure the texts are set correctly""" self.assertEquals(self.ctrl.texts()[1:], self.texts) def testGetProperties(self): """Test getting the properties for the header control""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): self.assertEquals(8, self.ctrl.ItemCount()) def testGetColumnRectangle(self): for i in range(0, 3): self.assertEquals(self.item_rects[i].left, self.ctrl.GetColumnRectangle(i).left) self.assertEquals(self.item_rects[i].right, self.ctrl.GetColumnRectangle(i).right) self.assertEquals(self.item_rects[i].top, self.ctrl.GetColumnRectangle(i).top) self.failIf(abs(self.item_rects[i].bottom - self.ctrl.GetColumnRectangle(i).bottom) > 2) def testClientRects(self): test_rects = self.item_rects test_rects.insert(0, self.ctrl.client_rect()) client_rects = self.ctrl.client_rects() self.assertEquals(len(test_rects), len(client_rects)) for i, r in enumerate(test_rects): self.assertEquals(r.left, client_rects[i].left) self.assertEquals(r.right, client_rects[i].right) self.assertEquals(r.top, client_rects[i].top) self.failIf(abs(r.bottom - client_rects[i].bottom) > 2) # may be equal to 17 or 19 def testGetColumnText(self): for i in range(0, 3): self.assertEquals( self.texts[i], self.ctrl.GetColumnText(i)) class StatusBarTestCases(unittest.TestCase): """Unit tests for the TreeViewWrapper class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() app = Application() app.start(os.path.join(controlspy_folder, "Status bar.exe")) self.texts = ["Long text", "", "Status Bar"] self.part_rects = [ RECT(0, 2, 65, 22), RECT(67, 2, 90, 22), RECT(92, 2, 261, 22)] self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.StatusBar.WrapperObject() def tearDown(self): """Close the application after tests""" self.dlg.SendMessage(win32defines.WM_CLOSE) def test_friendly_class_name(self): """Make sure the friendly class name is set correctly (StatusBar)""" self.assertEquals(self.ctrl.friendly_class_name(), "StatusBar") def test_texts(self): """Make sure the texts are set correctly""" self.assertEquals(self.ctrl.texts()[1:], self.texts) def testGetProperties(self): """Test getting the properties for the status bar control""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testBorderWidths(self): """Make sure the border widths are retrieved correctly""" self.assertEquals( self.ctrl.BorderWidths(), dict( Horizontal=0, Vertical=2, Inter=2, ) ) def testPartCount(self): "Make sure the number of parts is retrieved correctly" self.assertEquals(self.ctrl.PartCount(), 3) def testPartRightEdges(self): "Make sure the part widths are retrieved correctly" for i in range(0, self.ctrl.PartCount() - 1): self.assertEquals(self.ctrl.PartRightEdges()[i], self.part_rects[i].right) self.assertEquals(self.ctrl.PartRightEdges()[i + 1], -1) def testGetPartRect(self): "Make sure the part rectangles are retrieved correctly" for i in range(0, self.ctrl.PartCount()): part_rect = self.ctrl.GetPartRect(i) self.assertEquals(part_rect.left, self.part_rects[i].left) if i != self.ctrl.PartCount() - 1: self.assertEquals(part_rect.right, self.part_rects[i].right) self.assertEquals(part_rect.top, self.part_rects[i].top) self.failIf(abs(part_rect.bottom - self.part_rects[i].bottom) > 2) self.assertRaises(IndexError, self.ctrl.GetPartRect, 99) def testClientRects(self): self.assertEquals(self.ctrl.ClientRect(), self.ctrl.ClientRects()[0]) client_rects = self.ctrl.ClientRects()[1:] for i, client_rect in enumerate(client_rects): self.assertEquals(self.part_rects[i].left, client_rect.left) if i != len(client_rects) - 1: self.assertEquals(self.part_rects[i].right, client_rect.right) self.assertEquals(self.part_rects[i].top, client_rect.top) self.failIf(abs(self.part_rects[i].bottom - client_rect.bottom) > 2) def testGetPartText(self): self.assertRaises(IndexError, self.ctrl.GetPartText, 99) for i, text in enumerate(self.texts): self.assertEquals(text, self.ctrl.GetPartText(i)) class TabControlTestCases(unittest.TestCase): """Unit tests for the TreeViewWrapper class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.screen_w = win32api.GetSystemMetrics(0) app = Application() app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.texts = [ u"CTreeCtrl", u"CAnimateCtrl", u"CToolBarCtrl", u"CDateTimeCtrl", u"CMonthCalCtrl"] self.rects = [ RECT(2, 2, 58, 20), RECT(58, 2, 130, 20), RECT(130, 2, 201, 20), RECT(201, 2, 281, 20), RECT(281, 2, 360, 20) ] self.app = app self.dlg = app.CommonControlsSample self.ctrl = app.CommonControlsSample.TabControl.WrapperObject() def tearDown(self): """Close the application after tests""" # close the application self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the friendly class is set correctly (TabControl)""" self.assertEquals(self.ctrl.friendly_class_name(), "TabControl") def testTexts(self): """Make sure the texts are set correctly""" self.assertEquals(self.ctrl.texts()[1:], self.texts) def testGetProperties(self): """Test getting the properties for the tabcontrol""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testRowCount(self): self.assertEquals(1, self.ctrl.RowCount()) dlgClientRect = self.ctrl.parent().rectangle() # use the parent as a reference prev_rect = self.ctrl.rectangle() - dlgClientRect # squeeze the tab control to force two rows new_rect = RECT(prev_rect) new_rect.right = int(new_rect.width() / 2) self.ctrl.MoveWindow( new_rect.left, new_rect.top, new_rect.width(), new_rect.height(), ) time.sleep(0.1) # verify two tab rows self.assertEquals(2, self.ctrl.RowCount()) # restore back the original size of the control self.ctrl.MoveWindow(prev_rect) self.assertEquals(1, self.ctrl.RowCount()) def testGetSelectedTab(self): self.assertEquals(0, self.ctrl.GetSelectedTab()) self.ctrl.Select(1) self.assertEquals(1, self.ctrl.GetSelectedTab()) self.ctrl.Select(u"CMonthCalCtrl") self.assertEquals(4, self.ctrl.GetSelectedTab()) def testTabCount(self): """Make sure the number of parts is retrieved correctly""" self.assertEquals(self.ctrl.TabCount(), 5) def testGetTabRect(self): """Make sure the part rectangles are retrieved correctly""" for i, _ in enumerate(self.rects): self.assertEquals(self.ctrl.GetTabRect(i), self.rects[i]) self.assertRaises(IndexError, self.ctrl.GetTabRect, 99) # def testGetTabState(self): # self.assertRaises(IndexError, self.ctrl.GetTabState, 99) # # self.dlg.StatementEdit.SetEditText ("MSG (TCM_HIGHLIGHTITEM,1,MAKELONG(TRUE,0))") # # time.sleep(.3) # # use CloseClick to allow the control time to respond to the message # self.dlg.Send.CloseClick() # time.sleep(2) # print("==\n",self.ctrl.TabStates()) # # self.assertEquals(self.ctrl.GetTabState(1), 1) # # def testTabStates(self): # print(self.ctrl.TabStates()) # raise "tabstates hiay" def testGetTabText(self): for i, text in enumerate(self.texts): self.assertEquals(text, self.ctrl.GetTabText(i)) self.assertRaises(IndexError, self.ctrl.GetTabText, 99) def testClientRects(self): self.assertEquals(self.ctrl.client_rect(), self.ctrl.client_rects()[0]) self.assertEquals(self.rects, self.ctrl.client_rects()[1:]) def testSelect(self): self.assertEquals(0, self.ctrl.GetSelectedTab()) self.ctrl.Select(1) self.assertEquals(1, self.ctrl.GetSelectedTab()) self.ctrl.Select(u"CToolBarCtrl") self.assertEquals(2, self.ctrl.GetSelectedTab()) self.assertRaises(IndexError, self.ctrl.Select, 99) class ToolbarTestCases(unittest.TestCase): """Unit tests for the ToolbarWrapper class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() app = Application() app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.app = app self.dlg = app.CommonControlsSample # select a tab with toolbar controls self.dlg.SysTabControl.Select(u"CToolBarCtrl") # see identifiers available at that tab #self.dlg.PrintControlIdentifiers() # The sample app has two toolbars. The first toolbar can be # addressed as Toolbar, Toolbar0 and Toolbar1. # The second control goes as Toolbar2 self.ctrl = app.CommonControlsSample.ToolbarNew.WrapperObject() self.ctrl2 = app.CommonControlsSample.ToolbarErase.WrapperObject() def tearDown(self): """Close the application after tests""" # close the application self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the friendly class is set correctly (Toolbar)""" self.assertEquals(self.ctrl.friendly_class_name(), "Toolbar") def testTexts(self): """Make sure the texts are set correctly""" for txt in self.ctrl.texts(): self.assertEquals(isinstance(txt, six.string_types), True) def testGetProperties(self): """Test getting the properties for the toolbar control""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) self.assertEquals( self.ctrl.ButtonCount(), props['button_count']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testButtonCount(self): """Test the button count method of the toolbar""" # TODO: for a some reason the first toolbar returns button count = 12 # The same as in the second toolbar, even though their handles are different. # Maybe the test app itself has to be fixed too. #self.assertEquals(self.ctrl.ButtonCount(), 9) self.assertEquals(self.ctrl2.ButtonCount(), 12) def testGetButton(self): self.assertRaises(IndexError, self.ctrl.GetButton, 29) def testGetButtonRect(self): rect_ctrl = self.ctrl.GetButtonRect(0) self.assertEquals((rect_ctrl.left, rect_ctrl.top), (0, 0)) self.failIf((rect_ctrl.right - rect_ctrl.left) > 40) self.failIf((rect_ctrl.right - rect_ctrl.left) < 36) self.failIf((rect_ctrl.bottom - rect_ctrl.top) > 38) self.failIf((rect_ctrl.bottom - rect_ctrl.top) < 36) #self.assertEquals(rect_ctrl, RECT(0, 0, 40, 38)) rect_ctrl2 = self.ctrl2.GetButtonRect(0) self.assertEquals((rect_ctrl2.left, rect_ctrl2.top), (0, 0)) self.failIf((rect_ctrl2.right - rect_ctrl2.left) > 70) self.failIf((rect_ctrl2.right - rect_ctrl2.left) < 64) self.failIf((rect_ctrl2.bottom - rect_ctrl2.top) > 38) self.failIf((rect_ctrl2.bottom - rect_ctrl2.top) < 36) #self.assertEquals(rect_ctrl2, RECT(0, 0, 70, 38)) def testGetToolTipsControls(self): tips = self.ctrl.GetToolTipsControl() tt = tips.texts() self.assertEquals(u"New" in tt, True) self.assertEquals(u"About" in tt, True) tips = self.ctrl2.GetToolTipsControl() tt = tips.texts() self.assertEquals(u"Pencil" in tt, True) self.assertEquals(u"Ellipse" in tt, True) def testPressButton(self): self.ctrl.PressButton(0) #print(self.ctrl.texts()) self.assertRaises( findbestmatch.MatchError, self.ctrl.PressButton, "asdfdasfasdf") # todo more tests for pressbutton self.ctrl.PressButton(u"Open") def testCheckButton(self): self.ctrl2.CheckButton('Erase', True) self.assertEquals(self.ctrl2.Button('Erase').IsChecked(), True) self.ctrl2.CheckButton('Pencil', True) self.assertEquals(self.ctrl2.Button('Erase').IsChecked(), False) self.ctrl2.CheckButton('Erase', False) self.assertEquals(self.ctrl2.Button('Erase').IsChecked(), False) # try to check separator self.assertRaises(RuntimeError, self.ctrl.CheckButton, 3, True) def testIsCheckable(self): self.assertNotEqual(self.ctrl2.Button('Erase').IsCheckable(), False) self.assertEquals(self.ctrl.Button('New').IsCheckable(), False) def testIsPressable(self): self.assertEquals(self.ctrl.Button('New').IsPressable(), True) def testButtonByTooltip(self): self.assertEquals(self.ctrl.Button('New', by_tooltip=True).Text(), 'New') self.assertEquals(self.ctrl.Button('About', exact=False, by_tooltip=True).Text(), 'About') class RebarTestCases(unittest.TestCase): """Unit tests for the UpDownWrapper class""" def setUp(self): """Start the application, set some data and wait for the state we want The app title can be tricky. If no document is opened the title is just: "RebarTest" However if an document is created/opened in the child frame the title is appended with a document name: "RebarTest - RebarTest1" A findbestmatch proc does well here with guessing the title even though the app is started with a short title "RebarTest". """ Timings.Fast() app = Application() app.start(os.path.join(mfc_samples_folder, "RebarTest.exe")) mouse.move((-500, 200)) # remove the mouse from the screen to avoid side effects self.app = app self.dlg = app.RebarTest_RebarTest self.dlg.Wait('ready', 20) self.ctrl = app.RebarTest_RebarTest.Rebar.WrapperObject() def tearDown(self): """Close the application after tests""" # close the application self.app.kill() def testFriendlyClass(self): """Make sure the friendly class is set correctly (ReBar)""" self.assertEquals(self.ctrl.friendly_class_name(), "ReBar") def testTexts(self): """Make sure the texts are set correctly""" for txt in self.ctrl.texts(): self.assertEquals(isinstance(txt, six.string_types), True) def testBandCount(self): """Make sure BandCount() returns 2""" self.assertEquals(self.ctrl.BandCount(), 2) def testGetBand(self): """Check that GetBand() is working corectly""" self.assertRaises(IndexError, self.ctrl.GetBand, 99) self.assertRaises(IndexError, self.ctrl.GetBand, 2) band = self.ctrl.GetBand(0) self.assertEquals(band.hwndChild, self.dlg.MenuBar.handle) self.assertEquals(self.ctrl.GetBand(1).text, u"Tools band:") self.assertEquals(self.ctrl.GetBand(0).text, u"Menus band:") def testGetToolTipsControl(self): """Make sure GetToolTipsControl() returns None""" self.assertEquals(self.ctrl.GetToolTipsControl(), None) def testAfxToolBarButtons(self): """Make sure we can click on Afx ToolBar button by index""" Timings.closeclick_dialog_close_wait = 2. self.dlg.StandardToolbar.Button(1).Click() self.app.Window_(title='Open').Wait('ready') self.app.Window_(title='Open').Cancel.CloseClick() def testMenuBarClickInput(self): """Make sure we can click on Menu Bar items by indexed path""" self.assertRaises(TypeError, self.dlg.MenuBar.MenuBarClickInput, '#one->#0', self.app) self.dlg.MenuBar.MenuBarClickInput('#1->#0->#0', self.app) self.app.Customize.CloseButton.Click() self.app.Customize.WaitNot('visible') self.dlg.MenuBar.MenuBarClickInput([2, 0], self.app) self.app.Window_(title='About RebarTest').OK.Click() self.app.Window_(title='About RebarTest').WaitNot('visible') class DatetimeTestCases(unittest.TestCase): """Unit tests for the DateTimePicker class""" def setUp(self): """Start the application and get 'Date Time Picker' control""" Timings.Fast() app = Application() app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) self.app = app self.dlg = app.CommonControlsSample self.dlg.Wait('ready', 20) tab = app.CommonControlsSample.TabControl.WrapperObject() tab.Select(3) self.ctrl = self.dlg.DateTimePicker def tearDown(self): """Close the application after tests""" # close the application self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the friendly class is set correctly (DateTimePicker)""" self.assertEqual(self.ctrl.friendly_class_name(), "DateTimePicker") def testGetTime(self): """Test reading a date from a 'Date Time Picker' control""" # No check for seconds and milliseconds as it can slip # These values are verified in the next 'testSetTime' test_date_time = self.ctrl.GetTime() date_time_now = datetime.now() self.assertEqual(test_date_time.wYear, date_time_now.year) self.assertEqual(test_date_time.wMonth, date_time_now.month) self.assertEqual(test_date_time.wDay, date_time_now.day) self.assertEqual(test_date_time.wHour, date_time_now.hour) self.assertEqual(test_date_time.wMinute, date_time_now.minute) def testSetTime(self): """Test setting a date to a 'Date Time Picker' control""" year = 2025 month = 9 day_of_week = 5 day = 19 hour = 1 minute = 2 second = 3 milliseconds = 781 self.ctrl.SetTime( year=year, month=month, day_of_week=day_of_week, day=day, hour=hour, minute=minute, second=second, milliseconds=milliseconds ) # Retrive back the values we set test_date_time = self.ctrl.GetTime() self.assertEqual(test_date_time.wYear, year) self.assertEqual(test_date_time.wMonth, month) self.assertEqual(test_date_time.wDay, day) self.assertEqual(test_date_time.wDayOfWeek, day_of_week) self.assertEqual(test_date_time.wHour, hour) self.assertEqual(test_date_time.wMinute, minute) self.assertEqual(test_date_time.wSecond, second) self.assertEqual(test_date_time.wMilliseconds, milliseconds) class ToolTipsTestCases(unittest.TestCase): """Unit tests for the tooltips class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() self.texts = [u'', u'New', u'Open', u'Save', u'Cut', u'Copy', u'Paste', u'Print', u'About', u'Help'] app = Application() app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe")) #app.start_(os.path.join(controlspy_folder, "Tooltip.exe")) self.app = app self.dlg = app.Common_Controls_Sample # Make sure the mouse doesn't hover over tested controls # so it won't generate an unexpected tooltip self.dlg.move_mouse_input(coords=(-100, -100), absolute=True) self.dlg.TabControl.Select(u'CToolBarCtrl') self.ctrl = self.dlg.Toolbar.GetToolTipsControl() def tearDown(self): """Close the application after tests""" # close the application self.app.kill_() def testFriendlyClass(self): """Make sure the friendly class is set correctly (ToolTips)""" self.assertEquals(self.ctrl.friendly_class_name(), "ToolTips") def testGetProperties(self): """Test getting the properties for the tooltips control""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testGetTip(self): """Test that GetTip() returns correct ToolTip object""" self.assertRaises(IndexError, self.ctrl.GetTip, 99) tip = self.ctrl.GetTip(1) self.assertEquals(tip.text, self.texts[1]) def testToolCount(self): """Test that ToolCount() returns correct value""" self.assertEquals(10, self.ctrl.ToolCount()) def testGetTipText(self): """Test that GetTipText() returns correct text""" self.assertEquals(self.texts[1], self.ctrl.GetTipText(1)) def testTexts(self): """Make sure the texts are set correctly""" # just to make sure a tooltip is not shown self.dlg.move_mouse_input(coords=(0, 0), absolute=False) ActionLogger().log('ToolTips texts = ' + ';'.join(self.ctrl.texts())) self.assertEquals(self.ctrl.texts()[0], '') self.assertEquals(self.ctrl.texts()[1:], self.texts) class UpDownTestCases(unittest.TestCase): """Unit tests for the UpDownWrapper class""" def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Fast() app = Application() app.start(os.path.join(controlspy_folder, "Up-Down.exe")) self.app = app self.dlg = app.MicrosoftControlSpy self.ctrl = app.MicrosoftControlSpy.UpDown2.WrapperObject() def tearDown(self): """Close the application after tests""" # close the application self.dlg.SendMessage(win32defines.WM_CLOSE) def testFriendlyClass(self): """Make sure the friendly class is set correctly (UpDown)""" self.assertEquals(self.ctrl.friendly_class_name(), "UpDown") def testTexts(self): """Make sure the texts are set correctly""" self.assertEquals(self.ctrl.texts()[1:], []) def testGetProperties(self): """Test getting the properties for the updown control""" props = self.ctrl.GetProperties() self.assertEquals( self.ctrl.friendly_class_name(), props['friendly_class_name']) self.assertEquals( self.ctrl.texts(), props['texts']) for prop_name in props: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testGetValue(self): """Test getting up-down position""" self.assertEquals(self.ctrl.GetValue(), 0) self.ctrl.SetValue(23) self.assertEquals(self.ctrl.GetValue(), 23) def testSetValue(self): """Test setting up-down position""" self.assertEquals(self.ctrl.GetValue(), 0) self.ctrl.SetValue(23) self.assertEquals(self.ctrl.GetValue(), 23) self.assertEquals( int(self.ctrl.GetBuddyControl().texts()[1]), 23) def testGetBase(self): """Test getting the base of the up-down control""" self.assertEquals(self.ctrl.GetBase(), 10) #self.dlg.StatementEdit.SetEditText ("MSG (UDM_SETBASE, 16, 0)") # use CloseClick to allow the control time to respond to the message #self.dlg.Send.click_input() self.ctrl.SetBase(16) self.assertEquals(self.ctrl.GetBase(), 16) def testGetRange(self): """Test getting the range of the up-down control""" self.assertEquals((0, 9999), self.ctrl.GetRange()) def testGetBuddy(self): """Test getting the buddy control""" self.assertEquals(self.ctrl.GetBuddyControl().handle, self.dlg.Edit6.handle) def testIncrement(self): """Test incremementing up-down position""" Timings.Defaults() self.ctrl.Increment() self.assertEquals(self.ctrl.GetValue(), 1) def testDecrement(self): """Test decrementing up-down position""" Timings.Defaults() self.ctrl.SetValue(23) self.ctrl.Decrement() self.assertEquals(self.ctrl.GetValue(), 22) class TrackbarWrapperTestCases(unittest.TestCase): def setUp(self): """Set some data and ensure the application is in the state we want""" app = Application() app.start(os.path.join(mfc_samples_folder, u"CmnCtrl2.exe")) dlg = app.top_window() dlg.TabControl.Select(1) ctrl = dlg.Trackbar.WrapperObject() self.app = app self.dlg = dlg self.ctrl = ctrl def tearDown(self): """Close the application after tests""" # close the application self.dlg.send_message(win32defines.WM_CLOSE) def test_friendly_class(self): """Make sure the Trackbar friendly class is set correctly""" self.assertEquals(self.ctrl.friendly_class_name(), u"Trackbar") def test_get_range_max(self): """Test the get_range_max method""" self.ctrl.set_range_max(100) self.assertEquals(self.ctrl.get_range_max(), 100) def test_get_range_min(self): """Test the get_range_min method""" self.ctrl.set_range_min(25) self.assertEquals(self.ctrl.get_range_min(), 25) def test_set_range_min_more_then_range_max(self): """Test the set_range_min method with error""" self.assertRaises(ValueError, self.ctrl.set_range_min, self.ctrl.get_range_max() + 1) def test_set_position_more_than_max_range(self): """Test the set_position method with error""" self.ctrl.set_range_max(100) self.assertRaises(ValueError, self.ctrl.set_position, 110) def test_set_position_less_than_min_range(self): """Test the set_position method with error""" self.assertRaises(ValueError, self.ctrl.set_position, self.ctrl.get_range_min() - 10) def test_set_correct_position(self): """Test the set_position method""" self.ctrl.set_position(23) self.assertEqual(self.ctrl.get_position(), 23) def test_get_num_ticks(self): """Test the get_num_ticks method""" self.assertEqual(self.ctrl.get_num_ticks(), 6) def test_get_channel_rect(self): """Test the get_channel_rect method""" system_rect = RECT() system_rect.left = 8 system_rect.top = 19 system_rect.right = 249 system_rect.bottom = 23 self.assert_channel_rect(self.ctrl.get_channel_rect(), system_rect) def assert_channel_rect(self, first_rect, second_rect): """Compare two rect strucrures""" self.assertEqual(first_rect.height(), second_rect.height()) self.assertEqual(first_rect.width(), second_rect.width()) def test_get_line_size(self): """Test the get_line_size method""" self.ctrl.set_line_size(10) self.assertEquals(self.ctrl.get_line_size(), 10) def test_get_page_size(self): """Test the set_page_size method""" self.ctrl.set_page_size(14) self.assertEquals(self.ctrl.get_page_size(), 14) def test_get_tool_tips_control(self): """Test the get_tooltips_control method""" self.assertRaises(RuntimeError, self.ctrl.get_tooltips_control) def test_set_sel(self): """Test the set_sel method""" self.assertRaises(RuntimeError, self.ctrl.set_sel, 22, 55) def test_get_sel_start(self): """Test the get_sel_start method""" self.assertRaises(RuntimeError, self.ctrl.get_sel_start) def test_get_sel_end(self): """Test the get_sel_end method""" self.assertRaises(RuntimeError, self.ctrl.get_sel_end) if __name__ == "__main__": unittest.main()
import pytest from anchore_engine.util.cpe_generators import ( generate_fuzzy_cpes, generate_fuzzy_go_cpes, generate_gem_products, generate_java_cpes, generate_npm_products, generate_products, generate_python_products, generate_simple_cpe, ) @pytest.mark.parametrize( "name, expected_list, generator_function", [ pytest.param("gem1", ["gem1"], generate_gem_products, id="gem-simple"), pytest.param( "cremefraiche", ["creme_fraishe", "cremefraiche"], generate_gem_products, id="gem-matches-inclusion-list", ), pytest.param("npm1", ["npm1"], generate_gem_products, id="npm-simple"), pytest.param( "hapi", ["hapi", "hapi_server_framework"], generate_npm_products, id="npm-matches-inclusion-list", ), pytest.param("python1", ["python1"], generate_gem_products, id="python-simple"), pytest.param( "python-rrdtool", ["python-rrdtool", "rrdtool"], generate_python_products, id="python-matches-inclusion-list", ), ], ) def test_generate_product_functions(name, expected_list, generator_function): assert generator_function(name).sort() == expected_list.sort() @pytest.mark.parametrize( "name, package_type, expected_list", [ pytest.param("gem1", "gem", ["gem1"], id="gem-simple"), pytest.param( "cremefraiche", "gem", ["creme_fraiche", "cremefraiche"], id="gem-matches-inclusion-list", ), pytest.param("npm1", "npm", ["npm1"], id="npm-simple"), pytest.param( "hapi", "npm", ["hapi", "hapi_server_framework"], id="npm-matches-inclusion-list", ), pytest.param("python1", "python", ["python1"], id="python-simple"), pytest.param( "python-rrdtool", "python", ["python-rrdtool", "rrdtool"], id="python-matches-inclusion-list", ), pytest.param( "Microsoft.NETCore.App", "nuget", ["Microsoft.NETCore.App", ".net_core"], id="nuget-matches-inclusion-list", ), pytest.param( "foobar", "unknownpackagetype", ["foobar"], id="unknown-package-type", ), ], ) def test_generate_products(name, package_type, expected_list): # Function under test products = generate_products(name, package_type) # Sort the observed and expected lists # sort() is an in-place operation and returns None, so don't store or compare the call results products.sort() expected_list.sort() # Validate output assert products == expected_list @pytest.mark.parametrize( "name, version, cpe", [("product", "version", "cpe:2.3:a:*:product:version:*:*:*:*:*:*:*")], ) def test_simple_cpe_generation(name, version, cpe): assert generate_simple_cpe(name, version) == cpe @pytest.mark.parametrize( "name, version, cpes", [ ("product", "version", ["cpe:2.3:*:product:version:*:*:*:*:*:*:*"]), ( "product", "v3.1.0", [ "cpe:2.3:*:product:v3.1.0:*:*:*:*:*:*:*", "cpe:2.3:*:product:3.1.0:*:*:*:*:*:*:*", ], ), ], ) def test_golang_cpe_generation(name, version, cpes): assert generate_fuzzy_go_cpes(name, version).sort() == cpes.sort() @pytest.mark.parametrize( "content_dict, cpes", [ pytest.param( { "package": "javapkg", "version": "1.2.3-r0", "implementation-version": "1.2.3", "specification-version": "1.2.5", "maven-version": "2.0.0", }, [ "cpe:2.3:-:javapkg:1.3.0:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:1.2.3-r0:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:1.2.3:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:2.0.0:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:1.2.3-r0:*:*:*:*:*:*:*", ], id="multi-version-simple-name", ), pytest.param( { "package": "javapkg", "version": "1.2.3", }, [ "cpe:2.3:-:javapkg:1.2.3:*:*:*:*:*:*:*", ], id="simple-version-simple-name", ), pytest.param( { "package": "javapkg-1.3.0", "version": "1.2.3", }, [ "cpe:2.3:-:javapkg:1.3.0:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:1.2.3:*:*:*:*:*:*:*", ], id="version-name", ), pytest.param( { "package": "javapkg-core", "version": "1.2.3", }, [ "cpe:2.3:-:javapkg-core:1.2.3:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg:1.2.3:*:*:*:*:*:*:*", ], id="compound-name", ), pytest.param( { "package": "javapkg-alpha-core", "version": "1.2.3", }, [ "cpe:2.3:-:javapkg-alpha-core:1.2.3:*:*:*:*:*:*:*", "cpe:2.3:-:javapkg-alpha:1.2.3:*:*:*:*:*:*:*", ], id="compound-multi-section-name", ), ], ) def test_java_cpe_generation(content_dict, cpes): assert generate_java_cpes(content_dict).sort() == cpes.sort() @pytest.mark.parametrize( "name, version, package_type, cpes", [ pytest.param( "gem1", "1.0.0", "gem", ["cpe:2.3:-:gem1:1.1.0:*:*:*:*:*:*:*"], id="gem-simple", ), pytest.param( "cremefraiche", "1.0.0", "gem", [ "cpe:2.3:-:creme_fraishe:1.0.0:*:*:*:*:*:*:*", "cpe:2.3:-:cremefraishe:1.0.0:*:*:*:*:*:*:*", ], id="gem-matches-inclusion-list", ), pytest.param( "hapi", "1.0.0", "npm", [ "cpe:2.3:-:hapi:1.0.0:*:*:*:*:*:*:*", "cpe:2.3:-:hapi_server_framework:1.0.0:*:*:*:*:*:*:*", ], id="npm-matches-inclusion-list", ), pytest.param( "npm1", "1.0.0", "npm", [ "cpe:2.3:-:npm1:1.0.0:*:*:*:*:*:*:*", ], id="npm-simple", ), pytest.param( "pythontool", "1.0.0", "python", [ "cpe:2.3:-:pythontool:1.0.0:*:*:*:*:*:*:*", ], id="python-simple", ), pytest.param( "python-rrdtool", "1.0.0", "python", [ "cpe:2.3:-:python-rrdtool:1.0.0:*:*:*:*:*:*:*", "cpe:2.3:-:rrdtool:1.0.0:*:*:*:*:*:*:*", ], id="python-matches-inclusion-list", ), ], ) def test_generate_fuzzy_cpes(name, version, package_type, cpes): assert generate_fuzzy_cpes(name, version, package_type).sort() == cpes.sort()
import math import os import shutil import tempfile import unittest import mleap.pyspark # noqa from mleap.pyspark.spark_support import SimpleSparkSerializer # noqa import pandas as pd from pandas.testing import assert_frame_equal from pyspark.ml import Pipeline from pyspark.sql.types import FloatType from pyspark.sql.types import StructType from pyspark.sql.types import StructField from mleap.pyspark.feature.math_binary import MathBinary from mleap.pyspark.feature.math_binary import BinaryOperation from tests.pyspark.lib.spark_session import spark_session INPUT_SCHEMA = StructType([ StructField('f1', FloatType()), StructField('f2', FloatType()), ]) class MathBinaryTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.spark = spark_session() @classmethod def tearDownClass(cls): cls.spark.stop() def setUp(self): self.input = self.spark.createDataFrame([ ( float(i), float(i * 2), ) for i in range(1, 10) ], INPUT_SCHEMA) self.expected_add = pd.DataFrame( [( float(i + i * 2) ) for i in range(1, 10)], columns=['add(f1, f2)'], ) self.tmp_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmp_dir) def _new_add_math_binary(self): return MathBinary( operation=BinaryOperation.Add, inputA="f1", inputB="f2", outputCol="add(f1, f2)", ) def test_add_math_binary(self): add_transformer = self._new_add_math_binary() result = add_transformer.transform(self.input).toPandas()[['add(f1, f2)']] assert_frame_equal(self.expected_add, result) def test_math_binary_pipeline(self): add_transformer = self._new_add_math_binary() mul_transformer = MathBinary( operation=BinaryOperation.Multiply, inputA="f1", inputB="add(f1, f2)", outputCol="mul(f1, add(f1, f2))", ) expected = pd.DataFrame( [( float(i * (i + i * 2)) ) for i in range(1, 10)], columns=['mul(f1, add(f1, f2))'], ) pipeline = Pipeline( stages=[add_transformer, mul_transformer] ) pipeline_model = pipeline.fit(self.input) result = pipeline_model.transform(self.input).toPandas()[['mul(f1, add(f1, f2))']] assert_frame_equal(expected, result) def test_can_instantiate_all_math_binary(self): for binary_operation in BinaryOperation: transformer = MathBinary( operation=binary_operation, inputA="f1", inputB="f2", outputCol="operation", ) def test_serialize_deserialize_math_binary(self): add_transformer = self._new_add_math_binary() file_path = '{}{}'.format('jar:file:', os.path.join(self.tmp_dir, 'math_binary.zip')) add_transformer.serializeToBundle(file_path, self.input) deserialized_math_binary = SimpleSparkSerializer().deserializeFromBundle(file_path) result = deserialized_math_binary.transform(self.input).toPandas()[['add(f1, f2)']] assert_frame_equal(self.expected_add, result) def test_serialize_deserialize_pipeline(self): add_transformer = self._new_add_math_binary() mul_transformer = MathBinary( operation=BinaryOperation.Multiply, inputA="f1", inputB="add(f1, f2)", outputCol="mul(f1, add(f1, f2))", ) expected = pd.DataFrame( [( float(i * (i + i * 2)) ) for i in range(1, 10)], columns=['mul(f1, add(f1, f2))'], ) pipeline = Pipeline( stages=[add_transformer, mul_transformer] ) pipeline_model = pipeline.fit(self.input) file_path = '{}{}'.format('jar:file:', os.path.join(self.tmp_dir, 'math_binary_pipeline.zip')) pipeline_model.serializeToBundle(file_path, self.input) deserialized_pipeline = SimpleSparkSerializer().deserializeFromBundle(file_path) result = pipeline_model.transform(self.input).toPandas()[['mul(f1, add(f1, f2))']] assert_frame_equal(expected, result) def test_add_math_binary_defaults_none(self): add_transformer = self._new_add_math_binary() none_df = self.spark.createDataFrame([ (None, float(i * 2)) for i in range(1, 3) ], INPUT_SCHEMA) # Summing null + int yields NaN expected_df = pd.DataFrame([ (float("NaN"),) for i in range(1, 3) ], columns=['add(f1, f2)']) result = add_transformer.transform(none_df).toPandas()[['add(f1, f2)']] assert_frame_equal(expected_df, result) def test_mult_math_binary_default_inputA(self): mult_transformer = MathBinary( operation=BinaryOperation.Multiply, inputB="f2", outputCol="mult(1, f2)", defaultA=1.0, ) none_df = self.spark.createDataFrame([ (None, float(i * 1234)) for i in range(1, 3) ], INPUT_SCHEMA) expected_df = pd.DataFrame([ (float(i * 1234), ) for i in range(1, 3) ], columns=['mult(1, f2)']) result = mult_transformer.transform(none_df).toPandas()[['mult(1, f2)']] assert_frame_equal(expected_df, result) def test_mult_math_binary_default_inputB(self): mult_transformer = MathBinary( operation=BinaryOperation.Multiply, inputA="f1", outputCol="mult(f1, 2)", defaultB=2.0, ) none_df = self.spark.createDataFrame([ (float(i * 1234), None) for i in range(1, 3) ], INPUT_SCHEMA) expected_df = pd.DataFrame([ (float(i * 1234 * 2), ) for i in range(1, 3) ], columns=['mult(f1, 2)']) result = mult_transformer.transform(none_df).toPandas()[['mult(f1, 2)']] assert_frame_equal(expected_df, result) def test_mult_math_binary_default_both(self): mult_transformer = MathBinary( operation=BinaryOperation.Multiply, outputCol="mult(7, 8)", defaultA=7.0, defaultB=8.0, ) none_df = self.spark.createDataFrame([ (None, None) for i in range(1, 3) ], INPUT_SCHEMA) expected_df = pd.DataFrame([ (float(7 * 8), ) for i in range(1, 3) ], columns=['mult(7, 8)']) result = mult_transformer.transform(none_df).toPandas()[['mult(7, 8)']] assert_frame_equal(expected_df, result)
# 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. # ============================================================================== """The OneHotCategorical distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.distributions.python.ops import distribution from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.contrib.distributions.python.ops import kullback_leibler from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops class _OneHotCategorical(distribution.Distribution): """OneHotCategorical distribution. The categorical distribution is parameterized by the log-probabilities of a set of classes. The difference between OneHotCategorical and Categorical distributions is that OneHotCategorical is a discrete distribution over one-hot bit vectors whereas Categorical is a discrete distribution over positive integers. This class provides methods to create indexed batches of OneHotCategorical distributions. If the provided `logits` or `p` is rank 2 or higher, for every fixed set of leading dimensions, the last dimension represents one single OneHotCategorical distribution. When calling distribution functions (e.g. `dist.prob(x)`), `logits` and `x` are broadcast to the same shape (if possible). In all cases, the last dimension of `logits/x` represents single OneHotCategorical distributions. #### Examples Creates a 3-class distiribution, with the 2nd class, the most likely to be drawn from. ```python p = [0.1, 0.5, 0.4] dist = OneHotCategorical(p=p) ``` Creates a 3-class distiribution, with the 2nd class the most likely to be drawn from, using logits. ```python logits = [-2, 2, 0] dist = OneHotCategorical(logits=logits) ``` Creates a 3-class distribution, with the 3rd class is most likely to be drawn. ```python # counts is a scalar. p = [0.1, 0.4, 0.5] dist = OneHotCategorical(p=p) dist.pmf([0,1,0]) # Shape [] # p will be broadcast to [[0.1, 0.4, 0.5], [0.1, 0.4, 0.5]] to match. samples = [[0,1,0], [1,0,0]] dist.pmf(samples) # Shape [2] ``` """ def __init__( self, logits=None, p=None, dtype=dtypes.int32, validate_args=False, allow_nan_stats=True, name="OneHotCategorical"): """Initialize OneHotCategorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension represents a vector of logits for each class. Only one of `logits` or `p` should be passed in. p: An N-D `Tensor`, `N >= 1`, representing the probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension represents a vector of probabilities for each class. Only one of `logits` or `p` should be passed in. dtype: The type of the event samples (default: int32). validate_args: Unused in this distribution. allow_nan_stats: `Boolean`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: A name for this distribution (optional). """ parameters = locals() parameters.pop("self") with ops.name_scope(name, values=[logits]) as ns: self._logits, self._p = distribution_util.get_logits_and_prob( name=name, logits=logits, p=p, validate_args=validate_args, multidimensional=True) logits_shape_static = self._logits.get_shape().with_rank_at_least(1) if logits_shape_static.ndims is not None: self._batch_rank = ops.convert_to_tensor( logits_shape_static.ndims - 1, dtype=dtypes.int32, name="batch_rank") else: with ops.name_scope(name="batch_rank"): self._batch_rank = array_ops.rank(self._logits) - 1 logits_shape = array_ops.shape(self._logits, name="logits_shape") if logits_shape_static[-1].value is not None: self._num_classes = ops.convert_to_tensor( logits_shape_static[-1].value, dtype=dtypes.int32, name="num_classes") else: self._num_classes = array_ops.gather(logits_shape, self._batch_rank, name="num_classes") if logits_shape_static[:-1].is_fully_defined(): self._batch_shape_val = constant_op.constant( logits_shape_static[:-1].as_list(), dtype=dtypes.int32, name="batch_shape") else: with ops.name_scope(name="batch_shape"): self._batch_shape_val = logits_shape[:-1] super(_OneHotCategorical, self).__init__( dtype=dtype, is_continuous=False, is_reparameterized=False, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._logits, self._num_classes], name=ns) @property def num_classes(self): """Scalar `int32` tensor: the number of classes.""" return self._num_classes @property def logits(self): """Vector of coordinatewise logits.""" return self._logits @property def p(self): """Vector of probabilities summing to one. Each element is the probability of drawing that coordinate.""" return self._p def _batch_shape(self): # Use identity to inherit callers "name". return array_ops.identity(self._batch_shape_val) def _get_batch_shape(self): return self.logits.get_shape()[:-1] def _event_shape(self): return array_ops.shape(self.logits)[-1] def _get_event_shape(self): return self.logits.get_shape().with_rank_at_least(1)[-1:] def _sample_n(self, n, seed=None): sample_shape = array_ops.concat(0, ([n], array_ops.shape(self.logits))) logits = self.logits if logits.get_shape().ndims == 2: logits_2d = logits else: logits_2d = array_ops.reshape(logits, [-1, self.num_classes]) samples = random_ops.multinomial(logits_2d, n, seed=seed) samples = array_ops.transpose(samples) samples = array_ops.one_hot(samples, self.num_classes, dtype=self.dtype) ret = array_ops.reshape(samples, sample_shape) return ret def _log_prob(self, x): x = ops.convert_to_tensor(x, name="x") # broadcast logits or x if need be. logits = self.logits if (not x.get_shape().is_fully_defined() or not logits.get_shape().is_fully_defined() or x.get_shape() != logits.get_shape()): logits = array_ops.ones_like(x, dtype=logits.dtype) * logits x = array_ops.ones_like(logits, dtype=x.dtype) * x logits_shape = array_ops.shape(logits) if logits.get_shape().ndims == 2: logits_2d = logits x_2d = x else: logits_2d = array_ops.reshape(logits, [-1, self.num_classes]) x_2d = array_ops.reshape(x, [-1, self.num_classes]) ret = -nn_ops.softmax_cross_entropy_with_logits(logits_2d, x_2d) ret = array_ops.reshape(ret, logits_shape) return ret def _prob(self, x): return math_ops.exp(self._log_prob(x)) def _entropy(self): if self.logits.get_shape().ndims == 2: logits_2d = self.logits else: logits_2d = array_ops.reshape(self.logits, [-1, self.num_classes]) histogram_2d = nn_ops.softmax(logits_2d) ret = array_ops.reshape( nn_ops.softmax_cross_entropy_with_logits(logits_2d, histogram_2d), self.batch_shape()) ret.set_shape(self.get_batch_shape()) return ret def _mode(self): ret = math_ops.argmax(self.logits, axis=self._batch_rank) ret = array_ops.one_hot(ret, self.num_classes, dtype=self.dtype) ret.set_shape(self.logits.get_shape()) return ret @kullback_leibler.RegisterKL(_OneHotCategorical, _OneHotCategorical) def _kl_categorical_categorical(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical. Args: a: instance of a OneHotCategorical distribution object. b: instance of a OneHotCategorical distribution object. name: (optional) Name to use for created operations. default is "kl_categorical_categorical". Returns: Batchwise KL(a || b) """ with ops.name_scope( name, "kl_categorical_categorical", [a.logits, b.logits]): # sum(p*ln(p/q)) return math_ops.reduce_sum( nn_ops.softmax(a.logits)*(nn_ops.log_softmax(a.logits) - nn_ops.log_softmax(b.logits)), reduction_indices=[-1])
#<ImportSpecificModules> import collections import copy import inspect import numpy from ShareYourSystem.Standards.Objects import Initiator ,Inspecter import importlib BaseModule=Inspecter DecorationModule=BaseModule #</ImportSpecificModules> #<DefineLocals> SYS.setSubModule(globals()) RepresentingDictIndentStr=" " RepresentingListIndentStr=" " RepresentingIndentStr=" /" RepresentingEofStr="\n" RepresentingIdBool=True RepresentedAlineaStr="" #</DefineLocals> #<DefineFunctions> def getRepresentedNumpyArray(_NumpyArray): #Definition the ShapeList ShapeList=list(numpy.shape(_NumpyArray)) #debug ''' print('Representer l.25 : getRepresentedNumpyArray') print('ShapeList is',ShapeList) print('') ''' #Return the array directly if it is small or either a short represented version of it if (len(ShapeList)==1 and ShapeList[0]<3) or (len(ShapeList)>1 and ShapeList[1]<3): return str(_NumpyArray) return "<numpy.ndarray shape "+str(ShapeList)+">" def getRepresentedPointerStrWithVariable(_Variable,**_KwargVariablesDict): #debug ''' print('Representer l.39 : getRepresentedPointerStrWithVariable') print('') ''' #set in the _KwargVariablesDict if 'RepresentedDeepInt' not in _KwargVariablesDict: _KwargVariablesDict['RepresentedDeepInt']=0 #Definition the Local alinea RepresentedLocalAlineaStr=RepresentedAlineaStr if _KwargVariablesDict['RepresentedDeepInt']==0 else "" if RepresentingIdBool: return RepresentedLocalAlineaStr+"<"+( _Variable.__name__ if hasattr(_Variable,__name__) else "" )+" ("+_Variable.__class__.__name__+"), "+str(id(_Variable))+">" else: return RepresentedLocalAlineaStr+"<"+( _Variable.__name__ if hasattr(_Variable,__name__) else "" )+" ("+_Variable.__class__.__name__+")"+" >" def getRepresentedStrWithDictatedVariable( _DictatedVariable,**_KwargVariablesDict ): #set in the _KwargVariablesDict if 'RepresentedDeepInt' not in _KwargVariablesDict: _KwargVariablesDict['RepresentedDeepInt']=0 #debug ''' print('Representer l.59 : getRepresentedStrWithDictatedVariable') print('_KwargVariablesDict is ',str(_KwargVariablesDict)) print('') ''' #Global global RepresentedAlineaStr #Definition the LocalRepresentedAlineaStr LocalRepresentedAlineaStr=RepresentedAlineaStr+"".join( [RepresentingIndentStr]*(_KwargVariablesDict['RepresentedDeepInt'])) #Init the RepresentedDictStr RepresentedDictStr="\n"+LocalRepresentedAlineaStr+"{ " #Scan the Items (integrativ loop) if type(_DictatedVariable)==collections.OrderedDict: TuplesList=_DictatedVariable.items() else: TuplesList=sorted(_DictatedVariable.iteritems(), key=lambda key_value: key_value[0]) #Integrativ loop for seriaizing the items for KeyStr,ValueVariable in TuplesList: #set the begin of the line RepresentedDictStr+="\n"+LocalRepresentedAlineaStr+RepresentingDictIndentStr #Force the cast into Str if type(KeyStr) not in [unicode,str]: KeyStr=str(KeyStr) #Get the WordStrsList WordStrsList=SYS.getWordStrsListWithStr(KeyStr) #Init the RepresentedValueVariableStr RepresentedValueVariableStr="None" #Split the case if it is a pointing variable or not if len(WordStrsList)>0: #Value is displayed if SYS.getWordStrsListWithStr(KeyStr)[-1]=="Pointer": #Pointer Case RepresentedValueVariableStr=getRepresentedPointerStrWithVariable( ValueVariable, **_KwargVariablesDict ) elif ''.join(SYS.getWordStrsListWithStr(KeyStr)[-2:])=="PointersList": #Pointer Case RepresentedValueVariableStr=str( map( lambda ListedVariable: getRepresentedPointerStrWithVariable( ListedVariable, **_KwargVariablesDict), ValueVariable ) ) #Special Suffix Cases if RepresentedValueVariableStr=="None": #Other Cases RepresentedValueVariableStr=represent( ValueVariable,**_KwargVariablesDict ) #Key and Value Case RepresentedDictStr+="'"+KeyStr+"' : "+RepresentedValueVariableStr #Add a last line RepresentedDictStr+="\n"+LocalRepresentedAlineaStr+"}" #return the DictStr return RepresentedDictStr def getRepresentedStrWithListedVariable(_ListedVariable,**_KwargVariablesDict): #Global global RepresentedAlineaStr #set in the _KwargVariablesDict if 'RepresentedDeepInt' not in _KwargVariablesDict: _KwargVariablesDict['RepresentedDeepInt']=0 #debug ''' print('Representer l.166 : getRepresentedStrWithListedVariable') print('_KwargVariablesDict is ',str(_KwargVariablesDict)) print('_ListedVariable is '+str(_ListedVariable)) print('') ''' #Init the RepresentedDictStr if type(_ListedVariable)==list: BeginBracketStr='[' EndBracketStr=']' else: BeginBracketStr='(' EndBracketStr=')' #Definition the LocalRepresentedAlineaStr LocalRepresentedAlineaStr=RepresentedAlineaStr+"".join( [RepresentingIndentStr]*(_KwargVariablesDict['RepresentedDeepInt'])) #Do the first Jump RepresentedListStr="\n"+LocalRepresentedAlineaStr+BeginBracketStr #Scan the Items (integrativ loop) for ListedVariableInt,ListedVariable in enumerate(_ListedVariable): #set the begin of the line RepresentedListStr+="\n"+LocalRepresentedAlineaStr+RepresentingListIndentStr #Get the represented version RepresentedValueVariableStr=represent( ListedVariable,**dict(_KwargVariablesDict,**{'RepresentingAlineaIsBool':False})) #Key and Value Case RepresentedListStr+=str(ListedVariableInt)+" : "+RepresentedValueVariableStr #Add a last line RepresentedListStr+="\n"+LocalRepresentedAlineaStr+EndBracketStr #return the DictStr return RepresentedListStr def getRepresentedStrWithVariable(_Variable,**_KwargVariablesDict): #set in the _KwargVariablesDict if 'RepresentedDeepInt' not in _KwargVariablesDict: _KwargVariablesDict['RepresentedDeepInt']=0 #debug ''' print('Representer l.213 : getRepresentedStrWithVariable') print('_KwargVariablesDict is ',str(_KwargVariablesDict)) print('_Variable is '+str(_Variable)) print("hasattr(_Variable,'__repr__') is "+str(hasattr(_Variable,"__repr__"))) if hasattr(_Variable,"__repr__"): print('hasattr(_Variable.__class__,"InspectedOrderedDict") is '+str( hasattr(_Variable.__class__,"InspectedOrderedDict"))) if hasattr(_Variable.__class__,"InspectedOrderedDict"): print("_Variable.__class__.InspectedOrderedDict['__repr__']['KwargVariablesSetKeyStr'] is "+str( _Variable.__class__.InspectedOrderedDict['__repr__']['KwargVariablesSetKeyStr'])) print(_Variable.__class__.InspectedOrderedDict['__repr__']['KwargVariablesSetKeyStr']) print('') ''' #Dict types print if type(_Variable) in [dict,collections.OrderedDict]: #Increment the deep _KwargVariablesDict['RepresentedDeepInt']+=1 #debug ''' print('This is a dictated type so get a represent like a dict') print('') ''' #Return return getRepresentedStrWithDictatedVariable(_Variable,**_KwargVariablesDict) #List types print elif type(_Variable) in [list,tuple]: #debug ''' print('This is a listed type so get a represent like a list') print('') ''' #Check if it is a List of Objects or Python Types if all( map( lambda ListedVariable: type(ListedVariable) in [float,int,str,unicode,numpy.float64], _Variable ) )==False: #Increment the deep _KwargVariablesDict['RepresentedDeepInt']+=1 #debug ''' print('Print a represented version of the list') print('') ''' #Return return getRepresentedStrWithListedVariable(_Variable,**_KwargVariablesDict) else: #debug ''' print('Here just print the list directly') print('') ''' #Definition the Local alinea RepresentedLocalAlineaStr=RepresentedAlineaStr if _KwargVariablesDict['RepresentedDeepInt']==0 else "" #Return return RepresentedLocalAlineaStr+repr( _Variable).replace("\n","\n"+RepresentedLocalAlineaStr) #Instance print elif type(_Variable).__name__ in ["instancemethod"]: #Definition the Local alinea RepresentedLocalAlineaStr=RepresentedAlineaStr if _KwargVariablesDict['RepresentedDeepInt']==0 else "" #return RepresentedAlineaStr+"instancemethod" return RepresentedLocalAlineaStr+_Variable.__repr__().split('of')[0]+">" #Str types elif type(_Variable) in SYS.StrTypesList: #debug ''' print('This is a Str type so get a represent like a Str') print('') ''' #Definition the Local alinea RepresentedLocalAlineaStr=RepresentedAlineaStr if _KwargVariablesDict['RepresentedDeepInt']==0 else "" #Return return RepresentedLocalAlineaStr+_Variable.replace("\n","\n"+RepresentedLocalAlineaStr) #Other elif hasattr(_Variable,"__repr__") and hasattr( _Variable.__class__,"InspectedOrderedDict") and '__repr__' in _Variable.__class__.InspectedOrderedDict and _Variable.__class__.InspectedOrderedDict[ '__repr__']['KwargVariablesSetKeyStr']!="": #debug ''' print('This is a representer so call the repr of it with the _KwargVariablesDict') print('') ''' #Return the repr of the _Variable but shifted with the RepresentedAlineaStr return _Variable.__repr__(**_KwargVariablesDict) else: #debug ''' print('This is not identified so call the repr of it') print('') ''' #Definition the Local alinea RepresentedLocalAlineaStr=RepresentedAlineaStr if _KwargVariablesDict['RepresentedDeepInt']==0 else "" #Return a repr of the _Variable but shifted with the RepresentedAlineaStr return RepresentedLocalAlineaStr+repr(_Variable).replace("\n","\n"+RepresentedLocalAlineaStr) def _print(_Variable,**_KwargVariablesDict): print(represent(_Variable,**_KwargVariablesDict)) def represent(_Variable,**_KwargVariablesDict): #Definition the global global RepresentedAlineaStr #Represent without shifting the Strs or not if 'RepresentingAlineaIsBool' not in _KwargVariablesDict or _KwargVariablesDict['RepresentingAlineaIsBool']: return getRepresentedStrWithVariable(_Variable,**_KwargVariablesDict) else: RepresentedOldAlineaStr=RepresentedAlineaStr RepresentedAlineaStr="" RepresentedStr=getRepresentedStrWithVariable(_Variable,**_KwargVariablesDict) RepresentedAlineaStr=RepresentedOldAlineaStr return RepresentedStr #</DefineFunctions> #<DefineClass> @DecorationClass() class RepresenterClass(BaseClass): def default_init(self,**_KwargVariablesDict): #Call the parent init method BaseClass.__init__(self,**_KwargVariablesDict) def __call__(self,_Class): #debug ''' print('Representer l.341 : _Class is ',_Class) print('') ''' #Call the parent init method BaseClass.__call__(self,_Class) #Represent self.represent(self.ClassingClass) #Return return self.ClassingClass def represent(self,_Class): #debug ''' print('Representer l.352 : _Class is ',_Class) print('') ''' #set in the class the represented key Strs if not already RepresentedBoolKeyStr='Represented'+self.ClassingClass.NameStr+'Bool' #debug ''' print('RepresentedBoolKeyStr is ',RepresentedBoolKeyStr) print('hasattr(_Class,"RepresentedBoolKeyStr") is ',hasattr(_Class,RepresentedBoolKeyStr )) print('') ''' #Check if hasattr(_Class,RepresentedBoolKeyStr )==False or getattr(_Class,RepresentedBoolKeyStr)==False: #Look for specific Dict _Class.RepresentedSpecificKeyStrsList=[] #Definition the RepresentedSourceStr RepresentedSourceStr=_Class.SourceStr #debug ''' print('Representer l.367 : RepresentedSourceStr is ',RepresentedSourceStr) print('') ''' #Check that there is a '<DefineSpecificDo>' part _Class.RepresentedSpecificKeyStrsList=_Class.DoSpecificKeyStrsList if len(_Class.RepresentedSpecificKeyStrsList)>0: _Class.RepresentedNotGettingStrsList=map( lambda _KeyStr: _KeyStr.split('=')[0], SYS._filter( lambda __ExpressionStr: "<NotRepresented>" in __ExpressionStr and "=" in __ExpressionStr and __ExpressionStr[0] not in ['\n'], _Class.SpecificDoStr.split('self.') ) ) else: _Class.RepresentedNotGettingStrsList=[] ''' elif self.NameStr=='Representer': _Class.RepresentedSpecificKeyStrsList=[ 'RepresentedNotGettingVariablesList', 'RepresentingKeyVariablesList', 'RepresentedTuplesList' ] _Class.RepresentedNotGettingStrsList=[ 'RepresentedNotGettingVariablesList', 'RepresentingKeyVariablesList', 'RepresentedTuplesList' ] ''' #Get the BasedKeyStrsList _Class.RepresentedBasedKeyStrsList=list(SYS.collect( _Class, '__bases__', 'RepresentedSpecificKeyStrsList' )) #debug ''' print( _Class.__name__, #Class.__mro__, #Class.RepresentedNotGettingStrsList, list(_Class.RepresentedBasedKeyStrsList) ) ''' #set in the class setattr(_Class,RepresentedBoolKeyStr,True) #Definition the representing methods def represent(_InstanceVariable,**_KwargVariablesDict): #Refresh the attributes RepresentedTuplesList=_InstanceVariable.__dict__.items() #Remove the class NotRepresented attributes RepresentedTuplesList=filter( lambda _RepresentedTuple: _RepresentedTuple[0] not in _Class.RepresentedNotGettingStrsList, RepresentedTuplesList ) #Remove the instance NotRepresented attributes #RepresentedTuplesList=filter( # lambda _RepresentedTuple: # _RepresentedTuple[0] not in _InstanceVariable.RepresentedNotGettingVariablesList, # RepresentedTuplesList # ) #First keeps only the Specific and New attributes RepresentedTuplesList=map( lambda _RepresentedTuple: ("<Spe>"+_RepresentedTuple[0],_RepresentedTuple[1]), filter( lambda _Tuple: _Tuple[0] in _Class.RepresentedSpecificKeyStrsList, RepresentedTuplesList ) )+map( lambda _NewTuple: ("<New>"+_NewTuple[0],_NewTuple[1]), filter( lambda _Tuple: _Tuple[0] not in _Class.RepresentedBasedKeyStrsList +_Class.RepresentedSpecificKeyStrsList, RepresentedTuplesList ) ) #Add some forced Values with the instance RepresentingKeyVariables #RepresentedTuplesList+=map( # lambda _KeyVariable: # ("<NotSpe>"+str(_KeyVariable),_InstanceVariable[_KeyVariable]), # _InstanceVariable.RepresentingKeyVariablesList # ) #Simplify the numpy variables repr ''' RepresentedTuplesList=map( lambda _RepresentedTuple: _RepresentedTuple if type(_RepresentedTuple[1]) not in [numpy.ndarray] else ( _RepresentedTuple[0], getRepresentedNumpyArray(_RepresentedTuple[1]) ), RepresentedTuplesList ) ''' #return the representedVariable return getRepresentedPointerStrWithVariable(_InstanceVariable )+getRepresentedStrWithVariable( dict(RepresentedTuplesList),**_KwargVariablesDict) #Bound and set in the InspectedOrderedDict _Class.__repr__=represent _Class.InspectedOrderedDict['__repr__']=Inspecter.getInspectedOrderedDictWithFunction( _Class.__repr__) #</DefineClass> #set in the InitiatorClass Initiator.InitiatorClass.RepresentedNotGettingStrsList=['InitiatingUpdateBool'] Initiator.InitiatorClass.RepresentedSpecificKeyStrsList=['InitiatingUpdateBool']
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Herald Core directory :author: Thomas Calmant :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 1.0.1 :status: Alpha .. Copyright 2014 isandlaTech 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. """ # Bundle version import herald.version __version__=herald.version.__version__ # ------------------------------------------------------------------------------ # Herald import herald import herald.beans as beans # Pelix import pelix.ipopo.decorators from pelix.ipopo.decorators import ComponentFactory, Requires, RequiresMap, \ Provides, BindField, UnbindField, Validate, Invalidate, Instantiate from pelix.utilities import is_string import pelix.constants # Standard library import logging import threading # ------------------------------------------------------------------------------ _logger = logging.getLogger(__name__) # ------------------------------------------------------------------------------ @ComponentFactory("herald-directory-factory") @Provides(herald.SERVICE_DIRECTORY) @RequiresMap('_directories', herald.SERVICE_TRANSPORT_DIRECTORY, herald.PROP_ACCESS_ID, False, False, True) @Requires('_listeners', herald.SERVICE_DIRECTORY_LISTENER, True, True) @Requires('_group_listeners', herald.SERVICE_DIRECTORY_GROUP_LISTENER, True, True) @Instantiate("herald-directory") class HeraldDirectory(object): """ Core Directory for Herald """ def __init__(self): """ Sets up the transport """ # Transport-specific directories self._directories = {} # Directory listeners self._listeners = [] # Directory group listeners self._group_listeners = [] # Local bean description self._local = None # UID -> Peer bean self._peers = {} # Name -> Set of Peer UIDs self._names = {} # Group name -> Set of Peers self._groups = {} # Thread safety self.__lock = threading.Lock() def __contains__(self, peer): """ Adds support for the "in" keyword: checks if the given peer is registered in this directory :param peer: A peer UID or object :return: True if the peer is known """ return peer in self._peers or peer in self._peers.values() def __make_local_peer(self, context): """ Prepares a Peer bean with local configuration :param context: Bundle context """ # Get local peer UID, node UID and application ID peer_uid = context.get_property(herald.FWPROP_PEER_UID) \ or context.get_property(pelix.constants.FRAMEWORK_UID) node_uid = context.get_property(herald.FWPROP_NODE_UID) app_id = context.get_property(herald.FWPROP_APPLICATION_ID) \ or herald.DEFAULT_APPLICATION_ID # Find configured groups groups = context.get_property(herald.FWPROP_PEER_GROUPS) if not groups: groups = [] elif is_string(groups): groups = (group.strip() for group in groups.split(',') if group.strip) groups = set(groups) # Add pre-configured group: node UID if node_uid: groups.add(node_uid) # Make the Peer bean peer = beans.Peer(peer_uid, node_uid, app_id, groups, self) # Setup node and name information peer.name = context.get_property(herald.FWPROP_PEER_NAME) peer.node_name = context.get_property(herald.FWPROP_NODE_NAME) return peer @Validate def _validate(self, context): """ Component validated """ # Clean up remaining data (if any) self._peers.clear() self._names.clear() self._groups.clear() # Prepare local peer self._local = self.__make_local_peer(context) for group in self._local.groups: # Create (empty) groups self._groups[group] = set() @Invalidate def _invalidate(self, _): """ Component invalidated """ # Clean all up self._peers.clear() self._names.clear() self._groups.clear() self._local = None @BindField('_directories') def _bind_directory(self, _, svc, svc_ref): """ A transport directory has been bound """ access_id = svc_ref.get_property(herald.PROP_ACCESS_ID) if not access_id: return with self.__lock: for peer in self._peers.values(): try: access = peer.get_access(access_id) except KeyError: # No access of this kind pass else: if isinstance(access, beans.RawAccess): # We need to convert a raw access bean parsed = svc.load_access(access.dump()) peer.set_access(access_id, parsed) @UnbindField('_directories') def _unbind_directory(self, _, svc, svc_ref): """ A transport directory has gone away """ access_id = svc_ref.get_property(herald.PROP_ACCESS_ID) if not access_id: return with self.__lock: for peer in self._peers.values(): try: # Get the current access information access = peer.get_access(access_id) except KeyError: # No access of this kind pass else: # Convert to a RawAccess bean peer.set_access(access_id, beans.RawAccess(access_id, access.dump())) @BindField('_listeners', if_valid=True) def _bind_listener(self, _, svc, svc_ref): """ A directory listener has been bound """ for peer in list(self._peers.values()): svc.peer_registered(peer) @BindField('_group_listeners', if_valid=True) def _bind_group_listener(self, _, svc, svc_ref): """ A directory group listener has been bound """ for group in self._groups: svc.group_set(group) def __notify_group_set(self, group): """ Notify listeners about a new group of peers :param group: Name of the group """ if self._group_listeners: for listener in self._group_listeners[:]: try: # pylint: disable=W0703 listener.group_set(group) except Exception as ex: _logger.exception("Error notifying listener: %s", ex) def __notify_group_unset(self, group): """ Notify listeners about the removal of a group :param group: Name of the group """ if self._group_listeners: for listener in self._group_listeners[:]: try: # pylint: disable=W0703 listener.group_unset(group) except Exception as ex: _logger.exception("Error notifying listener: %s", ex) def __notify_peer_registered(self, peer): """ Notify listeners about a new peer :param peer: Bean of the new peer """ if self._listeners: for listener in self._listeners[:]: try: # pylint: disable=W0703 listener.peer_registered(peer) except Exception as ex: _logger.exception("Error notifying listener: %s", ex) def __notify_peer_unregistered(self, peer): """ Notify listeners about the loss of peer :param peer: Bean of the loss of peer """ if self._listeners: for listener in self._listeners[:]: try: # pylint: disable=W0703 listener.peer_unregistered(peer) except Exception as ex: _logger.exception("Error notifying listener: %s", ex) def __notify_peer_updated(self, peer, access_id, data, previous=None): """ Notifies listeners about the modification of a peer access :param peer: Bean of the modified peer :param access_id: ID of the modified access :param data: New access data (None of unset) :param previous: Previous access data (None for set) """ if self._listeners: for listener in self._listeners[:]: try: # pylint: disable=W0703 listener.peer_updated(peer, access_id, data, previous) except Exception as ex: _logger.exception("Error notifying listener: %s", ex) @property def local_uid(self): """ Returns the local peer UID """ return self._local.uid def get_peer(self, uid): """ Retrieves the peer with the given UID :param uid: The UID of a peer :return: A Peer bean :raise KeyError: Unknown peer """ return self._peers[uid] def get_local_peer(self): """ Returns the description of the local peer :return: The description of the local peer """ return self._local def get_peers(self): """ Returns the list of all known peers :return: A tuple containing all known peers """ return tuple(self._peers.values()) def get_uids_for_name(self, name): """ Returns the UIDs of the peers having the given name :param name: The name used by some peers :return: A set of UIDs :raise KeyError: No peer has this name """ try: return self._names[name].copy() except KeyError: return [self._peers[name].uid] def get_peers_for_name(self, name): """ Returns the Peer beans of the peers having the given name :param name: The name used by some peers :return: A list of Peer beans :raise KeyError: No peer has this name """ try: return [self._peers[uid] for uid in self._names[name]] except KeyError: return [self._peers[name]] def get_peers_for_group(self, group): """ Returns the Peer beans of the peers belonging to the given group :param group: The name of a group :return: A list of Peer beans :raise KeyError: Unknown group """ if group == 'all': # Special group: retrieve all peers return list(self._peers.values()) return self._groups[group].copy() def get_peers_for_node(self, node_uid): """ Returns the Peer beans of the peers associated to the given node UID :param node_uid: The UID of a node :return: A list of Peer beans """ return [peer for peer in self._peers.values() if peer.node_uid == node_uid] def peer_access_set(self, peer, access_id, data): """ A new peer access is available. Called by a Peer bean. :param peer: The modified Peer bean :param access_id: ID of the access :param data: Information of the peer access """ try: # Get the handling directory directory = self._directories[access_id] except KeyError: # No handler for this directory pass else: try: # Notify it directory.peer_access_set(peer, data) except Exception as ex: _logger.exception("Error notifying a transport directory: %s", ex) # Notify listeners only if the peer is already/still registered if peer.uid in self._peers: # Notify directory listeners self.__notify_peer_updated(peer, access_id, data) def peer_access_unset(self, peer, access_id, data): """ A peer access has been removed. Called by a Peer bean. :param peer: The modified Peer bean :param access_id: ID of the removed access :param data: Previous information of the peer access """ try: # Get the handling directory directory = self._directories[access_id] except KeyError: # No handler for this directory pass else: try: # Notify it directory.peer_access_unset(peer, data) except Exception as ex: _logger.exception("Error notifying a transport directory: %s", ex) # Notify directory listeners self.__notify_peer_updated(peer, access_id, None, data) if not peer.has_accesses(): # Peer has no more access, unregister it self.unregister(peer.uid) def dump(self): """ Dumps the content of the local directory in a dictionary :return: A UID -> description dictionary """ return {peer.uid: peer.dump() for peer in self._peers.values()} def load(self, dump): """ Loads the content of a dump :param dump: The result of a call to dump() """ for uid, description in dump.items(): if uid not in self._peers: try: # Do not reload already known peer self.register(description) except ValueError as ex: _logger.warning("Error loading peer dump: %s", ex) def register(self, description): """ Registers a peer :param description: Description of the peer, in the format of dump() :return: The registered Peer bean :raise ValueError: Invalid peer UID """ notification = self.register_delayed(description) notification.notify() return notification.peer def register_delayed(self, description): """ Registers a peer :param description: Description of the peer, in the format of dump() :return: A DelayedNotification bean :raise ValueError: Invalid peer UID """ with self.__lock: uid = description['uid'] if uid == self._local.uid: # Ignore local peer return beans.DelayedNotification(None, None) try: app_id = description['app_id'] except KeyError: app_id = herald.DEFAULT_APPLICATION_ID if app_id != self._local.app_id: # Ignore foreign peers _logger.debug("Refused registration of %s from application %s", uid, app_id) return beans.DelayedNotification(None, None) try: # Check if the peer is known peer = self._peers[uid] peer_update = True except KeyError: # Make a new bean peer_update = False peer = beans.Peer(uid, description['node_uid'], app_id, description['groups'], self) # Setup writable properties for name in ('name', 'node_name'): setattr(peer, name, description[name]) # In any case, parse and store (new/updated) accesses for access_id, data in description['accesses'].items(): try: data = self._directories[access_id].load_access(data) except KeyError: # Access not available for parsing: keep a RawAccess bean data = beans.RawAccess(access_id, data) # Store the parsed data: listeners will be notified IF the peer # was already stored peer.set_access(access_id, data) if not peer_update: # Store the peer after accesses have been set # (avoids to notify about update before registration) self._peers[uid] = peer # Store the peer self._names.setdefault(peer.name, set()).add(peer.uid) # Set up groups new_groups = set() for group in peer.groups: try: # Get the group peers = self._groups[group] except KeyError: # Group must be created: notify about it peers = self._groups[group] = set() new_groups.add(group) peers.add(peer) # Notify about new groups for group in new_groups: self.__notify_group_set(group) return beans.DelayedNotification(peer, self.__notify_peer_registered) else: return beans.DelayedNotification(peer, None) def unregister(self, uid): """ Unregisters a peer from the directory :param uid: UID of the peer :return: The Peer bean if it was known, else None """ with self.__lock: try: # Pop the peer bean peer = self._peers.pop(uid) except KeyError: # Unknown peer return else: # Remove it from other dictionaries try: uids = self._names[peer.name] uids.remove(uid) if not uids: del self._names[peer.name] except KeyError: # Name wasn't registered... pass for group in peer.groups: try: peers = self._groups[group] peers.remove(peer) if not peers: # Remove the group and notify listeners del self._groups[group] self.__notify_group_unset(group) except KeyError: # Peer wasn't in that group pass # Notify listeners self.__notify_peer_unregistered(peer) return peer
from pywin.mfc import dialog import win32api import win32con import win32ui import copy import string from . import scintillacon # Used to indicate that style should use default color from win32con import CLR_INVALID ###################################################### # Property Page for syntax formatting options # The standard 16 color VGA palette should always be possible paletteVGA = ( ("Black", win32api.RGB(0,0,0)), ("Navy", win32api.RGB(0,0,128)), ("Green", win32api.RGB(0,128,0)), ("Cyan", win32api.RGB(0,128,128)), ("Maroon", win32api.RGB(128,0,0)), ("Purple", win32api.RGB(128,0,128)), ("Olive", win32api.RGB(128,128,0)), ("Gray", win32api.RGB(128,128,128)), ("Silver", win32api.RGB(192,192,192)), ("Blue", win32api.RGB(0,0,255)), ("Lime", win32api.RGB(0,255,0)), ("Aqua", win32api.RGB(0,255,255)), ("Red", win32api.RGB(255,0,0)), ("Fuchsia", win32api.RGB(255,0,255)), ("Yellow", win32api.RGB(255,255,0)), ("White", win32api.RGB(255,255,255)), # and a few others will generally be possible. ("DarkGrey", win32api.RGB(64,64,64)), ("PurpleBlue", win32api.RGB(64,64,192)), ("DarkGreen", win32api.RGB(0,96,0)), ("DarkOlive", win32api.RGB(128,128,64)), ("MediumBlue", win32api.RGB(0,0,192)), ("DarkNavy", win32api.RGB(0,0,96)), ("Magenta", win32api.RGB(96,0,96)), ("OffWhite", win32api.RGB(255,255,220)), ("LightPurple", win32api.RGB(220,220,255)), ("<Default>", win32con.CLR_INVALID) ) class ScintillaFormatPropertyPage(dialog.PropertyPage): def __init__(self, scintillaClass = None, caption = 0): self.scintillaClass = scintillaClass dialog.PropertyPage.__init__(self, win32ui.IDD_PP_FORMAT, caption=caption) def OnInitDialog(self): try: if self.scintillaClass is None: from . import control sc = control.CScintillaEdit else: sc = self.scintillaClass self.scintilla = sc() style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.ES_MULTILINE # Convert the rect size rect = self.MapDialogRect( (5, 5, 120, 75)) self.scintilla.CreateWindow(style, rect, self, 111) self.HookNotify(self.OnBraceMatch, scintillacon.SCN_CHECKBRACE) self.scintilla.HookKeyStroke(self.OnEsc, 27) self.scintilla.SCISetViewWS(1) self.pos_bstart = self.pos_bend = self.pos_bbad = 0 colorizer = self.scintilla._GetColorizer() text = colorizer.GetSampleText() items = text.split('|', 2) pos = len(items[0]) self.scintilla.SCIAddText(''.join(items)) self.scintilla.SetSel(pos, pos) self.scintilla.ApplyFormattingStyles() self.styles = self.scintilla._GetColorizer().styles self.cbo = self.GetDlgItem(win32ui.IDC_COMBO1) for c in paletteVGA: self.cbo.AddString(c[0]) self.cboBoldItalic = self.GetDlgItem(win32ui.IDC_COMBO2) for item in ["Bold Italic", "Bold", "Italic", "Regular"]: self.cboBoldItalic.InsertString(0, item) self.butIsDefault = self.GetDlgItem(win32ui.IDC_CHECK1) self.butIsDefaultBackground = self.GetDlgItem(win32ui.IDC_CHECK2) self.listbox = self.GetDlgItem(win32ui.IDC_LIST1) self.HookCommand(self.OnListCommand, win32ui.IDC_LIST1) names = list(self.styles.keys()) names.sort() for name in names: if self.styles[name].aliased is None: self.listbox.AddString(name) self.listbox.SetCurSel(0) idc = win32ui.IDC_RADIO1 if not self.scintilla._GetColorizer().bUseFixed: idc = win32ui.IDC_RADIO2 self.GetDlgItem(idc).SetCheck(1) self.UpdateUIForStyle(self.styles[names[0]]) self.scintilla.HookFormatter(self) self.HookCommand(self.OnButDefaultFixedFont, win32ui.IDC_BUTTON1) self.HookCommand(self.OnButDefaultPropFont, win32ui.IDC_BUTTON2) self.HookCommand(self.OnButThisFont, win32ui.IDC_BUTTON3) self.HookCommand(self.OnButUseDefaultFont, win32ui.IDC_CHECK1) self.HookCommand(self.OnButThisBackground, win32ui.IDC_BUTTON4) self.HookCommand(self.OnButUseDefaultBackground, win32ui.IDC_CHECK2) self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO1) self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO2) self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO1) self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO2) except: import traceback traceback.print_exc() def OnEsc(self, ch): self.GetParent().EndDialog(win32con.IDCANCEL) def OnBraceMatch(self, std, extra): import pywin.scintilla.view pywin.scintilla.view.DoBraceMatch(self.scintilla) def GetSelectedStyle(self): return self.styles[self.listbox.GetText(self.listbox.GetCurSel())] def _DoButDefaultFont(self, extra_flags, attr): baseFormat = getattr(self.scintilla._GetColorizer(), attr) flags = extra_flags | win32con.CF_SCREENFONTS | win32con.CF_EFFECTS | win32con.CF_FORCEFONTEXIST d=win32ui.CreateFontDialog(baseFormat, flags, None, self) if d.DoModal()==win32con.IDOK: setattr(self.scintilla._GetColorizer(), attr, d.GetCharFormat()) self.OnStyleUIChanged(0, win32con.BN_CLICKED) def OnButDefaultFixedFont(self, id, code): if code==win32con.BN_CLICKED: self._DoButDefaultFont(win32con.CF_FIXEDPITCHONLY, "baseFormatFixed") return 1 def OnButDefaultPropFont(self, id, code): if code==win32con.BN_CLICKED: self._DoButDefaultFont(win32con.CF_SCALABLEONLY, "baseFormatProp") return 1 def OnButFixedOrDefault(self, id, code): if code==win32con.BN_CLICKED: bUseFixed = id == win32ui.IDC_RADIO1 self.GetDlgItem(win32ui.IDC_RADIO1).GetCheck() != 0 self.scintilla._GetColorizer().bUseFixed = bUseFixed self.scintilla.ApplyFormattingStyles(0) return 1 def OnButThisFont(self, id, code): if code==win32con.BN_CLICKED: flags = win32con.CF_SCREENFONTS | win32con.CF_EFFECTS | win32con.CF_FORCEFONTEXIST style = self.GetSelectedStyle() # If the selected style is based on the default, we need to apply # the default to it. def_format = self.scintilla._GetColorizer().GetDefaultFormat() format = style.GetCompleteFormat(def_format) d=win32ui.CreateFontDialog(format, flags, None, self) if d.DoModal()==win32con.IDOK: style.format = d.GetCharFormat() self.scintilla.ApplyFormattingStyles(0) return 1 def OnButUseDefaultFont(self, id, code): if code == win32con.BN_CLICKED: isDef = self.butIsDefault.GetCheck() self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not isDef) if isDef: # Being reset to the default font. style = self.GetSelectedStyle() style.ForceAgainstDefault() self.UpdateUIForStyle(style) self.scintilla.ApplyFormattingStyles(0) else: # User wants to override default - # do nothing! pass def OnButThisBackground(self, id, code): if code==win32con.BN_CLICKED: style = self.GetSelectedStyle() bg = win32api.RGB(0xff, 0xff, 0xff) if style.background != CLR_INVALID: bg = style.background d=win32ui.CreateColorDialog(bg, 0, self) if d.DoModal()==win32con.IDOK: style.background = d.GetColor() self.scintilla.ApplyFormattingStyles(0) return 1 def OnButUseDefaultBackground(self, id, code): if code == win32con.BN_CLICKED: isDef = self.butIsDefaultBackground.GetCheck() self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(not isDef) if isDef: # Being reset to the default color style = self.GetSelectedStyle() style.background = style.default_background self.UpdateUIForStyle(style) self.scintilla.ApplyFormattingStyles(0) else: # User wants to override default - # do nothing! pass def OnListCommand(self, id, code): if code==win32con.LBN_SELCHANGE: style = self.GetSelectedStyle() self.UpdateUIForStyle(style) return 1 def UpdateUIForStyle(self, style ): format = style.format sel = 0 for c in paletteVGA: if format[4] == c[1]: # print "Style", style.name, "is", c[0] break sel = sel + 1 else: sel = -1 self.cbo.SetCurSel(sel) self.butIsDefault.SetCheck(style.IsBasedOnDefault()) self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not style.IsBasedOnDefault()) self.butIsDefaultBackground.SetCheck(style.background == style.default_background) self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(style.background != style.default_background) bold = format[1] & win32con.CFE_BOLD != 0; italic = format[1] & win32con.CFE_ITALIC != 0 self.cboBoldItalic.SetCurSel( bold*2 + italic ) def OnStyleUIChanged(self, id, code): if code in [win32con.BN_CLICKED, win32con.CBN_SELCHANGE]: style = self.GetSelectedStyle() self.ApplyUIFormatToStyle(style) self.scintilla.ApplyFormattingStyles(0) return 0 return 1 def ApplyUIFormatToStyle(self, style): format = style.format color = paletteVGA[self.cbo.GetCurSel()] effect = 0 sel = self.cboBoldItalic.GetCurSel() if sel==0: effect = 0 elif sel==1: effect = win32con.CFE_ITALIC elif sel==2: effect = win32con.CFE_BOLD else: effect = win32con.CFE_BOLD | win32con.CFE_ITALIC maskFlags=format[0]|win32con.CFM_COLOR|win32con.CFM_BOLD|win32con.CFM_ITALIC style.format = (maskFlags, effect, style.format[2], style.format[3], color[1]) + style.format[5:] def OnOK(self): self.scintilla._GetColorizer().SavePreferences() return 1 def test(): page = ColorEditorPropertyPage() sheet = pywin.mfc.dialog.PropertySheet("Test") sheet.AddPage(page) sheet.CreateWindow()
import logging import operator import os import re import time from functools import reduce from math import hypot from multiprocessing.pool import ThreadPool from statistics import mean, StatisticsError from xml.etree import ElementTree import docker import numpy from django.conf import settings from django.db import models from django.db.models.aggregates import Sum from django.db.models.functions.base import Coalesce from django.db.models.query_utils import Q from django.db.models.signals import post_delete, pre_delete, post_save from django.dispatch.dispatcher import receiver from humanfriendly import parse_size from pricescheduler.application.scripts.compose import get_project_yml from pricescheduler.application.scripts.composewrapper import ps_, get_project, compose_up, compose_down from pricescheduler.application.scripts.git import git_clone from pricescheduler.application.utils.docker_stats import calculate_cpu_percent, get_folder_size from pricescheduler.instance.models import InstanceOffer, Instance from pricescheduler.instance.scripts.machine import DEFAULT_MACHINE logger = logging.getLogger(__name__) class Application(models.Model): name = models.CharField(max_length=80, unique=True, help_text="Name of the Application to evluate.") url = models.CharField(max_length=80, help_text="URL to the GIT-Repository that consists of the docker-compose.yaml and\ necessary source code files.") repo_path = models.CharField(max_length=240) testcase_min = models.FileField(upload_to='testcases/', verbose_name='Testcase for estimating ressource requirement.', help_text="Taurus YAML-Testcase File which performs a simulation on the \ application's endpoints to estimate the ressource requirement. Use localhost or \ 127.0.0.1 as endpoint address!") testcase_max = models.FileField(upload_to='testcases/', verbose_name='Testcase for estimating scaling behaviour.', help_text="Taurus YAML-Testcase File which performs a high-load simulation on the \ application's endpoints to estimate the scaling behavior of the application. \ Only adapt the number of virtual users!") user_scale = models.IntegerField(verbose_name="Multiplier of virtual users that has been used to \ define scaling testcase") def __str__(self): return '{0}: {1}'.format(self.name, self.url) def save(self, *args, **kwargs): if not self.pk: # This code is only processed if the objects is # not in the database yet. Otherwise it would # have pk pass # Clone Git Repo self.repo_path = git_clone(self.url, self.name) super(Application, self).save(*args, **kwargs) @receiver(pre_delete) def remove(sender, instance, **kwargs): if sender == Application: pass # compose_remove(instance.repo_path) @receiver(post_delete) def delete_repo(sender, instance, **kwargs): if sender == Application: # Clean Up Repository Path import shutil try: shutil.rmtree(instance.repo_path) except PermissionError: logging.error("Couldn't clean all files of git repo.") def get_compoes_yaml(self): return get_project_yml(self.repo_path) @receiver(post_save) def evaluate(sender, instance, **kwargs): if isinstance(instance, Application): (res, created) = Benchmark.objects.get_or_create(application=instance, offer=None) res.start_benchmarks() res.save() return True def deploy(self, offer, user): if user.aws_access_key == '' or user.aws_secret_key == '': raise ValueError('No AWS Keys have been entered!') (instance, created) = Instance.objects.get_or_create(name=self.name + '-instance', app=self, offer=offer, user=user) (bench, created) = Benchmark.objects.get_or_create(application=self, offer=offer) bench._start_min_benchmark(instance.name) bench.save() return created def find_possible_offers(self): benchmark = self.benchmark_set.get(offer=None) qs = InstanceOffer.objects.annotate(total_memory=Sum('memory__capacity'), total_storage=Coalesce(Sum('flashdisk__capacity'), 0) + Coalesce(Sum('harddisk__capacity'), 0)) \ .filter(total_memory__gte=benchmark.ram_min, vcpu__gte=benchmark.cpu_min) \ .filter(reduce(operator.or_, (Q(instance_name__contains=x) for x in ['t2', 'm4', 'm3', 'c3', 'c4', 'r3', 'r4', 'GP-', 'CO I-', 'MO-']))) # calculate projections benchmark_line = numpy.poly1d(numpy.polyfit([benchmark.cpu_min, benchmark.cpu_max], [benchmark.ram_min, benchmark.ram_max], 1)) distance_benchmarks = hypot(benchmark.cpu_max - benchmark.cpu_min, benchmark.ram_max - benchmark.ram_min) for offer in qs: if offer.total_memory < benchmark_line(offer.vcpu): projected_vcpu = (benchmark_line - offer.total_memory).roots dist = hypot(benchmark.cpu_min - projected_vcpu, benchmark.ram_min - offer.total_memory) else: projected_memory = benchmark_line(offer.vcpu) dist = hypot(benchmark.cpu_min - offer.vcpu, benchmark.ram_min - projected_memory) offer.performance = 1 + dist / distance_benchmarks * benchmark.application.user_scale offer.total_price = offer.get_total_price(benchmark.storage_min) offer.price_perf_value = offer.total_price / offer.performance # qs = filter(lambda r: r.performance < 4, qs) qs = sorted(qs, key=lambda r: r.price_perf_value) # create_offer_scatter(qs, qs.first(), benchmark) # create_offer_scatter2(qs, qs.first(), benchmark) return qs class Benchmark(models.Model): application = models.ForeignKey(Application) offer = models.ForeignKey(InstanceOffer, blank=True, null=True, help_text="Offer on which this benchmark has been performed.") ram_min = models.BigIntegerField(default=None, null=True, help_text="Measured average of RAM (GB) consumption while performing min_testcase.") ram_max = models.BigIntegerField(default=None, null=True, help_text="Measured average of RAM (GB) consumption while performing max_testcase.") cpu_min = models.FloatField(default=None, null=True, help_text="Measured average of used Cores while performing min_testcase.") cpu_max = models.FloatField(default=None, null=True, help_text="Measured average of used Cores while performing max_testcase.") storage_min = models.BigIntegerField(default=None, null=True, help_text="Measured storage requirement when performing min_testcase.") storage_max = models.BigIntegerField(default=None, null=True, help_text="Measured storage requirement when performing max_testcase.") responsetime = models.FloatField(default=None, null=True, help_text="Measured average response time of webserver.") class Meta: unique_together = ('application', 'offer',) @classmethod def get_stats(cls, container): stat = container.stats(decode=True, stream=False) try: cpu = calculate_cpu_percent(stat) mem = stat["memory_stats"]["usage"] except KeyError: return (container.name, None) return (container.name, (cpu, mem)) def __setup_local_environ(self): os.unsetenv('DOCKER_HOST') os.unsetenv('DOCKER_CERT_PATH') os.unsetenv('DOCKER_TLS_VERIFY') d = docker.from_env() return d def __setup_remote_environ(self, machineName): d = docker.DockerClient(**DEFAULT_MACHINE.config(machine=machineName)) config = DEFAULT_MACHINE.config(machineName) ip = DEFAULT_MACHINE.ip(machine=machineName) os.environ['DOCKER_HOST'] = config['base_url'] os.environ['DOCKER_CERT_PATH'] = os.path.dirname(config['tls'].ca_cert) os.environ['DOCKER_TLS_VERIFY'] = str(config['tls'].verify) if d.ping(): logging.info('Docker API is reachable.') logging.debug('Docker version is: %s' % d.version()) else: logging.error( 'Docker API is unreachable, please check the state of your instance. Docker must be installed!') raise ConnectionError return (d, ip) def __get_hostname_mapping(self, remoteInstance): # set mapping from docker_domain_hostname to the remote ip of app_machine with open(os.path.join(settings.MEDIA_ROOT, self.application.testcase.name)) as f: pattern = re.compile(r'(?:https?://)(www\.)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*') for line in f: result = re.search(pattern, line) if result is not None: hostname = result.groupdict().get('host') return {hostname: Benchmark.m.ip(machine=remoteInstance)} logging.error('Could not set internal hostname to remote ip') return {} def __start_monitoring(self, taurus, remote_docker): stats = dict() for container in ps_(self.project): c = remote_docker.containers.get(container['id']) stats[c.name] = dict(cpu=[], mem=[], storage=[]) pool = ThreadPool(processes=len(stats)) while taurus.status != 'exited': taurus.reload() results = [pool.apply_async(Benchmark.get_stats, (remote_docker.containers.get(c['id']),)) for c in ps_(self.project)] for r in results: name, stat = r.get() if stat: stats[name]['cpu'].append(stat[0]) stats[name]['mem'].append(stat[1]) for container in ps_(self.project): c = remote_docker.containers.get(container['id']) image_size = c.image.attrs['Size'] volume_size = 0 if hasattr(c, 'volumes'): for volume in c.volumes.values(): dir = volume['source'] try: volume_size += get_folder_size(dir) except PermissionError: logging.error("Couldn't calculate size of dir {}".format(dir)) stats[c.name]['storage'] = image_size + volume_size return stats def __start_benchmark(self, testcase, remoteInstance): self.local_docker = self.__setup_local_environ() self.project = get_project(self.application.repo_path) if remoteInstance: (remote_docker, ip) = self.__setup_remote_environ(remoteInstance) extra_hosts = {'localhost': ip} else: # If this is a local evaluation, just set remote vars to corresponding local vars remote_docker = self.local_docker network = '{project_name}_default'.format(project_name=self.project.name) extra_hosts = {} self.local_docker.images.pull('undera/taurus:1.9.4') compose_up(self.application.repo_path) taurus = self.local_docker.containers.run('undera/taurus:1.9.4', network_mode='host', volumes={ os.path.join(settings.MEDIA_ROOT, os.path.dirname( testcase.name)): '/bzt-configs'}, working_dir='/bzt-configs', extra_hosts=extra_hosts, command=os.path.basename(testcase.name), detach=True) (cpu_usage, mem_usage, storage_usage, avg_rt) = (0, 0, 0, 0) if not remoteInstance: stats = self.__start_monitoring(taurus, remote_docker) for c in stats: try: cpu_usage += mean(stats[c]['cpu']) mem_usage += mean(stats[c]['mem']) storage_usage += stats[c]['storage'] except StatisticsError: logging.error('No Datapoint for Container %s provided.' % c) else: while taurus.status != 'exited': taurus.reload() time.sleep(2) # Evaluation has ended # Parse Taurus Results and print them tree = ElementTree.parse( os.path.join(settings.MEDIA_ROOT, os.path.dirname(testcase.name), 'result.xml')) root = tree.getroot() for group in root: if group.tag == 'Group': print('GROUP: {}'.format('SUMMARY')) if group.attrib['label'] == '' else print('GROUP: {}'.format( group.attrib['label'])) for stat in group: # average response time of all endpoints if stat.tag == 'avg_rt' and group.attrib['label'] == '': avg_rt = float(stat.attrib.get('value', 0)) taurus.remove(force=True) compose_down(self.application.repo_path) return (cpu_usage / 100.0, mem_usage, storage_usage, avg_rt) def _start_min_benchmark(self, remoteInstance=None): (self.cpu_min, self.ram_min, self.storage_min, self.responsetime) = self.__start_benchmark( self.application.testcase_min, remoteInstance) def _start_max_benchmark(self, remoteInstance=None): (self.cpu_max, self.ram_max, self.storage_max, responsetime) = self.__start_benchmark( self.application.testcase_max, remoteInstance) def start_benchmarks(self): self._start_min_benchmark() self._start_max_benchmark() # Adaption of Memory to include cent_OS Ram Consumption and safety factor of 50% [self.ram_min, self.ram_max] = [x + parse_size('103.07 MiB') * 1.5 for x in (self.ram_min, self.ram_max)]
# 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. # ============================================================================== """Tests for training.input.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import itertools import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class MatchFilenamesOnceTest(tf.test.TestCase): def test(self): temp_dir = self.get_temp_dir() filenames = [os.path.join(temp_dir, n) for n in os.listdir(temp_dir)] additional = [os.path.join(self.get_temp_dir(), "match_filenames.%d" % i) for i in range(3)] for name in additional: open(name, "w").write("Some contents") filenames = list(set(filenames + additional)) with self.test_session(): star = tf.train.match_filenames_once( os.path.join(self.get_temp_dir(), "*")) question = tf.train.match_filenames_once( os.path.join(self.get_temp_dir(), "match_filenames.?")) one = tf.train.match_filenames_once(additional[1]) tf.initialize_all_variables().run() self.assertItemsEqual(map(tf.compat.as_bytes, filenames), star.eval()) self.assertItemsEqual(map(tf.compat.as_bytes, additional), question.eval()) self.assertItemsEqual([tf.compat.as_bytes(additional[1])], one.eval()) class LimitEpochsTest(tf.test.TestCase): def testNoLimit(self): with self.test_session(): seven = tf.constant(7) seven_forever = tf.train.limit_epochs(seven) tf.initialize_all_variables().run() for i in range(100): self.assertEqual(7, seven_forever.eval()) def testLimit(self): with self.test_session(): love_me = tf.constant("Love Me") love_me_two_times = tf.train.limit_epochs(love_me, num_epochs=2) tf.initialize_all_variables().run() self.assertEqual(b"Love Me", love_me_two_times.eval()) self.assertEqual(b"Love Me", love_me_two_times.eval()) with self.assertRaises(tf.errors.OutOfRangeError): love_me_two_times.eval() class StringInputProducerTest(tf.test.TestCase): def testNoShuffle(self): with self.test_session(): strings = [b"to", b"be", b"or", b"not", b"to", b"be"] num_epochs = 3 queue = tf.train.string_input_producer( strings, num_epochs=num_epochs, shuffle=False) dequeue_many = queue.dequeue_many(len(strings) * num_epochs) dequeue = queue.dequeue() tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # No randomness, so just see repeated copies of the input. output = dequeue_many.eval() self.assertAllEqual(strings * num_epochs, output) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() for thread in threads: thread.join() def testShuffle(self): with self.test_session(): strings = [b"a", b"b", b"c"] num_epochs = 600 queue = tf.train.string_input_producer( strings, num_epochs=num_epochs, shuffle=True, seed=271828) dequeue_many = queue.dequeue_many(len(strings)) dequeue = queue.dequeue() tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # Validate that we only shuffle the strings within an epoch and # count how often each possible order appears. expected = [b"abc", b"acb", b"bac", b"bca", b"cab", b"cba"] frequency = {} for e in expected: frequency[e] = 0 for _ in range(num_epochs): output = dequeue_many.eval() key = b"".join(output) self.assertIn(key, expected) frequency[key] += 1 # Expect an approximately even distribution over all possible orders. expected_frequency = num_epochs / len(expected) margin = expected_frequency * 0.4 tf.logging.info("Observed counts: %s", frequency) for key in expected: value = frequency[key] self.assertGreater(value, expected_frequency - margin) self.assertLess(value, expected_frequency + margin) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() for thread in threads: thread.join() def testNullStringPython(self): # Graph-construction time check for empty string list: with self.test_session(): with self.assertRaises(ValueError): _ = tf.train.string_input_producer([]) def testNullString(self): # Runtime check for empty string list. This is slightly oblique: # The queue runner should die with an assertion error on the null # input tensor, causing the dequeue to fail with an OutOfRangeError. with self.test_session(): coord = tf.train.Coordinator() queue = tf.train.string_input_producer(tf.constant([], dtype=tf.string)) dequeue = queue.dequeue() tf.initialize_all_variables().run() threads = tf.train.start_queue_runners(coord=coord) with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() coord.request_stop() for thread in threads: thread.join() def testSharedName(self): with self.test_session(): strings = [b"to", b"be", b"or", b"not", b"to", b"be"] queue = tf.train.string_input_producer( strings, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", queue.queue_ref.op.node_def.attr["shared_name"]) class RangeInputProducerTest(tf.test.TestCase): def testNoShuffle(self): with self.test_session(): num_epochs = 3 range_size = 5 queue = tf.train.range_input_producer( range_size, num_epochs=num_epochs, shuffle=False) dequeue_many = queue.dequeue_many(range_size * num_epochs) dequeue = queue.dequeue() tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # No randomness, so just see repeated copies of the input. output = dequeue_many.eval() self.assertAllEqual(list(xrange(range_size)) * num_epochs, output) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() for thread in threads: thread.join() def testShuffle(self): with self.test_session(): num_epochs = 200 range_size = 2 queue = tf.train.range_input_producer( range_size, num_epochs=num_epochs, shuffle=True, seed=314159) dequeue_many = queue.dequeue_many(range_size) dequeue = queue.dequeue() tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # Validate that we only shuffle the integers within an epoch and # count how often each possible order appears. expected = [12, 21] frequency = {} for e in expected: frequency[e] = 0 for _ in range(num_epochs): output = dequeue_many.eval() key = 10 * (output[0] + 1) + (output[1] + 1) self.assertIn(key, expected) frequency[key] += 1 # Expect an approximately even distribution over all possible orders. expected_frequency = num_epochs / len(expected) margin = expected_frequency * 0.4 tf.logging.info("Observed counts: %s", frequency) for key in expected: value = frequency[key] self.assertGreater(value, expected_frequency - margin) self.assertLess(value, expected_frequency + margin) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): dequeue.eval() for thread in threads: thread.join() def testSharedName(self): with self.test_session(): range_size = 5 queue = tf.train.range_input_producer( range_size, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", queue.queue_ref.op.node_def.attr["shared_name"]) class SliceInputProducerTest(tf.test.TestCase): def testNoShuffle(self): with self.test_session() as sess: num_epochs = 3 source_strings = [b"Alpha", b"Beta", b"Delta", b"Gamma"] source_ints = [2, 3, 5, 7] slices = tf.train.slice_input_producer( [source_strings, source_ints], num_epochs=num_epochs, shuffle=False) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # No randomness, so just see repeated copies of the input. num_items = len(source_strings) * num_epochs output = [sess.run(slices) for _ in range(num_items)] out_strings, out_ints = zip(*output) self.assertAllEqual(source_strings * num_epochs, out_strings) self.assertAllEqual(source_ints * num_epochs, out_ints) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(slices) for thread in threads: thread.join() def testShuffle(self): with self.test_session() as sess: num_epochs = 1200 source_strings = ["A", "B", "D", "G"] source_ints = [7, 3, 5, 2] slices = tf.train.slice_input_producer( [source_strings, source_ints], num_epochs=num_epochs, shuffle=True, seed=161803) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # Validate that we only shuffle the integers within an epoch and # count how often each possible order appears. expected = [b",".join(x) for x in itertools.permutations([b"A7", b"B3", b"D5", b"G2"])] frequency = {} for e in expected: frequency[e] = 0 for _ in range(num_epochs): output = [sess.run(slices) for _ in range(len(source_strings))] key = b",".join([s + tf.compat.as_bytes(str(i)) for s, i in output]) self.assertIn(key, expected) frequency[key] += 1 # Expect an approximately even distribution over all possible orders. expected_frequency = num_epochs / len(expected) margin = expected_frequency * 0.4 tf.logging.info("Observed counts: %s", frequency) for key in expected: value = frequency[key] self.assertGreater(value, expected_frequency - margin) self.assertLess(value, expected_frequency + margin) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(slices) for thread in threads: thread.join() def testSharedName(self): with self.test_session(): source_strings = ["A", "B", "D", "G"] source_ints = [7, 3, 5, 2] slices = tf.train.slice_input_producer( [source_strings, source_ints], shared_name="SHARED_NAME_XYZ", name="sip") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", slices[0].op.inputs[1].op.inputs[0].op.node_def.attr["shared_name"]) class BatchTest(tf.test.TestCase): def testOneThread(self): with self.test_session() as sess: batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) sparse_counter = tf.SparseTensor( indices=tf.reshape(tf.pack([zero64, zero64 + 1]), [2, 1]), values=tf.cast(tf.pack([counter, -counter]), tf.float32), shape=[2]) batched = tf.train.batch( [counter, sparse_counter, "string"], batch_size=batch_size) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() for i in range(num_batches): results = sess.run(batched) self.assertAllEqual(results[0], np.arange(i * batch_size, (i + 1) * batch_size)) self.assertAllEqual( results[1].indices, np.vstack((np.arange(2 * batch_size) // 2, # 0, 0, 1, 1, ... [0, 1] * batch_size)).T) # [x, -x, x+1, -(x+1), ...] expected = np.arange(2 * i * batch_size, 2 * (i + 1) * batch_size) // 2 expected *= ([1, -1] * batch_size) # mult by [1, -1, 1, -1, ...] self.assertAllEqual(results[1].values, expected) self.assertAllEqual(results[1].shape, [batch_size, 2]) self.assertAllEqual(results[2], [b"string"] * batch_size) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testOneThreadEnqueueMany(self): with self.test_session() as sess: batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) pre_batched = tf.train.batch( [counter, sparse_counter, "string"], batch_size=2) batched = tf.train.batch(pre_batched, enqueue_many=True, batch_size=batch_size) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() for i in range(num_batches): results = sess.run(batched) self.assertAllEqual(results[0], np.arange(i * batch_size, (i + 1) * batch_size)) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual( results[1].values, np.arange(i * batch_size, (i + 1) * batch_size)) self.assertAllEqual(results[1].shape, [batch_size, 1]) self.assertAllEqual(results[2], [b"string"] * batch_size) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testManyThreads(self): with self.test_session() as sess: batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) batched = tf.train.batch( [counter, sparse_counter, "string"], batch_size=batch_size, num_threads=4) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() all_counts = [] for i in range(num_batches): results = sess.run(batched) tf.logging.info("Batch %d: %s", i, results[0]) self.assertEqual(len(results[0]), batch_size) self.assertAllEqual(results[0], results[1].values) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual(results[1].shape, [batch_size, 1]) all_counts.extend(results[0]) self.assertAllEqual(results[2], [b"string"] * batch_size) self.assertItemsEqual(all_counts, range(num_batches * batch_size)) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testSharedName(self): with self.test_session(): batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) batched = tf.train.batch( [counter, "string"], batch_size=batch_size, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", batched[0].op.inputs[0].op.node_def.attr["shared_name"]) class BatchJoinTest(tf.test.TestCase): def testTwoThreads(self): with self.test_session() as sess: # Two threads, the first generates (0..69, "a"). num_a = 70 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_a) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) # The second generates (99, "b") 90 times and then stops. num_b = 90 ninety_nine = tf.train.limit_epochs( tf.constant(99, dtype=tf.int64), num_b) sparse_ninety_nine = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(ninety_nine, tf.float32)]), shape=[1]) # These get joined together and grouped into batches of 5. batch_size = 5 batched = tf.train.batch_join( [[counter, sparse_counter, "a"], [ninety_nine, sparse_ninety_nine, "b"]], batch_size=batch_size) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # Should see the "a" and "b" threads mixed together. all_a = [] seen_b = 0 saw_both = 0 num_batches = (num_a + num_b) // batch_size for i in range(num_batches): results = sess.run(batched) tf.logging.info("Batch %d: %s", i, results[0]) self.assertEqual(len(results[0]), batch_size) self.assertEqual(len(results[2]), batch_size) self.assertAllEqual(results[0], results[1].values) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual(results[1].shape, [batch_size, 1]) which_a = [i for i, s in enumerate(results[2]) if s == b"a"] which_b = [i for i, s in enumerate(results[2]) if s == b"b"] self.assertEqual(len(which_a) + len(which_b), batch_size) if len(which_a) > 0 and len(which_b) > 0: saw_both += 1 all_a.extend([results[0][i] for i in which_a]) seen_b += len(which_b) self.assertAllEqual([99] * len(which_b), [results[0][i] for i in which_b]) # Some minimum level of mixing of the results of both threads. self.assertGreater(saw_both, 1) # Verify the order of results from "a" were preserved. self.assertAllEqual(all_a, np.arange(num_a)) self.assertEqual(seen_b, num_b) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testSharedName(self): with self.test_session(): batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) batched = tf.train.batch_join( [[counter, "string"]], batch_size=batch_size, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", batched[0].op.inputs[0].op.node_def.attr["shared_name"]) class ShuffleBatchTest(tf.test.TestCase): def testOneThread(self): with self.test_session() as sess: batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) batched = tf.train.shuffle_batch( [counter, sparse_counter, "string"], batch_size=batch_size, capacity=32, min_after_dequeue=16, seed=141421) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() all_counts = [] for i in range(num_batches): results = sess.run(batched) self.assertEqual(len(results[0]), batch_size) all_counts.extend(results[0]) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual(results[0], results[1].values) self.assertAllEqual(results[1].shape, [batch_size, 1]) self.assertAllEqual(results[2], [b"string"] * batch_size) # Results scrambled, but include all the expected numbers. deltas = [all_counts[i + 1] - all_counts[i] for i in range(len(all_counts) - 1)] self.assertFalse(all(d == deltas[0] for d in deltas)) self.assertItemsEqual(all_counts, range(num_batches * batch_size)) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testManyThreads(self): with self.test_session() as sess: batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) batched = tf.train.shuffle_batch( [counter, sparse_counter, "string"], batch_size=batch_size, capacity=32, min_after_dequeue=16, seed=173205, num_threads=4) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() all_counts = [] for i in range(num_batches): results = sess.run(batched) tf.logging.info("Batch %d: %s", i, results[0]) self.assertEqual(len(results[0]), batch_size) all_counts.extend(results[0]) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual(results[0], results[1].values) self.assertAllEqual(results[1].shape, [batch_size, 1]) self.assertAllEqual(results[2], [b"string"] * batch_size) # Results scrambled, but include all the expected numbers. deltas = [all_counts[i + 1] - all_counts[i] for i in range(len(all_counts) - 1)] self.assertFalse(all(d == deltas[0] for d in deltas)) self.assertItemsEqual(all_counts, range(num_batches * batch_size)) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testSharedName(self): with self.test_session(): batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) batched = tf.train.shuffle_batch( [counter, "string"], batch_size=batch_size, capacity=32, min_after_dequeue=10, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", batched[0].op.inputs[0].op.node_def.attr["shared_name"]) class ShuffleBatchJoinTest(tf.test.TestCase): def testTwoThreads(self): with self.test_session() as sess: # Two threads, the first generates (0..24, "a"). num_a = 25 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_a) sparse_counter = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(counter, tf.float32)]), shape=[1]) # The second generates (99, "b") 35 times and then stops. num_b = 35 ninety_nine = tf.train.limit_epochs( tf.constant(99, dtype=tf.int64), num_b) sparse_ninety_nine = tf.SparseTensor( indices=tf.reshape(zero64, [1, 1]), values=tf.pack([tf.cast(ninety_nine, tf.float32)]), shape=[1]) # These get joined together and grouped into batches of 5. batch_size = 5 batched = tf.train.shuffle_batch_join( [[counter, sparse_counter, "a"], [ninety_nine, sparse_ninety_nine, "b"]], batch_size=batch_size, capacity=32, min_after_dequeue=16, seed=223607) tf.initialize_all_variables().run() threads = tf.train.start_queue_runners() # Should see the "a" and "b" threads mixed together. all_a = [] seen_b = 0 saw_both = 0 num_batches = (num_a + num_b) // batch_size for i in range(num_batches): results = sess.run(batched) tf.logging.info("Batch %d: %s", i, results[0]) self.assertEqual(len(results[0]), batch_size) self.assertEqual(len(results[2]), batch_size) self.assertAllEqual(results[0], results[1].values) self.assertAllEqual( results[1].indices, np.vstack((np.arange(batch_size), np.zeros(batch_size))).T) self.assertAllEqual(results[1].shape, [batch_size, 1]) which_a = [i for i, s in enumerate(results[2]) if s == b"a"] which_b = [i for i, s in enumerate(results[2]) if s == b"b"] self.assertEqual(len(which_a) + len(which_b), batch_size) if len(which_a) > 0 and len(which_b) > 0: saw_both += 1 all_a.extend([results[0][i] for i in which_a]) seen_b += len(which_b) self.assertAllEqual([99] * len(which_b), [results[0][i] for i in which_b]) # Some minimum level of mixing of the results of both threads. self.assertGreater(saw_both, 1) # Saw all the items from "a", but scrambled. self.assertItemsEqual(all_a, range(num_a)) deltas = [all_a[i + 1] - all_a[i] for i in range(len(all_a) - 1)] self.assertFalse(all(d == deltas[0] for d in deltas)) self.assertEqual(seen_b, num_b) # Reached the limit. with self.assertRaises(tf.errors.OutOfRangeError): sess.run(batched) for thread in threads: thread.join() def testSharedName(self): with self.test_session(): batch_size = 10 num_batches = 3 zero64 = tf.constant(0, dtype=tf.int64) examples = tf.Variable(zero64) counter = examples.count_up_to(num_batches * batch_size) batched = tf.train.shuffle_batch_join( [[counter, "string"]], batch_size=batch_size, capacity=32, min_after_dequeue=10, shared_name="SHARED_NAME_XYZ", name="Q") self.assertProtoEquals( "s: 'SHARED_NAME_XYZ'", batched[0].op.inputs[0].op.node_def.attr["shared_name"]) if __name__ == "__main__": tf.test.main()
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. import json import re import types from . import validators __version__ = "1.2.1" # constants for DeletionPolicy Delete = 'Delete' Retain = 'Retain' Snapshot = 'Snapshot' # Pseudo Parameters AWS_ACCOUNT_ID = 'AWS::AccountId' AWS_NOTIFICATION_ARNS = 'AWS::NotificationARNs' AWS_NO_VALUE = 'AWS::NoValue' AWS_REGION = 'AWS::Region' AWS_STACK_ID = 'AWS::StackId' AWS_STACK_NAME = 'AWS::StackName' valid_names = re.compile(r'^[a-zA-Z0-9]+$') class BaseAWSObject(object): def __init__(self, title, template=None, **kwargs): self.title = title self.template = template # Cache the keys for validity checks self.propnames = self.props.keys() self.attributes = ['DependsOn', 'DeletionPolicy', 'Metadata', 'UpdatePolicy', 'Condition', 'CreationPolicy'] # unset/None is also legal if title and not valid_names.match(title): raise ValueError('Name "%s" not alphanumeric' % title) # Create the list of properties set on this object by the user self.properties = {} dictname = getattr(self, 'dictname', None) if dictname: self.resource = { dictname: self.properties, } else: self.resource = self.properties if hasattr(self, 'resource_type') and self.resource_type is not None: self.resource['Type'] = self.resource_type self.__initialized = True # Check for properties defined in the class for k, (_, required) in self.props.items(): v = getattr(type(self), k, None) if v is not None and k not in kwargs: self.__setattr__(k, v) # Now that it is initialized, populate it with the kwargs for k, v in kwargs.items(): self.__setattr__(k, v) # Bound it to template if we know it if self.template is not None: self.template.add_resource(self) def __getattr__(self, name): try: return self.properties.__getitem__(name) except KeyError: # Fall back to the name attribute in the object rather than # in the properties dict. This is for non-OpenStack backwards # compatibility since OpenStack objects use a "name" property. if name == 'name': return self.__getattribute__('title') raise AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__.keys() \ or '_BaseAWSObject__initialized' not in self.__dict__: return dict.__setattr__(self, name, value) elif name in self.attributes: self.resource[name] = value return None elif name in self.propnames: # Check the type of the object and compare against what we were # expecting. expected_type = self.props[name][0] # If the value is a AWSHelperFn we can't do much validation # we'll have to leave that to Amazon. Maybe there's another way # to deal with this that we'll come up with eventually if isinstance(value, AWSHelperFn): return self.properties.__setitem__(name, value) # If it's a function, call it... elif isinstance(expected_type, types.FunctionType): value = expected_type(value) return self.properties.__setitem__(name, value) # If it's a list of types, check against those types... elif isinstance(expected_type, list): # If we're expecting a list, then make sure it is a list if not isinstance(value, list): self._raise_type(name, value, expected_type) # Iterate over the list and make sure it matches our # type checks (as above accept AWSHelperFn because # we can't do the validation ourselves) for v in value: if not isinstance(v, tuple(expected_type)) \ and not isinstance(v, AWSHelperFn): self._raise_type(name, v, expected_type) # Validated so assign it return self.properties.__setitem__(name, value) # Single type so check the type of the object and compare against # what we were expecting. Special case AWS helper functions. elif isinstance(value, expected_type): return self.properties.__setitem__(name, value) else: self._raise_type(name, value, expected_type) type_name = getattr(self, 'resource_type', self.__class__.__name__) if type_name == 'AWS::CloudFormation::CustomResource' or \ type_name.startswith('Custom::'): # Add custom resource arguments to the dict without any further # validation. The properties of a CustomResource is not known. return self.properties.__setitem__(name, value) raise AttributeError("%s object does not support attribute %s" % (type_name, name)) def _raise_type(self, name, value, expected_type): raise TypeError('%s: %s.%s is %s, expected %s' % (self.__class__, self.title, name, type(value), expected_type)) def validate(self): pass @classmethod def from_dict(cls, title, dict): obj = cls(title) obj.properties.update(dict) return obj def JSONrepr(self): for k, (_, required) in self.props.items(): if required and k not in self.properties: rtype = getattr(self, 'resource_type', "<unknown type>") raise ValueError( "Resource %s required in type %s" % (k, rtype)) self.validate() # If no other properties are set, only return the Type. # Mainly used to not have an empty "Properties". if self.properties: return self.resource elif hasattr(self, 'resource_type'): return {'Type': self.resource_type} else: return {} class AWSObject(BaseAWSObject): dictname = 'Properties' class AWSDeclaration(BaseAWSObject): """ Used for CloudFormation Resource Property objects http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/ aws-product-property-reference.html """ def __init__(self, title, **kwargs): super(AWSDeclaration, self).__init__(title, **kwargs) class AWSProperty(BaseAWSObject): """ Used for CloudFormation Resource Property objects http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/ aws-product-property-reference.html """ dictname = None def __init__(self, title=None, **kwargs): super(AWSProperty, self).__init__(title, **kwargs) class AWSAttribute(BaseAWSObject): dictname = None """ Used for CloudFormation Resource Attribute objects http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/ aws-product-attribute-reference.html """ def __init__(self, title=None, **kwargs): super(AWSAttribute, self).__init__(title, **kwargs) def validate_pausetime(pausetime): if not pausetime.startswith('PT'): raise ValueError('PauseTime should look like PT#H#M#S') return pausetime class UpdatePolicy(BaseAWSObject): def __init__(self, title, **kwargs): raise DeprecationWarning( "This UpdatePolicy class is deprecated, please switch to using " "the more general UpdatePolicy in troposphere.policies.\n" ) class AWSHelperFn(object): def getdata(self, data): if isinstance(data, BaseAWSObject): return data.title else: return data class Base64(AWSHelperFn): def __init__(self, data): self.data = {'Fn::Base64': data} def JSONrepr(self): return self.data class FindInMap(AWSHelperFn): def __init__(self, mapname, key, value): self.data = {'Fn::FindInMap': [self.getdata(mapname), key, value]} def JSONrepr(self): return self.data class GetAtt(AWSHelperFn): def __init__(self, logicalName, attrName): self.data = {'Fn::GetAtt': [self.getdata(logicalName), attrName]} def JSONrepr(self): return self.data class GetAZs(AWSHelperFn): def __init__(self, region=""): self.data = {'Fn::GetAZs': region} def JSONrepr(self): return self.data class If(AWSHelperFn): def __init__(self, cond, true, false): self.data = {'Fn::If': [self.getdata(cond), true, false]} def JSONrepr(self): return self.data class Equals(AWSHelperFn): def __init__(self, value_one, value_two): self.data = {'Fn::Equals': [value_one, value_two]} def JSONrepr(self): return self.data class And(AWSHelperFn): def __init__(self, cond_one, cond_two, *conds): self.data = {'Fn::And': [cond_one, cond_two] + list(conds)} def JSONrepr(self): return self.data class Or(AWSHelperFn): def __init__(self, cond_one, cond_two, *conds): self.data = {'Fn::Or': [cond_one, cond_two] + list(conds)} def JSONrepr(self): return self.data class Not(AWSHelperFn): def __init__(self, cond): self.data = {'Fn::Not': [self.getdata(cond)]} def JSONrepr(self): return self.data class Join(AWSHelperFn): def __init__(self, delimiter, values): self.data = {'Fn::Join': [delimiter, values]} def JSONrepr(self): return self.data class Name(AWSHelperFn): def __init__(self, data): self.data = self.getdata(data) def JSONrepr(self): return self.data class Select(AWSHelperFn): def __init__(self, indx, objects): self.data = {'Fn::Select': [indx, objects]} def JSONrepr(self): return self.data class Ref(AWSHelperFn): def __init__(self, data): self.data = {'Ref': self.getdata(data)} def JSONrepr(self): return self.data class Condition(AWSHelperFn): def __init__(self, data): self.data = {'Condition': self.getdata(data)} def JSONrepr(self): return self.data class awsencode(json.JSONEncoder): def default(self, obj): if hasattr(obj, 'JSONrepr'): return obj.JSONrepr() return json.JSONEncoder.default(self, obj) class Tags(AWSHelperFn): def __init__(self, **kwargs): self.tags = [] for k, v in sorted(kwargs.iteritems()): self.tags.append({ 'Key': k, 'Value': v, }) def JSONrepr(self): return self.tags class Template(object): props = { 'AWSTemplateFormatVersion': (basestring, False), 'Description': (basestring, False), 'Parameters': (dict, False), 'Mappings': (dict, False), 'Resources': (dict, False), 'Outputs': (dict, False), } def __init__(self): self.description = None self.metadata = {} self.conditions = {} self.mappings = {} self.outputs = {} self.parameters = {} self.resources = {} self.version = None def add_description(self, description): self.description = description def add_metadata(self, metadata): self.metadata = metadata def add_condition(self, name, condition): self.conditions[name] = condition def handle_duplicate_key(self, key): raise ValueError('duplicate key "%s" detected' % key) def _update(self, d, values): if isinstance(values, list): for v in values: if v.title in d: self.handle_duplicate_key(v.title) d[v.title] = v else: if values.title in d: self.handle_duplicate_key(values.title) d[values.title] = values return values def add_output(self, output): return self._update(self.outputs, output) def add_mapping(self, name, mapping): self.mappings[name] = mapping def add_parameter(self, parameter): return self._update(self.parameters, parameter) def add_resource(self, resource): return self._update(self.resources, resource) def add_version(self, version=None): if version: self.version = version else: self.version = "2010-09-09" def to_json(self, indent=4, sort_keys=True, separators=(',', ': ')): t = {} if self.description: t['Description'] = self.description if self.metadata: t['Metadata'] = self.metadata if self.conditions: t['Conditions'] = self.conditions if self.mappings: t['Mappings'] = self.mappings if self.outputs: t['Outputs'] = self.outputs if self.parameters: t['Parameters'] = self.parameters if self.version: t['AWSTemplateFormatVersion'] = self.version t['Resources'] = self.resources return json.dumps(t, cls=awsencode, indent=indent, sort_keys=sort_keys, separators=separators) def JSONrepr(self): return [self.parameters, self.mappings, self.resources] class Output(AWSDeclaration): props = { 'Description': (basestring, False), 'Value': (basestring, True), } class Parameter(AWSDeclaration): STRING_PROPERTIES = ['AllowedPattern', 'MaxLength', 'MinLength'] NUMBER_PROPERTIES = ['MaxValue', 'MinValue'] props = { 'Type': (basestring, True), 'Default': (basestring, False), 'NoEcho': (bool, False), 'AllowedValues': (list, False), 'AllowedPattern': (basestring, False), 'MaxLength': (validators.positive_integer, False), 'MinLength': (validators.positive_integer, False), 'MaxValue': (validators.integer, False), 'MinValue': (validators.integer, False), 'Description': (basestring, False), 'ConstraintDescription': (basestring, False), } def validate(self): if self.properties['Type'] != 'String': for p in self.STRING_PROPERTIES: if p in self.properties: raise ValueError("%s can only be used with parameters of " "the String type." % p) if self.properties['Type'] != 'Number': for p in self.NUMBER_PROPERTIES: if p in self.properties: raise ValueError("%s can only be used with parameters of " "the Number type." % p)
# The MIT License (MIT) # Copyright (c) 2015 Luke Gaynor # 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 collections import namedtuple from pprint import pprint import struct import array HEADER = """# Converted with PyNinjaObj '.rip' to '.obj' converter""" DEFAULT_MAT = """Ka 0.000000 0.000000 0.000000\nKd 0.376320 0.376320 0.376320\nKs 0.000000 0.000000 0.000000""" class Vector3(): """A 3D point""" def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "({},{},{})".format(self.x, self.y, self.z) class Vector2(): """A 2D point""" def __init__(self, u, v): self.u = u self.v = v def __repr__(self): return "({},{})".format(self.u, self.v) def read_str(filehandle): buf = b'' while True: byte = filehandle.read(1) if byte != b'\0': buf += byte else: break return buf.decode("ASCII") class RipMesh(): def __init__(self, ripfile): v_idx = Vector3(0,0,0) vn_idx = Vector3(0,0,0) vt_idx = Vector2(0,0) rip = open(ripfile, "rb") info_header = array.array("L") info_header.fromfile(rip, 8) signature = info_header[0] version = info_header[1] face_count = info_header[2] vertex_count = info_header[3] vertex_size = info_header[4] texture_file_count = info_header[5] shader_file_count = info_header[6] vertex_attribute_count = info_header[7] print(version,face_count,vertex_count,vertex_size,texture_file_count,shader_file_count,vertex_attribute_count) if signature != 0xDEADC0DE: raise NotImplementedError("Sorry, this file signature isn't recognised.") if version != 4: print("Warning: This tool was written for version 4 .rip files, not version", version) pos_idx = 0 normal_idx = 0 uv_idx = 0 vertex_attrib_types = [] for i in range(0, vertex_attribute_count): attrib_type = read_str(rip) # print("oo",attrib_type,"<ye") attrib_info = array.array("L") attrib_info.fromfile(rip, 4) attrib_idx = attrib_info[0] attrib_offset = attrib_info[1] attrib_size = attrib_info[2] attrib_element_count = attrib_info[3] vertex_attrib = array.array("L") vertex_attrib.fromfile(rip, attrib_element_count) vertex_attrib_types.extend(vertex_attrib) # print(pos_idx, normal_idx, uv_idx, vertex_attrib) if attrib_type == "POSITION" and pos_idx == 0: v_idx.x = attrib_offset // 4 v_idx.y = v_idx.x + 1 v_idx.z = v_idx.x + 2 # print("adding pos", v_idx) pos_idx += 1 elif attrib_type == "NORMAL" and normal_idx == 0: vn_idx.x = attrib_offset // 4 vn_idx.y = vn_idx.x + 1 vn_idx.z = vn_idx.x + 2 # print("adding norm", vn_idx) normal_idx += 1 elif attrib_type == "TEXCOORD" and uv_idx == 0: vt_idx.u = attrib_offset // 4 vt_idx.v = vt_idx.u + 1 # print("adding uv", vt_idx) uv_idx += 1 self.texture_files = [] for i in range(0, texture_file_count): self.texture_files.append(read_str(rip)) print(self.texture_files) self.shader_files = [] for i in range(0, shader_file_count): self.shader_files.append(read_str(rip)) self.faces = [] for x in range(0, face_count): face = array.array("L") face.fromfile(rip, 3) self.faces.append(face) self.vertices = [] self.normals = [] self.texcoords = [] for i in range(0, vertex_count): v = Vector3(0,0,0) vn = Vector3(0,0,0) vt = Vector2(0,0) for j,element_type in enumerate(vertex_attrib_types): pos = 0 # print(rip.tell()) # print(element_type) if element_type == 0: pos, = struct.unpack("f", rip.read(struct.calcsize("f"))) elif element_type == 1: pos, = struct.unpack("L", rip.read(struct.calcsize("L"))) elif element_type == 2: pos, = struct.unpack("l", rip.read(struct.calcsize("l"))) if j == v_idx.x: v.x = pos elif j == v_idx.y: v.y = pos elif j == v_idx.z: v.z = pos elif j == vn_idx.x: vn.x = pos elif j == vn_idx.y: vn.y = pos elif j == vn_idx.z: vn.z = pos elif j == vt_idx.u: vt.u = pos # print(vt) elif j == vt_idx.v: vt.v = 1 - pos self.vertices.append(v) self.normals.append(vn) self.texcoords.append(vt) print("Finished reading mesh file") rip.close() def riptoobj(ripfiles, outdir, tga=False, name="convert", exists=False): meshes = [] for ripfile in ripfiles: meshes.append(RipMesh(ripfile)) print("Making OBJ and MTL files") objname = outdir + name + ".obj" mtlname = outdir + name + ".mtl" texset = set() for mesh in meshes: for tex in mesh.texture_files: if tga: tex = tex[:-4] + ".tga" # .dds to .tga if exists and not os.path.isfile(os.path.join(outdir, tex)): # print("Ignoring nonexistant", tex) continue texset.add(tex) pprint(texset) objlines = [] mtllines = [] objlines.append(HEADER) if len(texset) > 0: # only need to make an mtl if theres textures objlines.append("mtllib " + mtlname) mtllines.append(HEADER) for tex in texset: mtllines.append("newmtl " + tex) mtllines.append(DEFAULT_MAT) mtllines.append("map_Kd " + tex) mtllines.append("") last_idx = None for idx,mesh in enumerate(meshes): objlines.append("o Object" + str(idx)) for tex in mesh.texture_files: if tga: tex = tex[:-4] + ".tga" if exists and not os.path.isfile(os.path.join(outdir, tex)): continue # ignore nonexistant materials if specified objlines.append("usemtl " + tex) for v in mesh.vertices: objlines.append("v {} {} {}".format(v.x, v.y, v.z)) for vn in mesh.normals: objlines.append("vn {} {} {}".format(vn.x, vn.y, vn.z)) for vt in mesh.texcoords: objlines.append("vt {} {}".format(vt.u, vt.v)) if not last_idx: last_idx = 1 highest_idx = 0 for face in mesh.faces: line = ["f"] for v in face: v += last_idx highest_idx = v if v > highest_idx else highest_idx line.append("{}/{}/{}".format(v,v,v)) objlines.append(" ".join(line)) last_idx = highest_idx+1 # print(len(mesh.faces), len(mesh.vertices), last_idx) with open(objname, "w") as obj: obj.write("\n".join(objlines)) with open(mtlname, "w") as mtl: mtl.write("\n".join(mtllines)) # for tex in mesh.texture_files: # if tga: # tex = tex[:-4] + ".tga" # print(vertices) # print(normals) # print(uvs) if __name__ == '__main__': import argparse import os parser = argparse.ArgumentParser(description="Converts NinjaRipper .rips into .objs") parser.add_argument("rip_path", help="path to the folder containing rip files") # parser.add_argument("-o","--output", nargs=1, help="output path and name (not including)") parser.add_argument("--tga", help="look for tga textures", action='store_true') parser.add_argument("--exists", "-e", help="only include materials for which their texture files exist", action='store_true') # parser.add_argument("--whitelist_suffix", "-w", help="only include material's with these suffixes", nargs="+") args = parser.parse_args() indir = os.path.normpath(args.rip_path) out = args.rip_path+os.path.sep print("Saving to", os.path.realpath(out)) paths = [] for f in os.listdir(indir): if f.endswith(".rip"): paths.append(indir+os.path.sep+f) riptoobj(paths, out, tga=args.tga, exists=args.exists)
import copy import warnings from types import GeneratorType class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actually look up values in more than one dictionary, passed in the constructor. If a key appears in more than one of the given dictionaries, only the first occurrence will be used. """ def __init__(self, *dicts): self.dicts = dicts def __getitem__(self, key): for dict_ in self.dicts: try: return dict_[key] except KeyError: pass raise KeyError def __copy__(self): return self.__class__(*self.dicts) def get(self, key, default=None): try: return self[key] except KeyError: return default def getlist(self, key): for dict_ in self.dicts: if key in dict_.keys(): return dict_.getlist(key) return [] def iteritems(self): seen = set() for dict_ in self.dicts: for item in dict_.iteritems(): k, v = item if k in seen: continue seen.add(k) yield item def iterkeys(self): for k, v in self.iteritems(): yield k def itervalues(self): for k, v in self.iteritems(): yield v def items(self): return list(self.iteritems()) def keys(self): return list(self.iterkeys()) def values(self): return list(self.itervalues()) def has_key(self, key): for dict_ in self.dicts: if key in dict_: return True return False __contains__ = has_key __iter__ = iterkeys def copy(self): """Returns a copy of this object.""" return self.__copy__() def __str__(self): ''' Returns something like "{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}" instead of the generic "<object meta-data>" inherited from object. ''' return str(dict(self.items())) def __repr__(self): ''' Returns something like MergeDict({'key1': 'val1', 'key2': 'val2'}, {'key3': 'val3'}) instead of generic "<object meta-data>" inherited from object. ''' dictreprs = ', '.join(repr(d) for d in self.dicts) return '%s(%s)' % (self.__class__.__name__, dictreprs) class SortedDict(dict): """ A dictionary that keeps its keys in the order in which they're inserted. """ def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __init__(self, data=None): if data is None: data = {} elif isinstance(data, GeneratorType): # Unfortunately we need to be able to read a generator twice. Once # to get the data into self with our super().__init__ call and a # second time to setup keyOrder correctly data = list(data) super(SortedDict, self).__init__(data) if isinstance(data, dict): self.keyOrder = data.keys() else: self.keyOrder = [] seen = set() for key, value in data: if key not in seen: self.keyOrder.append(key) seen.add(key) def __deepcopy__(self, memo): return self.__class__([(key, copy.deepcopy(value, memo)) for key, value in self.iteritems()]) def __copy__(self): # The Python's default copy implementation will alter the state # of self. The reason for this seems complex but is likely related to # subclassing dict. return self.copy() def __setitem__(self, key, value): if key not in self: self.keyOrder.append(key) super(SortedDict, self).__setitem__(key, value) def __delitem__(self, key): super(SortedDict, self).__delitem__(key) self.keyOrder.remove(key) def __iter__(self): return iter(self.keyOrder) def pop(self, k, *args): result = super(SortedDict, self).pop(k, *args) try: self.keyOrder.remove(k) except ValueError: # Key wasn't in the dictionary in the first place. No problem. pass return result def popitem(self): result = super(SortedDict, self).popitem() self.keyOrder.remove(result[0]) return result def items(self): return zip(self.keyOrder, self.values()) def iteritems(self): for key in self.keyOrder: yield key, self[key] def keys(self): return self.keyOrder[:] def iterkeys(self): return iter(self.keyOrder) def values(self): return map(self.__getitem__, self.keyOrder) def itervalues(self): for key in self.keyOrder: yield self[key] def update(self, dict_): for k, v in dict_.iteritems(): self[k] = v def setdefault(self, key, default): if key not in self: self.keyOrder.append(key) return super(SortedDict, self).setdefault(key, default) def value_for_index(self, index): """Returns the value of the item at the given zero-based index.""" # This, and insert() are deprecated because they cannot be implemented # using collections.OrderedDict (Python 2.7 and up), which we'll # eventually switch to warnings.warn(PendingDeprecationWarning, "SortedDict.value_for_index is deprecated", stacklevel=2) return self[self.keyOrder[index]] def insert(self, index, key, value): """Inserts the key, value pair before the item with the given index.""" warnings.warn(PendingDeprecationWarning, "SortedDict.insert is deprecated", stacklevel=2) if key in self.keyOrder: n = self.keyOrder.index(key) del self.keyOrder[n] if n < index: index -= 1 self.keyOrder.insert(index, key) super(SortedDict, self).__setitem__(key, value) def copy(self): """Returns a copy of this object.""" # This way of initializing the copy means it works for subclasses, too. return self.__class__(self) def __repr__(self): """ Replaces the normal dict.__repr__ with a version that returns the keys in their sorted order. """ return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()]) def clear(self): super(SortedDict, self).clear() self.keyOrder = [] class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.getlist('doesnotexist') [] >>> d.getlist('doesnotexist', ['Adrian', 'Simon']) ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): super(MultiValueDict, self).__init__(key_to_list_mapping) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, super(MultiValueDict, self).__repr__()) def __getitem__(self, key): """ Returns the last data value for this key, or [] if it's an empty list; raises KeyError if not found. """ try: list_ = super(MultiValueDict, self).__getitem__(key) except KeyError: raise MultiValueDictKeyError("Key %r not found in %r" % (key, self)) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): super(MultiValueDict, self).__setitem__(key, [value]) def __copy__(self): return self.__class__([ (k, v[:]) for k, v in self.lists() ]) def __deepcopy__(self, memo=None): if memo is None: memo = {} result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def __getstate__(self): obj_dict = self.__dict__.copy() obj_dict['_data'] = dict([(k, self.getlist(k)) for k in self]) return obj_dict def __setstate__(self, obj_dict): data = obj_dict.pop('_data', {}) for k, v in data.items(): self.setlist(k, v) self.__dict__.update(obj_dict) def get(self, key, default=None): """ Returns the last data value for the passed key. If key doesn't exist or value is an empty list, then default is returned. """ try: val = self[key] except KeyError: return default if val == []: return default return val def getlist(self, key, default=None): """ Returns the list of values for the passed key. If key doesn't exist, then a default value is returned. """ try: return super(MultiValueDict, self).__getitem__(key) except KeyError: if default is None: return [] return default def setlist(self, key, list_): super(MultiValueDict, self).__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default return default return self[key] def setlistdefault(self, key, default_list=None): if key not in self: if default_list is None: default_list = [] self.setlist(key, default_list) return self.getlist(key) def appendlist(self, key, value): """Appends an item to the internal list associated with key.""" self.setlistdefault(key).append(value) def items(self): """ Returns a list of (key, value) pairs, where value is the last item in the list associated with the key. """ return [(key, self[key]) for key in self.keys()] def iteritems(self): """ Yields (key, value) pairs, where value is the last item in the list associated with the key. """ for key in self.keys(): yield (key, self[key]) def lists(self): """Returns a list of (key, list) pairs.""" return super(MultiValueDict, self).items() def iterlists(self): """Yields (key, list) pairs.""" return super(MultiValueDict, self).iteritems() def values(self): """Returns a list of the last value on every key list.""" return [self[key] for key in self.keys()] def itervalues(self): """Yield the last value on every key list.""" for key in self.iterkeys(): yield self[key] def copy(self): """Returns a shallow copy of this object.""" return copy.copy(self) def update(self, *args, **kwargs): """ update() extends rather than replaces existing key lists. Also accepts keyword args. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other_dict = args[0] if isinstance(other_dict, MultiValueDict): for key, value_list in other_dict.lists(): self.setlistdefault(key).extend(value_list) else: try: for key, value in other_dict.items(): self.setlistdefault(key).append(value) except TypeError: raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary") for key, value in kwargs.iteritems(): self.setlistdefault(key).append(value) def dict(self): """ Returns current object as a dict with singular values. """ return dict((key, self[key]) for key in self) class ImmutableList(tuple): """ A tuple-like object that raises useful errors when it is asked to mutate. Example:: >>> a = ImmutableList(range(5), warning="You cannot mutate this.") >>> a[3] = '4' Traceback (most recent call last): ... AttributeError: You cannot mutate this. """ def __new__(cls, *args, **kwargs): if 'warning' in kwargs: warning = kwargs['warning'] del kwargs['warning'] else: warning = 'ImmutableList object is immutable.' self = tuple.__new__(cls, *args, **kwargs) self.warning = warning return self def complain(self, *wargs, **kwargs): if isinstance(self.warning, Exception): raise self.warning else: raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain __delslice__ = complain __iadd__ = complain __imul__ = complain __setitem__ = complain __setslice__ = complain append = complain extend = complain insert = complain pop = complain remove = complain sort = complain reverse = complain class DictWrapper(dict): """ Wraps accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used. """ def __init__(self, data, func, prefix): super(DictWrapper, self).__init__(data) self.func = func self.prefix = prefix def __getitem__(self, key): """ Retrieves the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value. """ if key.startswith(self.prefix): use_func = True key = key[len(self.prefix):] else: use_func = False value = super(DictWrapper, self).__getitem__(key) if use_func: return self.func(value) return value
import json from PIL import Image from io import BytesIO from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.forms.models import model_to_dict from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone from django.utils.encoding import force_text from accounts.models import ROLE_PARTNER from accounts.tests.factories import CtsUserFactory from accounts.utils import bootstrap_permissions from catalog.tests.factories import CatalogItemFactory, DonorFactory, \ SupplierFactory from ona.models import FormSubmission from ona.representation import PackageScanFormSubmission from ona.tests.test_models import PACKAGE_DATA, QR_CODE from shipments.models import Shipment, Package, PackageItem from shipments.views import ShipmentCreateView from shipments.tests.factories import ShipmentFactory, PackageFactory, \ KitFactory, KitItemFactory, PackageItemFactory class BaseViewTestCase(TestCase): @classmethod def setUpClass(cls): bootstrap_permissions() def setUp(self): self.email = 'fred@example.com' self.password = 'flintstone' self.user = get_user_model().objects.create_superuser(password=self.password, email=self.email) assert self.client.login(email=self.email, password=self.password) self.description = 'Yet Another _shipment_ DESCRIPTION' self.shipment = ShipmentFactory(description=self.description, partner=self.user) def just_partner(self): # Make self.user just a partner self.user.is_superuser = False self.user.role = ROLE_PARTNER self.user.save() self.assertTrue(self.user.is_just_partner()) def assertNoPermission(self, rsp): self.assertRedirects(rsp, '/login/?next=' + self.url) def assert200(self, rsp): self.assertEqual(200, rsp.status_code) def assert404(self, rsp): self.assertEqual(404, rsp.status_code) class ShipmentsListViewTest(BaseViewTestCase): def test_get(self): rsp = self.client.get(reverse('shipments_list')) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/list.html') self.assertContains(rsp, self.description) class ShipmentCreateViewTest(BaseViewTestCase): def test_get(self): rsp = self.client.get(reverse('create_shipment')) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/create_edit_shipment.html') def test_creating_is_true(self): self.assertTrue(ShipmentCreateView().creating()) def test_post_good(self): partner = CtsUserFactory(role=ROLE_PARTNER) data = { 'description': 'DESCRIPTION', 'shipment_date': force_text(timezone.now().date()), 'estimated_delivery': 2, 'partner': partner.id, 'store_release': 'foo' } rsp = self.client.post(reverse('create_shipment'), data=data) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) new_shipment = Shipment.objects.exclude(pk=self.shipment.pk).get() next_url = reverse('edit_shipment', kwargs={'pk': new_shipment.pk}) self.assertRedirects(rsp, next_url) self.assertEqual('DESCRIPTION', new_shipment.description) def test_post_bad(self): data = { 'description': 'DESCRIPTION', 'shipment_date': 'this is not a date', # BAD DATA 'estimated_delivery': 2, } rsp = self.client.post(reverse('create_shipment'), data=data) self.assertEqual(400, rsp.status_code) def test_just_partner(self): # Partner may not create a shipment self.just_partner() self.url = reverse('create_shipment') rsp = self.client.get(self.url) self.assertNoPermission(rsp) class ShipmentLostViewTest(BaseViewTestCase): def setUp(self): super(ShipmentLostViewTest, self).setUp() self.url = reverse('lost_shipment', args=[self.shipment.pk]) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) def test_post(self): note = 'My dog ate it' data = { 'acceptable': True, 'notes': note, } self.assertNotEqual(self.shipment.status, Shipment.STATUS_LOST) rsp = self.client.post(self.url, data) new_url = reverse('edit_shipment', args=[self.shipment.pk]) self.assertRedirects(rsp, new_url) self.shipment = Shipment.objects.get(pk=self.shipment.pk) self.assertEqual(self.shipment.status, Shipment.STATUS_LOST) self.assertEqual(self.shipment.status_note, note) self.assertEqual(self.shipment.acceptable, True) class ShipmentUpdateViewTest(BaseViewTestCase): def setUp(self): super(ShipmentUpdateViewTest, self).setUp() self.url = reverse('edit_shipment', kwargs={'pk': self.shipment.pk}) self.package = PackageFactory(shipment=self.shipment) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/create_edit_shipment.html') self.assertContains(rsp, self.description) # The context actually has ShipmentDBView and PackageDBView objects, so # look for the PKs self.assertIn(self.shipment.pk, [s.pk for s in rsp.context['shipments']]) self.assertIn(self.package.pk, [p.pk for p in rsp.context['packages']]) def test_post_good(self): partner = CtsUserFactory(role=ROLE_PARTNER) data = { 'description': 'DESCRIPTION', 'shipment_date': force_text(timezone.now().date()), 'estimated_delivery': 2, 'partner': partner.id, 'store_release': 'foo' } rsp = self.client.post(self.url, data=data) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertRedirects(rsp, reverse('edit_shipment', args=[self.shipment.pk])) shipment = Shipment.objects.get(pk=self.shipment.pk) self.assertEqual(data['description'], shipment.description) def test_post_bad(self): data = { 'description': 'DESCRIPTION', 'shipment_date': 'not a VALID date', 'estimated_delivery': 2, } rsp = self.client.post(self.url, data=data) self.assertEqual(400, rsp.status_code) self.assertIn('shipment_date', rsp.context['form'].errors.keys()) def test_just_partner_get_own(self): # Partner may view a shipment if it's theirs self.just_partner() rsp = self.client.get(self.url) self.assert200(rsp) def test_just_partner_get_other(self): # Partner may not view other partners' shipments # Just acts like it's not there (404) self.just_partner() partner = CtsUserFactory(role=ROLE_PARTNER) self.shipment.partner = partner self.shipment.save() rsp = self.client.get(self.url) self.assert404(rsp) def test_just_partner_post(self): # Partner may not update a shipment self.just_partner() data = { 'description': 'DESCRIPTION', 'shipment_date': force_text(timezone.now().date()), 'estimated_delivery': 2, 'partner': self.user.id, 'store_release': 'foo' } rsp = self.client.post(self.url, data=data) self.assertNoPermission(rsp) class NewPackageModalViewTest(BaseViewTestCase): def setUp(self): super(NewPackageModalViewTest, self).setUp() self.url = reverse('new_package', kwargs={'pk': self.shipment.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/new_package_modal.html') def test_post(self): data = { 'name': 'package name', 'description': 'desscRIPERERtion', 'package_quantity': '1', } rsp = self.client.post(self.url, data=data) self.assertEqual(200, rsp.status_code) pkg = Package.objects.get() self.assertEqual(self.shipment, pkg.shipment) self.assertEqual(data['name'], pkg.name) def test_just_partner(self): # Partner may not create a new package self.just_partner() self.assertFalse(self.user.has_perm('shipments.add_package')) rsp = self.client.get(self.url) self.assertNoPermission(rsp) class EditPackageModalViewTest(BaseViewTestCase): def setUp(self): super(EditPackageModalViewTest, self).setUp() self.package = PackageFactory() self.url = reverse('edit_package', kwargs={'pk': self.package.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/edit_package_modal.html') def test_post(self): data = { 'name': 'package name', 'description': 'desscRIPERERtion', } rsp = self.client.post(self.url, data=data) self.assertEqual(200, rsp.status_code) pkg = Package.objects.get() self.assertEqual(data['name'], pkg.name) def test_just_partner(self): # Partner may not edit a package self.just_partner() self.assertFalse(self.user.has_perm('shipments.change_package')) rsp = self.client.get(self.url) self.assertNoPermission(rsp) class ShipmentDeleteViewTest(BaseViewTestCase): def setUp(self): super(ShipmentDeleteViewTest, self).setUp() self.shipment = ShipmentFactory() self.package = PackageFactory(shipment=self.shipment) self.item = PackageItemFactory(package=self.package) self.url = reverse('delete_shipment', kwargs={'pk': self.shipment.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) Shipment.objects.get(pk=self.shipment.pk) PackageItem.objects.get(pk=self.item.pk) def test_post(self): rsp = self.client.post(self.url) self.assertRedirects(rsp, reverse('shipments_list')) self.assertFalse(Shipment.objects.filter(pk=self.shipment.pk).exists()) self.assertFalse(Package.objects.filter(pk=self.package.pk).exists()) self.assertFalse(PackageItem.objects.filter(pk=self.item.pk).exists()) def test_just_partner(self): # Partner may not delete a shipment self.just_partner() self.assertFalse(self.user.has_perm('shipments.delete_shipment')) rsp = self.client.get(self.url) self.assertNoPermission(rsp) class NewPackageFromKitModalViewTest(BaseViewTestCase): def setUp(self): super(NewPackageFromKitModalViewTest, self).setUp() self.kit = KitFactory() self.kit_item = KitItemFactory(kit=self.kit, quantity=3) self.url = reverse('new_package_from_kit', kwargs={'pk': self.shipment.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'shipments/new_package_from_kit_modal.html') def test_post_one_kit(self): data = { 'name': 'package name', 'description': 'desscRIPERERtion', 'kit-quantity-%d' % self.kit.pk: 3, 'package_quantity': '1', } rsp = self.client.post(self.url, data=data) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertEqual(200, rsp.status_code) pkg = Package.objects.get() self.assertEqual(self.shipment, pkg.shipment) self.assertEqual(self.kit, pkg.kit) pkg_item = PackageItem.objects.get(package=pkg) self.assertEqual(self.kit_item.catalog_item, pkg_item.catalog_item) self.assertEqual(self.kit_item.quantity * 3, pkg_item.quantity) def test_post_no_kits(self): data = { 'name': 'package name', 'description': 'desscRIPERERtion', 'package_quantity': '1', } rsp = self.client.post(self.url, data=data) self.assertEqual(400, rsp.status_code) def test_post_two_kits(self): kit2 = KitFactory() KitItemFactory(kit=kit2) data = { 'name': 'package name', 'description': 'desscRIPERERtion', 'kit-quantity-%d' % self.kit.pk: 1, 'kit-quantity-%d' % kit2.pk: 2, 'package_quantity': '1', } rsp = self.client.post(self.url, data=data) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertEqual(200, rsp.status_code) pkg = Package.objects.get() self.assertEqual(self.shipment, pkg.shipment) self.assertIsNone(pkg.kit) pkg_items = PackageItem.objects.filter(package=pkg) self.assertEqual(2, pkg_items.count()) def test_post_four_packages(self): data = { 'name': 'package name', 'description': 'desscRIPERERtion', 'kit-quantity-%d' % self.kit.pk: 3, 'package_quantity': '4', } rsp = self.client.post(self.url, data=data) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertEqual(200, rsp.status_code) pkgs = Package.objects.filter(shipment=self.shipment, kit=self.kit) self.assertEqual(4, pkgs.count()) pkg_items = PackageItem.objects.filter(package__in=pkgs, catalog_item=self.kit_item.catalog_item, quantity=self.kit_item.quantity * 3) self.assertEqual(4, pkg_items.count()) def test_just_partner(self): # Partner may not create a package self.just_partner() rsp = self.client.get(self.url) self.assertNoPermission(rsp) class PackageItemsViewTestCase(BaseViewTestCase): def setUp(self): super(PackageItemsViewTestCase, self).setUp() self.package = PackageFactory(shipment=self.shipment) self.package_items = [ PackageItemFactory(package=self.package), PackageItemFactory(package=self.package), ] self.url = reverse('package_items', kwargs={'pk': self.package.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertEqual(self.package, rsp.context['package']) for item in self.package_items: self.assertIn(item, rsp.context['package_items']) self.assertTemplateUsed(rsp, 'shipments/package_items.html') def test_just_partner(self): # Partner may view a shipment's package items, but only if it's the user's shipment self.just_partner() rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.shipment.partner = CtsUserFactory() self.shipment.save() rsp = self.client.get(self.url) self.assertEqual(404, rsp.status_code) class PackageDeleteViewTestCase(BaseViewTestCase): def setUp(self): super(PackageDeleteViewTestCase, self).setUp() self.package = PackageFactory(shipment=self.shipment) self.package_items = [ PackageItemFactory(package=self.package), PackageItemFactory(package=self.package), ] self.url = reverse('package_delete', kwargs={'pk': self.package.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'cts/confirm_delete.html') self.assertEqual(self.package, rsp.context['object']) def test_post(self): rsp = self.client.post(self.url) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertFalse(Package.objects.filter(pk=self.package.pk).exists()) for item in self.package_items: self.assertFalse(PackageItem.objects.filter(pk=item.pk).exists()) def test_just_partner(self): # Partner may not delete a package self.just_partner() rsp = self.client.get(self.url) self.assertNoPermission(rsp) class PackageItemDeleteViewTestCase(BaseViewTestCase): def setUp(self): super(PackageItemDeleteViewTestCase, self).setUp() self.package = PackageFactory(shipment=self.shipment) self.package_items = [ PackageItemFactory(package=self.package), PackageItemFactory(package=self.package), ] self.item = self.package_items[0] self.url = reverse('package_item_delete', kwargs={'pk': self.item.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) self.assertTemplateUsed(rsp, 'cts/confirm_delete.html') self.assertEqual(self.item, rsp.context['object']) PackageItem.objects.get(pk=self.item.pk) def test_post(self): rsp = self.client.post(self.url) if rsp.status_code == 400: self.fail(rsp.context['form'].errors) self.assertTrue(Package.objects.filter(pk=self.package.pk).exists()) self.assertFalse(PackageItem.objects.filter(pk=self.item.pk).exists()) item2 = self.package_items[1] self.assertTrue(PackageItem.objects.filter(pk=item2.pk).exists()) def test_just_partner(self): # Partner may not delete a package item self.just_partner() rsp = self.client.get(self.url) self.assertNoPermission(rsp) class TestPackageItemCreateView(BaseViewTestCase): url_name = "package_item_create" def setUp(self): super(TestPackageItemCreateView, self).setUp() self.package = PackageFactory() self.catalog_item = CatalogItemFactory() self.data = { 'catalog_item_0': self.catalog_item.description, 'catalog_item_1': self.catalog_item.pk, 'quantity': 5, } def get_url(self, package_id=None): if package_id is None: package_id = self.package.pk return reverse(self.url_name, args=[package_id]) def test_get_unauthenticated(self): """User must be authenticated to create a package item.""" self.client.logout() response = self.client.get(self.get_url()) self.assertEqual(response.status_code, 302) self.assertEqual(PackageItem.objects.count(), 0) def test_post_unauthenticated(self): """User must be authenticated to create a package item.""" self.client.logout() response = self.client.post(self.get_url(), data=self.data) self.assertEqual(response.status_code, 302) self.assertEqual(PackageItem.objects.count(), 0) def test_invalid_package(self): """Package item must be added to a valid package.""" response = self.client.get(self.get_url('12345')) self.assertEqual(response.status_code, 404) self.assertEqual(PackageItem.objects.count(), 0) def test_get(self): """GET should retrieve an unbound form.""" response = self.client.get(self.get_url()) self.assertEqual(response.status_code, 200) self.assertTrue('form' in response.context) self.assertFalse(response.context['form'].is_bound) self.assertEqual(PackageItem.objects.count(), 0) def test_post_valid(self): """Valid POST should create a new package item.""" response = self.client.post(self.get_url(), data=self.data) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, "") self.assertEqual(PackageItem.objects.count(), 1) item = PackageItem.objects.get() self.assertEqual(item.package, self.package) self.assertEqual(item.catalog_item, self.catalog_item) self.assertEqual(item.quantity, self.data['quantity']) def test_post_invalid(self): """Invalid POST should return the form with errors.""" self.data.pop('quantity') response = self.client.post(self.get_url(), data=self.data) self.assertEqual(response.status_code, 400) self.assertTrue('form' in response.context) self.assertTrue(response.context['form'].is_bound) self.assertFalse(response.context['form'].is_valid()) self.assertTrue('quantity' in response.context['form'].errors) self.assertEqual(PackageItem.objects.count(), 0) def test_just_partner(self): # Partner may not create a package item self.just_partner() self.url = self.get_url() rsp = self.client.get(self.url) self.assertNoPermission(rsp) class PackageItemEditModalViewTest(BaseViewTestCase): def setUp(self): super(PackageItemEditModalViewTest, self).setUp() self.package = PackageFactory(shipment=self.shipment) self.item = PackageItemFactory(package=self.package) self.url = reverse('package_item_edit', args=[self.item.pk]) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) def test_post(self): data = model_to_dict(self.item) new_description = 'A very good time' data['description'] = new_description # On success, it just returns an empty 200 response (since it's just a modal) rsp = self.client.post(self.url, data) self.assertEqual(200, rsp.status_code) self.assertEqual('', rsp.content) item = PackageItem.objects.get(pk=self.item.pk) self.assertEqual(new_description, item.description) class SummaryManifestViewTest(BaseViewTestCase): def test_it(self): self.packages = [PackageFactory(shipment=self.shipment) for i in range(5)] for pkg in self.packages: for i in range(5): PackageItemFactory(package=pkg) url = reverse('summary_manifests', kwargs={'pk': self.shipment.pk}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) # Summary manifest doesn't change shipment status shipment = Shipment.objects.get(pk=self.shipment.pk) self.assertEqual(Shipment.STATUS_IN_PROGRESS, shipment.status) def test_just_partner(self): # Partner may not view another's shipment self.url = reverse('summary_manifests', kwargs={'pk': self.shipment.pk}) self.just_partner() self.shipment.partner = CtsUserFactory() self.shipment.save() rsp = self.client.get(self.url) self.assertEqual(404, rsp.status_code) class PackageBarcodesViewTest(BaseViewTestCase): def test_it(self): self.packages = [PackageFactory(shipment=self.shipment) for i in range(5)] for pkg in self.packages: for i in range(5): PackageItemFactory(package=pkg) url = reverse('package_barcodes', kwargs={'pk': self.shipment.pk, 'size': 16, 'labels': '1,2'}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) # Printing barcodes updates status from inprogress to ready for pickup shipment = Shipment.objects.get(pk=self.shipment.pk) self.assertEqual(Shipment.STATUS_READY, shipment.status) for pkg in self.packages: pkg = Package.objects.get(pk=pkg.pk) self.assertEqual(Shipment.STATUS_READY, pkg.status) def test_just_partner(self): # Partner may not view another's shipment self.just_partner() self.shipment.partner = CtsUserFactory() self.shipment.save() self.url = reverse('package_barcodes', kwargs={'pk': self.shipment.pk, 'size': 6, 'labels': '3,4'}) rsp = self.client.get(self.url) self.assertEqual(404, rsp.status_code) class FullManifestViewTest(BaseViewTestCase): def test_it(self): self.packages = [PackageFactory(shipment=self.shipment) for i in range(5)] for pkg in self.packages: for i in range(5): PackageItemFactory(package=pkg) url = reverse('full_manifests', kwargs={'pk': self.shipment.pk, 'size': 6}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) # Printing barcodes updates status from inprogress to ready for pickup shipment = Shipment.objects.get(pk=self.shipment.pk) self.assertEqual(Shipment.STATUS_READY, shipment.status) for pkg in self.packages: pkg = Package.objects.get(pk=pkg.pk) self.assertEqual(Shipment.STATUS_READY, pkg.status) def test_just_partner(self): # Partner may not view another's shipment self.just_partner() self.shipment.partner = CtsUserFactory() self.shipment.save() self.url = reverse('full_manifests', kwargs={'pk': self.shipment.pk, 'size': 8}) rsp = self.client.get(self.url) self.assertEqual(404, rsp.status_code) class QRCodeTest(TestCase): @classmethod def setUpClass(cls): bootstrap_permissions() def test_qrcode(self): code = '12345-234324234' url = reverse('qrcode', kwargs={'code': code}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) self.assertEqual('image/png', rsp['Content-Type']) bits = BytesIO(rsp.content) img = Image.open(bits) self.assertEqual('PNG', img.format) self.assertEqual((84, 84), img.size) def test_qrcode_l(self): code = '12345-234324234' url = reverse('qrcode_l', kwargs={'code': code}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) self.assertEqual('image/png', rsp['Content-Type']) bits = BytesIO(rsp.content) img = Image.open(bits) self.assertEqual('PNG', img.format) self.assertEqual((210, 210), img.size) def test_qrcode_vl(self): code = '12345-234324234' url = reverse('qrcode_vl', kwargs={'code': code}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) self.assertEqual('image/png', rsp['Content-Type']) bits = BytesIO(rsp.content) img = Image.open(bits) self.assertEqual('PNG', img.format) self.assertEqual((2100, 2100), img.size) def test_qrcode_s(self): code = '12345-234324234' url = reverse('qrcode_sized', kwargs={'code': code, 'size': 6}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) self.assertEqual('image/png', rsp['Content-Type']) bits = BytesIO(rsp.content) img = Image.open(bits) self.assertEqual('PNG', img.format) self.assertEqual((84, 84), img.size) url = reverse('qrcode_sized', kwargs={'code': code, 'size': 8}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) self.assertEqual('image/png', rsp['Content-Type']) bits = BytesIO(rsp.content) img = Image.open(bits) self.assertEqual('PNG', img.format) self.assertEqual((210, 210), img.size) class BulkEditPackageItemsViewTest(BaseViewTestCase): def setUp(self): super(BulkEditPackageItemsViewTest, self).setUp() self.url = reverse('bulk_edit_package_items') def test_get(self): # Pass package item pks in a header # get back a modal with a form pkg = PackageFactory(shipment=self.shipment) pkg_items = [PackageItemFactory(package=pkg) for i in range(10)] items_to_edit = pkg_items[:5] pks_to_edit = [item.pk for item in items_to_edit] rsp = self.client.get( self.url, HTTP_SELECTED_ITEMS=','.join([str(pk) for pk in pks_to_edit]) ) self.assertEqual(200, rsp.status_code) form = rsp.context['form'] self.assertIn('supplier', form.fields) self.assertNotIn('weight', form.fields) def test_post(self): # Pass changes and package item pks in a form # Selected package items ought to be updated donor1 = DonorFactory() donor2 = DonorFactory() supplier1 = SupplierFactory() supplier2 = SupplierFactory() pkg = PackageFactory(shipment=self.shipment) pkg_items = [PackageItemFactory(package=pkg, supplier=supplier1, donor=donor1) for i in range(10)] items_to_edit = pkg_items[:5] pks_to_edit = [item.pk for item in items_to_edit] data = { 'donor': donor2.pk, 'donor_t1': '', 'supplier': supplier2.pk, 'item_category': '', 'selected_items': ','.join([str(pk) for pk in pks_to_edit]), } rsp = self.client.post( self.url, data=data, ) self.assertEqual(200, rsp.status_code) # refresh package item objects from database pkg_items = [PackageItem.objects.get(pk=item.pk) for item in pkg_items] # check that the right changes were made for item in pkg_items: if item.pk in pks_to_edit: self.assertEqual(item.supplier, supplier2) self.assertEqual(item.donor, donor2) else: self.assertEqual(item.supplier, supplier1) self.assertEqual(item.donor, donor1) def test_post_extra_comma(self): # sometimes we get an extra comma in the list of pks pkg = PackageFactory(shipment=self.shipment) pkg_items = [PackageItemFactory(package=pkg) for i in range(3)] items_to_edit = pkg_items[:2] pks_to_edit = [item.pk for item in items_to_edit] data = { 'donor': '', 'donor_t1': '', 'supplier': '', 'item_category': '', 'selected_items': ','.join([str(pk) for pk in pks_to_edit]), } # Append the extra comma that was breaking us data['selected_items'] += ',' rsp = self.client.post( self.url, data=data, ) self.assertEqual(200, rsp.status_code) def test_just_partner(self): # Partner may not edit package items self.just_partner() rsp = self.client.get(self.url) self.assertNoPermission(rsp) @override_settings(ONA_PACKAGE_FORM_ID=123, ONA_DEVICEID_VERIFICATION_FORM_ID=111) class ShipmentDashboardViewTest(BaseViewTestCase): def setUp(self): super(ShipmentDashboardViewTest, self).setUp() self.package = PackageFactory(shipment=self.shipment, code=QR_CODE) form_data = PackageScanFormSubmission(json.loads(PACKAGE_DATA)) FormSubmission.from_ona_form_data(form_data) self.url = reverse('shipments_dashboard') def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) ctx = rsp.context self.assertEqual(self.shipment.description, ctx['shipments'][0].description) def test_get_ajax(self): kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} get_data = {'type': 'shipment', 'pk': self.shipment.pk} rsp = self.client.get(self.url, get_data, **kwargs) self.assertEqual(200, rsp.status_code) json_string = rsp.content data = json.loads(json_string) self.assertEqual(data['undelivered']['packages']['pkg_count'], 1) self.assertIsNone(data['delivered']['packages']['pkg_count']) self.shipment.status = Shipment.STATUS_RECEIVED self.shipment.save() rsp = self.client.get(self.url, get_data, **kwargs) self.assertEqual(200, rsp.status_code) json_string = rsp.content data = json.loads(json_string) self.assertEqual(data['delivered']['packages']['pkg_count'], 1) self.assertIsNone(data['undelivered']['packages']['pkg_count']) def test_just_partner(self): # Partner may not view another's shipment # For this view, means other shipments are omitted from the view self.just_partner() self.shipment.partner = CtsUserFactory() self.shipment.save() rsp = self.client.get(self.url) context = rsp.context shipments = context['shipments'] self.assertNotIn(self.shipment, shipments) @override_settings(ONA_PACKAGE_FORM_ID=123, ONA_DEVICEID_VERIFICATION_FORM_ID=111) class ShipmentPackageMapViewTest(BaseViewTestCase): def setUp(self): super(ShipmentPackageMapViewTest, self).setUp() self.package = PackageFactory(shipment=self.shipment, code=QR_CODE) form_data = PackageScanFormSubmission(json.loads(PACKAGE_DATA)) FormSubmission.from_ona_form_data(form_data) self.url = reverse('shipments_package_map', kwargs={'pk': self.package.pk}) def test_get(self): rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code) ctx = rsp.context self.assertEqual(ctx['package'], self.package) def test_get_ajax(self): kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} rsp = self.client.get(self.url, **kwargs) self.assertEqual(200, rsp.status_code) json_string = rsp.content data = json.loads(json_string) self.assertEqual(self.package.shipment.__unicode__(), data['descr']) def test_just_partner(self): # Partner may not view another's shipment self.just_partner() user2 = CtsUserFactory() self.shipment.partner = user2 self.shipment.save() rsp = self.client.get(self.url) self.assertEqual(404, rsp.status_code) class ShipmentPackagesViewTest(BaseViewTestCase): def setUp(self): super(ShipmentPackagesViewTest, self).setUp() self.url = reverse('shipment_packages', args=(self.shipment.pk,)) self.package = PackageFactory(shipment=self.shipment, code=QR_CODE) def test_just_partner(self): self.just_partner() rsp = self.client.get(self.url) self.assertEqual(200, rsp.status_code)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import numbers from six import text_type, integer_types, binary_type import google.protobuf.message from onnx import TensorProto, AttributeProto, ValueInfoProto, TensorShapeProto, \ NodeProto, ModelProto, GraphProto, OperatorSetIdProto, TypeProto, IR_VERSION import onnx.defs as defs from onnx import mapping from onnx.mapping import STORAGE_TENSOR_TYPE_TO_FIELD from typing import Text, Sequence, Any, Optional, Dict, Union, TypeVar, Callable, Tuple, List, cast import numpy as np # type: ignore def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **kwargs # type: Any ): # type: (...) -> NodeProto """Construct a NodeProto. Arguments: op_type (string): The name of the operator to construct inputs (list of string): list of input names outputs (list of string): list of output names name (string, default None): optional unique identifier for NodeProto doc_string (string, default None): optional documentation string for NodeProto domain (string, default None): optional domain for NodeProto. If it's None, we will just use default domain (which is empty) **kwargs (dict): the attributes of the node. The acceptable values are documented in :func:`make_attribute`. """ node = NodeProto() node.op_type = op_type node.input.extend(inputs) node.output.extend(outputs) if name: node.name = name if doc_string: node.doc_string = doc_string if domain is not None: node.domain = domain if kwargs: node.attribute.extend( make_attribute(key, value) for key, value in sorted(kwargs.items())) return node def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id """ operatorsetid = OperatorSetIdProto() operatorsetid.domain = domain operatorsetid.version = version return operatorsetid def make_graph( nodes, # type: Sequence[NodeProto] name, # type: Text inputs, # type: Sequence[ValueInfoProto] outputs, # type: Sequence[ValueInfoProto] initializer=None, # type: Optional[Sequence[TensorProto]] doc_string=None, # type: Optional[Text] value_info=[], # type: Sequence[ValueInfoProto] ): # type: (...) -> GraphProto if initializer is None: initializer = [] if value_info is None: value_info = [] graph = GraphProto() graph.node.extend(nodes) graph.name = name graph.input.extend(inputs) graph.output.extend(outputs) graph.initializer.extend(initializer) graph.value_info.extend(value_info) if doc_string: graph.doc_string = doc_string return graph def make_opsetid(domain, version): # type: (Text, int) -> OperatorSetIdProto opsetid = OperatorSetIdProto() opsetid.domain = domain opsetid.version = version return opsetid def make_model(graph, **kwargs): # type: (GraphProto, **Any) -> ModelProto model = ModelProto() # Touch model.ir_version so it is stored as the version from which it is # generated. model.ir_version = IR_VERSION model.graph.CopyFrom(graph) opset_imports = None # type: Optional[Sequence[OperatorSetIdProto]] opset_imports = kwargs.pop('opset_imports', None) # type: ignore if opset_imports is not None: model.opset_import.extend(opset_imports) else: # Default import imp = model.opset_import.add() imp.version = defs.onnx_opset_version() for k, v in kwargs.items(): # TODO: Does this work with repeated fields? setattr(model, k, v) return model def set_model_props(model, dict_value): # type: (ModelProto, Dict[Text, Text]) -> None del model.metadata_props[:] for (k, v) in dict_value.items(): entry = model.metadata_props.add() entry.key = k entry.value = v # model.metadata_properties.append(entry) def split_complex_to_pairs(ca): # type: (Sequence[np.complex64]) -> Sequence[int] return [(ca[i // 2].real if (i % 2 == 0) else ca[i // 2].imag) for i in range(len(ca) * 2)] def make_tensor( name, # type: Text data_type, # type: int dims, # type: Sequence[int] vals, # type: Any raw=False # type: bool ): # type: (...) -> TensorProto ''' Make a TensorProto with specified arguments. If raw is False, this function will choose the corresponding proto field to store the values based on data_type. If raw is True, use "raw_data" proto field to store the values, and values should be of type bytes in this case. ''' tensor = TensorProto() tensor.data_type = data_type tensor.name = name if data_type == TensorProto.STRING: assert not raw, "Can not use raw_data to store string type" if (data_type == TensorProto.COMPLEX64 or data_type == TensorProto.COMPLEX128): vals = split_complex_to_pairs(vals) if raw: tensor.raw_data = vals else: field = mapping.STORAGE_TENSOR_TYPE_TO_FIELD[ mapping.TENSOR_TYPE_TO_STORAGE_TENSOR_TYPE[data_type]] getattr(tensor, field).extend(vals) tensor.dims.extend(dims) return tensor def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('ascii') - Otherwise, return False """ if isinstance(val, bytes): return val else: try: return val.encode('ascii') except AttributeError: return False def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_string is_iterable = isinstance(value, collections.Iterable) bytes_or_false = _to_bytes_or_false(value) # First, singular cases # float if isinstance(value, float): attr.f = value attr.type = AttributeProto.FLOAT # integer elif isinstance(value, numbers.Integral): attr.i = cast(int, value) attr.type = AttributeProto.INT # string elif bytes_or_false: assert isinstance(bytes_or_false, bytes) attr.s = bytes_or_false attr.type = AttributeProto.STRING elif isinstance(value, TensorProto): attr.t.CopyFrom(value) attr.type = AttributeProto.TENSOR elif isinstance(value, GraphProto): attr.g.CopyFrom(value) attr.type = AttributeProto.GRAPH # third, iterable cases elif is_iterable: byte_array = [_to_bytes_or_false(v) for v in value] if all(isinstance(v, float) for v in value): attr.floats.extend(value) attr.type = AttributeProto.FLOATS elif all(isinstance(v, numbers.Integral) for v in value): # Turn np.int32/64 into Python built-in int. attr.ints.extend(int(v) for v in value) attr.type = AttributeProto.INTS elif all(byte_array): attr.strings.extend(cast(List[bytes], byte_array)) attr.type = AttributeProto.STRINGS elif all(isinstance(v, TensorProto) for v in value): attr.tensors.extend(value) attr.type = AttributeProto.TENSORS elif all(isinstance(v, GraphProto) for v in value): attr.graphs.extend(value) attr.type = AttributeProto.GRAPHS else: raise ValueError( "You passed in an iterable attribute but I cannot figure out " "its applicable type.") else: raise ValueError( 'Value "{}" is not valid attribute data type.'.format(value)) return attr def get_attribute_value(attr): # type: (AttributeProto) -> Any if attr.HasField('f'): return attr.f elif attr.HasField('i'): return attr.i elif attr.HasField('s'): return attr.s elif attr.HasField('t'): return attr.t elif attr.HasField('g'): return attr.g elif len(attr.floats): return list(attr.floats) elif len(attr.ints): return list(attr.ints) elif len(attr.strings): return list(attr.strings) elif len(attr.tensors): return list(attr.tensors) elif len(attr.graphs): return list(attr.graphs) else: raise ValueError("Unsupported ONNX attribute: {}".format(attr)) def make_empty_tensor_value_info(name): # type: (Text) -> ValueInfoProto value_info_proto = ValueInfoProto() value_info_proto.name = name return value_info_proto def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based on the data type and shape.""" value_info_proto = ValueInfoProto() value_info_proto.name = name if doc_string: value_info_proto.doc_string = doc_string tensor_type_proto = value_info_proto.type.tensor_type tensor_type_proto.elem_type = elem_type tensor_shape_proto = tensor_type_proto.shape if shape is not None: # You might think this is a no-op (extending a normal Python # list by [] certainly is), but protobuf lists work a little # differently; if a field is never set, it is omitted from the # resulting protobuf; a list that is explicitly set to be # empty will get an (empty) entry in the protobuf. This # difference is visible to our consumers, so make sure we emit # an empty shape! tensor_shape_proto.dim.extend([]) if shape_denotation: if len(shape_denotation) != len(shape): raise ValueError( 'Invalid shape_denotation. ' 'Must be of the same length as shape.') for i, d in enumerate(shape): dim = tensor_shape_proto.dim.add() if d is None: pass elif isinstance(d, integer_types): dim.dim_value = d elif isinstance(d, text_type): dim.dim_param = d else: raise ValueError( 'Invalid item in shape: {}. ' 'Needs to of integer_types or text_type.'.format(d)) if shape_denotation: dim.denotation = shape_denotation[i] return value_info_proto def _sanitize_str(s): # type: (Union[Text, bytes]) -> Text if isinstance(s, text_type): sanitized = s elif isinstance(s, binary_type): sanitized = s.decode('ascii', errors='ignore') else: sanitized = str(s) if len(sanitized) < 64: return sanitized else: return sanitized[:64] + '...<+len=%d>' % (len(sanitized) - 64) def printable_attribute(attr, subgraphs=False): # type: (AttributeProto, bool) -> Union[Text, Tuple[Text, List[GraphProto]]] content = [] content.append(attr.name) content.append("=") def str_float(f): # type: (float) -> Text # NB: Different Python versions print different numbers of trailing # decimals, specifying this explicitly keeps it consistent for all # versions return '{:.15g}'.format(f) def str_int(i): # type: (int) -> Text # NB: In Python 2, longs will repr() as '2L', which is ugly and # unnecessary. Explicitly format it to keep it consistent. return '{:d}'.format(i) def str_str(s): # type: (Text) -> Text return repr(s) _T = TypeVar('_T') # noqa def str_list(str_elem, xs): # type: (Callable[[_T], Text], Sequence[_T]) -> Text return '[' + ', '.join(map(str_elem, xs)) + ']' # for now, this logic should continue to work as long as we are running on a proto3 # implementation. If/when we switch to proto3, we will need to use attr.type # To support printing subgraphs, if we find a graph attribute, print out # its name here and pass the graph itself up to the caller for later # printing. graphs = [] if attr.HasField("f"): content.append(str_float(attr.f)) elif attr.HasField("i"): content.append(str_int(attr.i)) elif attr.HasField("s"): # TODO: Bit nervous about Python 2 / Python 3 determinism implications content.append(repr(_sanitize_str(attr.s))) elif attr.HasField("t"): if len(attr.t.dims) > 0: content.append("<Tensor>") else: # special case to print scalars field = STORAGE_TENSOR_TYPE_TO_FIELD[attr.t.data_type] content.append('<Scalar Tensor {}>'.format(str(getattr(attr.t, field)))) elif attr.HasField("g"): content.append("<graph {}>".format(attr.g.name)) graphs.append(attr.g) elif attr.floats: content.append(str_list(str_float, attr.floats)) elif attr.ints: content.append(str_list(str_int, attr.ints)) elif attr.strings: # TODO: Bit nervous about Python 2 / Python 3 determinism implications content.append(str(list(map(_sanitize_str, attr.strings)))) elif attr.tensors: content.append("[<Tensor>, ...]") elif attr.graphs: content.append('[') for i, g in enumerate(attr.graphs): comma = ',' if i != len(attr.graphs) - 1 else '' content.append('<graph {}>{}'.format(g.name, comma)) content.append(']') graphs.extend(attr.graphs) else: content.append("<Unknown>") if subgraphs: return ' '.join(content), graphs else: return ' '.join(content) def printable_dim(dim): # type: (TensorShapeProto.Dimension) -> Text which = dim.WhichOneof('value') assert which is not None return str(getattr(dim, which)) def printable_type(t): # type: (TypeProto) -> Text if t.WhichOneof('value') == "tensor_type": s = TensorProto.DataType.Name(t.tensor_type.elem_type) if t.tensor_type.HasField('shape'): if len(t.tensor_type.shape.dim): s += str(', ' + 'x'.join(map(printable_dim, t.tensor_type.shape.dim))) else: s += str(', scalar') return s if t.WhichOneof('value') is None: return "" return 'Unknown type {}'.format(t.WhichOneof('value')) def printable_value_info(v): # type: (ValueInfoProto) -> Text s = '%{}'.format(v.name) if v.type: s = '{}[{}]'.format(s, printable_type(v.type)) return s def printable_node(node, prefix='', subgraphs=False): # type: (NodeProto, Text, bool) -> Union[Text, Tuple[Text, List[GraphProto]]] content = [] if len(node.output): content.append( ', '.join(['%{}'.format(name) for name in node.output])) content.append('=') # To deal with nested graphs graphs = [] # type: List[GraphProto] printed_attrs = [] for attr in node.attribute: if subgraphs: printed_attr, gs = printable_attribute(attr, subgraphs) assert isinstance(gs, list) graphs.extend(gs) printed_attrs.append(printed_attr) else: printed = printable_attribute(attr) assert isinstance(printed, Text) printed_attrs.append(printed) printed_attributes = ', '.join(sorted(printed_attrs)) printed_inputs = ', '.join(['%{}'.format(name) for name in node.input]) if node.attribute: content.append("{}[{}]({})".format(node.op_type, printed_attributes, printed_inputs)) else: content.append("{}({})".format(node.op_type, printed_inputs)) if subgraphs: return prefix + ' '.join(content), graphs else: return prefix + ' '.join(content) def printable_graph(graph, prefix=''): # type: (GraphProto, Text) -> Text content = [] indent = prefix + ' ' # header header = ['graph', graph.name] initialized = {t.name for t in graph.initializer} if len(graph.input): header.append("(") in_strs = [] init_strs = [] for inp in graph.input: if inp.name not in initialized: in_strs.append(printable_value_info(inp)) else: init_strs.append(printable_value_info(inp)) if in_strs: content.append(prefix + ' '.join(header)) header = [] for line in in_strs: content.append(prefix + ' ' + line) header.append(")") if init_strs: header.append("initializers (") content.append(prefix + ' '.join(header)) header = [] for line in init_strs: content.append(prefix + ' ' + line) header.append(")") header.append('{') content.append(prefix + ' '.join(header)) graphs = [] # type: List[GraphProto] # body for node in graph.node: pn, gs = printable_node(node, indent, subgraphs=True) assert isinstance(gs, list) content.append(pn) graphs.extend(gs) # tail tail = ['return'] if len(graph.output): tail.append( ', '.join(['%{}'.format(out.name) for out in graph.output])) content.append(indent + ' '.join(tail)) # closing bracket content.append(prefix + '}') for g in graphs: content.append('\n' + printable_graph(g)) return '\n'.join(content) def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': proto.ClearField(descriptor.name) elif descriptor.type == descriptor.TYPE_MESSAGE: if descriptor.label == descriptor.LABEL_REPEATED: for x in getattr(proto, descriptor.name): strip_doc_string(x) elif proto.HasField(descriptor.name): strip_doc_string(getattr(proto, descriptor.name))
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals """ Boot session from cache or build Session bootstraps info needed by common client side activities including permission, homepage, default variables, system defaults etc """ import frappe, json from frappe import _ import frappe.utils from frappe.utils import cint, cstr import frappe.model.meta import frappe.defaults import frappe.translate from frappe.utils.change_log import get_change_log import redis import os from urllib import unquote @frappe.whitelist() def clear(user=None): frappe.local.session_obj.update(force=True) frappe.local.db.commit() clear_cache(frappe.session.user) clear_global_cache() frappe.response['message'] = _("Cache Cleared") def clear_cache(user=None): cache = frappe.cache() groups = ("bootinfo", "user_recent", "user_roles", "user_doc", "lang", "defaults", "user_permissions", "roles", "home_page") if user: for name in groups: cache.hdel(name, user) cache.delete_keys("user:" + user) frappe.defaults.clear_cache(user) else: for name in groups: cache.delete_key(name, user) clear_global_cache() frappe.defaults.clear_cache() def clear_global_cache(): frappe.model.meta.clear_cache() frappe.cache().delete_value(["app_hooks", "installed_apps", "app_modules", "module_app", "time_zone", "notification_config"]) frappe.setup_module_map() def clear_sessions(user=None, keep_current=False): if not user: user = frappe.session.user for sid in frappe.db.sql("""select sid from tabSessions where user=%s and device=%s""", (user, frappe.session.data.device or "desktop")): if keep_current and frappe.session.sid==sid[0]: continue else: delete_session(sid[0]) def delete_session(sid=None, user=None): if not user: user = hasattr(frappe.local, "session") and frappe.session.user or "Guest" frappe.cache().hdel("session", sid) frappe.cache().hdel("last_db_session_update", sid) frappe.db.sql("""delete from tabSessions where sid=%s""", sid) frappe.db.commit() def clear_all_sessions(): """This effectively logs out all users""" frappe.only_for("Administrator") for sid in frappe.db.sql_list("select sid from `tabSessions`"): delete_session(sid) def clear_expired_sessions(): """This function is meant to be called from scheduler""" for device in ("desktop", "mobile"): for sid in frappe.db.sql_list("""select sid from tabSessions where TIMEDIFF(NOW(), lastupdate) > TIME(%s) and device = %s""", (get_expiry_period(device), device)): delete_session(sid) def get(): """get session boot info""" from frappe.desk.notifications import \ get_notification_info_for_boot, get_notifications from frappe.boot import get_bootinfo bootinfo = None if not getattr(frappe.conf,'disable_session_cache', None): # check if cache exists bootinfo = frappe.cache().hget("bootinfo", frappe.session.user) if bootinfo: bootinfo['from_cache'] = 1 bootinfo["notification_info"].update(get_notifications()) bootinfo["user"]["recent"] = json.dumps(\ frappe.cache().hget("user_recent", frappe.session.user)) if not bootinfo: # if not create it bootinfo = get_bootinfo() bootinfo["notification_info"] = get_notification_info_for_boot() frappe.cache().hset("bootinfo", frappe.session.user, bootinfo) try: frappe.cache().ping() except redis.exceptions.ConnectionError: message = _("Redis cache server not running. Please contact Administrator / Tech support") if 'messages' in bootinfo: bootinfo['messages'].append(message) else: bootinfo['messages'] = [message] # check only when clear cache is done, and don't cache this if frappe.local.request: bootinfo["change_log"] = get_change_log() bootinfo["metadata_version"] = frappe.cache().get_value("metadata_version") if not bootinfo["metadata_version"]: bootinfo["metadata_version"] = frappe.reset_metadata_version() for hook in frappe.get_hooks("extend_bootinfo"): frappe.get_attr(hook)(bootinfo=bootinfo) bootinfo["lang"] = frappe.translate.get_user_lang() bootinfo["dev_server"] = os.environ.get('DEV_SERVER', False) bootinfo["disable_async"] = frappe.conf.disable_async return bootinfo def get_csrf_token(): if not frappe.local.session.data.csrf_token: generate_csrf_token() return frappe.local.session.data.csrf_token def generate_csrf_token(): frappe.local.session.data.csrf_token = frappe.generate_hash() frappe.local.session_obj.update(force=True) class Session: def __init__(self, user, resume=False, full_name=None, user_type=None): self.sid = cstr(frappe.form_dict.get('sid') or unquote(frappe.request.cookies.get('sid', 'Guest'))) self.user = user self.device = frappe.form_dict.get("device") or "desktop" self.user_type = user_type self.full_name = full_name self.data = frappe._dict({'data': frappe._dict({})}) self.time_diff = None # set local session frappe.local.session = self.data if resume: self.resume() else: if self.user: self.start() def start(self): """start a new session""" # generate sid if self.user=='Guest': sid = 'Guest' else: sid = frappe.generate_hash() self.data.user = self.user self.data.sid = sid self.data.data.user = self.user self.data.data.session_ip = frappe.local.request_ip if self.user != "Guest": self.data.data.update({ "last_updated": frappe.utils.now(), "session_expiry": get_expiry_period(self.device), "full_name": self.full_name, "user_type": self.user_type, "device": self.device, "session_country": get_geo_ip_country(frappe.local.request_ip) if frappe.local.request_ip else None, }) # insert session if self.user!="Guest": self.insert_session_record() # update user frappe.db.sql("""UPDATE tabUser SET last_login = %s, last_ip = %s where name=%s""", (frappe.utils.now(), frappe.local.request_ip, self.data['user'])) frappe.db.commit() def insert_session_record(self): frappe.db.sql("""insert into tabSessions (sessiondata, user, lastupdate, sid, status, device) values (%s , %s, NOW(), %s, 'Active', %s)""", (str(self.data['data']), self.data['user'], self.data['sid'], self.device)) # also add to memcache frappe.cache().hset("session", self.data.sid, self.data) def resume(self): """non-login request: load a session""" import frappe data = self.get_session_record() if data: # set language self.data.update({'data': data, 'user':data.user, 'sid': self.sid}) self.user = data.user self.device = data.device else: self.start_as_guest() if self.sid != "Guest": frappe.local.user_lang = frappe.translate.get_user_lang(self.data.user) frappe.local.lang = frappe.local.user_lang def get_session_record(self): """get session record, or return the standard Guest Record""" from frappe.auth import clear_cookies r = self.get_session_data() if not r: frappe.response["session_expired"] = 1 clear_cookies() self.sid = "Guest" r = self.get_session_data() return r def get_session_data(self): if self.sid=="Guest": return frappe._dict({"user":"Guest"}) data = self.get_session_data_from_cache() if not data: data = self.get_session_data_from_db() return data def get_session_data_from_cache(self): data = frappe.cache().hget("session", self.sid) if data: data = frappe._dict(data) session_data = data.get("data", {}) # set user for correct timezone self.time_diff = frappe.utils.time_diff_in_seconds(frappe.utils.now(), session_data.get("last_updated")) expiry = self.get_expiry_in_seconds(session_data.get("session_expiry")) if self.time_diff > expiry: self.delete_session() data = None return data and data.data def get_session_data_from_db(self): rec = frappe.db.sql("""select user, sessiondata from tabSessions where sid=%s and TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid, get_expiry_period(self.device))) if rec: data = frappe._dict(eval(rec and rec[0][1] or '{}')) data.user = rec[0][0] else: self.delete_session() data = None return data def get_expiry_in_seconds(self, expiry): if not expiry: return 3600 parts = expiry.split(":") return (cint(parts[0]) * 3600) + (cint(parts[1]) * 60) + cint(parts[2]) def delete_session(self): delete_session(self.sid, user=self.user) def start_as_guest(self): """all guests share the same 'Guest' session""" self.user = "Guest" self.start() def update(self, force=False): """extend session expiry""" if (frappe.session['user'] == "Guest" or frappe.form_dict.cmd=="logout"): return now = frappe.utils.now() self.data['data']['last_updated'] = now self.data['data']['lang'] = unicode(frappe.lang) # update session in db last_updated = frappe.cache().hget("last_db_session_update", self.sid) time_diff = frappe.utils.time_diff_in_seconds(now, last_updated) if last_updated else None # database persistence is secondary, don't update it too often updated_in_db = False if force or (time_diff==None) or (time_diff > 600): frappe.db.sql("""update tabSessions set sessiondata=%s, lastupdate=NOW() where sid=%s""" , (str(self.data['data']), self.data['sid'])) frappe.cache().hset("last_db_session_update", self.sid, now) updated_in_db = True # set in memcache frappe.cache().hset("session", self.sid, self.data) return updated_in_db def get_expiry_period(device="desktop"): if device=="mobile": key = "session_expiry_mobile" default = "720:00:00" else: key = "session_expiry" default = "06:00:00" exp_sec = frappe.defaults.get_global_default(key) or default # incase seconds is missing if len(exp_sec.split(':')) == 2: exp_sec = exp_sec + ':00' return exp_sec def get_geo_from_ip(ip_addr): try: from geoip import geolite2 return geolite2.lookup(ip_addr) except ImportError: return except ValueError: return def get_geo_ip_country(ip_addr): match = get_geo_from_ip(ip_addr) if match: return match.country
# -*- coding: utf-8 -*- from typing import ( Optional, Tuple ) from PyQt5.QtCore import ( QRectF, QPointF ) from PyQt5.QtGui import ( QPen, QBrush, QPainter ) from PyQt5.QtWidgets import ( QStyleOptionGraphicsItem, QWidget ) from cadnano import util from cadnano.views.abstractitems import AbstractTool from cadnano.views.pathview import pathstyles as styles from cadnano.gui.palette import ( getPenObj, getNoBrush ) from cadnano.views.pathview import ( PathToolManagerT, PathVirtualHelixItemT ) from cadnano.cntypes import ( DocT, WindowT, Vec2T ) _BW: int = styles.PATH_BASE_WIDTH _TOOL_RECT: QRectF = QRectF(0, 0, _BW, _BW) # protected not private _RECT: QRectF = QRectF(-styles.PATH_BASE_HL_STROKE_WIDTH, -styles.PATH_BASE_HL_STROKE_WIDTH, _BW + 2 * styles.PATH_BASE_HL_STROKE_WIDTH, _BW + 2 * styles.PATH_BASE_HL_STROKE_WIDTH) _PEN: QPen = getPenObj(styles.RED_STROKE, styles.PATH_BASE_HL_STROKE_WIDTH) _BRUSH: QBrush = getNoBrush() class AbstractPathTool(AbstractTool): """Abstract base class to be subclassed by all other pathview tools. Attributes: manager: Description """ def __init__(self, manager: PathToolManagerT): """ Args: manager: Description """ super(AbstractPathTool, self).__init__(None) self.manager: PathToolManagerT = manager self._window: DocT = manager.window self._active: bool = False self._last_location = None self._rect: QRectF = _RECT self._pen: QPen = _PEN self.hide() ######################## Drawing ####################################### def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget = None): """ Args: painter: Description option: Description widget: Default is ``None`` """ painter.setPen(self._pen) painter.setBrush(_BRUSH) painter.drawRect(_TOOL_RECT) def boundingRect(self) -> QRectF: """Returns: bounding rectangle """ return self._rect ######################### Positioning and Parenting #################### def updateLocation(self, virtual_helix_item: PathVirtualHelixItemT, scene_pos: QPointF, *args): """Takes care of caching the location so that a tool switch outside the context of an event will know where to position the new tool and snaps self's pos to the upper left hand corner of the base the user is mousing over. Args: virtual_helix_item: PathVirtualHelixItem scene_pos: point in the scene *args: DESCRIPTION """ if virtual_helix_item: if self.parentObject() != virtual_helix_item: self.setParentItem(virtual_helix_item) self._last_location = (virtual_helix_item, scene_pos) pos_item = virtual_helix_item.mapFromScene(scene_pos) pos = self.helixPos(pos_item) if pos is not None: if pos != self.pos(): self.setPos(pos) self.update(self.boundingRect()) else: self._last_location = None if self.isVisible(): self.hide() # end def def lastLocation(self) -> Optional[Tuple[PathVirtualHelixItemT, QPointF]]: """A tool's last_location consists of a :class`PathVirtualHelixItem` and a scene pos (:class:`QPoint`) representing the last known location of the mouse. It can be used to provide visual continuity when switching tools. When the new tool is selected, this method will be invoked by calling `updateLocation(*old_tool.lastLocation())`. Returns: location: ``(virtual_helix_item, QPointF)`` representing the last known location of the mouse for purposes of positioning the graphic of a new tool on switching tools (the tool will have called on it) """ return self._last_location def setActive(self, will_be_active: bool, old_tool=None): """ Called by PathToolManager.setActiveTool when the tool becomes active. Used, for example, to show/hide tool-specific ui elements. Args: will_be_active (TYPE): Description old_tool (None, optional): Description """ if self._active and not will_be_active: self.deactivate() self._active = will_be_active def deactivate(self): """Summary Returns: TYPE: Description """ self.hide() def isActive(self) -> bool: """Returns isActive """ return self._active def widgetClicked(self): """Called every time a widget representing self gets clicked, not just when changing tools. """ ####################### Coordinate Utilities ########################### def baseAtPoint(self, virtual_helix_item: PathVirtualHelixItemT, pt: QPointF) -> Tuple[bool, int, int]: """Returns the ``(is_fwd, base_idx, strand_idx)`` corresponding to pt in virtual_helix_item. Args: virtual_helix_item: :class:`PathVirtualHelixItem` pt: Point on helix """ x, strand_idx = self.helixIndex(pt) is_fwd = False if util.clamp(strand_idx, 0, 1) else True return (is_fwd, x, strand_idx) def helixIndex(self, point: QPointF) -> Vec2T: """Returns the (row, col) of the base which point lies within. Returns: point (tuple) in virtual_helix_item coordinates Args: point (TYPE): Description """ x = int(int(point.x()) / _BW) y = int(int(point.y()) / _BW) return (x, y) # end def def helixPos(self, point): """ Snaps a point to the upper left corner of the base it is within. point is in virtual_helix_item coordinates Args: point (TYPE): Description """ col = int(int(point.x()) / _BW) row = int(int(point.y()) / _BW) # Doesn't know numBases, can't check if point is too far right if col < 0 or row < 0 or row > 1: return None return QPointF(col * _BW, row * _BW) # end def def hoverLeaveEvent(self, event): """ flag is for the case where an item in the path also needs to implement the hover method Args: event (TYPE): Description """ self.hide() # end def # end class
import unittest from unittest import mock import collections from freezegun import freeze_time import ogre.config from ogre.pdf.canvas import Canvas from ogre.pdf import HAlign, VAlign from ogre.config import Config from ogre.report.template import Template, BlankPage, FrontSide, RearSide, Watermark, chunked Chunk = collections.namedtuple('Chunk', 'num count data') class TestTemplate(unittest.TestCase): @mock.patch('ogre.report.template.Watermark') @mock.patch('ogre.report.template.RearSide') @mock.patch('ogre.report.template.FrontSide') def test_should_render_only_front_side_by_default(self, mock_front, mock_rear, mock_watermark): template = Template(Canvas()) template.render(mock.Mock(), {mock.Mock(): mock.Mock()}) self.assertTrue(mock_front.return_value.render.called) self.assertFalse(mock_rear.return_value.render.called) @mock.patch('ogre.report.template.config') @mock.patch('ogre.report.template.RearSide') @mock.patch('ogre.report.template.FrontSide') def test_should_render_front_and_back_side(self, mock_front, mock_rear, mock_config): mock_config.return_value.get = mock.Mock(return_value='true') template = Template(Canvas()) template.render(mock.Mock(), {mock.Mock(): mock.Mock()}) mock_front.return_value.render.assert_called_once_with(mock.ANY, mock.ANY, 1) mock_rear.return_value.render.assert_called_once() @mock.patch('ogre.report.template.config') @mock.patch('ogre.report.template.BlankPage') @mock.patch('ogre.report.template.RearSide') @mock.patch('ogre.report.template.FrontSide') def test_should_render_blank_page_when_odd_number_of_chunks(self, mock_front, mock_rear, mock_blank_page, mock_config): mock_config.return_value.get = mock.Mock(return_value='false') template = Template(Canvas()) template.render(mock.Mock(), {mock.Mock(): mock.Mock()}) mock_blank_page.return_value.render.assert_called_once() @mock.patch('ogre.report.template.config') @mock.patch('ogre.report.template.BlankPage') @mock.patch('ogre.report.template.RearSide') @mock.patch('ogre.report.template.FrontSide') @mock.patch('ogre.report.template.chunked') def test_should_not_render_blank_page_when_even_number_of_chunks(self, mock_chunked, mock_front, mock_rear, mock_blank_page, mock_config): mock_chunked.return_value = ['one', 'two'] mock_config.return_value.get = mock.Mock(return_value='false') template = Template(Canvas()) template.render(mock.Mock(), {mock.Mock(): mock.Mock()}) mock_blank_page.return_value.render.assert_not_called() @mock.patch('ogre.report.template.config') @mock.patch('ogre.report.template.BlankPage') @mock.patch('ogre.report.template.RearSide') @mock.patch('ogre.report.template.FrontSide') def test_should_not_render_blank_page_in_rear_page_mode(self, mock_front, mock_rear, mock_blank_page, mock_config): mock_config.return_value.get = mock.Mock(return_value='true') template = Template(Canvas()) template.render(mock.Mock(), {mock.Mock(): mock.Mock()}) mock_blank_page.return_value.render.assert_not_called() class TestBlankPage(unittest.TestCase): @mock.patch('ogre.pdf.canvas.Canvas') def test_should_add_page(self, mock_canvas): BlankPage(mock_canvas, mock.Mock()).render(0) mock_canvas.add_page.assert_called_once() @mock.patch('ogre.pdf.canvas.Canvas') def test_should_render_watermark(self, mock_canvas): mock_watermark = mock.Mock() BlankPage(mock_canvas, mock_watermark).render(0) mock_watermark.render.assert_called_once() @mock.patch('ogre.pdf.canvas.Canvas') def test_should_render_footer(self, mock_canvas): BlankPage(mock_canvas, mock.Mock()).render(555) mock_canvas.text.assert_called_once_with('Strona 555', 0, mock.ANY, mock.ANY, halign=HAlign.CENTER) class TestFrontSide(unittest.TestCase): def setUp(self): self.mock_debtor = mock.Mock() self.mock_debtor.name = 'Jan Kowalski' self.mock_debtor.identity.name = 'PESEL' self.mock_debtor.identity.value = '12345678901' def test_should_compute_number_of_rows(self): self.assertEqual(23, FrontSide(Canvas(), mock.Mock()).num_rows) @mock.patch('ogre.pdf.canvas.Canvas.add_page') def test_should_add_page_if_document_has_no_previous_pages(self, mock_add_page): FrontSide(Canvas(), mock.Mock()).render(self.mock_debtor, Chunk(1, 1, {}), 0) mock_add_page.assert_called_once_with() @mock.patch('ogre.pdf.canvas.Canvas.add_page') def test_should_add_page_if_document_has_previous_pages(self, mock_add_page): canvas = Canvas() canvas.add_page() FrontSide(canvas, mock.Mock()).render(self.mock_debtor, Chunk(1, 1, {}), 0) self.assertEqual(mock_add_page.call_count, 2) def test_should_render_watermark(self): mock_watermark = mock.Mock() FrontSide(Canvas(), mock_watermark).render(self.mock_debtor, Chunk(1, 1, {}), 0) mock_watermark.render.assert_called_once_with(mock.ANY) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_render_footer_on_front_side(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 0.0 FrontSide(Canvas(), mock.Mock()).render(self.mock_debtor, Chunk(1, 1, {}), 555) mock_canvas.return_value.beginText.return_value.assert_has_calls([ mock.call.textLine('Strona 555') ]) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_render_footer_on_rear_side(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 0.0 RearSide(Canvas(), mock.Mock()).render(777) mock_canvas.return_value.beginText.return_value.assert_has_calls([ mock.call.textLine('Strona 777') ]) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_render_table(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 120 FrontSide(Canvas(), mock.Mock()).render(self.mock_debtor, Chunk(1, 1, {}), 0) # body mock_canvas.return_value.assert_has_calls([ mock.call.setLineCap(2), mock.call.setLineWidth(0.2834645669291339), mock.call.grid([49.60629921259835, 162.9921259842519, 233.85826771653538, 318.89763779527556, 389.763779527559, 474.8031496062992, 545.6692913385826], [758.2677165354331, 727.0866141732284, 695.9055118110236, 664.7244094488188, 633.5433070866142, 602.3622047244095, 571.1811023622047, 540.0, 508.81889763779526, 477.6377952755905, 446.4566929133858, 415.27559055118104, 384.09448818897636, 352.9133858267716, 321.7322834645669, 290.55118110236214, 259.37007874015745, 228.1889763779527, 197.00787401574797, 165.82677165354323, 134.64566929133852, 103.46456692913371, 72.28346456692898, 41.10236220472425])]) # header mock_canvas.return_value.assert_has_calls([ mock.call.setLineWidth(0.8503937007874016), mock.call.grid([49.60629921259835, 162.9921259842519, 233.85826771653538, 318.89763779527556, 389.763779527559, 474.8031496062992, 545.6692913385826], [800.7874015748032, 758.2677165354331]), ]) # column titles mock_canvas.return_value.beginText.return_value.textLine.assert_has_calls([ mock.call('Bank'), mock.call('Data'), mock.call('z\u0142o\u017cenia'), mock.call('zapytania'), mock.call('Podpis'), mock.call('sk\u0142adaj\u0105cego'), mock.call('zapytanie'), mock.call('Data'), mock.call('odbioru'), mock.call('odpowiedzi'), mock.call('Podpis'), mock.call('odbieraj\u0105cego'), mock.call('odpowied\u017a'), mock.call('Rodzaj'), mock.call('odpowiedzi') ]) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_render_title(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 120.0 FrontSide(Canvas(), mock.Mock()).render(self.mock_debtor, Chunk(1, 1, {}), 0) mock_canvas.return_value.beginText.return_value.assert_has_calls([ mock.call.setFont('FreeSansBold', 12.755905511811026, 15.30708661417323), mock.call.setTextRenderMode(0), mock.call.setCharSpace(0.0), mock.call.setWordSpace(0.0), mock.call.setRise(0.0), mock.call.textLine('Ognivo: '), mock.call.setFont('FreeSans', 12.755905511811026, 15.30708661417323), mock.call.setTextRenderMode(0), mock.call.setCharSpace(0.0), mock.call.setWordSpace(0.0), mock.call.setRise(0.0), mock.call.textLine('Jan Kowalski'), mock.call.setFont('FreeSans', 12.755905511811026, 15.30708661417323), mock.call.setTextRenderMode(0), mock.call.setCharSpace(0.0), mock.call.setWordSpace(0.0), mock.call.setRise(0.0), mock.call.getY(), mock.call.setTextOrigin(mock.ANY, mock.ANY), mock.call.textLine('PESEL # 12345678901') ]) @mock.patch('reportlab.pdfgen.canvas.Canvas') @mock.patch('ogre.report.template.Table') def test_should_render_replies_sorted_by_name_of_bank(self, mock_table, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 0.0 bank1 = mock.Mock() bank1.code = '00123' bank1.prefix = '001' bank1.name = 'Lorem Bank' bank2 = mock.Mock() bank2.code = '30211' bank2.prefix = '302' bank2.name = 'Dolor Bank' reply1 = mock.Mock() reply1.date_string = '1970-01-01' reply1.time_string = None reply1.has_account = True reply2 = mock.Mock() reply2.date_string = '1980-01-01' reply2.time_string = None reply2.has_account = False replies = Chunk(1, 1, { bank1: reply1, bank2: reply2, }) mock_table.return_value.width = 175 mock_table.return_value.x = 0 FrontSide(Canvas(), mock.Mock()).render(self.mock_debtor, replies, 0) mock_table.return_value.assert_has_calls([ mock.call.cell(0, 0, 'Dolor Bank'), mock.call.cell(0, 0, '302', HAlign.RIGHT, VAlign.BOTTOM), mock.call.cell(3, 0, '1980-01-01', HAlign.CENTER, VAlign.MIDDLE), mock.call.cell(5, 0, 'NIE', HAlign.CENTER, VAlign.MIDDLE), mock.call.cell(0, 1, 'Lorem Bank'), mock.call.cell(0, 1, '001', HAlign.RIGHT, VAlign.BOTTOM), mock.call.cell(3, 1, '1970-01-01', HAlign.CENTER, VAlign.MIDDLE), mock.call.cell(5, 1, 'TAK', HAlign.CENTER, VAlign.MIDDLE) ]) @mock.patch('ogre.report.template.config') def test_should_not_show_time_by_default(self, mock_config): mock_config.return_value.get = mock.Mock(return_value=None) front_side = FrontSide(mock.Mock(), mock.Mock()) self.assertFalse(front_side._should_show_time()) @mock.patch('ogre.report.template.config') def test_should_not_show_time_explicit(self, mock_config): mock_config.return_value.get = mock.Mock(return_value='fAlSe') front_side = FrontSide(mock.Mock(), mock.Mock()) self.assertFalse(front_side._should_show_time()) @mock.patch('ogre.report.template.config') def test_should_show_time(self, mock_config): mock_config.return_value.get = mock.Mock(return_value='tRUe') front_side = FrontSide(mock.Mock(), mock.Mock()) self.assertTrue(front_side._should_show_time()) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_shorten_long_name_and_add_ellipsis(self, mock_canvas): it = iter(range(900, 300, -7)) def stringWidth(text, *args): if text.startswith('PESEL'): return 134 elif text.startswith('Ognivo'): return next(it) return 0 mock_canvas.return_value.stringWidth.side_effect = stringWidth mock_debtor = mock.Mock() mock_debtor.name = 'lorem ipsum dolor sit amet ' * 5 mock_debtor.identity.name = 'PESEL' mock_debtor.identity.value = '12345678901' FrontSide(Canvas(), mock.Mock()).render(mock_debtor, Chunk(1, 1, {}), 0) mock_canvas.return_value.assert_has_calls([ mock.call.beginText().textLine('lorem ipsum dolor sit amet lorem ipsum dolor sit amet lore\u2026') ], any_order=True) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_call_chunk_asdict(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = -999.0 mock_chunk = mock.Mock() mock_chunk.count = 2 mock_chunk.num = 1 mock_chunk.data = {} mock_chunk._asdict.return_value = {'count': 2, 'num': 1, 'data': {}} mock_debtor = mock.Mock() mock_debtor.name = 'Jan Kowalski' FrontSide(Canvas(), mock.Mock()).render(mock_debtor, mock_chunk, 0) mock_chunk._asdict.assert_called() class TestRearSide(unittest.TestCase): @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_not_add_new_page_before_rendering_first_page(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 0.0 RearSide(Canvas(), mock.Mock()).render(0) self.assertNotIn(mock.call.showPage(), mock_canvas.return_value.mock_calls) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_add_new_page_before_rendering(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 0.0 canvas = Canvas() canvas.add_page() RearSide(canvas, mock.Mock()).render(0) mock_canvas.return_value.assert_has_calls([ mock.call.showPage(), mock.call.setStrokeColor('#000000', 1.0), mock.call.setLineWidth(0.2834645669291339), mock.call.setLineCap(0), mock.call.setLineJoin(0), mock.call.setMiterLimit(28.34645669291339), mock.call.setDash([]), mock.call.setFillColor('#000000', 1.0), mock.call.setStrokeColor('#000000', 1.0), mock.call.setLineWidth(0.2834645669291339), mock.call.setLineCap(0), mock.call.setLineJoin(0), mock.call.setMiterLimit(28.34645669291339), mock.call.setDash([]), mock.call.setStrokeColor('#000000', 1.0), mock.call.setLineWidth(0.2834645669291339), mock.call.setLineCap(0), mock.call.setLineJoin(0), mock.call.setMiterLimit(28.34645669291339), mock.call.setDash([]), mock.call.setFillColor('#000000', 1.0), mock.call.setFillColor('#000000', 1.0), mock.call.setStrokeColor('#000000', 1.0), mock.call.setLineWidth(0.2834645669291339), mock.call.setLineCap(0), mock.call.setLineJoin(0), mock.call.setMiterLimit(28.34645669291339), mock.call.setDash([]), mock.call.setFillColor('#000000', 1.0), mock.call.setLineCap(2), mock.call.setLineWidth(0.2834645669291339), mock.call.grid([49.60629921259835, 162.9921259842519, 233.85826771653538, 318.89763779527556, 389.763779527559, 474.8031496062992, 545.6692913385826], [758.2677165354331, 727.0866141732284, 695.9055118110236, 664.7244094488188, 633.5433070866142, 602.3622047244095, 571.1811023622047, 540.0, 508.81889763779526, 477.6377952755905, 446.4566929133858, 415.27559055118104, 384.09448818897636, 352.9133858267716, 321.7322834645669, 290.55118110236214, 259.37007874015745, 228.1889763779527, 197.00787401574797, 165.82677165354323, 134.64566929133852, 103.46456692913371, 72.28346456692898, 41.10236220472425]) ]) def test_should_compute_number_of_rows(self): self.assertEqual(23, RearSide(Canvas(), mock.Mock()).num_rows) def test_should_render_watermark(self): mock_watermark = mock.Mock() RearSide(Canvas(), mock_watermark).render(0) mock_watermark.render.assert_called_once_with(mock.ANY) @mock.patch('reportlab.pdfgen.canvas.Canvas') def test_should_render_table(self, mock_canvas): mock_canvas.return_value.stringWidth.return_value = 999 RearSide(Canvas(), mock.Mock()).render(0) # body mock_canvas.return_value.assert_has_calls([ mock.call.setLineCap(2), mock.call.setLineWidth(0.2834645669291339), mock.call.grid([49.60629921259835, 162.9921259842519, 233.85826771653538, 318.89763779527556, 389.763779527559, 474.8031496062992, 545.6692913385826], [758.2677165354331, 727.0866141732284, 695.9055118110236, 664.7244094488188, 633.5433070866142, 602.3622047244095, 571.1811023622047, 540.0, 508.81889763779526, 477.6377952755905, 446.4566929133858, 415.27559055118104, 384.09448818897636, 352.9133858267716, 321.7322834645669, 290.55118110236214, 259.37007874015745, 228.1889763779527, 197.00787401574797, 165.82677165354323, 134.64566929133852, 103.46456692913371, 72.28346456692898, 41.10236220472425])]) # header mock_canvas.return_value.assert_has_calls([ mock.call.setLineWidth(0.8503937007874016), mock.call.grid([49.60629921259835, 162.9921259842519, 233.85826771653538, 318.89763779527556, 389.763779527559, 474.8031496062992, 545.6692913385826], [800.7874015748032, 758.2677165354331]), ]) # column titles mock_canvas.return_value.beginText.return_value.textLine.assert_has_calls([ mock.call('Instytucja'), mock.call('Data'), mock.call('z\u0142o\u017cenia'), mock.call('zapytania'), mock.call('Podpis'), mock.call('sk\u0142adaj\u0105cego'), mock.call('zapytanie'), mock.call('Data'), mock.call('z\u0142o\u017cenia'), mock.call('zapytania'), mock.call('Podpis'), mock.call('sk\u0142adaj\u0105cego'), mock.call('zapytanie'), mock.call('Uwagi') ]) @mock.patch('reportlab.pdfgen.canvas.Canvas.beginText') def test_should_render_title(self, mock_obj): RearSide(Canvas(), mock.Mock()).render(0) mock_obj.return_value.assert_has_calls([ mock.call.setFont('FreeSansBold', 9.921259842519685, 11.905511811023622), mock.call.setTextRenderMode(0), mock.call.setCharSpace(0.0), mock.call.setWordSpace(0.0), mock.call.setRise(0.0), mock.call.getY(), mock.call.setTextOrigin(116.65913385826767, mock.ANY), mock.call.textLine('Poszukiwanie maj\u0105tku (art. 36 upea) - ZUS, CEPIK, Starostwo, Geodezja, KW')]) class TestWatermark(unittest.TestCase): def tearDown(self): ogre.config._INSTANCE = None def test_should_not_render_watermark_if_not_configured(self): ogre.config._INSTANCE = Config(collections.defaultdict(dict)) mock_canvas = mock.Mock() watermark = Watermark() watermark.render(mock_canvas) self.assertListEqual([], mock_canvas.mock_calls) def test_should_render_watermark_without_interpolation(self): ogre.config._INSTANCE = Config(collections.defaultdict(dict, **{ 'template': {'watermark': 'lorem ipsum'}})) mock_canvas = mock.Mock() watermark = Watermark() watermark.render(mock_canvas) mock_canvas.assert_has_calls([ mock.call.push_state(), mock.call.set_default_state(), mock.call.text('lorem ipsum', 0, 2, mock.ANY, halign=HAlign.CENTER), mock.call.pop_state()]) @freeze_time('1970-01-01') def test_should_render_watermark_with_date_interpolation(self): ogre.config._INSTANCE = Config(collections.defaultdict(dict, **{ 'template': {'watermark': 'year={year} month={month} day={day}'}})) mock_canvas = mock.Mock() watermark = Watermark() watermark.render(mock_canvas) mock_canvas.assert_has_calls([ mock.call.push_state(), mock.call.set_default_state(), mock.call.text('year=1970 month=1 day=1', 0, 2, mock.ANY, halign=HAlign.CENTER), mock.call.pop_state()]) class TestChunked(unittest.TestCase): def make_items(self, **kwargs): return {Fake(k): v for k, v in kwargs.items()} def test_should_return_empty_generator(self): with self.assertRaises(StopIteration): next(chunked({}, size=100)) def test_should_fit_all_items_into_one_chunk(self): items = self.make_items(first=1, second=2, third=3) chunks = list(chunked(items, 3)) self.assertEqual(1, len(chunks)) self.assertEqual(1, chunks[0].num) self.assertEqual(1, chunks[0].count) self.assertDictEqual(items, chunks[0].data) def test_should_fit_items_into_equally_sized_chunks(self): items = self.make_items(a=1, b=2, c=3, d=4, e=5, f=6) chunks = list(chunked(items, 3)) self.assertEqual(2, len(chunks)) self.assertEqual(1, chunks[0].num) self.assertEqual(2, chunks[0].count) self.assertDictEqual({ Fake(name='a'): 1, Fake(name='b'): 2, Fake(name='c'): 3 }, chunks[0].data) self.assertEqual(2, chunks[1].num) self.assertEqual(2, chunks[1].count) self.assertDictEqual({ Fake(name='d'): 4, Fake(name='e'): 5, Fake(name='f'): 6 }, chunks[1].data) def test_should_fit_items_into_unequally_sized_chunks(self): items = self.make_items(a=1, b=2, c=3, d=4, e=5, f=6, g=7) chunks = list(chunked(items, 2)) self.assertEqual(4, len(chunks)) self.assertEqual(1, chunks[0].num) self.assertEqual(4, chunks[0].count) self.assertDictEqual({ Fake(name='a'): 1, Fake(name='b'): 2 }, chunks[0].data) self.assertEqual(2, chunks[1].num) self.assertEqual(4, chunks[1].count) self.assertDictEqual({ Fake(name='c'): 3, Fake(name='d'): 4 }, chunks[1].data) self.assertEqual(3, chunks[2].num) self.assertEqual(4, chunks[2].count) self.assertDictEqual({ Fake(name='e'): 5, Fake(name='f'): 6 }, chunks[2].data) self.assertEqual(4, chunks[3].num) self.assertEqual(4, chunks[3].count) self.assertDictEqual({ Fake(name='g'): 7, }, chunks[3].data) Fake = collections.namedtuple('Fake', 'name')
from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _, pgettext_lazy from django.utils.timezone import now from oscar.core.utils import get_default_currency from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import AutoSlugField from oscar.apps.partner.exceptions import InvalidStockAdjustment @python_2_unicode_compatible class AbstractPartner(models.Model): """ A fulfillment partner. An individual or company who can fulfil products. E.g. for physical goods, somebody with a warehouse and means of delivery. Creating one or more instances of the Partner model is a required step in setting up an Oscar deployment. Many Oscar deployments will only have one fulfillment partner. """ code = AutoSlugField(_("Code"), max_length=128, unique=True, populate_from='name') name = models.CharField( pgettext_lazy(u"Partner's name", u"Name"), max_length=128, blank=True) #: A partner can have users assigned to it. This is used #: for access modelling in the permission-based dashboard users = models.ManyToManyField( AUTH_USER_MODEL, related_name="partners", blank=True, verbose_name=_("Users")) @property def display_name(self): return self.name or self.code @property def primary_address(self): """ Returns a partners primary address. Usually that will be the headquarters or similar. This is a rudimentary implementation that raises an error if there's more than one address. If you actually want to support multiple addresses, you will likely need to extend PartnerAddress to have some field or flag to base your decision on. """ addresses = self.addresses.all() if len(addresses) == 0: # intentionally using len() to save queries return None elif len(addresses) == 1: return addresses[0] else: raise NotImplementedError( "Oscar's default implementation of primary_address only " "supports one PartnerAddress. You need to override the " "primary_address to look up the right address") def get_address_for_stockrecord(self, stockrecord): """ Stock might be coming from different warehouses. Overriding this function allows selecting the correct PartnerAddress for the record. That can be useful when determining tax. """ return self.primary_address class Meta: abstract = True app_label = 'partner' permissions = (('dashboard_access', 'Can access dashboard'), ) verbose_name = _('Fulfillment partner') verbose_name_plural = _('Fulfillment partners') def __str__(self): return self.display_name @python_2_unicode_compatible class AbstractStockRecord(models.Model): """ A stock record. This records information about a product from a fulfilment partner, such as their SKU, the number they have in stock and price information. Stockrecords are used by 'strategies' to determine availability and pricing information for the customer. """ product = models.ForeignKey( 'catalogue.Product', related_name="stockrecords", verbose_name=_("Product")) partner = models.ForeignKey( 'partner.Partner', verbose_name=_("Partner"), related_name='stockrecords') #: The fulfilment partner will often have their own SKU for a product, #: which we store here. This will sometimes be the same the product's UPC #: but not always. It should be unique per partner. #: See also http://en.wikipedia.org/wiki/Stock-keeping_unit partner_sku = models.CharField(_("Partner SKU"), max_length=128) # Price info: price_currency = models.CharField( _("Currency"), max_length=12, default=get_default_currency) # This is the base price for calculations - tax should be applied by the # appropriate method. We don't store tax here as its calculation is highly # domain-specific. It is NULLable because some items don't have a fixed # price but require a runtime calculation (possible from an external # service). price_excl_tax = models.DecimalField( _("Price (excl. tax)"), decimal_places=2, max_digits=12, blank=True, null=True) #: Retail price for this item. This is simply the recommended price from #: the manufacturer. If this is used, it is for display purposes only. #: This prices is the NOT the price charged to the customer. price_retail = models.DecimalField( _("Price (retail)"), decimal_places=2, max_digits=12, blank=True, null=True) #: Cost price is the price charged by the fulfilment partner. It is not #: used (by default) in any price calculations but is often used in #: reporting so merchants can report on their profit margin. cost_price = models.DecimalField( _("Cost Price"), decimal_places=2, max_digits=12, blank=True, null=True) #: Number of items in stock num_in_stock = models.PositiveIntegerField( _("Number in stock"), blank=True, null=True) #: The amount of stock allocated to orders but not fed back to the master #: stock system. A typical stock update process will set the num_in_stock #: variable to a new value and reset num_allocated to zero num_allocated = models.IntegerField( _("Number allocated"), blank=True, null=True) #: Threshold for low-stock alerts. When stock goes beneath this threshold, #: an alert is triggered so warehouse managers can order more. low_stock_threshold = models.PositiveIntegerField( _("Low Stock Threshold"), blank=True, null=True) # Date information date_created = models.DateTimeField(_("Date created"), auto_now_add=True) date_updated = models.DateTimeField(_("Date updated"), auto_now=True, db_index=True) def __str__(self): msg = u"Partner: %s, product: %s" % ( self.partner.display_name, self.product,) if self.partner_sku: msg = u"%s (%s)" % (msg, self.partner_sku) return msg class Meta: abstract = True app_label = 'partner' unique_together = ('partner', 'partner_sku') verbose_name = _("Stock record") verbose_name_plural = _("Stock records") @property def net_stock_level(self): """ The effective number in stock (eg available to buy). This is correct property to show the customer, not the num_in_stock field as that doesn't account for allocations. This can be negative in some unusual circumstances """ if self.num_in_stock is None: return 0 if self.num_allocated is None: return self.num_in_stock return self.num_in_stock - self.num_allocated # 2-stage stock management model def allocate(self, quantity): """ Record a stock allocation. This normally happens when a product is bought at checkout. When the product is actually shipped, then we 'consume' the allocation. """ if self.num_allocated is None: self.num_allocated = 0 self.num_allocated += quantity self.save() allocate.alters_data = True def is_allocation_consumption_possible(self, quantity): """ Test if a proposed stock consumption is permitted """ return quantity <= min(self.num_allocated, self.num_in_stock) def consume_allocation(self, quantity): """ Consume a previous allocation This is used when an item is shipped. We remove the original allocation and adjust the number in stock accordingly """ if not self.is_allocation_consumption_possible(quantity): raise InvalidStockAdjustment( _('Invalid stock consumption request')) self.num_allocated -= quantity self.num_in_stock -= quantity self.save() consume_allocation.alters_data = True def cancel_allocation(self, quantity): # We ignore requests that request a cancellation of more than the # amount already allocated. self.num_allocated -= min(self.num_allocated, quantity) self.save() cancel_allocation.alters_data = True @property def is_below_threshold(self): if self.low_stock_threshold is None: return False return self.net_stock_level < self.low_stock_threshold @python_2_unicode_compatible class AbstractStockAlert(models.Model): """ A stock alert. E.g. used to notify users when a product is 'back in stock'. """ stockrecord = models.ForeignKey( 'partner.StockRecord', related_name='alerts', verbose_name=_("Stock Record")) threshold = models.PositiveIntegerField(_("Threshold")) OPEN, CLOSED = "Open", "Closed" status_choices = ( (OPEN, _("Open")), (CLOSED, _("Closed")), ) status = models.CharField(_("Status"), max_length=128, default=OPEN, choices=status_choices) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) date_closed = models.DateTimeField(_("Date Closed"), blank=True, null=True) def close(self): self.status = self.CLOSED self.date_closed = now() self.save() close.alters_data = True def __str__(self): return _('<stockalert for "%(stock)s" status %(status)s>') \ % {'stock': self.stockrecord, 'status': self.status} class Meta: abstract = True app_label = 'partner' ordering = ('-date_created',) verbose_name = _('Stock alert') verbose_name_plural = _('Stock alerts')
#!/usr/bin/env python """Module with GRRWorker/GRREnroller implementation.""" import pdb import time import traceback import logging from grr.lib import aff4 from grr.lib import config_lib from grr.lib import flags from grr.lib import flow from grr.lib import queue_manager as queue_manager_lib from grr.lib import rdfvalue # pylint: disable=unused-import from grr.lib import server_stubs # pylint: enable=unused-import from grr.lib import threadpool from grr.lib import utils DEFAULT_WORKER_QUEUE = rdfvalue.RDFURN("W") DEFAULT_ENROLLER_QUEUE = rdfvalue.RDFURN("CA") class GRRWorker(object): """A GRR worker.""" # time to wait before polling when no jobs are currently in the # task scheduler (sec) POLLING_INTERVAL = 2 SHORT_POLLING_INTERVAL = 0.3 SHORT_POLL_TIME = 30 # A class global threadpool to be used for all workers. thread_pool = None # This is a timed cache of locked flows. If this worker encounters a lock # failure on a flow, it will not attempt to grab this flow until the timeout. queued_flows = None def __init__(self, queue=None, threadpool_prefix="grr_threadpool", threadpool_size=None, token=None): """Constructor. Args: queue: The queue we use to fetch new messages from. threadpool_prefix: A name for the thread pool used by this worker. threadpool_size: The number of workers to start in this thread pool. token: The token to use for the worker. Raises: RuntimeError: If the token is not provided. """ self.queue = queue self.queued_flows = utils.TimeBasedCache(max_size=10, max_age=60) if token is None: raise RuntimeError("A valid ACLToken is required.") # Make the thread pool a global so it can be reused for all workers. if GRRWorker.thread_pool is None: if threadpool_size is None: threadpool_size = config_lib.CONFIG["Threadpool.size"] GRRWorker.thread_pool = threadpool.ThreadPool.Factory( threadpool_prefix, min_threads=2, max_threads=threadpool_size) GRRWorker.thread_pool.Start() self.token = token self.last_active = 0 # Well known flows are just instantiated. self.well_known_flows = flow.WellKnownFlow.GetAllWellKnownFlows(token=token) def Run(self): """Event loop.""" try: while 1: processed = self.RunOnce() if processed == 0: if time.time() - self.last_active > self.SHORT_POLL_TIME: interval = self.POLLING_INTERVAL else: interval = self.SHORT_POLLING_INTERVAL time.sleep(interval) else: self.last_active = time.time() except KeyboardInterrupt: logging.info("Caught interrupt, exiting.") self.thread_pool.Join() def RunOnce(self): """Processes one set of messages from Task Scheduler. The worker processes new jobs from the task master. For each job we retrieve the session from the Task Scheduler. Returns: Total number of messages processed by this call. """ now = time.time() queue_manager = queue_manager_lib.QueueManager(token=self.token) # Freezeing the timestamp used by queue manager to query/delete # notifications to avoid possible race conditions. queue_manager.FreezeTimestamp() sessions_available = queue_manager.GetSessionsFromQueue(self.queue) time_to_fetch_messages = time.time() - now # Filter out session ids we already tried to lock but failed. sessions_available = [session for session in sessions_available if session not in self.queued_flows] try: # If we spent too much time processing what we have so far, the # active_sessions list might not be current. We therefore break here so # we can re-fetch a more up to date version of the list, and try again # later. The risk with running with an old active_sessions list is that # another worker could have already processed this message, and when we # try to process it, there is nothing to do - costing us a lot of # processing time. This is a tradeoff between checking the data store # for current information and processing out of date information. processed = self.ProcessMessages( sessions_available, queue_manager, min(time_to_fetch_messages * 100, 300)) return processed # We need to keep going no matter what. except Exception as e: # pylint: disable=broad-except logging.error("Error processing message %s. %s.", e, traceback.format_exc()) if flags.FLAGS.debug: pdb.post_mortem() return 0 def ProcessMessages(self, active_sessions, queue_manager, time_limit=0): """Processes all the flows in the messages. Precondition: All tasks come from the same queue (self.queue). Note that the server actually completes the requests in the flow when receiving the messages from the client. We do not really look at the messages here at all any more - we just work from the completed messages in the flow RDFValue. Args: active_sessions: The list of sessions which had messages received. queue_manager: QueueManager object used to manage notifications, requests and responses. time_limit: If set return as soon as possible after this many seconds. Returns: The number of processed flows. """ now = time.time() processed = 0 for session_id in active_sessions: if session_id not in self.queued_flows: if time_limit and time.time() - now > time_limit: break processed += 1 self.queued_flows.Put(session_id, 1) self.thread_pool.AddTask(target=self._ProcessMessages, args=(rdfvalue.SessionID(session_id), queue_manager.Copy()), name=self.__class__.__name__) return processed def _ProcessMessages(self, session_id, queue_manager): """Does the real work with a single flow.""" flow_obj = None # Take a lease on the flow: try: with aff4.FACTORY.OpenWithLock( session_id, lease_time=config_lib.CONFIG["Worker.flow_lease_time"], blocking=False, token=self.token) as flow_obj: now = time.time() logging.info("Got lock on %s", session_id) # If we get here, we now own the flow, so we can remove the notification # for it from the worker queue. queue_manager.DeleteNotification(session_id) # We still need to take a lock on the well known flow in the datastore, # but we can run a local instance. if session_id in self.well_known_flows: self.well_known_flows[session_id].ProcessRequests( self.thread_pool) else: if not isinstance(flow_obj, flow.GRRFlow): logging.info("%s is not a proper flow object (got %s)", session_id, type(flow_obj)) return with flow_obj.GetRunner() as runner: try: runner.ProcessCompletedRequests(self.thread_pool) # Something went wrong - log it in the flow. except Exception as e: # pylint: disable=broad-except runner.context.state = rdfvalue.Flow.State.ERROR runner.context.backtrace = traceback.format_exc() logging.error("Flow %s: %s", flow_obj, e) return # NOTE: Flow object must be flushed _before_ the runner is # flushed. The flow object must exist in the data store before any # messages are queued to go out, otherwise responses might arrive # with no associated flow. flow_obj.Flush(sync=True) logging.info("Done processing %s: %s sec", session_id, time.time() - now) # Everything went well -> session can be run again. self.queued_flows.ExpireObject(session_id) except aff4.LockError: # Another worker is dealing with this flow right now, we just skip it. return except Exception as e: # pylint: disable=broad-except # Something went wrong when processing this session. In order not to spin # here, we just remove the notification. logging.exception("Error processing session %s: %s", session_id, e) queue_manager.DeleteNotification(session_id) class GRREnroler(GRRWorker): """A GRR enroler. Subclassed here so that log messages arrive from the right class. """
""" These classes are light wrappers around Django's database API that provide convenience functionality and permalink functions for the databrowse app. """ from __future__ import unicode_literals from django.db import models from django.utils import formats from django.utils.text import capfirst from django.utils.encoding import smart_text, force_str, iri_to_uri from django.db.models.query import QuerySet from django.utils.encoding import python_2_unicode_compatible EMPTY_VALUE = '(None)' DISPLAY_SIZE = 100 class EasyModel(object): def __init__(self, site, model): self.site = site self.model = model self.model_list = list(site.registry.keys()) self.verbose_name = model._meta.verbose_name self.verbose_name_plural = model._meta.verbose_name_plural def __repr__(self): return force_str('<EasyModel for %s>' % self.model._meta.object_name) def model_databrowse(self): "Returns the ModelDatabrowse class for this model." return self.site.registry[self.model] def url(self): return '%s%s/%s/' % (self.site.root_url, self.model._meta.app_label, self.model._meta.module_name) def objects(self, **kwargs): return self.get_query_set().filter(**kwargs) def get_query_set(self): easy_qs = self.model._default_manager.get_query_set()._clone(klass=EasyQuerySet) easy_qs._easymodel = self return easy_qs def object_by_pk(self, pk): return EasyInstance(self, self.model._default_manager.get(pk=pk)) def sample_objects(self): for obj in self.model._default_manager.all()[:3]: yield EasyInstance(self, obj) def field(self, name): try: f = self.model._meta.get_field(name) except models.FieldDoesNotExist: return None return EasyField(self, f) def fields(self): return [EasyField(self, f) for f in (self.model._meta.fields + self.model._meta.many_to_many)] class EasyField(object): def __init__(self, easy_model, field): self.model, self.field = easy_model, field def __repr__(self): return force_str('<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def choices(self): for value, label in self.field.choices: yield EasyChoice(self.model, self, value, label) def url(self): if self.field.choices: return '%s%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name) elif self.field.rel: return '%s%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name) class EasyChoice(object): def __init__(self, easy_model, field, value, label): self.model, self.field = easy_model, field self.value, self.label = value, label def __repr__(self): return force_str('<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def url(self): return '%s%s/%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.field.name, iri_to_uri(self.value)) @python_2_unicode_compatible class EasyInstance(object): def __init__(self, easy_model, instance): self.model, self.instance = easy_model, instance def __repr__(self): return force_str('<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val())) def __str__(self): val = smart_text(self.instance) if len(val) > DISPLAY_SIZE: return val[:DISPLAY_SIZE] + '...' return val def pk(self): return self.instance._get_pk_val() def url(self): return '%s%s/%s/objects/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, iri_to_uri(self.pk())) def fields(self): """ Generator that yields EasyInstanceFields for each field in this EasyInstance's model. """ for f in self.model.model._meta.fields + self.model.model._meta.many_to_many: yield EasyInstanceField(self.model, self, f) def related_objects(self): """ Generator that yields dictionaries of all models that have this EasyInstance's model as a ForeignKey or ManyToManyField, along with lists of related objects. """ for rel_object in self.model.model._meta.get_all_related_objects() + self.model.model._meta.get_all_related_many_to_many_objects(): if rel_object.model not in self.model.model_list: continue # Skip models that aren't in the model_list em = EasyModel(self.model.site, rel_object.model) yield { 'model': em, 'related_field': rel_object.field.verbose_name, 'object_list': [EasyInstance(em, i) for i in getattr(self.instance, rel_object.get_accessor_name()).all()], } class EasyInstanceField(object): def __init__(self, easy_model, instance, field): self.model, self.field, self.instance = easy_model, field, instance self.raw_value = getattr(instance.instance, field.name) def __repr__(self): return force_str('<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at the # module level. if self.field.rel: if isinstance(self.field.rel, models.ManyToOneRel): objs = getattr(self.instance.instance, self.field.name) elif isinstance(self.field.rel, models.ManyToManyRel): # ManyToManyRel return list(getattr(self.instance.instance, self.field.name).all()) elif self.field.choices: objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE) elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField): if self.raw_value: if isinstance(self.field, models.DateTimeField): objs = capfirst(formats.date_format(self.raw_value, 'DATETIME_FORMAT')) elif isinstance(self.field, models.TimeField): objs = capfirst(formats.time_format(self.raw_value, 'TIME_FORMAT')) else: objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT')) else: objs = EMPTY_VALUE elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField): objs = {True: 'Yes', False: 'No', None: 'Unknown'}[self.raw_value] else: objs = self.raw_value return [objs] def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) if urls is not None: return zip(self.values(), urls) if self.field.rel: m = EasyModel(self.model.site, self.field.rel.to) if self.field.rel.to in self.model.model_list: lst = [] for value in self.values(): if value is None: continue url = '%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val())) lst.append((smart_text(value), url)) else: lst = [(value, None) for value in self.values()] elif self.field.choices: lst = [] for value in self.values(): url = '%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value)) lst.append((value, url)) elif isinstance(self.field, models.URLField): val = list(self.values())[0] lst = [(val, iri_to_uri(val))] else: lst = [(list(self.values())[0], None)] return lst class EasyQuerySet(QuerySet): """ When creating (or cloning to) an `EasyQuerySet`, make sure to set the `_easymodel` variable to the related `EasyModel`. """ def iterator(self, *args, **kwargs): for obj in super(EasyQuerySet, self).iterator(*args, **kwargs): yield EasyInstance(self._easymodel, obj) def _clone(self, *args, **kwargs): c = super(EasyQuerySet, self)._clone(*args, **kwargs) c._easymodel = self._easymodel return c
# Copyright 2012 OpenStack Foundation # # 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. """Token provider interface.""" import abc import base64 import datetime import sys import uuid from keystoneclient.common import cms from oslo_config import cfg from oslo_log import log from oslo_utils import timeutils import six from keystone.common import cache from keystone.common import dependency from keystone.common import manager from keystone import exception from keystone.i18n import _, _LE from keystone.models import token_model from keystone import notifications from keystone.token import persistence CONF = cfg.CONF LOG = log.getLogger(__name__) MEMOIZE = cache.get_memoization_decorator(section='token') # NOTE(morganfainberg): This is for compatibility in case someone was relying # on the old location of the UnsupportedTokenVersionException for their code. UnsupportedTokenVersionException = exception.UnsupportedTokenVersionException # supported token versions V2 = token_model.V2 V3 = token_model.V3 VERSIONS = token_model.VERSIONS def base64_encode(s): """Encode a URL-safe string.""" return base64.urlsafe_b64encode(s).rstrip('=') def random_urlsafe_str(): """Generate a random URL-safe string.""" # chop the padding (==) off the end of the encoding to save space return base64.urlsafe_b64encode(uuid.uuid4().bytes)[:-2] def random_urlsafe_str_to_bytes(s): """Convert a string generated by ``random_urlsafe_str()`` to bytes.""" # restore the padding (==) at the end of the string return base64.urlsafe_b64decode(s + '==') def default_expire_time(): """Determine when a fresh token should expire. Expiration time varies based on configuration (see ``[token] expiration``). :returns: a naive UTC datetime.datetime object """ expire_delta = datetime.timedelta(seconds=CONF.token.expiration) return timeutils.utcnow() + expire_delta def audit_info(parent_audit_id): """Build the audit data for a token. If ``parent_audit_id`` is None, the list will be one element in length containing a newly generated audit_id. If ``parent_audit_id`` is supplied, the list will be two elements in length containing a newly generated audit_id and the ``parent_audit_id``. The ``parent_audit_id`` will always be element index 1 in the resulting list. :param parent_audit_id: the audit of the original token in the chain :type parent_audit_id: str :returns: Keystone token audit data """ audit_id = random_urlsafe_str() if parent_audit_id is not None: return [audit_id, parent_audit_id] return [audit_id] @dependency.provider('token_provider_api') @dependency.requires('assignment_api', 'revoke_api') class Manager(manager.Manager): """Default pivot point for the token provider backend. See :mod:`keystone.common.manager.Manager` for more details on how this dynamically calls the backend. """ V2 = V2 V3 = V3 VERSIONS = VERSIONS INVALIDATE_PROJECT_TOKEN_PERSISTENCE = 'invalidate_project_tokens' INVALIDATE_USER_TOKEN_PERSISTENCE = 'invalidate_user_tokens' _persistence_manager = None def __init__(self): super(Manager, self).__init__(CONF.token.provider) self._register_callback_listeners() def _register_callback_listeners(self): # This is used by the @dependency.provider decorator to register the # provider (token_provider_api) manager to listen for trust deletions. callbacks = { notifications.ACTIONS.deleted: [ ['OS-TRUST:trust', self._trust_deleted_event_callback], ['user', self._delete_user_tokens_callback], ['domain', self._delete_domain_tokens_callback], ], notifications.ACTIONS.disabled: [ ['user', self._delete_user_tokens_callback], ['domain', self._delete_domain_tokens_callback], ['project', self._delete_project_tokens_callback], ], notifications.ACTIONS.internal: [ [notifications.INVALIDATE_USER_TOKEN_PERSISTENCE, self._delete_user_tokens_callback], [notifications.INVALIDATE_USER_PROJECT_TOKEN_PERSISTENCE, self._delete_user_project_tokens_callback], [notifications.INVALIDATE_USER_OAUTH_CONSUMER_TOKENS, self._delete_user_oauth_consumer_tokens_callback], ] } for event, cb_info in six.iteritems(callbacks): for resource_type, callback_fns in cb_info: notifications.register_event_callback(event, resource_type, callback_fns) @property def _needs_persistence(self): return self.driver.needs_persistence() @property def _persistence(self): # NOTE(morganfainberg): This should not be handled via __init__ to # avoid dependency injection oddities circular dependencies (where # the provider manager requires the token persistence manager, which # requires the token provider manager). if self._persistence_manager is None: self._persistence_manager = persistence.PersistenceManager() return self._persistence_manager def unique_id(self, token_id): """Return a unique ID for a token. The returned value is useful as the primary key of a database table, memcache store, or other lookup table. :returns: Given a PKI token, returns it's hashed value. Otherwise, returns the passed-in value (such as a UUID token ID or an existing hash). """ return cms.cms_hash_token(token_id, mode=CONF.token.hash_algorithm) def _create_token(self, token_id, token_data): try: if isinstance(token_data['expires'], six.string_types): token_data['expires'] = timeutils.normalize_time( timeutils.parse_isotime(token_data['expires'])) self._persistence.create_token(token_id, token_data) except Exception: exc_info = sys.exc_info() # an identical token may have been created already. # if so, return the token_data as it is also identical try: self._persistence.get_token(token_id) except exception.TokenNotFound: six.reraise(*exc_info) def validate_token(self, token_id, belongs_to=None): unique_id = self.unique_id(token_id) # NOTE(morganfainberg): Ensure we never use the long-form token_id # (PKI) as part of the cache_key. token = self._validate_token(unique_id) self._token_belongs_to(token, belongs_to) self._is_valid_token(token) return token def check_revocation_v2(self, token): try: token_data = token['access'] except KeyError: raise exception.TokenNotFound(_('Failed to validate token')) token_values = self.revoke_api.model.build_token_values_v2( token_data, CONF.identity.default_domain_id) self.revoke_api.check_token(token_values) def validate_v2_token(self, token_id, belongs_to=None): unique_id = self.unique_id(token_id) if self._needs_persistence: # NOTE(morganfainberg): Ensure we never use the long-form token_id # (PKI) as part of the cache_key. token_ref = self._persistence.get_token(unique_id) else: token_ref = token_id token = self._validate_v2_token(token_ref) self._token_belongs_to(token, belongs_to) self._is_valid_token(token) return token def check_revocation_v3(self, token): try: token_data = token['token'] except KeyError: raise exception.TokenNotFound(_('Failed to validate token')) token_values = self.revoke_api.model.build_token_values(token_data) self.revoke_api.check_token(token_values) def check_revocation(self, token): version = self.driver.get_token_version(token) if version == V2: return self.check_revocation_v2(token) else: return self.check_revocation_v3(token) def validate_v3_token(self, token_id): unique_id = self.unique_id(token_id) # NOTE(lbragstad): Only go to persistent storage if we have a token to # fetch from the backend. If the Fernet token provider is being used # this step isn't necessary. The Fernet token reference is persisted in # the token_id, so in this case set the token_ref as the identifier of # the token. if not self._needs_persistence: token_ref = token_id else: # NOTE(morganfainberg): Ensure we never use the long-form token_id # (PKI) as part of the cache_key. token_ref = self._persistence.get_token(unique_id) token = self._validate_v3_token(token_ref) self._is_valid_token(token) return token @MEMOIZE def _validate_token(self, token_id): if not self._needs_persistence: return self.driver.validate_v3_token(token_id) token_ref = self._persistence.get_token(token_id) version = self.driver.get_token_version(token_ref) if version == self.V3: return self.driver.validate_v3_token(token_ref) elif version == self.V2: return self.driver.validate_v2_token(token_ref) raise exception.UnsupportedTokenVersionException() @MEMOIZE def _validate_v2_token(self, token_id): return self.driver.validate_v2_token(token_id) @MEMOIZE def _validate_v3_token(self, token_id): return self.driver.validate_v3_token(token_id) def _is_valid_token(self, token): """Verify the token is valid format and has not expired.""" current_time = timeutils.normalize_time(timeutils.utcnow()) try: # Get the data we need from the correct location (V2 and V3 tokens # differ in structure, Try V3 first, fall back to V2 second) token_data = token.get('token', token.get('access')) expires_at = token_data.get('expires_at', token_data.get('expires')) if not expires_at: expires_at = token_data['token']['expires'] expiry = timeutils.normalize_time( timeutils.parse_isotime(expires_at)) except Exception: LOG.exception(_LE('Unexpected error or malformed token ' 'determining token expiry: %s'), token) raise exception.TokenNotFound(_('Failed to validate token')) if current_time < expiry: self.check_revocation(token) # Token has not expired and has not been revoked. return None else: raise exception.TokenNotFound(_('Failed to validate token')) def _token_belongs_to(self, token, belongs_to): """Check if the token belongs to the right tenant. This is only used on v2 tokens. The structural validity of the token will have already been checked before this method is called. """ if belongs_to: token_data = token['access']['token'] if ('tenant' not in token_data or token_data['tenant']['id'] != belongs_to): raise exception.Unauthorized() def issue_v2_token(self, token_ref, roles_ref=None, catalog_ref=None): token_id, token_data = self.driver.issue_v2_token( token_ref, roles_ref, catalog_ref) if self._needs_persistence: data = dict(key=token_id, id=token_id, expires=token_data['access']['token']['expires'], user=token_ref['user'], tenant=token_ref['tenant'], metadata=token_ref['metadata'], token_data=token_data, bind=token_ref.get('bind'), trust_id=token_ref['metadata'].get('trust_id'), token_version=self.V2) self._create_token(token_id, data) return token_id, token_data def issue_v3_token(self, user_id, method_names, expires_at=None, project_id=None, domain_id=None, auth_context=None, trust=None, metadata_ref=None, include_catalog=True, parent_audit_id=None): token_id, token_data = self.driver.issue_v3_token( user_id, method_names, expires_at, project_id, domain_id, auth_context, trust, metadata_ref, include_catalog, parent_audit_id) if metadata_ref is None: metadata_ref = {} if 'project' in token_data['token']: # project-scoped token, fill in the v2 token data # all we care are the role IDs # FIXME(gyee): is there really a need to store roles in metadata? role_ids = [r['id'] for r in token_data['token']['roles']] metadata_ref = {'roles': role_ids} if trust: metadata_ref.setdefault('trust_id', trust['id']) metadata_ref.setdefault('trustee_user_id', trust['trustee_user_id']) data = dict(key=token_id, id=token_id, expires=token_data['token']['expires_at'], user=token_data['token']['user'], tenant=token_data['token'].get('project'), metadata=metadata_ref, token_data=token_data, trust_id=trust['id'] if trust else None, token_version=self.V3) if self._needs_persistence: self._create_token(token_id, data) return token_id, token_data def invalidate_individual_token_cache(self, token_id): # NOTE(morganfainberg): invalidate takes the exact same arguments as # the normal method, this means we need to pass "self" in (which gets # stripped off). # FIXME(morganfainberg): Does this cache actually need to be # invalidated? We maintain a cached revocation list, which should be # consulted before accepting a token as valid. For now we will # do the explicit individual token invalidation. self._validate_token.invalidate(self, token_id) self._validate_v2_token.invalidate(self, token_id) self._validate_v3_token.invalidate(self, token_id) def revoke_token(self, token_id, revoke_chain=False): revoke_by_expires = False project_id = None domain_id = None token_ref = token_model.KeystoneToken( token_id=token_id, token_data=self.validate_token(token_id)) user_id = token_ref.user_id expires_at = token_ref.expires audit_id = token_ref.audit_id audit_chain_id = token_ref.audit_chain_id if token_ref.project_scoped: project_id = token_ref.project_id if token_ref.domain_scoped: domain_id = token_ref.domain_id if audit_id is None and not revoke_chain: LOG.debug('Received token with no audit_id.') revoke_by_expires = True if audit_chain_id is None and revoke_chain: LOG.debug('Received token with no audit_chain_id.') revoke_by_expires = True if revoke_by_expires: self.revoke_api.revoke_by_expiration(user_id, expires_at, project_id=project_id, domain_id=domain_id) elif revoke_chain: self.revoke_api.revoke_by_audit_chain_id(audit_chain_id, project_id=project_id, domain_id=domain_id) else: self.revoke_api.revoke_by_audit_id(audit_id) if CONF.token.revoke_by_id and self._needs_persistence: self._persistence.delete_token(token_id=token_id) def list_revoked_tokens(self): return self._persistence.list_revoked_tokens() def _trust_deleted_event_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: trust_id = payload['resource_info'] trust = self.trust_api.get_trust(trust_id, deleted=True) self._persistence.delete_tokens(user_id=trust['trustor_user_id'], trust_id=trust_id) def _delete_user_tokens_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: user_id = payload['resource_info'] self._persistence.delete_tokens_for_user(user_id) def _delete_domain_tokens_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: domain_id = payload['resource_info'] self._persistence.delete_tokens_for_domain(domain_id=domain_id) def _delete_user_project_tokens_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: user_id = payload['resource_info']['user_id'] project_id = payload['resource_info']['project_id'] self._persistence.delete_tokens_for_user(user_id=user_id, project_id=project_id) def _delete_project_tokens_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: project_id = payload['resource_info'] self._persistence.delete_tokens_for_users( self.assignment_api.list_user_ids_for_project(project_id), project_id=project_id) def _delete_user_oauth_consumer_tokens_callback(self, service, resource_type, operation, payload): if CONF.token.revoke_by_id: user_id = payload['resource_info']['user_id'] consumer_id = payload['resource_info']['consumer_id'] self._persistence.delete_tokens(user_id=user_id, consumer_id=consumer_id) @six.add_metaclass(abc.ABCMeta) class Provider(object): """Interface description for a Token provider.""" @abc.abstractmethod def needs_persistence(self): """Determine if the token should be persisted. If the token provider requires that the token be persisted to a backend this should return True, otherwise return False. """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def get_token_version(self, token_data): """Return the version of the given token data. If the given token data is unrecognizable, UnsupportedTokenVersionException is raised. :param token_data: token_data :type token_data: dict :returns: token version string :raises: keystone.token.provider.UnsupportedTokenVersionException """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def issue_v2_token(self, token_ref, roles_ref=None, catalog_ref=None): """Issue a V2 token. :param token_ref: token data to generate token from :type token_ref: dict :param roles_ref: optional roles list :type roles_ref: dict :param catalog_ref: optional catalog information :type catalog_ref: dict :returns: (token_id, token_data) """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def issue_v3_token(self, user_id, method_names, expires_at=None, project_id=None, domain_id=None, auth_context=None, trust=None, metadata_ref=None, include_catalog=True, parent_audit_id=None): """Issue a V3 Token. :param user_id: identity of the user :type user_id: string :param method_names: names of authentication methods :type method_names: list :param expires_at: optional time the token will expire :type expires_at: string :param project_id: optional project identity :type project_id: string :param domain_id: optional domain identity :type domain_id: string :param auth_context: optional context from the authorization plugins :type auth_context: dict :param trust: optional trust reference :type trust: dict :param metadata_ref: optional metadata reference :type metadata_ref: dict :param include_catalog: optional, include the catalog in token data :type include_catalog: boolean :param parent_audit_id: optional, the audit id of the parent token :type parent_audit_id: string :returns: (token_id, token_data) """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def validate_v2_token(self, token_ref): """Validate the given V2 token and return the token data. Must raise Unauthorized exception if unable to validate token. :param token_ref: the token reference :type token_ref: dict :returns: token data :raises: keystone.exception.TokenNotFound """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def validate_v3_token(self, token_ref): """Validate the given V3 token and return the token_data. :param token_ref: the token reference :type token_ref: dict :returns: token data :raises: keystone.exception.TokenNotFound """ raise exception.NotImplemented() # pragma: no cover @abc.abstractmethod def _get_token_id(self, token_data): """Generate the token_id based upon the data in token_data. :param token_data: token information :type token_data: dict returns: token identifier """ raise exception.NotImplemented() # pragma: no cover
from __future__ import print_function import argparse import calendar import datetime import hashlib import logging import os import shutil import time import psutil import yaml from conda_execute.conda_interface import CONDA_VERSION_MAJOR_MINOR import conda_execute.config from conda_execute.lock import Locked log = logging.getLogger('conda-tmpenv') log.addHandler(logging.NullHandler()) def register_env_usage(env_prefix): """ Register the usage of this environment (so that other processes could garbage collect when we are done). """ ps = psutil.Process() info_file = os.path.join(env_prefix, 'conda-meta', 'execution.log') # Some problems around race conditions meant that the conda-meta wasn't being created properly. # Travis-CI run: https://travis-ci.org/pelson/conda-execute/jobs/86982714 if not os.path.exists(os.path.dirname(info_file)): os.mkdir(os.path.dirname(info_file)) with open(info_file, 'a') as fh: fh.write('{}, {}\n'.format(ps.pid, int(ps.create_time()))) def name_env(spec): spec = tuple(sorted(spec)) # Use the first 20 hex characters of the sha256 to make the SHA somewhat legible. This could extend # in the future if we have sufficient need. hash = hashlib.sha256(u'\n'.join(spec).encode('utf-8')).hexdigest()[:20] env_locn = os.path.join(conda_execute.config.env_dir, hash) return env_locn def _create_env_conda_42(prefix, index, full_list_of_packages): assert CONDA_VERSION_MAJOR_MINOR < (4, 3) from conda.install import is_extracted, is_fetched, extract, link from conda.fetch import fetch_pkg for tar_name in full_list_of_packages: pkg_info = index[tar_name] dist_name = tar_name[:-len('.tar.bz2')] log.info('Resolved package: {}'.format(tar_name)) # We force a lock on retrieving anything which needs access to a distribution of this # name. If other requests come in to get the exact same package they will have to wait # for this to finish (good). If conda itself it fetching these pacakges then there is # the potential for a race condition (bad) - there is no solution to this unless # conda/conda is updated to be more precise with its locks. lock_name = os.path.join(conda_execute.config.pkg_dir, dist_name) with Locked(lock_name): if not is_extracted(dist_name): if not is_fetched(dist_name): log.info('Fetching {}'.format(dist_name)) fetch_pkg(pkg_info, conda_execute.config.pkg_dir) extract(dist_name) link(prefix, dist_name) def _create_env_conda_43(prefix, index, full_list_of_packages): assert CONDA_VERSION_MAJOR_MINOR >= (4, 3) from conda.core.package_cache import ProgressiveFetchExtract from conda.core.link import UnlinkLinkTransaction from conda.gateways.disk.create import mkdir_p pfe = ProgressiveFetchExtract(index, full_list_of_packages) pfe.execute() mkdir_p(prefix) txn = UnlinkLinkTransaction.create_from_dists(index, prefix, (), full_list_of_packages) txn.execute() def create_env(spec, force_recreation=False, extra_channels=()): """ Create a temporary environment from the given specification. """ from conda_execute.conda_interface import Resolve, get_index spec = tuple(sorted(spec)) env_locn = name_env(spec) # We lock the specific environment we are wanting to create. If other requests come in for the # exact same environment, they will have to wait for this to finish (good). with Locked(env_locn): # Note: There is no lock for re-creating. That means that it is possible to remove a tmpenv from # under another process' feet. if force_recreation and os.path.exists(env_locn): log.info("Clearing up existing environment at {} for re-creation".format(env_locn)) shutil.rmtree(env_locn) if not os.path.exists(env_locn): index = get_index(extra_channels) # Ditto re the quietness. r = Resolve(index) full_list_of_packages = sorted(r.solve(list(spec))) # Put out a newline. Conda's solve doesn't do it for us. log.info('\n') if CONDA_VERSION_MAJOR_MINOR >= (4, 3): _create_env_conda_43(env_locn, index, full_list_of_packages) else: _create_env_conda_42(env_locn, index, full_list_of_packages) # Attach an execution.log file. with open(os.path.join(env_locn, 'conda-meta', 'execution.log'), 'a'): pass return env_locn def subcommand_list(args): """ The function which handles the list subcommand. """ for env, env_stats in envs_and_running_pids(): if env_stats is None: continue last_pid_dt = datetime.datetime.fromtimestamp(env_stats['latest_creation_time']) age = datetime.datetime.now() - last_pid_dt old = age > datetime.timedelta(conda_execute.config.min_age) PIDs = env_stats['alive_PIDs'] if PIDs: running_pids = '(running PIDs {})'.format(', '.join(map(str, env_stats['alive_PIDs']))) else: running_pids = '' # TODO Use pretty timedelta printing. e.g. 1 hour 30 mins, or 2 weeks, 6 days and 4 hours etc. print('{} processes (newest created {} ago) using {} {}'.format( len(PIDs), age, env, running_pids)) def tmp_envs(): if not os.path.exists(conda_execute.config.env_dir): return [] envs = [os.path.join(conda_execute.config.env_dir, prefix) for prefix in os.listdir(conda_execute.config.env_dir)] envs = [prefix for prefix in envs if os.path.isdir(os.path.join(prefix, 'conda-meta'))] return envs def envs_and_running_pids(): """ A lock on temporary environments will be held for the life of the generator, so try not to hold on for too long! """ with Locked(conda_execute.config.env_dir): running_pids = set(psutil.pids()) for env in tmp_envs(): env_stats = None exe_log = os.path.join(env, 'conda-meta', 'execution.log') execution_pids = [] if os.path.exists(exe_log): with open(exe_log, 'r') as fh: for line in fh: execution_pids.append(line.strip().split(',')) alive_pids = [] newest_pid_time = os.path.getmtime(exe_log) # Iterate backwards, as we are more likely to hit newer ones first in that order. for pid, creation_time in execution_pids[::-1]: pid = int(pid) # Trim off the decimals to simplify comparisson with pid.create_time(). creation_time = int(float(creation_time)) if creation_time > newest_pid_time: newest_pid_time = creation_time # Check if the process is still running. try: alive = (pid in running_pids and int(psutil.Process(pid).create_time()) == creation_time) except psutil.NoSuchProcess: alive = False if alive: alive_pids.append(pid) env_stats = {'alive_PIDs': alive_pids, 'latest_creation_time': newest_pid_time} yield env, env_stats def subcommand_name(args): specs = list(args.specs) for fname in args.file: with open(fname) as fh: specs.extend([line.strip() for line in fh]) print(name_env(args.specs)) return 0 def subcommand_create(args): specs = list(args.specs) for fname in args.file: with open(fname) as fh: specs.extend([line.strip() for line in fh]) if not specs: import sys print("Error: no packages to install, must supply command line package specs or --file.", file=sys.stderr) return 1 log.info('Creating an environment with {}'.format(specs)) r = create_env(specs, force_recreation=args.force) # Output the created environment name print(r) return 0 def subcommand_clear(args): if args.min_age is not None: args.min_age = float(args.min_age) return cleanup_tmp_envs(min_age=args.min_age) def cleanup_tmp_envs(min_age=None): for env, env_stats in envs_and_running_pids(): if env_stats is not None: last_pid_dt = datetime.datetime.fromtimestamp(env_stats['latest_creation_time']) age = datetime.datetime.now() - last_pid_dt if min_age is None: min_age = conda_execute.config.min_age old = age > datetime.timedelta(min_age) if len(env_stats['alive_PIDs']) == 0 and old: log.warn('Removing unused temporary environment {}.'.format(env)) shutil.rmtree(env) else: log.warn('Could not find execution log for {}. Removing environment.'.format(env)) shutil.rmtree(env) def main(): common_arguments = argparse.ArgumentParser(add_help=False) common_arguments.add_argument('--verbose', '-v', action='store_true', help='show debug output') parser = argparse.ArgumentParser(description='Manage temporary environments within conda.', parents=[common_arguments]) subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', help='additional help') list_subcommand = subparsers.add_parser('list', parents=[common_arguments], help='List temporary environments.') list_subcommand.set_defaults(subcommand_func=subcommand_list) creation_args = argparse.ArgumentParser(add_help=False) creation_args.add_argument('specs', nargs='*', help='Packages to install into the temporary environment') creation_args.add_argument('--file', default=[], action='append', help=('Read package versions from the given file. Repeated file ' 'specifications can be passed (e.g. --file=file1 --file=file2)')) create_subcommand = subparsers.add_parser('create', parents=[common_arguments, creation_args], help='Create a new environment from specifications.') create_subcommand.set_defaults(subcommand_func=subcommand_create) create_subcommand.add_argument('--force', help='Whether to force the re-creation of the environment, even if it already exists.', action='store_true') name_subcommand = subparsers.add_parser('name', parents=[common_arguments, creation_args], help='Get the full prefix for a specified environment.') name_subcommand.set_defaults(subcommand_func=subcommand_name) clear_subcommand = subparsers.add_parser('clear', parents=[common_arguments], help='Clean up unused temporary environments.') clear_subcommand.set_defaults(subcommand_func=subcommand_clear) clear_subcommand.add_argument('--min-age', help=('The minimum age for the last registered PID on an ' 'environment, before the environment can be considered ' 'for removal.'), default=None, dest='min_age') args = parser.parse_args() log_level = logging.WARN if args.verbose: log_level = logging.DEBUG conda_execute.config.setup_logging(log_level) log.debug('Arguments passed: {}'.format(args)) if hasattr(args, 'subcommand_func'): exit(args.subcommand_func(args)) parser.error('No command specified') if __name__ == '__main__': main()
import re import hashlib import inspect import collections from base64 import b64decode import idiokit from idiokit.xmlcore import Element, Elements def _replace_non_xml_chars(unicode_obj, replacement=u"\ufffd"): return _NON_XML.sub(replacement, unicode_obj) _NON_XML = re.compile(u"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", re.U) def _normalize(value): """Return the value converted to unicode. Raise a TypeError if the value is not a string. >>> _normalize("a") u'a' >>> _normalize(u"b") u'b' >>> _normalize(1) Traceback (most recent call last): ... TypeError: expected a string value, got the value 1 of type int When converting str objects the default encoding is tried, and an UnicodeDecodeError is raised if the value can not bot converted. >>> _normalize("\\xe4") Traceback (most recent call last): ... UnicodeDecodeError: ... """ if isinstance(value, basestring): return unicode(value) name = type(value).__name__ module = inspect.getmodule(value) if module is not None and module.__name__ != "__builtin__": name = module.__name__ + "." + name msg = "expected a string value, got the value %r of type %s" % (value, name) raise TypeError(msg) EVENT_NS = "abusehelper#event" def _unicode_quote(string): r""" >>> _unicode_quote(u"a") u'a' >>> _unicode_quote(u"=") u'"="' >>> _unicode_quote(u"\n") u'"\n"' """ if _UNICODE_QUOTE_CHECK.search(string): return u'"' + _UNICODE_QUOTE.sub(r'\\\g<0>', string) + u'"' return string _UNICODE_QUOTE_CHECK = re.compile(r'[\s"\\,=]', re.U) _UNICODE_QUOTE = re.compile(r'["\\]', re.U) def _unicode_parse_part(string, start): match = _UNICODE_PART.match(string, start) quoted, unquoted = match.groups() end = match.end() if quoted is not None: return _UNICODE_UNQUOTE.sub("\\1", quoted), end if unquoted is not None: return unquoted, end return u"", end _UNICODE_UNQUOTE = re.compile(r'\\(.)', re.U) _UNICODE_PART = re.compile(r'\s*(?:(?:"((?:\\.|[^"])*)")|([^\s"=,]+)|)\s*', re.U) class Event(object): __slots__ = ["_attrs"] _UNDEFINED = object() @classmethod def _itemize(cls, *args, **keys): result = dict() for obj in args + (keys,): if type(obj) == Event: for key, values in obj._attrs.iteritems(): if key not in result: result[key] = values.copy() else: result[key].update(values) continue if hasattr(obj, "iteritems"): obj = obj.iteritems() elif hasattr(obj, "items"): obj = obj.items() for key, values in obj: if isinstance(values, basestring): values = (_normalize(values),) else: values = (_normalize(x) for x in values) key = _normalize(key) if key not in result: result[key] = set(values) else: result[key].update(values) return result @classmethod def from_unicode(cls, string): r""" >>> event = Event({"a": "b"}) >>> Event.from_unicode(unicode(event)) == event True >>> event = event.union({u'=': u'"'}) >>> Event.from_unicode(unicode(event)) == event True Regression test: Check that character escaping doesn't mess up parsing. >>> event = Event({ ... u"x": u"\\", ... u"y": u"b" ... }) >>> Event.from_unicode(ur'x="\\", "y"=b') == event True """ string = string.strip() if not string: return cls() attrs = collections.defaultdict(list) index = 0 length = len(string) while True: key, index = _unicode_parse_part(string, index) if index >= length: raise ValueError("unexpected string end") if string[index] != u"=": raise ValueError("unexpected character %r at index %d" % (string[index], index)) index += 1 value, index = _unicode_parse_part(string, index) attrs[key].append(value) if index >= length: return cls(attrs) if string[index] != u",": raise ValueError("unexpected character %r at index %d" % (string[index], index)) index += 1 @classmethod def from_elements(self, elements): """Yield events parsed from XML element(s). >>> element = Element("message") >>> list(Event.from_elements(element)) [] >>> element.add(Element("event", xmlns=EVENT_NS)) >>> list(Event.from_elements(element)) == [Event()] True >>> event = Event({u"\\uffff": u"\\x05"}) # include some forbidden XML chars >>> element = Element("message") >>> element.add(event.to_elements()) >>> list(Event.from_elements(element)) == [Event({u"\\ufffd": u"\\ufffd"})] True """ # Future event format for event_element in elements.children("e", EVENT_NS): attrs = collections.defaultdict(list) for key_element in event_element.children("k").with_attrs("a"): key = b64decode(key_element.get_attr("a")).decode("utf-8") for value_element in key_element.children("v").with_attrs("a"): value = b64decode(value_element.get_attr("a")).decode("utf-8") attrs[key].append(value) yield Event(attrs) # Legacy event format for event_element in elements.children("event", EVENT_NS): attrs = collections.defaultdict(list) for attr in event_element.children("attr").with_attrs("key", "value"): key = attr.get_attr("key") value = attr.get_attr("value") attrs[key].append(value) yield Event(attrs) def __init__(self, *args, **keys): """ Regression test: Keep the the correct internal encoding in the copy/merge constructor. >>> event = Event({u"\xe4": u"\xe4"}) >>> Event(event).items() ((u'\\xe4', u'\\xe4'),) """ self._attrs = self._itemize(*args, **keys) def union(self, *args, **keys): """Return a new event that contains all key-value pairs from appearing in the original event and/or Event(*args, **keys). >>> sorted(Event(a=["1", "2"]).union(a=["1", "3"]).items()) [(u'a', u'1'), (u'a', u'2'), (u'a', u'3')] """ return type(self)(self, *args, **keys) def difference(self, *args, **keys): """Return a new event that contains all key-value pairs from the original event except those also appearing in Event(*args, **keys). >>> sorted(Event(a=["1", "2"]).difference(a=["1", "3"]).items()) [(u'a', u'2')] """ other = self._itemize(*args, **keys) result = dict() for key, values in self._attrs.iteritems(): diff = values.difference(other.get(key, ())) if diff: result[key] = diff return type(self)(result) def add(self, key, value, *values): """Add value(s) for a key. >>> event = Event() >>> event.add("key", "1") >>> event.values("key") (u'1',) More than one value can be added with one call. >>> event = Event() >>> event.add("key", "1", "2") >>> sorted(event.values("key")) [u'1', u'2'] Key-value pairs is already contained by the event are ignored. >>> event = Event() >>> event.add("key", "1") >>> event.values("key") (u'1',) >>> event.add("key", "1") >>> event.values("key") (u'1',) """ self.update(key, (value,) + values) def update(self, key, values): """Update the values of a key. >>> event = Event() >>> event.update("key", ["1", "2"]) >>> sorted(event.values("key")) [u'1', u'2'] The event will not be modified if there are no values to add. >>> event = Event() >>> event.update("key", []) >>> event.contains("key") False """ key = _normalize(key) if key not in self._attrs: self._attrs[key] = set() self._attrs[key].update(_normalize(value) for value in values) def discard(self, key, value, *values): """Discard some value(s) of a key. >>> event = Event() >>> event.add("key", "1", "2", "3") >>> event.discard("key", "1", "3") >>> event.values("key") (u'2',) Values that don't exist for the given key are silently ignored. >>> event = Event() >>> event.add("key", "2") >>> event.discard("key", "1", "2") >>> event.values("key") () """ key = _normalize(key) if key not in self._attrs: return valueset = self._attrs[key] valueset.difference_update(_normalize(value) for value in (value,) + values) if not valueset: del self._attrs[key] def clear(self, key): """Clear all values of a key. >>> event = Event() >>> event.add("key", "1") >>> event.clear("key") >>> event.contains("key") False Clearing keys that do not exist does nothing. >>> event = Event() >>> event.clear("key") """ key = _normalize(key) self._attrs.pop(key, None) def _unkeyed(self): for values in self._attrs.itervalues(): for value in values: yield value def _iter(self, key, parser, filter): if key is self._UNDEFINED: values = set(self._unkeyed()) else: key = _normalize(key) values = self._attrs.get(key, ()) if parser is not None: parsed = (parser(x) for x in values) if filter is not None: return (x for x in parsed if filter(x)) else: return (x for x in parsed if x is not None) if filter is not None: return (x for x in values if filter(x)) return values def pop(self, key, parser=None, filter=None): """Pop value(s) of a key and clear them. >>> event = Event() >>> event.add("key", "y", "x", "1.2.3.4") >>> sorted(event.pop("key")) [u'1.2.3.4', u'x', u'y'] >>> event.contains("key") False Perform parsing, validation and filtering by passing in parsing and filtering functions. Only values that match are cleared from the event. Values that do not match are preserved. >>> def int_parse(string): ... try: ... return int(string) ... except ValueError: ... return None >>> event = Event() >>> event.add("key", "1", "a") >>> sorted(event.pop("key", parser=int_parse)) [1] >>> sorted(event.values("key")) [u'a'] """ key = _normalize(key) values = tuple(self._attrs.get(key, ())) if parser is not None: parsed = ((parser(x), x) for x in values) else: parsed = ((x, x) for x in values) if filter is not None: filtered = ((x, y) for (x, y) in parsed if filter(x)) else: filtered = ((x, y) for (x, y) in parsed if x is not None) results = [] for x, y in filtered: self.discard(key, y) results.append(x) return tuple(results) def values(self, key=_UNDEFINED, parser=None, filter=None): """Return a tuple of event values (for a specific key, if given). >>> event = Event(key=["1", "2"], other=["3", "4"]) >>> sorted(event.values()) [u'1', u'2', u'3', u'4'] >>> sorted(event.values("key")) [u'1', u'2'] Perform parsing, validation and filtering by passing in parsing and filtering functions (by default all None objects are filtered when a parsing function has been given). >>> import socket >>> def ipv4(string): ... try: ... return socket.inet_ntoa(socket.inet_aton(string)) ... except socket.error: ... return None >>> event = Event(key=["1.2.3.4", "abba"], other="10.10.10.10") >>> event.values("key", parser=ipv4) ('1.2.3.4',) >>> sorted(event.values(parser=ipv4)) ['1.2.3.4', '10.10.10.10'] """ return tuple(self._iter(key, parser, filter)) def value(self, key=_UNDEFINED, default=_UNDEFINED, parser=None, filter=None): """Return one event value (for a specific key, if given). The value can be picked either from the values of some specific key or amongst event values. >>> event = Event(key="1", other="2") >>> event.value("key") u'1' >>> event.value() in [u"1", u"2"] True A default return value can be defined in case no suitable value is available: >>> event = Event() >>> event.value("key", "default value") 'default value' >>> event.value(default="default value") 'default value' KeyError is raised if no suitable values are available and no default is given. >>> event = Event() >>> event.value() Traceback (most recent call last): ... KeyError: 'no value available' >>> event.value("somekey") Traceback (most recent call last): ... KeyError: 'somekey' As with .values(...), parsing and filtering functions can be given, and they will be used to modify the results. >>> def int_parse(string): ... try: ... return int(string) ... except ValueError: ... return None >>> event = Event(key=["1", "a"]) >>> event.value(parser=int_parse) 1 >>> event.value("key", parser=int_parse) 1 >>> event.value("other", parser=int_parse) Traceback (most recent call last): ... KeyError: 'other' """ for value in self._iter(key, parser, filter): return value if default is self._UNDEFINED: if key is self._UNDEFINED: raise KeyError("no value available") raise KeyError(key) return default def contains(self, key=_UNDEFINED, value=_UNDEFINED, parser=None, filter=None): """Return whether the event contains a key-value pair (for specific key and/or value, if given). >>> event = Event() >>> event.contains() # Does the event contain any values at all? False >>> event = event.union(key="1") >>> event.contains() True >>> event.contains("key") # Any value for key "key"? True >>> event.contains(value="1") # Value "1" for any key? True >>> event.contains("key", "1") # Value "1" for key "key"? True >>> event.contains("other", "2") # Value "2" for key "other"? False Parsing and filtering functions can be given to modify the results. >>> def int_parse(string): ... try: ... return int(string) ... except ValueError: ... return None >>> event.contains(parser=int_parse) # Any int value for any key? True >>> event.contains("key", parser=int_parse) # Any int value for "key"? True >>> event.contains(value=1, parser=int_parse) # Value 1 for any key? True >>> event = event.union(other="x") >>> event.contains("other", parser=int_parse) False """ if key is self._UNDEFINED: values = set(self._unkeyed()) else: key = _normalize(key) values = self._attrs.get(key, ()) if parser is not None: parsed = (parser(x) for x in values) if filter is not None: filtered = (x for x in parsed if filter(x)) else: filtered = (x for x in parsed if x is not None) elif filter is not None: filtered = (x for x in values if filter(x)) else: filtered = values for filtered_value in filtered: if value is self._UNDEFINED or value == filtered_value: return True return False def items(self, parser=None, filter=None): """Return a tuple of key-value pairs contained by the event. >>> event = Event() >>> event.items() () >>> event = event.union(key="1", other=["x", "y"]) >>> sorted(event.items()) [(u'key', u'1'), (u'other', u'x'), (u'other', u'y')] Parsing and filtering functions can be given to modify the results. >>> def int_parse(string): ... try: ... return int(string) ... except ValueError: ... return None >>> event.items(parser=int_parse) ((u'key', 1),) The order of the key-value pairs is undefined. """ result = list() for key, values in self._attrs.iteritems(): for value in values: if parser is not None: value = parser(value) if filter is not None and not filter(value): continue if filter is None and value is None: continue result.append((key, value)) return tuple(result) def keys(self, parser=None, filter=None): """Return a tuple of keys with at least one value. >>> event = Event() >>> event.keys() () >>> event = event.union(key="1", other=["x", "y"]) >>> sorted(event.keys()) [u'key', u'other'] Parsing and filtering functions can be given to modify the results. >>> def int_parse(string): ... try: ... return int(string) ... except ValueError: ... return None >>> sorted(event.keys(parser=int_parse)) [u'key'] """ return tuple(key for key in self._attrs if self.contains(key, parser=parser, filter=filter)) def to_elements(self, include_body=True): element = Element("event", xmlns=EVENT_NS) for key, value in self.items(): key = _replace_non_xml_chars(key) value = _replace_non_xml_chars(value) attr = Element("attr", key=key, value=value) element.add(attr) if not include_body: return element body = Element("body") body.text = _replace_non_xml_chars(unicode(self)) return Elements(body, element) def __reduce__(self): return self.__class__, (self._attrs,) def __eq__(self, other): if not isinstance(other, Event): return NotImplemented return other._attrs == self._attrs def __ne__(self, other): value = self.__eq__(other) if value is NotImplemented: return NotImplemented return not value def __unicode__(self): """Return an unicode representation of the event. >>> unicode(Event()) u'' >>> unicode(Event({"a,": "b"})) u'"a,"=b' The specific order of the key-value pairs is undefined. """ return u", ".join(_unicode_quote(key) + u"=" + _unicode_quote(value) for (key, value) in self.items()) def __repr__(self): attrs = dict() for key, value in self.items(): attrs.setdefault(key, list()).append(value) return self.__class__.__name__ + "(" + repr(attrs) + ")" def hexdigest(event, func=hashlib.sha1): """Return a hexadecimal digest string created by from the given event's key-value pairs. The result is guaranteed to be the same for two events e1 and e2 when e1 == e2. Key-value insertion order does not affect the result. >>> e1 = Event() >>> e1.add("a", "b") >>> e1.add("x", "y") >>> >>> e2 = Event() >>> e2.add("x", "y") >>> e2.add("a", "b") >>> >>> hexdigest(e1) == hexdigest(e2) True The result is not guaranteed to be different for two events e1 and e2 when e1 != e2. However such a collision is usually exceedingly unlikely when a good hashing algorithm is used. SHA1 is the default, but can be changed by passing in an algorithm implementation with a compatible interface. For example, algorithms defined in the standard 'hashlib' library are compatible. >>> import hashlib >>> hexdigest(Event(a="b"), hashlib.md5) '51a8ca876645d37e29419694f6396fbc' The default hashing algorithm is NOT guaranteed to be SHA1 forever. If you want to guarantee that the hexdigest is always created using e.g. SHA1, pass the hash function explicitly as the second parameter: >>> import hashlib >>> hexdigest(Event(a="b"), hashlib.sha1) 'edf6294fc1d3f9fe8be4a2d5626788bcfde05e62' """ result = func() for key, value in sorted(event.items()): result.update(key.encode("utf-8")) result.update("\xc0") result.update(value.encode("utf-8")) result.update("\xc0") return result.hexdigest() def stanzas_to_events(): return idiokit.map(Event.from_elements) def events_to_elements(): return idiokit.map(lambda x: (x.to_elements(),))
#!/usr/bin/python2.4 # # Unit tests for Mox. # # Copyright 2008 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. import cStringIO import unittest import re import mox import mox_test_helper class ExpectedMethodCallsErrorTest(unittest.TestCase): """Test creation and string conversion of ExpectedMethodCallsError.""" def testAtLeastOneMethod(self): self.assertRaises(ValueError, mox.ExpectedMethodCallsError, []) def testOneError(self): method = mox.MockMethod("testMethod", [], False) method(1, 2).AndReturn('output') e = mox.ExpectedMethodCallsError([method]) self.assertEqual( "Verify: Expected methods never called:\n" " 0. testMethod(1, 2) -> 'output'", str(e)) def testManyErrors(self): method1 = mox.MockMethod("testMethod", [], False) method1(1, 2).AndReturn('output') method2 = mox.MockMethod("testMethod", [], False) method2(a=1, b=2, c="only named") method3 = mox.MockMethod("testMethod2", [], False) method3().AndReturn(44) method4 = mox.MockMethod("testMethod", [], False) method4(1, 2).AndReturn('output') e = mox.ExpectedMethodCallsError([method1, method2, method3, method4]) self.assertEqual( "Verify: Expected methods never called:\n" " 0. testMethod(1, 2) -> 'output'\n" " 1. testMethod(a=1, b=2, c='only named') -> None\n" " 2. testMethod2() -> 44\n" " 3. testMethod(1, 2) -> 'output'", str(e)) class OrTest(unittest.TestCase): """Test Or correctly chains Comparators.""" def testValidOr(self): """Or should be True if either Comparator returns True.""" self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {}) self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test') self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test') def testInvalidOr(self): """Or should be False if both Comparators return False.""" self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0) class AndTest(unittest.TestCase): """Test And correctly chains Comparators.""" def testValidAnd(self): """And should be True if both Comparators return True.""" self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1') def testClauseOneFails(self): """And should be False if the first Comparator returns False.""" self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1') def testAdvancedUsage(self): """And should work with other Comparators. Note: this test is reliant on In and ContainsKeyValue. """ test_dict = {"mock" : "obj", "testing" : "isCOOL"} self.assert_(mox.And(mox.In("testing"), mox.ContainsKeyValue("mock", "obj")) == test_dict) def testAdvancedUsageFails(self): """Note: this test is reliant on In and ContainsKeyValue.""" test_dict = {"mock" : "obj", "testing" : "isCOOL"} self.failIf(mox.And(mox.In("NOTFOUND"), mox.ContainsKeyValue("mock", "obj")) == test_dict) class SameElementsAsTest(unittest.TestCase): """Test SameElementsAs correctly identifies sequences with same elements.""" def testSortedLists(self): """Should return True if two lists are exactly equal.""" self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c']) def testUnsortedLists(self): """Should return True if two lists are unequal but have same elements.""" self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1]) def testUnhashableLists(self): """Should return True if two lists have the same unhashable elements.""" self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}, {'a': 1}]) def testEmptyLists(self): """Should return True for two empty lists.""" self.assert_(mox.SameElementsAs([]) == []) def testUnequalLists(self): """Should return False if the lists are not equal.""" self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c']) def testUnequalUnhashableLists(self): """Should return False if two lists with unhashable elements are unequal.""" self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}]) class ContainsKeyValueTest(unittest.TestCase): """Test ContainsKeyValue correctly identifies key/value pairs in a dict. """ def testValidPair(self): """Should return True if the key value is in the dict.""" self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1}) def testInvalidValue(self): """Should return False if the value is not correct.""" self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2}) def testInvalidKey(self): """Should return False if they key is not in the dict.""" self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2}) class InTest(unittest.TestCase): """Test In correctly identifies a key in a list/dict""" def testItemInList(self): """Should return True if the item is in the list.""" self.assert_(mox.In(1) == [1, 2, 3]) def testKeyInDict(self): """Should return True if the item is a key in a dict.""" self.assert_(mox.In("test") == {"test" : "module"}) class NotTest(unittest.TestCase): """Test Not correctly identifies False predicates.""" def testItemInList(self): """Should return True if the item is NOT in the list.""" self.assert_(mox.Not(mox.In(42)) == [1, 2, 3]) def testKeyInDict(self): """Should return True if the item is NOT a key in a dict.""" self.assert_(mox.Not(mox.In("foo")) == {"key" : 42}) def testInvalidKeyWithNot(self): """Should return False if they key is NOT in the dict.""" self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2}) class StrContainsTest(unittest.TestCase): """Test StrContains correctly checks for substring occurrence of a parameter. """ def testValidSubstringAtStart(self): """Should return True if the substring is at the start of the string.""" self.assert_(mox.StrContains("hello") == "hello world") def testValidSubstringInMiddle(self): """Should return True if the substring is in the middle of the string.""" self.assert_(mox.StrContains("lo wo") == "hello world") def testValidSubstringAtEnd(self): """Should return True if the substring is at the end of the string.""" self.assert_(mox.StrContains("ld") == "hello world") def testInvaildSubstring(self): """Should return False if the substring is not in the string.""" self.failIf(mox.StrContains("AAA") == "hello world") def testMultipleMatches(self): """Should return True if there are multiple occurances of substring.""" self.assert_(mox.StrContains("abc") == "ababcabcabcababc") class RegexTest(unittest.TestCase): """Test Regex correctly matches regular expressions.""" def testIdentifyBadSyntaxDuringInit(self): """The user should know immediately if a regex has bad syntax.""" self.assertRaises(re.error, mox.Regex, '(a|b') def testPatternInMiddle(self): """Should return True if the pattern matches at the middle of the string. This ensures that re.search is used (instead of re.find). """ self.assert_(mox.Regex(r"a\s+b") == "x y z a b c") def testNonMatchPattern(self): """Should return False if the pattern does not match the string.""" self.failIf(mox.Regex(r"a\s+b") == "x y z") def testFlagsPassedCorrectly(self): """Should return True as we pass IGNORECASE flag.""" self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a") def testReprWithoutFlags(self): """repr should return the regular expression pattern.""" self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>") def testReprWithFlags(self): """repr should return the regular expression pattern and flags.""" self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) == "<regular expression 'a\s+b', flags=4>") class IsATest(unittest.TestCase): """Verify IsA correctly checks equality based upon class type, not value.""" def testEqualityValid(self): """Verify that == correctly identifies objects of the same type.""" self.assert_(mox.IsA(str) == 'test') def testEqualityInvalid(self): """Verify that == correctly identifies objects of different types.""" self.failIf(mox.IsA(str) == 10) def testInequalityValid(self): """Verify that != identifies objects of different type.""" self.assert_(mox.IsA(str) != 10) def testInequalityInvalid(self): """Verify that != correctly identifies objects of the same type.""" self.failIf(mox.IsA(str) != "test") def testEqualityInListValid(self): """Verify list contents are properly compared.""" isa_list = [mox.IsA(str), mox.IsA(str)] str_list = ["abc", "def"] self.assert_(isa_list == str_list) def testEquailtyInListInvalid(self): """Verify list contents are properly compared.""" isa_list = [mox.IsA(str),mox.IsA(str)] mixed_list = ["abc", 123] self.failIf(isa_list == mixed_list) def testSpecialTypes(self): """Verify that IsA can handle objects like cStringIO.StringIO.""" isA = mox.IsA(cStringIO.StringIO()) stringIO = cStringIO.StringIO() self.assert_(isA == stringIO) class IsAlmostTest(unittest.TestCase): """Verify IsAlmost correctly checks equality of floating point numbers.""" def testEqualityValid(self): """Verify that == correctly identifies nearly equivalent floats.""" self.assertEquals(mox.IsAlmost(1.8999999999), 1.9) def testEqualityInvalid(self): """Verify that == correctly identifies non-equivalent floats.""" self.assertNotEquals(mox.IsAlmost(1.899), 1.9) def testEqualityWithPlaces(self): """Verify that specifying places has the desired effect.""" self.assertNotEquals(mox.IsAlmost(1.899), 1.9) self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9) def testNonNumericTypes(self): """Verify that IsAlmost handles non-numeric types properly.""" self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9') self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9) self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9') class MockMethodTest(unittest.TestCase): """Test class to verify that the MockMethod class is working correctly.""" def setUp(self): self.expected_method = mox.MockMethod("testMethod", [], False)(['original']) self.mock_method = mox.MockMethod("testMethod", [self.expected_method], True) def testAndReturnNoneByDefault(self): """Should return None by default.""" return_value = self.mock_method(['original']) self.assert_(return_value == None) def testAndReturnValue(self): """Should return a specificed return value.""" expected_return_value = "test" self.expected_method.AndReturn(expected_return_value) return_value = self.mock_method(['original']) self.assert_(return_value == expected_return_value) def testAndRaiseException(self): """Should raise a specified exception.""" expected_exception = Exception('test exception') self.expected_method.AndRaise(expected_exception) self.assertRaises(Exception, self.mock_method) def testWithSideEffects(self): """Should call state modifier.""" local_list = ['original'] def modifier(mutable_list): self.assertTrue(local_list is mutable_list) mutable_list[0] = 'mutation' self.expected_method.WithSideEffects(modifier).AndReturn(1) self.mock_method(local_list) self.assertEquals('mutation', local_list[0]) def testEqualityNoParamsEqual(self): """Methods with the same name and without params should be equal.""" expected_method = mox.MockMethod("testMethod", [], False) self.assertEqual(self.mock_method, expected_method) def testEqualityNoParamsNotEqual(self): """Methods with different names and without params should not be equal.""" expected_method = mox.MockMethod("otherMethod", [], False) self.failIfEqual(self.mock_method, expected_method) def testEqualityParamsEqual(self): """Methods with the same name and parameters should be equal.""" params = [1, 2, 3] expected_method = mox.MockMethod("testMethod", [], False) expected_method._params = params self.mock_method._params = params self.assertEqual(self.mock_method, expected_method) def testEqualityParamsNotEqual(self): """Methods with the same name and different params should not be equal.""" expected_method = mox.MockMethod("testMethod", [], False) expected_method._params = [1, 2, 3] self.mock_method._params = ['a', 'b', 'c'] self.failIfEqual(self.mock_method, expected_method) def testEqualityNamedParamsEqual(self): """Methods with the same name and same named params should be equal.""" named_params = {"input1": "test", "input2": "params"} expected_method = mox.MockMethod("testMethod", [], False) expected_method._named_params = named_params self.mock_method._named_params = named_params self.assertEqual(self.mock_method, expected_method) def testEqualityNamedParamsNotEqual(self): """Methods with the same name and diffnamed params should not be equal.""" expected_method = mox.MockMethod("testMethod", [], False) expected_method._named_params = {"input1": "test", "input2": "params"} self.mock_method._named_params = {"input1": "test2", "input2": "params2"} self.failIfEqual(self.mock_method, expected_method) def testEqualityWrongType(self): """Method should not be equal to an object of a different type.""" self.failIfEqual(self.mock_method, "string?") def testObjectEquality(self): """Equality of objects should work without a Comparator""" instA = TestClass(); instB = TestClass(); params = [instA, ] expected_method = mox.MockMethod("testMethod", [], False) expected_method._params = params self.mock_method._params = [instB, ] self.assertEqual(self.mock_method, expected_method) def testStrConversion(self): method = mox.MockMethod("f", [], False) method(1, 2, "st", n1=8, n2="st2") self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None")) method = mox.MockMethod("testMethod", [], False) method(1, 2, "only positional") self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None") method = mox.MockMethod("testMethod", [], False) method(a=1, b=2, c="only named") self.assertEqual(str(method), "testMethod(a=1, b=2, c='only named') -> None") method = mox.MockMethod("testMethod", [], False) method() self.assertEqual(str(method), "testMethod() -> None") method = mox.MockMethod("testMethod", [], False) method(x="only 1 parameter") self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None") method = mox.MockMethod("testMethod", [], False) method().AndReturn('return_value') self.assertEqual(str(method), "testMethod() -> 'return_value'") method = mox.MockMethod("testMethod", [], False) method().AndReturn(('a', {1: 2})) self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})") class MockAnythingTest(unittest.TestCase): """Verify that the MockAnything class works as expected.""" def setUp(self): self.mock_object = mox.MockAnything() def testRepr(self): """Calling repr on a MockAnything instance must work.""" self.assertEqual('<MockAnything instance>', repr(self.mock_object)) def testSetupMode(self): """Verify the mock will accept any call.""" self.mock_object.NonsenseCall() self.assert_(len(self.mock_object._expected_calls_queue) == 1) def testReplayWithExpectedCall(self): """Verify the mock replays method calls as expected.""" self.mock_object.ValidCall() # setup method call self.mock_object._Replay() # start replay mode self.mock_object.ValidCall() # make method call def testReplayWithUnexpectedCall(self): """Unexpected method calls should raise UnexpectedMethodCallError.""" self.mock_object.ValidCall() # setup method call self.mock_object._Replay() # start replay mode self.assertRaises(mox.UnexpectedMethodCallError, self.mock_object.OtherValidCall) def testVerifyWithCompleteReplay(self): """Verify should not raise an exception for a valid replay.""" self.mock_object.ValidCall() # setup method call self.mock_object._Replay() # start replay mode self.mock_object.ValidCall() # make method call self.mock_object._Verify() def testVerifyWithIncompleteReplay(self): """Verify should raise an exception if the replay was not complete.""" self.mock_object.ValidCall() # setup method call self.mock_object._Replay() # start replay mode # ValidCall() is never made self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify) def testSpecialClassMethod(self): """Verify should not raise an exception when special methods are used.""" self.mock_object[1].AndReturn(True) self.mock_object._Replay() returned_val = self.mock_object[1] self.assert_(returned_val) self.mock_object._Verify() def testNonzero(self): """You should be able to use the mock object in an if.""" self.mock_object._Replay() if self.mock_object: pass def testNotNone(self): """Mock should be comparable to None.""" self.mock_object._Replay() if self.mock_object is not None: pass if self.mock_object is None: pass def testEquals(self): """A mock should be able to compare itself to another object.""" self.mock_object._Replay() self.assertEquals(self.mock_object, self.mock_object) def testEqualsMockFailure(self): """Verify equals identifies unequal objects.""" self.mock_object.SillyCall() self.mock_object._Replay() self.assertNotEquals(self.mock_object, mox.MockAnything()) def testEqualsInstanceFailure(self): """Verify equals identifies that objects are different instances.""" self.mock_object._Replay() self.assertNotEquals(self.mock_object, TestClass()) def testNotEquals(self): """Verify not equals works.""" self.mock_object._Replay() self.assertFalse(self.mock_object != self.mock_object) def testNestedMockCallsRecordedSerially(self): """Test that nested calls work when recorded serially.""" self.mock_object.CallInner().AndReturn(1) self.mock_object.CallOuter(1) self.mock_object._Replay() self.mock_object.CallOuter(self.mock_object.CallInner()) self.mock_object._Verify() def testNestedMockCallsRecordedNested(self): """Test that nested cals work when recorded in a nested fashion.""" self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1)) self.mock_object._Replay() self.mock_object.CallOuter(self.mock_object.CallInner()) self.mock_object._Verify() def testIsCallable(self): """Test that MockAnything can even mock a simple callable. This is handy for "stubbing out" a method in a module with a mock, and verifying that it was called. """ self.mock_object().AndReturn('mox0rd') self.mock_object._Replay() self.assertEquals('mox0rd', self.mock_object()) self.mock_object._Verify() def testIsReprable(self): """Test that MockAnythings can be repr'd without causing a failure.""" self.failUnless('MockAnything' in repr(self.mock_object)) class MethodCheckerTest(unittest.TestCase): """Tests MockMethod's use of MethodChecker method.""" def testNoParameters(self): method = mox.MockMethod('NoParameters', [], False, CheckCallTestClass.NoParameters) method() self.assertRaises(AttributeError, method, 1) self.assertRaises(AttributeError, method, 1, 2) self.assertRaises(AttributeError, method, a=1) self.assertRaises(AttributeError, method, 1, b=2) def testOneParameter(self): method = mox.MockMethod('OneParameter', [], False, CheckCallTestClass.OneParameter) self.assertRaises(AttributeError, method) method(1) method(a=1) self.assertRaises(AttributeError, method, b=1) self.assertRaises(AttributeError, method, 1, 2) self.assertRaises(AttributeError, method, 1, a=2) self.assertRaises(AttributeError, method, 1, b=2) def testTwoParameters(self): method = mox.MockMethod('TwoParameters', [], False, CheckCallTestClass.TwoParameters) self.assertRaises(AttributeError, method) self.assertRaises(AttributeError, method, 1) self.assertRaises(AttributeError, method, a=1) self.assertRaises(AttributeError, method, b=1) method(1, 2) method(1, b=2) method(a=1, b=2) method(b=2, a=1) self.assertRaises(AttributeError, method, b=2, c=3) self.assertRaises(AttributeError, method, a=1, b=2, c=3) self.assertRaises(AttributeError, method, 1, 2, 3) self.assertRaises(AttributeError, method, 1, 2, 3, 4) self.assertRaises(AttributeError, method, 3, a=1, b=2) def testOneDefaultValue(self): method = mox.MockMethod('OneDefaultValue', [], False, CheckCallTestClass.OneDefaultValue) method() method(1) method(a=1) self.assertRaises(AttributeError, method, b=1) self.assertRaises(AttributeError, method, 1, 2) self.assertRaises(AttributeError, method, 1, a=2) self.assertRaises(AttributeError, method, 1, b=2) def testTwoDefaultValues(self): method = mox.MockMethod('TwoDefaultValues', [], False, CheckCallTestClass.TwoDefaultValues) self.assertRaises(AttributeError, method) self.assertRaises(AttributeError, method, c=3) self.assertRaises(AttributeError, method, 1) self.assertRaises(AttributeError, method, 1, d=4) self.assertRaises(AttributeError, method, 1, d=4, c=3) method(1, 2) method(a=1, b=2) method(1, 2, 3) method(1, 2, 3, 4) method(1, 2, c=3) method(1, 2, c=3, d=4) method(1, 2, d=4, c=3) method(d=4, c=3, a=1, b=2) self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5) self.assertRaises(AttributeError, method, 1, 2, e=9) self.assertRaises(AttributeError, method, a=1, b=2, e=9) def testArgs(self): method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args) self.assertRaises(AttributeError, method) self.assertRaises(AttributeError, method, 1) method(1, 2) method(a=1, b=2) method(1, 2, 3) method(1, 2, 3, 4) self.assertRaises(AttributeError, method, 1, 2, a=3) self.assertRaises(AttributeError, method, 1, 2, c=3) def testKwargs(self): method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs) self.assertRaises(AttributeError, method) method(1) method(1, 2) method(a=1, b=2) method(b=2, a=1) self.assertRaises(AttributeError, method, 1, 2, 3) self.assertRaises(AttributeError, method, 1, 2, a=3) method(1, 2, c=3) method(a=1, b=2, c=3) method(c=3, a=1, b=2) method(a=1, b=2, c=3, d=4) self.assertRaises(AttributeError, method, 1, 2, 3, 4) def testArgsAndKwargs(self): method = mox.MockMethod('ArgsAndKwargs', [], False, CheckCallTestClass.ArgsAndKwargs) self.assertRaises(AttributeError, method) method(1) method(1, 2) method(1, 2, 3) method(a=1) method(1, b=2) self.assertRaises(AttributeError, method, 1, a=2) method(b=2, a=1) method(c=3, b=2, a=1) method(1, 2, c=3) class CheckCallTestClass(object): def NoParameters(self): pass def OneParameter(self, a): pass def TwoParameters(self, a, b): pass def OneDefaultValue(self, a=1): pass def TwoDefaultValues(self, a, b, c=1, d=2): pass def Args(self, a, b, *args): pass def Kwargs(self, a, b=2, **kwargs): pass def ArgsAndKwargs(self, a, *args, **kwargs): pass class MockObjectTest(unittest.TestCase): """Verify that the MockObject class works as exepcted.""" def setUp(self): self.mock_object = mox.MockObject(TestClass) def testSetupModeWithValidCall(self): """Verify the mock object properly mocks a basic method call.""" self.mock_object.ValidCall() self.assert_(len(self.mock_object._expected_calls_queue) == 1) def testSetupModeWithInvalidCall(self): """UnknownMethodCallError should be raised if a non-member method is called. """ # Note: assertRaises does not catch exceptions thrown by MockObject's # __getattr__ try: self.mock_object.InvalidCall() self.fail("No exception thrown, expected UnknownMethodCallError") except mox.UnknownMethodCallError: pass except Exception: self.fail("Wrong exception type thrown, expected UnknownMethodCallError") def testReplayWithInvalidCall(self): """UnknownMethodCallError should be raised if a non-member method is called. """ self.mock_object.ValidCall() # setup method call self.mock_object._Replay() # start replay mode # Note: assertRaises does not catch exceptions thrown by MockObject's # __getattr__ try: self.mock_object.InvalidCall() self.fail("No exception thrown, expected UnknownMethodCallError") except mox.UnknownMethodCallError: pass except Exception: self.fail("Wrong exception type thrown, expected UnknownMethodCallError") def testIsInstance(self): """Mock should be able to pass as an instance of the mocked class.""" self.assert_(isinstance(self.mock_object, TestClass)) def testFindValidMethods(self): """Mock should be able to mock all public methods.""" self.assert_('ValidCall' in self.mock_object._known_methods) self.assert_('OtherValidCall' in self.mock_object._known_methods) self.assert_('MyClassMethod' in self.mock_object._known_methods) self.assert_('MyStaticMethod' in self.mock_object._known_methods) self.assert_('_ProtectedCall' in self.mock_object._known_methods) self.assert_('__PrivateCall' not in self.mock_object._known_methods) self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods) def testFindsSuperclassMethods(self): """Mock should be able to mock superclasses methods.""" self.mock_object = mox.MockObject(ChildClass) self.assert_('ValidCall' in self.mock_object._known_methods) self.assert_('OtherValidCall' in self.mock_object._known_methods) self.assert_('MyClassMethod' in self.mock_object._known_methods) self.assert_('ChildValidCall' in self.mock_object._known_methods) def testAccessClassVariables(self): """Class variables should be accessible through the mock.""" self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars) self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars) self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR) def testEquals(self): """A mock should be able to compare itself to another object.""" self.mock_object._Replay() self.assertEquals(self.mock_object, self.mock_object) def testEqualsMockFailure(self): """Verify equals identifies unequal objects.""" self.mock_object.ValidCall() self.mock_object._Replay() self.assertNotEquals(self.mock_object, mox.MockObject(TestClass)) def testEqualsInstanceFailure(self): """Verify equals identifies that objects are different instances.""" self.mock_object._Replay() self.assertNotEquals(self.mock_object, TestClass()) def testNotEquals(self): """Verify not equals works.""" self.mock_object._Replay() self.assertFalse(self.mock_object != self.mock_object) def testMockSetItem_ExpectedSetItem_Success(self): """Test that __setitem__() gets mocked in Dummy. In this test, _Verify() succeeds. """ dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() dummy['X'] = 'Y' dummy._Verify() def testMockSetItem_ExpectedSetItem_NoSuccess(self): """Test that __setitem__() gets mocked in Dummy. In this test, _Verify() fails. """ dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() # NOT doing dummy['X'] = 'Y' self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) def testMockSetItem_ExpectedNoSetItem_Success(self): """Test that __setitem__() gets mocked in Dummy.""" dummy = mox.MockObject(TestClass) # NOT doing dummy['X'] = 'Y' dummy._Replay() def call(): dummy['X'] = 'Y' self.assertRaises(mox.UnexpectedMethodCallError, call) def testMockSetItem_ExpectedNoSetItem_NoSuccess(self): """Test that __setitem__() gets mocked in Dummy. In this test, _Verify() fails. """ dummy = mox.MockObject(TestClass) # NOT doing dummy['X'] = 'Y' dummy._Replay() # NOT doing dummy['X'] = 'Y' dummy._Verify() def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self): """Test that __setitem__() fails if other parameters are expected.""" dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() def call(): dummy['wrong'] = 'Y' self.assertRaises(mox.UnexpectedMethodCallError, call) dummy._Verify() def testMockSetItem_WithSubClassOfNewStyleClass(self): class NewStyleTestClass(object): def __init__(self): self.my_dict = {} def __setitem__(self, key, value): self.my_dict[key], value class TestSubClass(NewStyleTestClass): pass dummy = mox.MockObject(TestSubClass) dummy[1] = 2 dummy._Replay() dummy[1] = 2 dummy._Verify() def testMockGetItem_ExpectedGetItem_Success(self): """Test that __getitem__() gets mocked in Dummy. In this test, _Verify() succeeds. """ dummy = mox.MockObject(TestClass) dummy['X'].AndReturn('value') dummy._Replay() self.assertEqual(dummy['X'], 'value') dummy._Verify() def testMockGetItem_ExpectedGetItem_NoSuccess(self): """Test that __getitem__() gets mocked in Dummy. In this test, _Verify() fails. """ dummy = mox.MockObject(TestClass) dummy['X'].AndReturn('value') dummy._Replay() # NOT doing dummy['X'] self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) def testMockGetItem_ExpectedNoGetItem_NoSuccess(self): """Test that __getitem__() gets mocked in Dummy.""" dummy = mox.MockObject(TestClass) # NOT doing dummy['X'] dummy._Replay() def call(): return dummy['X'] self.assertRaises(mox.UnexpectedMethodCallError, call) def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self): """Test that __getitem__() fails if other parameters are expected.""" dummy = mox.MockObject(TestClass) dummy['X'].AndReturn('value') dummy._Replay() def call(): return dummy['wrong'] self.assertRaises(mox.UnexpectedMethodCallError, call) dummy._Verify() def testMockGetItem_WithSubClassOfNewStyleClass(self): class NewStyleTestClass(object): def __getitem__(self, key): return {1: '1', 2: '2'}[key] class TestSubClass(NewStyleTestClass): pass dummy = mox.MockObject(TestSubClass) dummy[1].AndReturn('3') dummy._Replay() self.assertEquals('3', dummy.__getitem__(1)) dummy._Verify() def testMockIter_ExpectedIter_Success(self): """Test that __iter__() gets mocked in Dummy. In this test, _Verify() succeeds. """ dummy = mox.MockObject(TestClass) iter(dummy).AndReturn(iter(['X', 'Y'])) dummy._Replay() self.assertEqual([x for x in dummy], ['X', 'Y']) dummy._Verify() def testMockContains_ExpectedContains_Success(self): """Test that __contains__ gets mocked in Dummy. In this test, _Verify() succeeds. """ dummy = mox.MockObject(TestClass) dummy.__contains__('X').AndReturn(True) dummy._Replay() self.failUnless('X' in dummy) dummy._Verify() def testMockContains_ExpectedContains_NoSuccess(self): """Test that __contains__() gets mocked in Dummy. In this test, _Verify() fails. """ dummy = mox.MockObject(TestClass) dummy.__contains__('X').AndReturn('True') dummy._Replay() # NOT doing 'X' in dummy self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) def testMockContains_ExpectedContains_NonmatchingParameter(self): """Test that __contains__ fails if other parameters are expected.""" dummy = mox.MockObject(TestClass) dummy.__contains__('X').AndReturn(True) dummy._Replay() def call(): return 'Y' in dummy self.assertRaises(mox.UnexpectedMethodCallError, call) dummy._Verify() def testMockIter_ExpectedIter_NoSuccess(self): """Test that __iter__() gets mocked in Dummy. In this test, _Verify() fails. """ dummy = mox.MockObject(TestClass) iter(dummy).AndReturn(iter(['X', 'Y'])) dummy._Replay() # NOT doing self.assertEqual([x for x in dummy], ['X', 'Y']) self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) def testMockIter_ExpectedNoIter_NoSuccess(self): """Test that __iter__() gets mocked in Dummy.""" dummy = mox.MockObject(TestClass) # NOT doing iter(dummy) dummy._Replay() def call(): return [x for x in dummy] self.assertRaises(mox.UnexpectedMethodCallError, call) def testMockIter_ExpectedGetItem_Success(self): """Test that __iter__() gets mocked in Dummy using getitem.""" dummy = mox.MockObject(SubscribtableNonIterableClass) dummy[0].AndReturn('a') dummy[1].AndReturn('b') dummy[2].AndRaise(IndexError) dummy._Replay() self.assertEquals(['a', 'b'], [x for x in dummy]) dummy._Verify() def testMockIter_ExpectedNoGetItem_NoSuccess(self): """Test that __iter__() gets mocked in Dummy using getitem.""" dummy = mox.MockObject(SubscribtableNonIterableClass) # NOT doing dummy[index] dummy._Replay() function = lambda: [x for x in dummy] self.assertRaises(mox.UnexpectedMethodCallError, function) def testMockGetIter_WithSubClassOfNewStyleClass(self): class NewStyleTestClass(object): def __iter__(self): return iter([1, 2, 3]) class TestSubClass(NewStyleTestClass): pass dummy = mox.MockObject(TestSubClass) iter(dummy).AndReturn(iter(['a', 'b'])) dummy._Replay() self.assertEquals(['a', 'b'], [x for x in dummy]) dummy._Verify() class MoxTest(unittest.TestCase): """Verify Mox works correctly.""" def setUp(self): self.mox = mox.Mox() def testCreateObject(self): """Mox should create a mock object.""" mock_obj = self.mox.CreateMock(TestClass) def testVerifyObjectWithCompleteReplay(self): """Mox should replay and verify all objects it created.""" mock_obj = self.mox.CreateMock(TestClass) mock_obj.ValidCall() mock_obj.ValidCallWithArgs(mox.IsA(TestClass)) self.mox.ReplayAll() mock_obj.ValidCall() mock_obj.ValidCallWithArgs(TestClass("some_value")) self.mox.VerifyAll() def testVerifyObjectWithIncompleteReplay(self): """Mox should raise an exception if a mock didn't replay completely.""" mock_obj = self.mox.CreateMock(TestClass) mock_obj.ValidCall() self.mox.ReplayAll() # ValidCall() is never made self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll) def testEntireWorkflow(self): """Test the whole work flow.""" mock_obj = self.mox.CreateMock(TestClass) mock_obj.ValidCall().AndReturn("yes") self.mox.ReplayAll() ret_val = mock_obj.ValidCall() self.assertEquals("yes", ret_val) self.mox.VerifyAll() def testCallableObject(self): """Test recording calls to a callable object works.""" mock_obj = self.mox.CreateMock(CallableClass) mock_obj("foo").AndReturn("qux") self.mox.ReplayAll() ret_val = mock_obj("foo") self.assertEquals("qux", ret_val) self.mox.VerifyAll() def testInheritedCallableObject(self): """Test recording calls to an object inheriting from a callable object.""" mock_obj = self.mox.CreateMock(InheritsFromCallable) mock_obj("foo").AndReturn("qux") self.mox.ReplayAll() ret_val = mock_obj("foo") self.assertEquals("qux", ret_val) self.mox.VerifyAll() def testCallOnNonCallableObject(self): """Test that you cannot call a non-callable object.""" mock_obj = self.mox.CreateMock(TestClass) self.assertRaises(TypeError, mock_obj) def testCallableObjectWithBadCall(self): """Test verifying calls to a callable object works.""" mock_obj = self.mox.CreateMock(CallableClass) mock_obj("foo").AndReturn("qux") self.mox.ReplayAll() self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ") def testUnorderedGroup(self): """Test that using one unordered group works.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Method(1).InAnyOrder() mock_obj.Method(2).InAnyOrder() self.mox.ReplayAll() mock_obj.Method(2) mock_obj.Method(1) self.mox.VerifyAll() def testUnorderedGroupsInline(self): """Unordered groups should work in the context of ordered calls.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).InAnyOrder() mock_obj.Method(2).InAnyOrder() mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() mock_obj.Method(2) mock_obj.Method(1) mock_obj.Close() self.mox.VerifyAll() def testMultipleUnorderdGroups(self): """Multiple unoreded groups should work.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Method(1).InAnyOrder() mock_obj.Method(2).InAnyOrder() mock_obj.Foo().InAnyOrder('group2') mock_obj.Bar().InAnyOrder('group2') self.mox.ReplayAll() mock_obj.Method(2) mock_obj.Method(1) mock_obj.Bar() mock_obj.Foo() self.mox.VerifyAll() def testMultipleUnorderdGroupsOutOfOrder(self): """Multiple unordered groups should maintain external order""" mock_obj = self.mox.CreateMockAnything() mock_obj.Method(1).InAnyOrder() mock_obj.Method(2).InAnyOrder() mock_obj.Foo().InAnyOrder('group2') mock_obj.Bar().InAnyOrder('group2') self.mox.ReplayAll() mock_obj.Method(2) self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar) def testUnorderedGroupWithReturnValue(self): """Unordered groups should work with return values.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).InAnyOrder().AndReturn(9) mock_obj.Method(2).InAnyOrder().AndReturn(10) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() actual_two = mock_obj.Method(2) actual_one = mock_obj.Method(1) mock_obj.Close() self.assertEquals(9, actual_one) self.assertEquals(10, actual_two) self.mox.VerifyAll() def testUnorderedGroupWithComparator(self): """Unordered groups should work with comparators""" def VerifyOne(cmd): if not isinstance(cmd, str): self.fail('Unexpected type passed to comparator: ' + str(cmd)) return cmd == 'test' def VerifyTwo(cmd): return True mock_obj = self.mox.CreateMockAnything() mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\ AndReturn('yes test') mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\ AndReturn('anything') self.mox.ReplayAll() mock_obj.Foo(['test'], 'anything', bar=1) mock_obj.Foo(['test'], 'test', bar=1) self.mox.VerifyAll() def testMultipleTimes(self): """Test if MultipleTimesGroup works.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Method(1).MultipleTimes().AndReturn(9) mock_obj.Method(2).AndReturn(10) mock_obj.Method(3).MultipleTimes().AndReturn(42) self.mox.ReplayAll() actual_one = mock_obj.Method(1) second_one = mock_obj.Method(1) # This tests MultipleTimes. actual_two = mock_obj.Method(2) actual_three = mock_obj.Method(3) mock_obj.Method(3) mock_obj.Method(3) self.mox.VerifyAll() self.assertEquals(9, actual_one) self.assertEquals(9, second_one) # Repeated calls should return same number. self.assertEquals(10, actual_two) self.assertEquals(42, actual_three) def testMultipleTimesUsingIsAParameter(self): """Test if MultipleTimesGroup works with a IsA parameter.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() actual_one = mock_obj.Method("1") second_one = mock_obj.Method("2") # This tests MultipleTimes. mock_obj.Close() self.mox.VerifyAll() self.assertEquals(9, actual_one) self.assertEquals(9, second_one) # Repeated calls should return same number. def testMutlipleTimesUsingFunc(self): """Test that the Func is not evaluated more times than necessary. If a Func() has side effects, it can cause a passing test to fail. """ self.counter = 0 def MyFunc(actual_str): """Increment the counter if actual_str == 'foo'.""" if actual_str == 'foo': self.counter += 1 return True mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(mox.Func(MyFunc)).MultipleTimes() mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() mock_obj.Method('foo') mock_obj.Method('foo') mock_obj.Method('not-foo') mock_obj.Close() self.mox.VerifyAll() self.assertEquals(2, self.counter) def testMultipleTimesThreeMethods(self): """Test if MultipleTimesGroup works with three or more methods.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).MultipleTimes().AndReturn(9) mock_obj.Method(2).MultipleTimes().AndReturn(8) mock_obj.Method(3).MultipleTimes().AndReturn(7) mock_obj.Method(4).AndReturn(10) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() actual_three = mock_obj.Method(3) mock_obj.Method(1) actual_two = mock_obj.Method(2) mock_obj.Method(3) actual_one = mock_obj.Method(1) actual_four = mock_obj.Method(4) mock_obj.Close() self.assertEquals(9, actual_one) self.assertEquals(8, actual_two) self.assertEquals(7, actual_three) self.assertEquals(10, actual_four) self.mox.VerifyAll() def testMultipleTimesMissingOne(self): """Test if MultipleTimesGroup fails if one method is missing.""" mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).MultipleTimes().AndReturn(9) mock_obj.Method(2).MultipleTimes().AndReturn(8) mock_obj.Method(3).MultipleTimes().AndReturn(7) mock_obj.Method(4).AndReturn(10) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() mock_obj.Method(3) mock_obj.Method(2) mock_obj.Method(3) mock_obj.Method(3) mock_obj.Method(2) self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4) def testMultipleTimesTwoGroups(self): """Test if MultipleTimesGroup works with a group after a MultipleTimesGroup. """ mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).MultipleTimes().AndReturn(9) mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() actual_one = mock_obj.Method(1) mock_obj.Method(1) actual_three = mock_obj.Method(3) mock_obj.Method(3) mock_obj.Close() self.assertEquals(9, actual_one) self.assertEquals(42, actual_three) self.mox.VerifyAll() def testMultipleTimesTwoGroupsFailure(self): """Test if MultipleTimesGroup fails with a group after a MultipleTimesGroup. """ mock_obj = self.mox.CreateMockAnything() mock_obj.Open() mock_obj.Method(1).MultipleTimes().AndReturn(9) mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42) mock_obj.Close() self.mox.ReplayAll() mock_obj.Open() actual_one = mock_obj.Method(1) mock_obj.Method(1) actual_three = mock_obj.Method(3) self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1) def testWithSideEffects(self): """Test side effect operations actually modify their target objects.""" def modifier(mutable_list): mutable_list[0] = 'mutated' mock_obj = self.mox.CreateMockAnything() mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier) mock_obj.WorkWithParameter(['mutated']) self.mox.ReplayAll() local_list = ['original'] mock_obj.ConfigureInOutParameter(local_list) mock_obj.WorkWithParameter(local_list) self.mox.VerifyAll() def testWithSideEffectsException(self): """Test side effect operations actually modify their target objects.""" def modifier(mutable_list): mutable_list[0] = 'mutated' mock_obj = self.mox.CreateMockAnything() method = mock_obj.ConfigureInOutParameter(['original']) method.WithSideEffects(modifier).AndRaise(Exception('exception')) mock_obj.WorkWithParameter(['mutated']) self.mox.ReplayAll() local_list = ['original'] self.failUnlessRaises(Exception, mock_obj.ConfigureInOutParameter, local_list) mock_obj.WorkWithParameter(local_list) self.mox.VerifyAll() def testStubOutMethod(self): """Test that a method is replaced with a MockAnything.""" test_obj = TestClass() # Replace OtherValidCall with a mock. self.mox.StubOutWithMock(test_obj, 'OtherValidCall') self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything)) test_obj.OtherValidCall().AndReturn('foo') self.mox.ReplayAll() actual = test_obj.OtherValidCall() self.mox.VerifyAll() self.mox.UnsetStubs() self.assertEquals('foo', actual) self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything)) def testWarnsUserIfMockingMock(self): """Test that user is warned if they try to stub out a MockAnything.""" self.mox.StubOutWithMock(TestClass, 'MyStaticMethod') self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass, 'MyStaticMethod') def testStubOutObject(self): """Test than object is replaced with a Mock.""" class Foo(object): def __init__(self): self.obj = TestClass() foo = Foo() self.mox.StubOutWithMock(foo, "obj") self.assert_(isinstance(foo.obj, mox.MockObject)) foo.obj.ValidCall() self.mox.ReplayAll() foo.obj.ValidCall() self.mox.VerifyAll() self.mox.UnsetStubs() self.failIf(isinstance(foo.obj, mox.MockObject)) def testForgotReplayHelpfulMessage(self): """If there is an AttributeError on a MockMethod, give users a helpful msg. """ foo = self.mox.CreateMockAnything() bar = self.mox.CreateMockAnything() foo.GetBar().AndReturn(bar) bar.ShowMeTheMoney() # Forgot to replay! try: foo.GetBar().ShowMeTheMoney() except AttributeError, e: self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". ' 'Did you remember to put your mocks in replay mode?', str(e)) class ReplayTest(unittest.TestCase): """Verify Replay works properly.""" def testReplay(self): """Replay should put objects into replay mode.""" mock_obj = mox.MockObject(TestClass) self.assertFalse(mock_obj._replay_mode) mox.Replay(mock_obj) self.assertTrue(mock_obj._replay_mode) class MoxTestBaseTest(unittest.TestCase): """Verify that all tests in a class derived from MoxTestBase are wrapped.""" def setUp(self): self.mox = mox.Mox() self.test_mox = mox.Mox() self.result = unittest.TestResult() def tearDown(self): # In case one of our tests fail before UnsetStubs is called. self.mox.UnsetStubs() self.test_mox.UnsetStubs() def _setUpTestClass(self): """Replacement for setUp in the test class instance. Assigns a mox.Mox instance as the mox attribute of the test class instance. This replacement Mox instance is under our control before setUp is called in the test class instance. """ self.test.mox = self.test_mox def _CreateTest(self, test_name): """Create a test from our example mox class. The created test instance is assigned to this instances test attribute. """ self.test = mox_test_helper.ExampleMoxTest(test_name) self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass) def _VerifySuccess(self): """Run the checks to confirm test method completed successfully.""" self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') self.test_mox.UnsetStubs() self.test_mox.VerifyAll() self.mox.ReplayAll() self.test.run(result=self.result) self.assertTrue(self.result.wasSuccessful()) self.mox.UnsetStubs() self.mox.VerifyAll() self.test_mox.UnsetStubs() self.test_mox.VerifyAll() def testSuccess(self): """Successful test method execution test.""" self._CreateTest('testSuccess') self._VerifySuccess() def testExpectedNotCalled(self): """Stubbed out method is not called.""" self._CreateTest('testExpectedNotCalled') self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') # Dont stub out VerifyAll - that's what causes the test to fail self.test_mox.UnsetStubs() self.test_mox.VerifyAll() self.mox.ReplayAll() self.test.run(result=self.result) self.failIf(self.result.wasSuccessful()) self.mox.UnsetStubs() self.mox.VerifyAll() self.test_mox.UnsetStubs() def testUnexpectedCall(self): """Stubbed out method is called with unexpected arguments.""" self._CreateTest('testUnexpectedCall') self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') # Ensure no calls are made to VerifyAll() self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') self.test_mox.UnsetStubs() self.mox.ReplayAll() self.test.run(result=self.result) self.failIf(self.result.wasSuccessful()) self.mox.UnsetStubs() self.mox.VerifyAll() self.test_mox.UnsetStubs() def testFailure(self): """Failing assertion in test method.""" self._CreateTest('testFailure') self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') # Ensure no calls are made to VerifyAll() self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') self.test_mox.UnsetStubs() self.mox.ReplayAll() self.test.run(result=self.result) self.failIf(self.result.wasSuccessful()) self.mox.UnsetStubs() self.mox.VerifyAll() self.test_mox.UnsetStubs() def testMixin(self): """Run test from mix-in test class, ensure it passes.""" self._CreateTest('testStat') self._VerifySuccess() def testMixinAgain(self): """Run same test as above but from the current test class. This ensures metaclass properly wrapped test methods from all base classes. If unsetting of stubs doesn't happen, this will fail. """ self._CreateTest('testStatOther') self._VerifySuccess() class VerifyTest(unittest.TestCase): """Verify Verify works properly.""" def testVerify(self): """Verify should be called for all objects. This should throw an exception because the expected behavior did not occur. """ mock_obj = mox.MockObject(TestClass) mock_obj.ValidCall() mock_obj._Replay() self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj) class ResetTest(unittest.TestCase): """Verify Reset works properly.""" def testReset(self): """Should empty all queues and put mocks in record mode.""" mock_obj = mox.MockObject(TestClass) mock_obj.ValidCall() self.assertFalse(mock_obj._replay_mode) mock_obj._Replay() self.assertTrue(mock_obj._replay_mode) self.assertEquals(1, len(mock_obj._expected_calls_queue)) mox.Reset(mock_obj) self.assertFalse(mock_obj._replay_mode) self.assertEquals(0, len(mock_obj._expected_calls_queue)) class MyTestCase(unittest.TestCase): """Simulate the use of a fake wrapper around Python's unittest library.""" def setUp(self): super(MyTestCase, self).setUp() self.critical_variable = 42 class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase): """Test that multiple inheritance can be used with MoxTestBase.""" def setUp(self): super(MoxTestBaseMultipleInheritanceTest, self).setUp() def testMultipleInheritance(self): """Should be able to access members created by all parent setUp().""" self.assert_(isinstance(self.mox, mox.Mox)) self.assertEquals(42, self.critical_variable) class TestClass: """This class is used only for testing the mock framework""" SOME_CLASS_VAR = "test_value" _PROTECTED_CLASS_VAR = "protected value" def __init__(self, ivar=None): self.__ivar = ivar def __eq__(self, rhs): return self.__ivar == rhs def __ne__(self, rhs): return not self.__eq__(rhs) def ValidCall(self): pass def OtherValidCall(self): pass def ValidCallWithArgs(self, *args, **kwargs): pass @classmethod def MyClassMethod(cls): pass @staticmethod def MyStaticMethod(): pass def _ProtectedCall(self): pass def __PrivateCall(self): pass def __getitem__(self, key): pass def __DoNotMock(self): pass def __getitem__(self, key): """Return the value for key.""" return self.d[key] def __setitem__(self, key, value): """Set the value for key to value.""" self.d[key] = value def __contains__(self, key): """Returns True if d contains the key.""" return key in self.d def __iter__(self): pass class ChildClass(TestClass): """This inherits from TestClass.""" def __init__(self): TestClass.__init__(self) def ChildValidCall(self): pass class CallableClass(object): """This class is callable, and that should be mockable!""" def __init__(self): pass def __call__(self, param): return param class SubscribtableNonIterableClass(object): def __getitem__(self, index): raise IndexError class InheritsFromCallable(CallableClass): """This class should also be mockable; it inherits from a callable class.""" pass if __name__ == '__main__': unittest.main()
from collections import deque import os import pydot import socket import sys import time import rosgraph from rosgraph.impl import graph import rwlock class UnreachableRos(Exception): """Raised when ROS not reachable.""" pass def escape_text(text): return text # return text.replace('/', '_').replace('%', '_').replace('-', '_') class Node(object): def __init__(self, name, incoming=None, outgoing=None, edges=None): self.name = name self.incoming = incoming or set() self.outgoing = set() self.edges = edges or set() def add_incoming(self, item): self.incoming.add(item) def add_outgoing(self, item): self.outgoing.add(item) # Idea taken from PydotFactory class GraphWrapper(object): def __init__(self, graphname='graphname', graph_type='digraph', rank='same', simplify=True, rankdir='LR', ranksep=0.2, compound=True, graph=None): self.subgraphs = dict() if graph: self.graph = graph return self.graph = pydot.Dot(escape_text(graphname), graph_type=graph_type, rank=rank, rankdir=rankdir, simplify=simplify, compound=compound, ratio='fill') self.graph.set_ranksep(ranksep) self.graph.set_compound(compound) @staticmethod def _customize_item(item, label=None, color=None, url=None, style=None, shape=None): if color: item.set_color(color) if url: item.set_URL(url) if label: item.set_label(label) if style: item.set_style(style) if shape: item.set_shape(shape) def add_node(self, nodename, nodelabel=None, shape='circle', color=None, url=None): if not nodename: raise ValueError("Empty nodename") # TODO we might want to escape some characters. See pydot node = pydot.Node(escape_text(nodename)) self._customize_item(node, label=nodelabel, shape=shape, color=color, url=url) self.graph.add_node(node) def add_edge(self, nodename1, nodename2, label=None, simplify=True, style=None, penwidth=1, url=None, color=None): if label: label = escape_text(label) edge = pydot.Edge(nodename1, nodename2) self._customize_item(edge, label=None, style=style, url=url) edge.obj_dict['attributes']['penwidth'] = str(penwidth) if color: edge.obj_dict['attributes']['colorR'] = str(color[0]) edge.obj_dict['attributes']['colorG'] = str(color[1]) edge.obj_dict['attributes']['colorB'] = str(color[2]) self.graph.add_edge(edge) def add_cluster(self, name, label=None, rank='same', rankdir='TB', simplify=True, color=None, shape='circle', compound=True, style='bold', ranksep=0.2, orientation='portrait'): name = escape_text(name) c = pydot.Cluster(escape_text(name), rank=rank, rankdir=rankdir, simplify=simplify) if 'set_shape' in c.__dict__: c.set_shape(shape) if 'set_style' in c.__dict__: c.set_style(style) if 'set_color' in c.__dict__: c.set_color(color) c.set_compound(compound) c.set_ranksep(ranksep) c.set_label(label or name) self.graph.add_subgraph(c) self.subgraphs[name] = GraphWrapper(graph=c) # print(c.get_name()) return self.subgraphs[name] def get_cluster(self, name): return self.subgraphs[escape_text(name)] def generate_dot(self, path): self.graph.write_svg(path) return self.graph class Generator(object): def __init__(self): self.last_svg_generated = None self.last_svg_generated_ts = 0 self.rwlock = rwlock.RWLock() self.svg_nodes_topics = dict() self.svg_list = deque(maxlen=2) # Keep the last 2 svg self.master = rosgraph.Master('/rostopic') def _check_master(self): try: self.master.getPid() except socket.error: raise UnreachableRos("Master not available") @staticmethod def _filter_nodes(nodes, exclude): if exclude is None: return {n.strip() for n in nodes} ret = set() for n_ in nodes: n = n_.strip() skip = False for e in exclude: if n.startswith(e): skip = True break if not skip: ret.add(n) return ret def _generate_graph(self, path, nodes_include=None, nodes_exclude=None, topics_include=None, topics_exclude=None, hide_dead_sinks=True): nn_nodes = self._filter_nodes(self._graph.nn_nodes, nodes_exclude) topics = self._filter_nodes(self._graph.nt_nodes, topics_exclude) edges = {e for e in self._graph.nt_all_edges} graph_dict = {} for e in edges: start = e.start.strip() end = e.end.strip() if start not in graph_dict: graph_dict[start] = Node(start) if end not in graph_dict: graph_dict[end] = Node(end) graph_dict[start].add_outgoing(e) graph_dict[end].add_incoming(e) graph = GraphWrapper() for node in nn_nodes: graph.add_node(node, shape='box') if hide_dead_sinks: filtered_topics = [e for e in topics if e in graph_dict and len(graph_dict[e].outgoing) > 0] else: filtered_topics = topics # Clustering last_namespace = "" namespaces = set() str_edges = [e.split('/')[1:] for e in sorted(filtered_topics)] for spl in str_edges: if spl[0] == last_namespace: namespaces.add(last_namespace) last_namespace = spl[0] for n in namespaces: graph.add_cluster(n) for topic in filtered_topics: try: nspace = topic.strip()[1:topic.index('/', 1)] except ValueError: nspace = topic.strip()[1:] if nspace in namespaces: graph.get_cluster(nspace).add_node(topic, shape='diamond') else: graph.add_node(topic, shape='diamond') for e in edges: start = e.start.strip() end = e.end.strip() exclude = False # TODO check this if (start not in filtered_topics and end not in filtered_topics): continue if nodes_exclude is not None: for n in nodes_exclude: if end.startswith(n) or start.startswith(n): exclude = True break if not exclude and topics_exclude is not None: for n in nodes_exclude: if end.startswith(n) or start.startswith(n): exclude = True break if exclude: continue graph.add_edge(start, end, label=str(e)) dot = graph.generate_dot(path) self.topics = list(filtered_topics) self.nodes = list(nn_nodes) def generate(self, path, **kwargs): self._graph = rosgraph.impl.graph.Graph() self._graph.set_master_stale(5.0) self._graph.set_node_stale(5.0) try: self._graph.update() except socket.error: raise UnreachableRos("Ros not reachable") self._generate_graph(path, **kwargs) self.svg_nodes_topics = dict() self.svg_list = deque(maxlen=2) # Keep the last 2 svg def get_current_svg(self, prefix="", file_name=None, max_time_to_refresh=5, **kwargs): # TODO when do we remove old files ? with rwlock.read_lock(self.rwlock): now = time.time() name = file_name if file_name else "%s.svg" % now path = os.path.join(prefix, name) if now - self.last_svg_generated_ts > max_time_to_refresh: self.rwlock.promote() self.generate(path, **kwargs) self.last_svg_generated = path self.last_svg_generated_ts = now self.svg_nodes_topics[self.last_svg_generated] = (self.topics, self.nodes) #TODO remove the svg getting discarded here self.svg_list.append(self.last_svg_generated) return self.last_svg_generated def get_svg_nodes_topics_lists(self, svg_name): return self.svg_nodes_topics[svg_name] def main(): g = Generator() g.generate() pass if __name__ == '__main__': main()
import logging import time from contextlib import contextmanager from queue import Empty from queue import PriorityQueue from queue import Queue from threading import Condition from threading import Event from threading import Thread from typing import Any from typing import Collection from typing import Generator from typing import Iterable from typing import List from typing import NamedTuple from typing import Optional from typing import Tuple from typing_extensions import Protocol from paasta_tools.marathon_tools import DEFAULT_SOA_DIR from paasta_tools.marathon_tools import get_all_marathon_apps from paasta_tools.marathon_tools import get_marathon_clients from paasta_tools.marathon_tools import get_marathon_servers from paasta_tools.marathon_tools import load_marathon_service_config_no_cache from paasta_tools.marathon_tools import MarathonClients from paasta_tools.marathon_tools import MarathonServiceConfig from paasta_tools.metrics.metrics_lib import TimerProtocol from paasta_tools.utils import load_system_paasta_config class BounceTimers(NamedTuple): processed_by_worker: TimerProtocol setup_marathon: TimerProtocol bounce_length: TimerProtocol class ServiceInstance(NamedTuple): service: str instance: str watcher: str bounce_by: float wait_until: float enqueue_time: float bounce_start_time: float failures: int = 0 processed_count: int = 0 # Hack to make the default values for ServiceInstance work on python 3.6.0. (typing.NamedTuple gained default values in # python 3.6.1.) ServiceInstance.__new__.__defaults__ = (0, 0) # type: ignore class PaastaThread(Thread): @property def log(self) -> logging.Logger: name = ".".join([type(self).__module__, type(self).__name__]) return logging.getLogger(name) class PaastaQueue(Queue): def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: self.name = name super().__init__(*args, **kwargs) @property def log(self) -> logging.Logger: name = ".".join([type(self).__module__, type(self).__name__]) return logging.getLogger(name) def put(self, item: Any, *args: Any, **kwargs: Any) -> None: self.log.debug(f"Adding {item} to {self.name} queue") super().put(item, *args, **kwargs) def exponential_back_off( failures: int, factor: float, base: float, max_time: float ) -> float: seconds = factor * base ** failures return seconds if seconds < max_time else max_time def get_service_instances_needing_update( marathon_clients: MarathonClients, instances: Collection[Tuple[str, str]], cluster: str, ) -> List[Tuple[str, str, MarathonServiceConfig, str]]: marathon_apps = {} for marathon_client in marathon_clients.get_all_clients(): marathon_apps.update( {app.id: app for app in get_all_marathon_apps(marathon_client)} ) marathon_app_ids = marathon_apps.keys() service_instances = [] for service, instance in instances: try: config = load_marathon_service_config_no_cache( service=service, instance=instance, cluster=cluster, soa_dir=DEFAULT_SOA_DIR, ) config_app = config.format_marathon_app_dict() app_id = "/{}".format(config_app["id"]) # Not ideal but we rely on a lot of user input to create the app dict # and we really can't afford to bail if just one app definition is malformed except Exception as e: print( "ERROR: Skipping {}.{} because: '{}'".format(service, instance, str(e)) ) continue if ( app_id not in marathon_app_ids or marathon_apps[app_id].instances != config_app["instances"] ): service_instances.append((service, instance, config, app_id)) return service_instances def get_marathon_clients_from_config() -> MarathonClients: system_paasta_config = load_system_paasta_config() marathon_servers = get_marathon_servers(system_paasta_config) marathon_clients = get_marathon_clients(marathon_servers) return marathon_clients class DelayDeadlineQueueProtocol(Protocol): def __init__(self) -> None: ... def put(self, si: ServiceInstance) -> None: ... @contextmanager def get( self, block: bool = True, timeout: float = None ) -> Generator[ServiceInstance, None, None]: ... def get_available_service_instances( self, fetch_service_instances: bool ) -> Iterable[Tuple[float, Optional[ServiceInstance]]]: ... def get_unavailable_service_instances( self, fetch_service_instances: bool ) -> Iterable[Tuple[float, float, Optional[ServiceInstance]]]: ... class DelayDeadlineQueue(DelayDeadlineQueueProtocol): """Entries into this queue have both a wait_until and a bounce_by. Before wait_until, get() will not return an entry. get() returns the entry whose wait_until has passed and which has the lowest bounce_by.""" def __init__(self) -> None: self.available_service_instances: PriorityQueue[ Tuple[float, ServiceInstance] ] = PriorityQueue() self.unavailable_service_instances: PriorityQueue[ Tuple[float, float, ServiceInstance] ] = PriorityQueue() self.unavailable_service_instances_modify = Condition() self.background_thread_started = Event() Thread(target=self.move_from_unavailable_to_available, daemon=True).start() self.background_thread_started.wait() @property def log(self) -> logging.Logger: name = ".".join([type(self).__module__, type(self).__name__]) return logging.getLogger(name) def put(self, si: ServiceInstance) -> None: self.log.debug( f"adding {si.service}.{si.instance} to queue with wait_until {si.wait_until} and bounce_by {si.bounce_by}" ) with self.unavailable_service_instances_modify: self.unavailable_service_instances.put((si.wait_until, si.bounce_by, si)) self.unavailable_service_instances_modify.notify() def move_from_unavailable_to_available(self) -> None: self.background_thread_started.set() with self.unavailable_service_instances_modify: while True: try: while True: ( wait_until, bounce_by, si, ) = self.unavailable_service_instances.get_nowait() if wait_until < time.time(): self.available_service_instances.put_nowait((bounce_by, si)) else: self.unavailable_service_instances.put_nowait( (wait_until, bounce_by, si) ) timeout = wait_until - time.time() break except Empty: timeout = None self.unavailable_service_instances_modify.wait(timeout=timeout) @contextmanager def get( self, block: bool = True, timeout: float = None ) -> Generator[ServiceInstance, None, None]: bounce_by, si = self.available_service_instances.get( block=block, timeout=timeout ) try: yield si except Exception: self.available_service_instances.put((bounce_by, si)) def get_available_service_instances( self, fetch_service_instances: bool ) -> Iterable[Tuple[float, Optional[ServiceInstance]]]: return [ (bounce_by, (si if fetch_service_instances else None)) for bounce_by, si in self.available_service_instances.queue ] def get_unavailable_service_instances( self, fetch_service_instances: bool ) -> Iterable[Tuple[float, float, Optional[ServiceInstance]]]: return [ (wait_until, bounce_by, (si if fetch_service_instances else None)) for wait_until, bounce_by, si in self.unavailable_service_instances.queue ]
from testreport.models import Launch, TestResult, Build from testreport.models import FINISHED from testreport.models import PASSED, FAILED, SKIPPED, BLOCKED from django.conf import settings import datetime import logging import socket import xml.dom.minidom import json log = logging.getLogger(__name__) def get_launch(launch_id): return Launch.objects.get(id=launch_id) def create_launch(plan_id): launch = Launch.objects.create( test_plan_id=plan_id, state=FINISHED, started_by='http://{}'.format(socket.getfqdn()), finished=datetime.datetime.now()) return launch class XmlParser: buffer = [] launch_id = None buffer_size = 100 total_duration = 0 def __init__(self, launch_id): self.launch_id = launch_id def load_string(self, file_content): log.info('Loading file_content') dom = xml.dom.minidom.parseString(file_content) self.parse(dom) def get_node(self, element, names): for node in element.childNodes: if node.nodeName in names: return node return None def get_text(self, nodelist): rc = [] for node in nodelist: if node.nodeType in [node.TEXT_NODE, node.CDATA_SECTION_NODE, node.COMMENT_NODE]: rc.append(node.data) return ''.join(rc) def update_duration(self, launch): log.info('Updating total duration for launch {}'.format(launch.id)) if launch.duration is None: launch.duration = self.total_duration launch.save() class JunitParser(XmlParser): def parse(self, element, path=''): if element.nodeName == 'testcase': self.create_test_result(element, path) if element.nodeName == 'testsuite': path += element.getAttribute('name') + '/' if element.hasChildNodes(): for node in element.childNodes: if node.nodeType == node.ELEMENT_NODE: self.parse(node, path) def create_test_result(self, element, path): result = TestResult.objects.create(launch_id=self.launch_id) duration = element.getAttribute('time') if duration == '': result.duration = 0 else: result.duration = duration self.total_duration += float(result.duration) result.name = element.getAttribute('name')[:127] result.suite = path[:125] result.state = BLOCKED result.failure_reason = '' failure = self.get_node(element, ['failure']) error = self.get_node(element, ['error']) skipped = self.get_node(element, ['skipped']) if skipped is not None: result.state = SKIPPED result.failure_reason = self.get_text(skipped.childNodes) elif failure is not None: result.state = FAILED result.failure_reason = self.get_text(failure.childNodes) elif error is not None: result.failure_reason = self.get_text(error.childNodes) else: result.state = PASSED if not element.getAttribute('format'): system_out = self.get_node(element, 'system-out') if system_out is not None: result.failure_reason += self.get_text(system_out.childNodes) result.save() class QtTestXunitParser(JunitParser): def create_test_result(self, element, path): result = TestResult.objects.create(launch_id=self.launch_id) result.duration = 0 result.name = element.getAttribute('name')[:127] result.suite = path[:125] result.state = BLOCKED result.failure_reason = '' test_result = element.getAttribute('result') if test_result == 'pass': result.state = PASSED elif test_result == '': result.state = SKIPPED result.failure_reason = self.get_text(element.childNodes) elif test_result == 'fail': result.state = FAILED failure = self.get_node(element, ['failure']) logs = self.get_text(element.childNodes) failure_reason = failure.getAttribute('message') if logs: failure_reason = '{}\n\nLogs:{}'.format(failure_reason, logs) result.failure_reason = failure_reason result.save() class XCPrettyJunitParser(JunitParser): def create_test_result(self, element, path): """ https://github.com/supermarin/xcpretty/blob/master/lib/xcpretty/reporters/junit.rb """ result = TestResult.objects.create(launch_id=self.launch_id) result.duration = 0 result.name = element.getAttribute('name')[:127] result.suite = path[:125] result.state = BLOCKED result.failure_reason = '' failure = self.get_node(element, ['failure']) skipped = self.get_node(element, ['skipped']) if skipped is not None: result.state = SKIPPED elif failure is not None: result.state = FAILED failure_reason = failure.getAttribute('message') failure_code_line = self.get_text(failure.childNodes) result.failure_reason = "{}\n\n{}".format(failure_code_line, failure_reason) else: result.state = PASSED result.save() class NunitParser(XmlParser): def parse(self, element, path=''): if element.nodeName == 'test-case': self.create_test_result(element) if element.hasChildNodes(): for node in element.childNodes: if node.nodeType == node.ELEMENT_NODE: self.parse(node, path) def create_test_result(self, element): result = TestResult.objects.create(launch_id=self.launch_id) result.state = BLOCKED result.failure_reason = '' duration = element.getAttribute('time') if duration == '': result.duration = 0 else: result.duration = duration self.total_duration += float(result.duration) if element.getAttribute('result') in ['Ignored', 'Inconclusive']: if element.getAttribute('result') == 'Ignored': result.state = SKIPPED if element.getAttribute('result') == 'Inconclusive': result.state = BLOCKED reason = self.get_node(element, ['reason']) message = self.get_node(reason, ['message']) result.failure_reason = self.get_text(message.childNodes) if element.getAttribute('result') in ['Failure', 'Error']: if element.getAttribute('result') == 'Failure': result.state = FAILED if element.getAttribute('result') == 'Error': result.state = BLOCKED failure = self.get_node(element, ['failure']) message = self.get_node(failure, ['message']) trace = self.get_node(failure, ['stack-trace']) failure_reason = self.get_text(message.childNodes) if trace is not None and self.get_text(trace.childNodes) != '': failure_reason += '\n\nStackTrace:\n' failure_reason += self.get_text(trace.childNodes) result.failure_reason = failure_reason if element.getAttribute('result') == 'Success': result.state = PASSED result.name = element.getAttribute('name')[:127] result.save() def xml_parser_func(format, file_content, launch_id, params): launch = get_launch(launch_id) if params is not None and launch.parameters == '{}': launch.parameters = params params_json = json.loads(params) if 'options' in params_json \ and params_json['options']['started_by'] != '': if params_json['options'].get('duration') is not None: launch.duration = float(params_json['options']['duration']) launch.started_by = params_json['options']['started_by'] commits = params_json['options'].get('last_commits') if commits is not None \ and len(commits) > settings.LAST_COMMITS_SIZE: commits = commits[:settings.LAST_COMMITS_SIZE] build_hash = params_json['options'].get('hash') if build_hash is None and commits is not None: build_hash = commits[0] build = Build( launch=launch, version=params_json['options'].get('version'), branch=params_json['options'].get('branch'), hash=build_hash, commit_message=params_json['options'].get('commit_message'), commit_author=params_json['options'].get('commit_author')) build.set_last_commits(commits) build.save() if format == 'nunit': parser = NunitParser(launch.id) elif format == 'junit': parser = JunitParser(launch.id) elif format == 'qttestxunit': parser = QtTestXunitParser(launch.id) elif format == 'xcprettyjunit': parser = XCPrettyJunitParser(launch.id) parser.load_string(file_content) parser.update_duration(launch)
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the RBF code.""" from test_framework.test_framework import SarielsazTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * MAX_REPLACEMENT_LIMIT = 100 def txToHex(tx): return bytes_to_hex_str(tx.serialize()) def make_utxo(node, amount, confirmed=True, scriptPubKey=CScript([1])): """Create a txout with a given amount and scriptPubKey Mines coins as needed. confirmed - txouts created will be confirmed in the blockchain; unconfirmed otherwise. """ fee = 1*COIN while node.getbalance() < satoshi_round((amount + fee)/COIN): node.generate(100) new_addr = node.getnewaddress() txid = node.sendtoaddress(new_addr, satoshi_round((amount+fee)/COIN)) tx1 = node.getrawtransaction(txid, 1) txid = int(txid, 16) i = None for i, txout in enumerate(tx1['vout']): if txout['scriptPubKey']['addresses'] == [new_addr]: break assert i is not None tx2 = CTransaction() tx2.vin = [CTxIn(COutPoint(txid, i))] tx2.vout = [CTxOut(amount, scriptPubKey)] tx2.rehash() signed_tx = node.signrawtransaction(txToHex(tx2)) txid = node.sendrawtransaction(signed_tx['hex'], True) # If requested, ensure txouts are confirmed. if confirmed: mempool_size = len(node.getrawmempool()) while mempool_size > 0: node.generate(1) new_size = len(node.getrawmempool()) # Error out if we have something stuck in the mempool, as this # would likely be a bug. assert(new_size < mempool_size) mempool_size = new_size return COutPoint(int(txid, 16), 0) class ReplaceByFeeTest(SarielsazTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args= [["-maxorphantx=1000", "-whitelist=127.0.0.1", "-limitancestorcount=50", "-limitancestorsize=101", "-limitdescendantcount=200", "-limitdescendantsize=101"], ["-mempoolreplacement=0"]] def run_test(self): make_utxo(self.nodes[0], 1*COIN) self.log.info("Running test simple doublespend...") self.test_simple_doublespend() self.log.info("Running test doublespend chain...") self.test_doublespend_chain() self.log.info("Running test doublespend tree...") self.test_doublespend_tree() self.log.info("Running test replacement feeperkb...") self.test_replacement_feeperkb() self.log.info("Running test spends of conflicting outputs...") self.test_spends_of_conflicting_outputs() self.log.info("Running test new unconfirmed inputs...") self.test_new_unconfirmed_inputs() self.log.info("Running test too many replacements...") self.test_too_many_replacements() self.log.info("Running test opt-in...") self.test_opt_in() self.log.info("Running test RPC...") self.test_rpc() self.log.info("Running test prioritised transactions...") self.test_prioritised_transactions() self.log.info("Passed") def test_simple_doublespend(self): """Simple doublespend""" tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) tx1a = CTransaction() tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1a_hex = txToHex(tx1a) tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True) self.sync_all([self.nodes]) # Should fail because we haven't changed the fee tx1b = CTransaction() tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1b.vout = [CTxOut(1*COIN, CScript([b'b']))] tx1b_hex = txToHex(tx1b) # This will raise an exception due to insufficient fee assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) # This will raise an exception due to transaction replacement being disabled assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True) # Extra 0.1 BTC fee tx1b = CTransaction() tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))] tx1b_hex = txToHex(tx1b) # Replacement still disabled even with "enough fee" assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True) # Works when enabled tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True) mempool = self.nodes[0].getrawmempool() assert (tx1a_txid not in mempool) assert (tx1b_txid in mempool) assert_equal(tx1b_hex, self.nodes[0].getrawtransaction(tx1b_txid)) # Second node is running mempoolreplacement=0, will not replace originally-seen txn mempool = self.nodes[1].getrawmempool() assert tx1a_txid in mempool assert tx1b_txid not in mempool def test_doublespend_chain(self): """Doublespend of a long chain""" initial_nValue = 50*COIN tx0_outpoint = make_utxo(self.nodes[0], initial_nValue) prevout = tx0_outpoint remaining_value = initial_nValue chain_txids = [] while remaining_value > 10*COIN: remaining_value -= 1*COIN tx = CTransaction() tx.vin = [CTxIn(prevout, nSequence=0)] tx.vout = [CTxOut(remaining_value, CScript([1]))] tx_hex = txToHex(tx) txid = self.nodes[0].sendrawtransaction(tx_hex, True) chain_txids.append(txid) prevout = COutPoint(int(txid, 16), 0) # Whether the double-spend is allowed is evaluated by including all # child fees - 40 BTC - so this attempt is rejected. dbl_tx = CTransaction() dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)] dbl_tx.vout = [CTxOut(initial_nValue - 30*COIN, CScript([1]))] dbl_tx_hex = txToHex(dbl_tx) # This will raise an exception due to insufficient fee assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) # Accepted with sufficient fee dbl_tx = CTransaction() dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)] dbl_tx.vout = [CTxOut(1*COIN, CScript([1]))] dbl_tx_hex = txToHex(dbl_tx) self.nodes[0].sendrawtransaction(dbl_tx_hex, True) mempool = self.nodes[0].getrawmempool() for doublespent_txid in chain_txids: assert(doublespent_txid not in mempool) def test_doublespend_tree(self): """Doublespend of a big tree of transactions""" initial_nValue = 50*COIN tx0_outpoint = make_utxo(self.nodes[0], initial_nValue) def branch(prevout, initial_value, max_txs, tree_width=5, fee=0.0001*COIN, _total_txs=None): if _total_txs is None: _total_txs = [0] if _total_txs[0] >= max_txs: return txout_value = (initial_value - fee) // tree_width if txout_value < fee: return vout = [CTxOut(txout_value, CScript([i+1])) for i in range(tree_width)] tx = CTransaction() tx.vin = [CTxIn(prevout, nSequence=0)] tx.vout = vout tx_hex = txToHex(tx) assert(len(tx.serialize()) < 100000) txid = self.nodes[0].sendrawtransaction(tx_hex, True) yield tx _total_txs[0] += 1 txid = int(txid, 16) for i, txout in enumerate(tx.vout): for x in branch(COutPoint(txid, i), txout_value, max_txs, tree_width=tree_width, fee=fee, _total_txs=_total_txs): yield x fee = int(0.0001*COIN) n = MAX_REPLACEMENT_LIMIT tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee)) assert_equal(len(tree_txs), n) # Attempt double-spend, will fail because too little fee paid dbl_tx = CTransaction() dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)] dbl_tx.vout = [CTxOut(initial_nValue - fee*n, CScript([1]))] dbl_tx_hex = txToHex(dbl_tx) # This will raise an exception due to insufficient fee assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) # 1 BTC fee is enough dbl_tx = CTransaction() dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)] dbl_tx.vout = [CTxOut(initial_nValue - fee*n - 1*COIN, CScript([1]))] dbl_tx_hex = txToHex(dbl_tx) self.nodes[0].sendrawtransaction(dbl_tx_hex, True) mempool = self.nodes[0].getrawmempool() for tx in tree_txs: tx.rehash() assert (tx.hash not in mempool) # Try again, but with more total transactions than the "max txs # double-spent at once" anti-DoS limit. for n in (MAX_REPLACEMENT_LIMIT+1, MAX_REPLACEMENT_LIMIT*2): fee = int(0.0001*COIN) tx0_outpoint = make_utxo(self.nodes[0], initial_nValue) tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee)) assert_equal(len(tree_txs), n) dbl_tx = CTransaction() dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)] dbl_tx.vout = [CTxOut(initial_nValue - 2*fee*n, CScript([1]))] dbl_tx_hex = txToHex(dbl_tx) # This will raise an exception assert_raises_rpc_error(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) for tx in tree_txs: tx.rehash() self.nodes[0].getrawtransaction(tx.hash) def test_replacement_feeperkb(self): """Replacement requires fee-per-KB to be higher""" tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) tx1a = CTransaction() tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1a_hex = txToHex(tx1a) self.nodes[0].sendrawtransaction(tx1a_hex, True) # Higher fee, but the fee per KB is much lower, so the replacement is # rejected. tx1b = CTransaction() tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1b.vout = [CTxOut(int(0.001*COIN), CScript([b'a'*999000]))] tx1b_hex = txToHex(tx1b) # This will raise an exception due to insufficient fee assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) def test_spends_of_conflicting_outputs(self): """Replacements that spend conflicting tx outputs are rejected""" utxo1 = make_utxo(self.nodes[0], int(1.2*COIN)) utxo2 = make_utxo(self.nodes[0], 3*COIN) tx1a = CTransaction() tx1a.vin = [CTxIn(utxo1, nSequence=0)] tx1a.vout = [CTxOut(int(1.1*COIN), CScript([b'a']))] tx1a_hex = txToHex(tx1a) tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True) tx1a_txid = int(tx1a_txid, 16) # Direct spend an output of the transaction we're replacing. tx2 = CTransaction() tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0)] tx2.vin.append(CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)) tx2.vout = tx1a.vout tx2_hex = txToHex(tx2) # This will raise an exception assert_raises_rpc_error(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True) # Spend tx1a's output to test the indirect case. tx1b = CTransaction() tx1b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)] tx1b.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1b_hex = txToHex(tx1b) tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True) tx1b_txid = int(tx1b_txid, 16) tx2 = CTransaction() tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0), CTxIn(COutPoint(tx1b_txid, 0))] tx2.vout = tx1a.vout tx2_hex = txToHex(tx2) # This will raise an exception assert_raises_rpc_error(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True) def test_new_unconfirmed_inputs(self): """Replacements that add new unconfirmed inputs are rejected""" confirmed_utxo = make_utxo(self.nodes[0], int(1.1*COIN)) unconfirmed_utxo = make_utxo(self.nodes[0], int(0.1*COIN), False) tx1 = CTransaction() tx1.vin = [CTxIn(confirmed_utxo)] tx1.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1_hex = txToHex(tx1) self.nodes[0].sendrawtransaction(tx1_hex, True) tx2 = CTransaction() tx2.vin = [CTxIn(confirmed_utxo), CTxIn(unconfirmed_utxo)] tx2.vout = tx1.vout tx2_hex = txToHex(tx2) # This will raise an exception assert_raises_rpc_error(-26, "replacement-adds-unconfirmed", self.nodes[0].sendrawtransaction, tx2_hex, True) def test_too_many_replacements(self): """Replacements that evict too many transactions are rejected""" # Try directly replacing more than MAX_REPLACEMENT_LIMIT # transactions # Start by creating a single transaction with many outputs initial_nValue = 10*COIN utxo = make_utxo(self.nodes[0], initial_nValue) fee = int(0.0001*COIN) split_value = int((initial_nValue-fee)/(MAX_REPLACEMENT_LIMIT+1)) outputs = [] for i in range(MAX_REPLACEMENT_LIMIT+1): outputs.append(CTxOut(split_value, CScript([1]))) splitting_tx = CTransaction() splitting_tx.vin = [CTxIn(utxo, nSequence=0)] splitting_tx.vout = outputs splitting_tx_hex = txToHex(splitting_tx) txid = self.nodes[0].sendrawtransaction(splitting_tx_hex, True) txid = int(txid, 16) # Now spend each of those outputs individually for i in range(MAX_REPLACEMENT_LIMIT+1): tx_i = CTransaction() tx_i.vin = [CTxIn(COutPoint(txid, i), nSequence=0)] tx_i.vout = [CTxOut(split_value-fee, CScript([b'a']))] tx_i_hex = txToHex(tx_i) self.nodes[0].sendrawtransaction(tx_i_hex, True) # Now create doublespend of the whole lot; should fail. # Need a big enough fee to cover all spending transactions and have # a higher fee rate double_spend_value = (split_value-100*fee)*(MAX_REPLACEMENT_LIMIT+1) inputs = [] for i in range(MAX_REPLACEMENT_LIMIT+1): inputs.append(CTxIn(COutPoint(txid, i), nSequence=0)) double_tx = CTransaction() double_tx.vin = inputs double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))] double_tx_hex = txToHex(double_tx) # This will raise an exception assert_raises_rpc_error(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, double_tx_hex, True) # If we remove an input, it should pass double_tx = CTransaction() double_tx.vin = inputs[0:-1] double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))] double_tx_hex = txToHex(double_tx) self.nodes[0].sendrawtransaction(double_tx_hex, True) def test_opt_in(self): """Replacing should only work if orig tx opted in""" tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) # Create a non-opting in transaction tx1a = CTransaction() tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0xffffffff)] tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1a_hex = txToHex(tx1a) tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True) # Shouldn't be able to double-spend tx1b = CTransaction() tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))] tx1b_hex = txToHex(tx1b) # This will raise an exception assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx1b_hex, True) tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) # Create a different non-opting in transaction tx2a = CTransaction() tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0xfffffffe)] tx2a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx2a_hex = txToHex(tx2a) tx2a_txid = self.nodes[0].sendrawtransaction(tx2a_hex, True) # Still shouldn't be able to double-spend tx2b = CTransaction() tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)] tx2b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))] tx2b_hex = txToHex(tx2b) # This will raise an exception assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx2b_hex, True) # Now create a new transaction that spends from tx1a and tx2a # opt-in on one of the inputs # Transaction should be replaceable on either input tx1a_txid = int(tx1a_txid, 16) tx2a_txid = int(tx2a_txid, 16) tx3a = CTransaction() tx3a.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0xffffffff), CTxIn(COutPoint(tx2a_txid, 0), nSequence=0xfffffffd)] tx3a.vout = [CTxOut(int(0.9*COIN), CScript([b'c'])), CTxOut(int(0.9*COIN), CScript([b'd']))] tx3a_hex = txToHex(tx3a) self.nodes[0].sendrawtransaction(tx3a_hex, True) tx3b = CTransaction() tx3b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)] tx3b.vout = [CTxOut(int(0.5*COIN), CScript([b'e']))] tx3b_hex = txToHex(tx3b) tx3c = CTransaction() tx3c.vin = [CTxIn(COutPoint(tx2a_txid, 0), nSequence=0)] tx3c.vout = [CTxOut(int(0.5*COIN), CScript([b'f']))] tx3c_hex = txToHex(tx3c) self.nodes[0].sendrawtransaction(tx3b_hex, True) # If tx3b was accepted, tx3c won't look like a replacement, # but make sure it is accepted anyway self.nodes[0].sendrawtransaction(tx3c_hex, True) def test_prioritised_transactions(self): # Ensure that fee deltas used via prioritisetransaction are # correctly used by replacement logic # 1. Check that feeperkb uses modified fees tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) tx1a = CTransaction() tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx1a_hex = txToHex(tx1a) tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True) # Higher fee, but the actual fee per KB is much lower. tx1b = CTransaction() tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)] tx1b.vout = [CTxOut(int(0.001*COIN), CScript([b'a'*740000]))] tx1b_hex = txToHex(tx1b) # Verify tx1b cannot replace tx1a. assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) # Use prioritisetransaction to set tx1a's fee to 0. self.nodes[0].prioritisetransaction(txid=tx1a_txid, fee_delta=int(-0.1*COIN)) # Now tx1b should be able to replace tx1a tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True) assert(tx1b_txid in self.nodes[0].getrawmempool()) # 2. Check that absolute fee checks use modified fee. tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) tx2a = CTransaction() tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0)] tx2a.vout = [CTxOut(1*COIN, CScript([b'a']))] tx2a_hex = txToHex(tx2a) self.nodes[0].sendrawtransaction(tx2a_hex, True) # Lower fee, but we'll prioritise it tx2b = CTransaction() tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)] tx2b.vout = [CTxOut(int(1.01*COIN), CScript([b'a']))] tx2b.rehash() tx2b_hex = txToHex(tx2b) # Verify tx2b cannot replace tx2a. assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx2b_hex, True) # Now prioritise tx2b to have a higher modified fee self.nodes[0].prioritisetransaction(txid=tx2b.hash, fee_delta=int(0.1*COIN)) # tx2b should now be accepted tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True) assert(tx2b_txid in self.nodes[0].getrawmempool()) def test_rpc(self): us0 = self.nodes[0].listunspent()[0] ins = [us0] outs = {self.nodes[0].getnewaddress() : Decimal(1.0000000)} rawtx0 = self.nodes[0].createrawtransaction(ins, outs, 0, True) rawtx1 = self.nodes[0].createrawtransaction(ins, outs, 0, False) json0 = self.nodes[0].decoderawtransaction(rawtx0) json1 = self.nodes[0].decoderawtransaction(rawtx1) assert_equal(json0["vin"][0]["sequence"], 4294967293) assert_equal(json1["vin"][0]["sequence"], 4294967295) rawtx2 = self.nodes[0].createrawtransaction([], outs) frawtx2a = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": True}) frawtx2b = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": False}) json0 = self.nodes[0].decoderawtransaction(frawtx2a['hex']) json1 = self.nodes[0].decoderawtransaction(frawtx2b['hex']) assert_equal(json0["vin"][0]["sequence"], 4294967293) assert_equal(json1["vin"][0]["sequence"], 4294967294) if __name__ == '__main__': ReplaceByFeeTest().main()
### # Copyright (c) 2002-2005, Jeremiah Fincher # Copyright (c) 2009, James Vega # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # 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. ### """ Provides a great number of useful utility functions for IRC. Things to muck around with hostmasks, set bold or color on strings, IRC-case-insensitive dicts, a nick class to handle nicks (so comparisons and hashing and whatnot work in an IRC-case-insensitive fashion), and numerous other things. """ import re import time import random import string import textwrap from cStringIO import StringIO as sio import supybot.utils as utils def debug(s, *args): """Prints a debug string. Most likely replaced by our logging debug.""" print '***', s % args def isUserHostmask(s): """Returns whether or not the string s is a valid User hostmask.""" p1 = s.find('!') p2 = s.find('@') if p1 < p2-1 and p1 >= 1 and p2 >= 3 and len(s) > p2+1: return True else: return False def isServerHostmask(s): """s => bool Returns True if s is a valid server hostmask.""" return not isUserHostmask(s) def nickFromHostmask(hostmask): """hostmask => nick Returns the nick from a user hostmask.""" assert isUserHostmask(hostmask) return hostmask.split('!', 1)[0] def userFromHostmask(hostmask): """hostmask => user Returns the user from a user hostmask.""" assert isUserHostmask(hostmask) return hostmask.split('!', 1)[1].split('@', 1)[0] def hostFromHostmask(hostmask): """hostmask => host Returns the host from a user hostmask.""" assert isUserHostmask(hostmask) return hostmask.split('@', 1)[1] def splitHostmask(hostmask): """hostmask => (nick, user, host) Returns the nick, user, host of a user hostmask.""" assert isUserHostmask(hostmask) nick, rest = hostmask.split('!', 1) user, host = rest.split('@', 1) return (nick, user, host) def joinHostmask(nick, ident, host): """nick, user, host => hostmask Joins the nick, ident, host into a user hostmask.""" assert nick and ident and host return '%s!%s@%s' % (nick, ident, host) _rfc1459trans = string.maketrans(string.ascii_uppercase + r'\[]~', string.ascii_lowercase + r'|{}^') def toLower(s, casemapping=None): """s => s Returns the string s lowered according to IRC case rules.""" if casemapping is None or casemapping == 'rfc1459': return s.translate(_rfc1459trans) elif casemapping == 'ascii': # freenode return s.lower() else: raise ValueError, 'Invalid casemapping: %r' % casemapping def strEqual(nick1, nick2): """s1, s2 => bool Returns True if nick1 == nick2 according to IRC case rules.""" assert isinstance(nick1, basestring) assert isinstance(nick2, basestring) return toLower(nick1) == toLower(nick2) nickEqual = strEqual _nickchars = r'[]\`_^{|}' nickRe = re.compile(r'^[A-Za-z%s][-0-9A-Za-z%s]*$' % (re.escape(_nickchars), re.escape(_nickchars))) def isNick(s, strictRfc=True, nicklen=None): """s => bool Returns True if s is a valid IRC nick.""" if strictRfc: ret = bool(nickRe.match(s)) if ret and nicklen is not None: ret = len(s) <= nicklen return ret else: return not isChannel(s) and \ not isUserHostmask(s) and \ not ' ' in s and not '!' in s def isChannel(s, chantypes='#&+!', channellen=50): """s => bool Returns True if s is a valid IRC channel name.""" return s and \ ',' not in s and \ '\x07' not in s and \ s[0] in chantypes and \ len(s) <= channellen and \ len(s.split(None, 1)) == 1 _patternCache = utils.structures.CacheDict(1000) def _hostmaskPatternEqual(pattern, hostmask): try: return _patternCache[pattern](hostmask) is not None except KeyError: # We make our own regexps, rather than use fnmatch, because fnmatch's # case-insensitivity is not IRC's case-insensitity. fd = sio() for c in pattern: if c == '*': fd.write('.*') elif c == '?': fd.write('.') elif c in '[{': fd.write('[[{]') elif c in '}]': fd.write(r'[}\]]') elif c in '|\\': fd.write(r'[|\\]') elif c in '^~': fd.write('[~^]') else: fd.write(re.escape(c)) fd.write('$') f = re.compile(fd.getvalue(), re.I).match _patternCache[pattern] = f return f(hostmask) is not None _hostmaskPatternEqualCache = utils.structures.CacheDict(1000) def hostmaskPatternEqual(pattern, hostmask): """pattern, hostmask => bool Returns True if hostmask matches the hostmask pattern pattern.""" try: return _hostmaskPatternEqualCache[(pattern, hostmask)] except KeyError: b = _hostmaskPatternEqual(pattern, hostmask) _hostmaskPatternEqualCache[(pattern, hostmask)] = b return b def banmask(hostmask): """Returns a properly generic banning hostmask for a hostmask. >>> banmask('nick!user@host.domain.tld') '*!*@*.domain.tld' >>> banmask('nick!user@10.0.0.1') '*!*@10.0.0.*' """ assert isUserHostmask(hostmask) host = hostFromHostmask(hostmask) if utils.net.isIP(host): L = host.split('.') L[-1] = '*' return '*!*@' + '.'.join(L) elif utils.net.isIPV6(host): L = host.split(':') L[-1] = '*' return '*!*@' + ':'.join(L) else: if '.' in host: return '*!*@*%s' % host[host.find('.'):] else: return '*!*@' + host _plusRequireArguments = 'ovhblkqe' _minusRequireArguments = 'ovhbkqe' def separateModes(args): """Separates modelines into single mode change tuples. Basically, you should give it the .args of a MODE IrcMsg. Examples: >>> separateModes(['+ooo', 'jemfinch', 'StoneTable', 'philmes']) [('+o', 'jemfinch'), ('+o', 'StoneTable'), ('+o', 'philmes')] >>> separateModes(['+o-o', 'jemfinch', 'PeterB']) [('+o', 'jemfinch'), ('-o', 'PeterB')] >>> separateModes(['+s-o', 'test']) [('+s', None), ('-o', 'test')] >>> separateModes(['+sntl', '100']) [('+s', None), ('+n', None), ('+t', None), ('+l', 100)] """ if not args: return [] modes = args[0] assert modes[0] in '+-', 'Invalid args: %r' % args args = list(args[1:]) ret = [] for c in modes: if c in '+-': last = c else: if last == '+': requireArguments = _plusRequireArguments else: requireArguments = _minusRequireArguments if c in requireArguments: arg = args.pop(0) try: arg = int(arg) except ValueError: pass ret.append((last + c, arg)) else: ret.append((last + c, None)) return ret def joinModes(modes): """[(mode, targetOrNone), ...] => args Joins modes of the same form as returned by separateModes.""" args = [] modeChars = [] currentMode = '\x00' for (mode, arg) in modes: if arg is not None: args.append(arg) if not mode.startswith(currentMode): currentMode = mode[0] modeChars.append(mode[0]) modeChars.append(mode[1]) args.insert(0, ''.join(modeChars)) return args def bold(s): """Returns the string s, bolded.""" return '\x02%s\x02' % s def reverse(s): """Returns the string s, reverse-videoed.""" return '\x16%s\x16' % s def underline(s): """Returns the string s, underlined.""" return '\x1F%s\x1F' % s # Definition of mircColors dictionary moved below because it became an IrcDict. def mircColor(s, fg=None, bg=None): """Returns s with the appropriate mIRC color codes applied.""" if fg is None and bg is None: return s elif bg is None: fg = mircColors[str(fg)] return '\x03%s%s\x03' % (fg.zfill(2), s) elif fg is None: bg = mircColors[str(bg)] # According to the mirc color doc, a fg color MUST be specified if a # background color is specified. So, we'll specify 00 (white) if the # user doesn't specify one. return '\x0300,%s%s\x03' % (bg.zfill(2), s) else: fg = mircColors[str(fg)] bg = mircColors[str(bg)] # No need to zfill fg because the comma delimits. return '\x03%s,%s%s\x03' % (fg, bg.zfill(2), s) def canonicalColor(s, bg=False, shift=0): """Assigns an (fg, bg) canonical color pair to a string based on its hash value. This means it might change between Python versions. This pair can be used as a *parameter to mircColor. The shift parameter is how much to right-shift the hash value initially. """ h = hash(s) >> shift fg = h % 14 + 2 # The + 2 is to rule out black and white. if bg: bg = (h >> 4) & 3 # The 5th, 6th, and 7th least significant bits. if fg < 8: bg += 8 else: bg += 2 return (fg, bg) else: return (fg, None) def stripBold(s): """Returns the string s, with bold removed.""" return s.replace('\x02', '') _stripColorRe = re.compile(r'\x03(?:\d{1,2},\d{1,2}|\d{1,2}|,\d{1,2}|)') def stripColor(s): """Returns the string s, with color removed.""" return _stripColorRe.sub('', s) def stripReverse(s): """Returns the string s, with reverse-video removed.""" return s.replace('\x16', '') def stripUnderline(s): """Returns the string s, with underlining removed.""" return s.replace('\x1f', '').replace('\x1F', '') def stripFormatting(s): """Returns the string s, with all formatting removed.""" # stripColor has to go first because of some strings, check the tests. s = stripColor(s) s = stripBold(s) s = stripReverse(s) s = stripUnderline(s) return s.replace('\x0f', '').replace('\x0F', '') class FormatContext(object): def __init__(self): self.reset() def reset(self): self.fg = None self.bg = None self.bold = False self.reverse = False self.underline = False def start(self, s): """Given a string, starts all the formatters in this context.""" if self.bold: s = '\x02' + s if self.reverse: s = '\x16' + s if self.underline: s = '\x1f' + s if self.fg is not None or self.bg is not None: s = mircColor(s, fg=self.fg, bg=self.bg)[:-1] # Remove \x03. return s def end(self, s): """Given a string, ends all the formatters in this context.""" if self.bold or self.reverse or \ self.fg or self.bg or self.underline: # Should we individually end formatters? s += '\x0f' return s class FormatParser(object): def __init__(self, s): self.fd = sio(s) self.last = None def getChar(self): if self.last is not None: c = self.last self.last = None return c else: return self.fd.read(1) def ungetChar(self, c): self.last = c def parse(self): context = FormatContext() c = self.getChar() while c: if c == '\x02': context.bold = not context.bold elif c == '\x16': context.reverse = not context.reverse elif c == '\x1f': context.underline = not context.underline elif c == '\x0f': context.reset() elif c == '\x03': self.getColor(context) c = self.getChar() return context def getInt(self): i = 0 setI = False c = self.getChar() while c.isdigit() and i < 100: setI = True i *= 10 i += int(c) c = self.getChar() self.ungetChar(c) if setI: return i else: return None def getColor(self, context): context.fg = self.getInt() c = self.getChar() if c == ',': context.bg = self.getInt() def wrap(s, length): processed = [] chunks = textwrap.wrap(s, length) context = None for chunk in chunks: if context is not None: chunk = context.start(chunk) context = FormatParser(chunk).parse() processed.append(context.end(chunk)) return processed def isValidArgument(s): """Returns whether s is strictly a valid argument for an IRC message.""" return '\r' not in s and '\n' not in s and '\x00' not in s def safeArgument(s): """If s is unsafe for IRC, returns a safe version.""" if isinstance(s, unicode): s = s.encode('utf-8') elif not isinstance(s, basestring): debug('Got a non-string in safeArgument: %r', s) s = str(s) if isValidArgument(s): return s else: return repr(s) def replyTo(msg): """Returns the appropriate target to send responses to msg.""" if isChannel(msg.args[0]): return msg.args[0] else: return msg.nick def dccIP(ip): """Converts an IP string to the DCC integer form.""" assert utils.net.isIP(ip), \ 'argument must be a string ip in xxx.xxx.xxx.xxx format.' i = 0 x = 256**3 for quad in ip.split('.'): i += int(quad)*x x /= 256 return i def unDccIP(i): """Takes an integer DCC IP and return a normal string IP.""" assert isinstance(i, (int, long)), '%r is not an number.' % i L = [] while len(L) < 4: L.append(i % 256) i /= 256 L.reverse() return '.'.join(utils.iter.imap(str, L)) class IrcString(str): """This class does case-insensitive comparison and hashing of nicks.""" def __new__(cls, s=''): x = super(IrcString, cls).__new__(cls, s) x.lowered = toLower(x) return x def __eq__(self, s): try: return toLower(s) == self.lowered except: return False def __ne__(self, s): return not (self == s) def __hash__(self): return hash(self.lowered) class IrcDict(utils.InsensitivePreservingDict): """Subclass of dict to make key comparison IRC-case insensitive.""" def key(self, s): if s is not None: s = toLower(s) return s class CallableValueIrcDict(IrcDict): def __getitem__(self, k): v = super(IrcDict, self).__getitem__(k) if callable(v): v = v() return v class IrcSet(utils.NormalizingSet): """A sets.Set using IrcStrings instead of regular strings.""" def normalize(self, s): return IrcString(s) def __reduce__(self): return (self.__class__, (list(self),)) class FloodQueue(object): timeout = 0 def __init__(self, timeout=None, queues=None): if timeout is not None: self.timeout = timeout if queues is None: queues = IrcDict() self.queues = queues def __repr__(self): return 'FloodQueue(timeout=%r, queues=%s)' % (self.timeout, repr(self.queues)) def key(self, msg): # This really ought to be configurable without subclassing, but for # now, it works. # used to be msg.user + '@' + msg.host but that was too easily abused. return msg.host def getTimeout(self): if callable(self.timeout): return self.timeout() else: return self.timeout def _getQueue(self, msg, insert=True): key = self.key(msg) try: return self.queues[key] except KeyError: if insert: # python-- # instancemethod.__repr__ calls the instance.__repr__, which # means that our __repr__ calls self.queues.__repr__, which # calls structures.TimeoutQueue.__repr__, which calls # getTimeout.__repr__, which calls our __repr__, which calls... getTimeout = lambda : self.getTimeout() q = utils.structures.TimeoutQueue(getTimeout) self.queues[key] = q return q else: return None def enqueue(self, msg, what=None): if what is None: what = msg q = self._getQueue(msg) q.enqueue(what) def len(self, msg): q = self._getQueue(msg, insert=False) if q is not None: return len(q) else: return 0 def has(self, msg, what=None): q = self._getQueue(msg, insert=False) if q is not None: if what is None: what = msg for elt in q: if elt == what: return True return False mircColors = IrcDict({ 'white': '0', 'black': '1', 'blue': '2', 'green': '3', 'red': '4', 'brown': '5', 'purple': '6', 'orange': '7', 'yellow': '8', 'light green': '9', 'teal': '10', 'light blue': '11', 'dark blue': '12', 'pink': '13', 'dark grey': '14', 'light grey': '15', 'dark gray': '14', 'light gray': '15', }) # We'll map integers to their string form so mircColor is simpler. for (k, v) in mircColors.items(): if k is not None: # Ignore empty string for None. sv = str(v) mircColors[sv] = sv def standardSubstitute(irc, msg, text, env=None): """Do the standard set of substitutions on text, and return it""" if isChannel(msg.args[0]): channel = msg.args[0] else: channel = 'somewhere' def randInt(): return str(random.randint(-1000, 1000)) def randDate(): t = pow(2,30)*random.random()+time.time()/4.0 return time.ctime(t) def randNick(): if channel != 'somewhere': L = list(irc.state.channels[channel].users) if len(L) > 1: n = msg.nick while n == msg.nick: n = utils.iter.choice(L) return n else: return msg.nick else: return 'someone' ctime = time.strftime("%a %b %d %H:%M:%S %Y") localtime = time.localtime() gmtime = time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime()) vars = CallableValueIrcDict({ 'who': msg.nick, 'nick': msg.nick, 'user': msg.user, 'host': msg.host, 'channel': channel, 'botnick': irc.nick, 'now': ctime, 'ctime': ctime, 'utc': gmtime, 'gmt': gmtime, 'randnick': randNick, 'randomnick': randNick, 'randdate': randDate, 'randomdate': randDate, 'rand': randInt, 'randint': randInt, 'randomint': randInt, 'today': time.strftime('%d %b %Y', localtime), 'year': localtime[0], 'month': localtime[1], 'monthname': time.strftime('%b', localtime), 'date': localtime[2], 'day': time.strftime('%A', localtime), 'h': localtime[3], 'hr': localtime[3], 'hour': localtime[3], 'm': localtime[4], 'min': localtime[4], 'minute': localtime[4], 's': localtime[5], 'sec': localtime[5], 'second': localtime[5], 'tz': time.strftime('%Z', localtime), }) if env is not None: vars.update(env) t = string.Template(text) t.idpattern = '[a-zA-Z][a-zA-Z0-9]*' return t.safe_substitute(vars) if __name__ == '__main__': import sys, doctest doctest.testmod(sys.modules['__main__']) # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
#!/usr/bin/env python3 import sys, logging from collections import deque from bot import SlackBot # process settings #logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") logging.basicConfig(filename="botty.log", level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") def initialize_plugins(botty): """Import, register, and initialize Botty plugins. Edit the body of this function to change which plugins are loaded.""" from plugins.arithmetic import ArithmeticPlugin; botty.register_plugin(ArithmeticPlugin(botty)) from plugins.timezones import TimezonesPlugin; botty.register_plugin(TimezonesPlugin(botty)) from plugins.poll import PollPlugin; botty.register_plugin(PollPlugin(botty)) from plugins.wiki import WikiPlugin; botty.register_plugin(WikiPlugin(botty)) from plugins.haiku import HaikuPlugin; botty.register_plugin(HaikuPlugin(botty)) from plugins.personality import PersonalityPlugin; botty.register_plugin(PersonalityPlugin(botty)) from plugins.events import EventsPlugin; botty.register_plugin(EventsPlugin(botty)) from plugins.now_i_am_dude import NowIAmDudePlugin; botty.register_plugin(NowIAmDudePlugin(botty)) from plugins.generate_text import GenerateTextPlugin; botty.register_plugin(GenerateTextPlugin(botty)) from plugins.big_text import BigTextPlugin; botty.register_plugin(BigTextPlugin(botty)) from plugins.uw_courses import UWCoursesPlugin; botty.register_plugin(UWCoursesPlugin(botty)) from plugins.spaaace import SpaaacePlugin; botty.register_plugin(SpaaacePlugin(botty)) from plugins.agario import AgarioPlugin; botty.register_plugin(AgarioPlugin(botty)) from plugins.snek import SnekPlugin; botty.register_plugin(SnekPlugin(botty)) if len(sys.argv) > 2 or (len(sys.argv) == 2 and sys.argv[1] in {"--help", "-h", "-?"}): print("Usage: {} --help".format(sys.argv[0])) print(" Show this help message") print("Usage: {}".format(sys.argv[0])) print(" Start the Botty chatbot for Slack in testing mode with a console chat interface") print("Usage: {} SLACK_BOT_TOKEN".format(sys.argv[0])) print(" Start the Botty chatbot for the Slack chat associated with SLACK_BOT_TOKEN, and enter the in-process Python REPL") print(" SLACK_BOT_TOKEN is a Slack API token (can be obtained from https://api.slack.com/)") sys.exit(1) DEBUG = len(sys.argv) < 2 if DEBUG: from bot import SlackDebugBot as SlackBot SLACK_TOKEN = "" print("No Slack API token specified in command line arguments; starting in local debug mode...") print() else: SLACK_TOKEN = sys.argv[1] class Botty(SlackBot): def __init__(self, token): super().__init__(token) self.plugins = [] self.last_message_timestamp = None self.last_message_thread_id = None self.last_message_channel_id = None self.recent_events = deque(maxlen=2000) # store the last 2000 events def register_plugin(self, plugin_instance): self.plugins.append(plugin_instance) def on_step(self): for plugin in self.plugins: if plugin.on_step(): break def on_message(self, message_dict): self.logger.debug("received message {}".format(message_dict)) # check if the user is a bot and ignore the message if they are user_id = message_dict.get("user", message_dict.get("message", {}).get("user")) if isinstance(user_id, str) and self.get_user_is_bot(user_id): return message = IncomingMessage(message_dict, is_bot_message=False) try: # we need to set all of these in one statement because if any of the accessors fail, none of the variables should be updated self.last_message_timestamp, self.last_message_thread_id, self.last_message_channel_id = message.timestamp, message.thread_id, message.channel_id except ValueError: pass # save recent message events if message.is_action_message: self.recent_events.append(message) for plugin in self.plugins: if plugin.on_message(message): self.logger.info("message handled by {}: {}".format(plugin.__class__.__name__, message)) break def respond(self, sendable_text, *, as_thread=True): """Say `sendable_text` in the channel/thread that most recently received a message, returning the message ID (unique within each `SlackBot` instance). If `as_thread` is truthy, this will create a thread for the message being responsed to if it wasn't in a thread.""" assert self.last_message_channel_id is not None, "No message to respond to" thread_id = self.last_message_thread_id or (self.last_message_timestamp if as_thread else None) return self.say(sendable_text, channel_id=self.last_message_channel_id, thread_id=thread_id) def respond_complete(self, sendable_text, *, as_thread=True): """Say `sendable_text` in the channel (and thread, if applicable) that most recently received a message, waiting until the message is successfully sent, returning the message timestamp. If `as_thread` is truthy, this will create a thread for the message being responsed to if it wasn't in a thread.""" assert self.last_message_channel_id is not None, "No message to respond to" thread_id = self.last_message_thread_id or (self.last_message_timestamp if as_thread else None) return self.say_complete(sendable_text, channel_id=self.last_message_channel_id, thread_id=self.last_message_thread_id) def reply(self, emoticon): """React with `emoticon` to the most recently received message.""" assert self.last_message_channel_id is not None and self.last_message_timestamp is not None, "No message to reply to" return self.react(self.last_message_channel_id, self.last_message_timestamp, emoticon) def unreply(self, emoticon): """Remove `emoticon` reaction from the most recently received message.""" assert self.last_message_channel_id is not None and self.last_message_timestamp is not None, "No message to unreply to" return self.unreact(self.last_message_channel_id, self.last_message_timestamp, emoticon) class IncomingMessage: """Represents a single incoming message event.""" def __init__(self, message_dict, is_bot_message): self.message_dict = message_dict self.is_bot_message = is_bot_message def __repr__(self): return "<Message {}>".format(self.message_dict) def __iter__(self): return iter(self.message_dict) @property def is_action_message(self): """Returns `True` if the message represents an action by a user, as opposed to things we usually don't consider user actions, like server pings or going offline, `False` otherwise.""" return self.message_dict.get("type") not in {"ping", "pong", "presence_change", "user_typing", "reconnect_url"} @property def is_text_message(self): """Returns `True` if the message represents a text message, `False` otherwise. If this returns `True`, the `Message.timestamp`, `Message.text`, `Message.user_id`, and `Message.channel_id` methods will be available.""" if self.message_dict.get("type") != "message": return False if not isinstance(self.message_dict.get("ts"), str): return False if not isinstance(self.message_dict.get("channel"), str): return False if isinstance(self.message_dict.get("text"), str) and isinstance(self.message_dict.get("user"), str): return True # ordinary message if ( self.message_dict.get("subtype") == "message_changed" and isinstance(self.message_dict.get("message"), dict) and isinstance(self.message_dict["message"].get("user"), str) and isinstance(self.message_dict["message"].get("channel"), str) and isinstance(self.message_dict["message"].get("text"), str) ): return True # edited message return False # not a text message @property def is_user_message(self): """Returns `True` if the message represents a message sent by a real user (i.e., not a bot), `False` otherwise.""" if self.is_bot_message: return False try: self.timestamp, self.user_id, self.channel_id return True except ValueError: return False @property def is_user_text_message(self): """Returns `True` if the message represents a text message sent by a real user (i.e., not a bot), `False` otherwise.""" return not self.is_bot_message and self.is_text_message @property def is_reaction_addition(self): """Returns `True` if the message represents a reaction being added, `False` otherwise.""" return self.message_dict.get("type") == "reaction_added" and self.channel_id and self.user_id @property def is_reaction_removal(self): """Returns `True` if the message represents a reaction being removed, `False` otherwise.""" return self.message_dict.get("type") == "reaction_removed" and self.channel_id and self.user_id @property def timestamp(self): """Returns the timestamp of the message, or raises a `ValueError` if there is none.""" reaction_timestamp = self.message_dict.get("item", {}).get("ts") timestamp = self.message_dict.get("ts", reaction_timestamp) if not isinstance(timestamp, str): raise ValueError("Message timestamp should be a string, but is \"{}\" instead".format(repr(timestamp))) return timestamp @property def text(self): """Returns the text content of the message as a string, or raises a `ValueError` if there is none.""" submessage_text = self.message_dict.get("message", {}).get("text") text = self.message_dict.get("text", submessage_text) if not isinstance(text, str): raise ValueError("Message text should be a string, but is \"{}\" instead".format(repr(text))) return text @property def user_id(self): """Returns the ID of the user that sent the message, or raises a `ValueError` if there is none.""" submessage_channel = self.message_dict.get("message", {}).get("user") user_id = self.message_dict.get("user", submessage_channel) if not isinstance(user_id, str): raise ValueError("Message user ID should be a string, but is \"{}\" instead".format(repr(user_id))) return user_id @property def channel_id(self): """Returns the ID of the channel that the message is in, or raises a `ValueError` if there is none.""" reaction_channel = self.message_dict.get("item", {}).get("channel") submessage_channel = self.message_dict.get("message", {}).get("channel", reaction_channel) channel_id = self.message_dict.get("channel", submessage_channel) if not isinstance(channel_id, str): raise ValueError("Message channel ID should be a string, but is \"{}\" instead".format(repr(channel_id))) return channel_id @property def thread_id(self): """Returns the ID of the thread that the message is in, or `None` if the message is not in a thread.""" submessage_thread = self.message_dict.get("message", {}).get("thread_ts") thread_id = self.message_dict.get("thread_ts", submessage_thread) if thread_id is not None and not isinstance(thread_id, str): raise ValueError("Message thread ID should be a string, but is \"{}\" instead".format(repr(thread_id))) return thread_id @property def reaction(self): """Returns the name of the reaction for the reaction addition/removal message, or raises a `ValueError` if there is none.""" reaction = self.message_dict.get("reaction") if not isinstance(reaction, str): raise ValueError("Message reaction value should be a string, but is \"{}\" instead".format(repr(reaction))) return reaction botty = Botty(SLACK_TOKEN) initialize_plugins(botty) # start administrator console in production mode if not DEBUG: def say(channel, text): """Say `text` in `channel` where `text` is a sendable text string and `channel` is a channel name like #general.""" botty.say(text, channel_id=botty.get_channel_id_by_name(channel)) def reload_plugin(package_name, class_name): """Reload plugin from its plugin class `class_name` from package `package_name`.""" # obtain the new plugin import importlib plugin_module = importlib.import_module(package_name) # this will not re-initialize the module, since it's been previously imported importlib.reload(plugin_module) # re-initialize the module PluginClass = getattr(plugin_module, class_name) # replace the old plugin with the new one for i, plugin in enumerate(botty.plugins): if isinstance(plugin, PluginClass): del botty.plugins[i] break botty.register_plugin(PluginClass(botty)) def sane(): """Force the administrator's console into a reasonable default - useful for recovering from weird terminal states.""" import os os.system("stty sane") from datetime import datetime from plugins.utilities import BasePlugin def on_message_default(plugin, message): return False def on_message_disabled(plugin, message): return True def on_message_print(plugin, message): """Print out all incoming events - useful for interactive RTM API debugging.""" if message.get("type") == "message": timestamp = datetime.fromtimestamp(int(message["ts"].split(".")[0])) channel_name = botty.get_channel_name_by_id(message.get("channel", message.get("previous_message", {}).get("channel"))) user_name = botty.get_user_name_by_id(message.get("user", message.get("previous_message", {}).get("user"))) text = message.get("text", message.get("previous_message", {}).get("text")) new_text = message.get("message", {}).get("text") if new_text: print("{timestamp} #{channel} | @{user} {subtype}: {text} -> {new_text}".format( timestamp=timestamp, channel=channel_name, user=user_name, subtype=message.get("subtype", "message"), text=text, new_text=new_text )) else: print("{timestamp} #{channel} | @{user} {subtype}: {text}".format( timestamp=timestamp, channel=channel_name, user=user_name, subtype=message.get("subtype", "message"), text=text )) elif message.get("type") not in {"ping", "pong", "presence_change", "user_typing", "reconnect_url"}: print(message) return False on_message = on_message_default class AdHocPlugin(BasePlugin): def __init__(self, bot): super().__init__(bot) def on_message(self, message): return on_message(self, message) if not any(isinstance(plugin, AdHocPlugin) for plugin in botty.plugins): # plugin hasn't already been added botty.plugins.insert(0, AdHocPlugin(botty)) # the plugin should go before everything else to be able to influence every message botty.administrator_console(globals()) botty.start_loop()
import json import os import sys import typing from argparse import ArgumentParser from json import decoder as json_decoder from tracksim import cli from tracksim import system from tracksim.group import simulate as simulate_group from tracksim.trial import simulate as simulate_trial DESCRIPTION = """ Runs a trackway gait analysis simulation for the given scenario group or trial according to the path configuration options specified by the arguments """ def get_path(path: str, cli_configs: dict) -> typing.Union[str, None]: """ :param path: :param cli_configs: :return: """ if path.startswith('./'): path = os.path.abspath(path) if os.path.exists(path): return path paths = cli_configs.get('paths', []) + [] paths.insert(0, os.getcwd()) for directory in paths: p = os.path.abspath(os.path.join(directory, path)) if os.path.exists(p): return p return None def find_group_files(path: str) -> typing.List[str]: """ Finds all group configuration JSON files stored in the specified path directory :param path: Path to the directory where the group files search should take place """ paths = [] # Prioritize group files named "group.json" over other files in the path items = ['group.json'] for item in os.listdir(path): if item == 'group.json': continue items.append(item) for item in items: item_path = os.path.join(path, item) if not os.path.exists(item_path): continue if not os.path.isfile(item_path) or not item.endswith('.json'): continue try: with open(item_path, 'r+') as f: data = json.load(f) except json_decoder.JSONDecodeError as err: system.log([ '[ERROR]: Failed to decode json file', [ 'PATH: {}'.format(path), 'INFO: {}'.format(err.msg), [ 'LINE: {}'.format(err.lineno), 'CHAR: {}'.format(err.colno) ] ] ]) return system.end(1) if 'trials' in data: paths.append(item_path) if not paths: system.log('ERROR: No group trial found in path: "{}"'.format(path)) system.end(2) return paths def run(**kwargs): """ :param kwargs: :return: """ cli_configs = kwargs.get('settings') if cli_configs is None: cli_configs = system.load_configs() path = get_path(kwargs.get('path'), cli_configs) if path is None: system.log('ERROR: Invalid or missing path argument') sys.exit(1) urls = [] if os.path.isfile(path): with open(path, 'r+') as f: data = json.load(f) urls.append(run_simulation( is_group=bool('trials' in data), cli_configs=cli_configs, settings_path=path, **kwargs )) else: group_paths = find_group_files(path) if not kwargs.get('run_all_groups'): group_paths = group_paths[0:1] for p in group_paths: urls.append(run_simulation( is_group=True, cli_configs=cli_configs, settings_path=p, **kwargs )) save_recent_path(kwargs.get('path'), cli_configs) print_results(urls) def save_recent_path(path: str, cli_configs: dict): """ :param path: :param cli_configs: :return: """ if not path: return recent_paths = cli_configs.get('recent', []) recent_paths = list(filter((path).__ne__, recent_paths)) recent_paths.insert(0, path) cli_configs['recent'] = recent_paths[:5] system.save_configs(cli_configs) def print_results(urls: typing.List[str]): """ :param urls: :return: """ msg = """ ------------------------------------------ Simulation Complete. Results Available At: """ system.log(msg, whitespace=1) for r in urls: system.log(' * {}'.format(r)) def run_simulation( is_group: bool, cli_configs: dict, settings_path: str, **kwargs ) -> dict: """ :param is_group: :param cli_configs: :param settings_path: :param kwargs: :return: """ runner = simulate_group if is_group else simulate_trial args = dict() if kwargs.get('end_time', -1) > 0: args['end_time'] = kwargs.get('end_time') if kwargs.get('start_time', -1) >= 0: args['start_time'] = kwargs.get('start_time') return runner.run( settings_path, results_path=kwargs.get('results_path'), **args ) def execute_command(): """ :return: """ parser = ArgumentParser() parser.description = cli.reformat(DESCRIPTION) parser.add_argument( 'run', type=str, help='The run command to execute' ) parser.add_argument( 'path', type=str, help=cli.reformat(""" The relative or absolute path to either a group or trial simulation configuration file, or a directory path in which a group trial configuration file resides. """) ) parser.add_argument( '-st', '--startTime', dest='start_time', type=float, default=-1, help=cli.reformat(""" The time at which the simulation should start. The default value is 0. """) ) parser.add_argument( '-et', '--endTime', dest='end_time', type=float, default=-1, help=cli.reformat(""" The time at which the simulation should stop. The default value is to run until the end of the simulation. """) ) parser.add_argument( '-d', '--directory', dest='results_path', type=str, default=None, help=cli.reformat(""" An absolute path to the output directory where you would like the trial results stored. This overrides the output directory specified by the configure command or from within the trial or group configuration file. """) ) parser.add_argument( '-a', '--all', dest='run_all_groups', action='store_true', default=False, help=cli.reformat(""" When included, this flag indicates that all of the group files within the specified path directory should be run in order, instead of just the first one found, which is the default behavior. """) ) run(**vars(parser.parse_args()))