filename
stringlengths 4
198
| content
stringlengths 25
939k
| environment
list | variablearg
list | constarg
list | variableargjson
stringclasses 1
value | constargjson
stringlengths 2
3.9k
| lang
stringclasses 3
values | constargcount
float64 0
129
⌀ | variableargcount
float64 0
0
⌀ | sentence
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
python/mxnet/symbol.py
|
# coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-arguments, too-many-lines
# pylint: disable=import-error, no-name-in-module
"""Symbolic configuration API of MXNet."""
from __future__ import absolute_import as _abs
import ctypes
import warnings
from numbers import Number
import os as _os
import sys as _sys
import numpy as _numpy
from .base import _LIB, numeric_types
from .base import c_array, c_str, mx_uint, py_str, string_types
from .base import NDArrayHandle, ExecutorHandle, SymbolHandle, OpHandle
from .base import check_call, MXNetError, _Null # pylint: disable=unused-import
from .context import Context, cpu
from .ndarray import NDArray, _DTYPE_NP_TO_MX, _DTYPE_MX_TO_NP
from .name import NameManager # pylint: disable=unused-import
from .executor import Executor
from . import _symbol_internal as _internal
from .attribute import AttrScope
from .symbol_doc import _build_doc
# Use different version of SymbolBase
# When possible, use cython to speedup part of computation.
try:
if int(_os.environ.get("MXNET_ENABLE_CYTHON", True)) == 0:
from ._ctypes.symbol import SymbolBase, _set_symbol_class
from ._ctypes.symbol import _symbol_creator # pylint: disable=unused-import
elif _sys.version_info >= (3, 0):
from ._cy3.symbol import SymbolBase, _set_symbol_class
from ._cy3.symbol import _symbol_creator # pylint: disable=unused-import
else:
from ._cy2.symbol import SymbolBase, _set_symbol_class
from ._cy2.symbol import _symbol_creator # pylint: disable=unused-import
except ImportError:
if int(_os.environ.get("MXNET_ENFORCE_CYTHON", False)) != 0:
raise ImportError("Cython Module cannot be loaded but MXNET_ENFORCE_CYTHON=1")
from ._ctypes.symbol import SymbolBase, _set_symbol_class
from ._ctypes.symbol import _symbol_creator # pylint: disable=unused-import
_GRAD_REQ_MAP = {'null': 0, 'write': 1, 'add': 3}
class Symbol(SymbolBase):
"""Symbol is symbolic graph of the mxnet."""
# disable dictionary storage, also do not have parent type.
# pylint: disable=no-member
__slots__ = []
def __repr__(self):
"""Gets a string representation of the symbol."""
name = self.name
if name is None:
name = ', '.join([i.name for i in self])
return '<%s group [%s]>' % (self.__class__.__name__, name)
else:
return '<%s %s>' % (self.__class__.__name__, name)
def __iter__(self):
"""Returns a generator object of symbol.
One can loop through the returned object list to get outputs.
Example usage:
----------
>>> a = mx.sym.Variable('a')
>>> b = mx.sym.Variable('b')
>>> c = a+b
>>> d = mx.sym.Variable('d')
>>> e = d+c
>>> out = e.get_children()
>>> out
<Symbol Grouped>
>>> for i in out:
... i
...
<Symbol d>
<Symbol _plus0>
"""
return (self[i] for i in self.list_outputs())
def __add__(self, other):
"""x.__add__(y) <=> x+y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_add` instead. """
if isinstance(other, Symbol):
return _internal._Plus(self, other)
if isinstance(other, Number):
return _internal._PlusScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
"""x.__sub__(y) <=> x-y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_sub` instead. """
if isinstance(other, Symbol):
return _internal._Minus(self, other)
if isinstance(other, Number):
return _internal._MinusScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __rsub__(self, other):
"""x.__rsub__(y) <=> y-x
Only `NDArray` is supported for now.
Example usage:
----------
>>> x = mx.nd.ones((2,3))*3
>>> y = mx.nd.ones((2,3))
>>> x.__rsub__(y).asnumpy()
array([[-2., -2., -2.],
[-2., -2., -2.]], dtype=float32)
"""
if isinstance(other, Number):
return _internal._RMinusScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __mul__(self, other):
"""x.__mul__(y) <=> x*y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_mul` instead. """
if isinstance(other, Symbol):
return _internal._Mul(self, other)
if isinstance(other, Number):
return _internal._MulScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __rmul__(self, other):
return self.__mul__(other)
def __div__(self, other):
"""x.__div__(y) <=> x/y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_div` instead. """
if isinstance(other, Symbol):
return _internal._Div(self, other)
if isinstance(other, Number):
return _internal._DivScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __rdiv__(self, other):
"""x.__rdiv__(y) <=> y/x
Only `NDArray` is supported for now.
Example usage:
----------
>>> x = mx.nd.ones((2,3))*3
>>> y = mx.nd.ones((2,3))
>>> x.__rdiv__(y).asnumpy()
array([[ 0.33333334, 0.33333334, 0.33333334],
[ 0.33333334, 0.33333334, 0.33333334]], dtype=float32)
"""
if isinstance(other, Number):
return _internal._RDivScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __mod__(self, other):
"""x.__mod__(y) <=> x%y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_mod` instead. """
if isinstance(other, Symbol):
return _internal._Mod(self, other)
if isinstance(other, Number):
return _internal._ModScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __rmod__(self, other):
"""x.__rmod__(y) <=> y%x
Only `NDArray` is supported for now.
Example usage:
----------
>>> x = mx.nd.ones((2,3))*3
>>> y = mx.nd.ones((2,3))
>>> x.__rmod__(y).asnumpy()
array([[ 1., 1., 1.,
[ 1., 1., 1., dtype=float32)
"""
if isinstance(other, Number):
return _internal._RModScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __truediv__(self, other):
return self.__div__(other)
def __rtruediv__(self, other):
return self.__rdiv__(other)
def __pow__(self, other):
"""x.__pow__(y) <=> x**y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_pow` instead. """
if isinstance(other, Symbol):
return _internal._Power(self, other)
if isinstance(other, Number):
return _internal._PowerScalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __neg__(self):
"""x.__neg__() <=> -x
Numerical negative, element-wise.
Example usage:
----------
>>> a = mx.sym.Variable('a')
>>> a
<Symbol a>
>>> -a
<Symbol _mulscalar0>
>>> a_neg = a.__neg__()
>>> c = a_neg*b
>>> ex = c.eval(ctx=mx.cpu(), a=mx.nd.ones([2,3]), b=mx.nd.ones([2,3]))
>>> ex[0].asnumpy()
array([[-1., -1., -1.],
[-1., -1., -1.]], dtype=float32)
"""
return self.__mul__(-1.0)
def __copy__(self):
return self.__deepcopy__(None)
def __deepcopy__(self, _):
"""Returns a deep copy of the input object.
This function returns a deep copy of the input object including the current state
of all its parameters such as weights, biases, etc.
Any changes made to the deep copy do not reflect in the original object.
Example usage:
----------
>>> import copy
>>> data = mx.sym.Variable('data')
>>> data_1 = copy.deepcopy(data)
>>> data_1 = 2*data
>>> data_1.tojson()
>>> data_1 is data # Data got modified
False
"""
handle = SymbolHandle()
check_call(_LIB.MXSymbolCopy(self.handle,
ctypes.byref(handle)))
return Symbol(handle)
def __eq__(self, other):
"""x.__eq__(y) <=> x==y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_equal` instead. """
if isinstance(other, Symbol):
return _internal._equal(self, other)
if isinstance(other, numeric_types):
return _internal._equal_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __ne__(self, other):
"""x.__ne__(y) <=> x!=y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_not_equal` instead. """
if isinstance(other, Symbol):
return _internal._not_equal(self, other)
if isinstance(other, numeric_types):
return _internal._not_equal_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __gt__(self, other):
"""x.__gt__(y) <=> x>y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_greater` instead. """
if isinstance(other, Symbol):
return _internal._greater(self, other)
if isinstance(other, numeric_types):
return _internal._greater_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __ge__(self, other):
"""x.__ge__(y) <=> x>=y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_greater_equal` instead. """
if isinstance(other, Symbol):
return _internal._greater_equal(self, other)
if isinstance(other, numeric_types):
return _internal._greater_equal_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __lt__(self, other):
"""x.__lt__(y) <=> x<y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_lesser` instead. """
if isinstance(other, Symbol):
return _internal._lesser(self, other)
if isinstance(other, numeric_types):
return _internal._lesser_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __le__(self, other):
"""x.__le__(y) <=> x<=y
Scalar input is supported.
Broadcasting is not supported. Use `broadcast_lesser_equal` instead. """
if isinstance(other, Symbol):
return _internal._lesser_equal(self, other)
if isinstance(other, numeric_types):
return _internal._lesser_equal_scalar(self, scalar=other)
else:
raise TypeError('type %s not supported' % str(type(other)))
def __getstate__(self):
handle = self.handle
if handle is not None:
return {'handle': self.tojson()}
else:
return {'handle': None}
def __setstate__(self, state):
# pylint: disable=assigning-non-slot
handle = state['handle']
if handle is not None:
json_str = handle
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
self.handle = handle
else:
self.handle = None
def __call__(self, *args, **kwargs):
"""Composes symbol using inputs.
x.__call__(y, z) <=> x(y,z)
This function internally calls `_compose` to compose the symbol and
returns the composed symbol.
Example usage:
----------
>>> data = mx.symbol.Variable('data')
>>> net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)
>>> net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10)
>>> composed = net2(fc3_data=net1, name='composed')
>>> composed
<Symbol composed>
>>> called = net2.__call__(fc3_data=net1, name='composed')
>>> called
<Symbol composed>
Parameters
----------
args:
Positional arguments.
kwargs:
Keyword arguments.
Returns
-------
The resulting symbol.
"""
s = self.__copy__()
s._compose(*args, **kwargs)
return s
def _compose(self, *args, **kwargs):
"""Composes symbol using inputs.
x._compose(y, z) <=> x(y,z)
This function mutates the current symbol.
Example usage:
----------
>>> data = mx.symbol.Variable('data')
>>> net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)
>>> net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10)
>>> net2
<Symbol fc3>
>>> net2._compose(fc3_data=net1, name='composed')
>>> net2
<Symbol composed>
Parameters
----------
args:
Positional arguments.
kwargs:
Keyword arguments.
Returns
-------
The resulting symbol.
"""
name = kwargs.pop('name', None)
if name:
name = c_str(name)
if len(args) != 0 and len(kwargs) != 0:
raise TypeError('compose only accept input Symbols \
either as positional or keyword arguments, not both')
for arg in args:
if not isinstance(arg, Symbol):
raise TypeError('Compose expect `Symbol` as arguments')
for val in kwargs.values():
if not isinstance(val, Symbol):
raise TypeError('Compose expect `Symbol` as arguments')
num_args = len(args) + len(kwargs)
if len(kwargs) != 0:
keys = c_array(ctypes.c_char_p, [c_str(key) for key in kwargs])
args = c_array(SymbolHandle, [s.handle for s in kwargs.values()])
else:
keys = None
args = c_array(SymbolHandle, [s.handle for s in args])
check_call(_LIB.MXSymbolCompose(
self.handle, name, num_args, keys, args))
def __getitem__(self, index):
"""x.__getitem__(i) <=> x[i]
Returns a sliced view of the input symbol.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> a.__getitem__(0)
<Symbol a>
>>> a[0]
<Symbol a>
Parameters
----------
index : int or str
Indexing key
"""
if isinstance(index, string_types):
idx = None
for i, name in enumerate(self.list_outputs()):
if name == index:
if idx is not None:
raise ValueError('There are multiple outputs with name \"%s\"' % index)
idx = i
if idx is None:
raise ValueError('Cannot find output that matches name \"%s\"' % index)
index = idx
if not isinstance(index, int):
raise TypeError('Symbol only support integer index to fetch i-th output')
if index >= (len(self.list_outputs())):
# Important, python determines the end by this exception
raise IndexError
handle = SymbolHandle()
check_call(_LIB.MXSymbolGetOutput(
self.handle, mx_uint(index), ctypes.byref(handle)))
return Symbol(handle=handle)
@property
def name(self):
"""Gets name string from the symbol, this function only works for non-grouped symbol.
Returns
-------
value : str
The name of this symbol, returns ``None`` for grouped symbol.
"""
ret = ctypes.c_char_p()
success = ctypes.c_int()
check_call(_LIB.MXSymbolGetName(
self.handle, ctypes.byref(ret), ctypes.byref(success)))
if success.value != 0:
return py_str(ret.value)
else:
return None
def attr(self, key):
"""Returns the attribute string for corresponding input key from the symbol.
This function only works for non-grouped symbols.
Example usage:
----------
>>> data = mx.sym.Variable('data', attr={'mood': 'angry'})
>>> data.attr('mood')
'angry'
Parameters
----------
key : str
The key corresponding to the desired attribute.
Returns
-------
value : str
The desired attribute value, returns ``None`` if the attribute does not exist.
"""
ret = ctypes.c_char_p()
success = ctypes.c_int()
check_call(_LIB.MXSymbolGetAttr(
self.handle, c_str(key), ctypes.byref(ret), ctypes.byref(success)))
if success.value != 0:
return py_str(ret.value)
else:
return None
def list_attr(self, recursive=False):
"""Gets all attributes from the symbol.
Example usage:
----------
>>> data = mx.sym.Variable('data', attr={'mood': 'angry'})
>>> data.list_attr()
{'mood': 'angry'}
Returns
-------
ret : Dict of str to str
A dictionary mapping attribute keys to values.
"""
if recursive:
raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. "
"Please use attr_dict instead.")
size = mx_uint()
pairs = ctypes.POINTER(ctypes.c_char_p)()
f_handle = _LIB.MXSymbolListAttrShallow
check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
return {py_str(pairs[i * 2]): py_str(pairs[i * 2 + 1]) for i in range(size.value)}
def attr_dict(self):
"""Recursively gets all attributes from the symbol and its children.
Example usage:
----------
>>> a = mx.sym.Variable('a', attr={'a1':'a2'})
>>> b = mx.sym.Variable('b', attr={'b1':'b2'})
>>> c = a+b
>>> c.attr_dict()
{'a': {'a1': 'a2'}, 'b': {'b1': 'b2'}}
Returns
-------
ret : Dict of str to dict
There is a key in the returned dict for every child with non-empty attribute set.
For each symbol, the name of the symbol is its key in the dict
and the correspond value is that symbol's attribute list (itself a dictionary).
"""
size = mx_uint()
pairs = ctypes.POINTER(ctypes.c_char_p)()
f_handle = _LIB.MXSymbolListAttr
check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
ret = {}
for i in range(size.value):
name, key = py_str(pairs[i * 2]).split('$')
val = py_str(pairs[i * 2 + 1])
if name not in ret:
ret[name] = {}
ret[name][key] = val
return ret
def _set_attr(self, **kwargs):
"""Sets an attribute of the symbol.
For example. A._set_attr(foo="bar") adds the mapping ``"{foo: bar}"``
to the symbol's attribute dictionary.
Parameters
----------
**kwargs
The attributes to set
"""
for key, value in kwargs.items():
if not isinstance(value, string_types):
raise ValueError("Set Attr only accepts string values")
check_call(_LIB.MXSymbolSetAttr(
self.handle, c_str(key), c_str(str(value))))
def get_internals(self):
"""Gets a new grouped symbol `sgroup`. The output of `sgroup` is a list of
outputs of all of the internal nodes.
Consider the following code:
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> d = c.get_internals()
>>> d
<Symbol Grouped>
>>> d.list_outputs()
['a', 'b', '_plus4_output']
Returns
-------
sgroup : Symbol
A symbol group containing all internal and leaf nodes of the computation graph
used to compute the symbol.
"""
handle = SymbolHandle()
check_call(_LIB.MXSymbolGetInternals(
self.handle, ctypes.byref(handle)))
return Symbol(handle=handle)
def get_children(self):
"""Gets a new grouped symbol whose output contains
inputs to output nodes of the original symbol.
Example usage:
----------
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.Variable('y')
>>> z = mx.sym.Variable('z')
>>> a = y+z
>>> b = x+a
>>> b.get_children()
<Symbol Grouped>
>>> b.get_children().list_outputs()
['x', '_plus10_output']
>>> b.get_children().get_children().list_outputs()
['y', 'z']
Returns
-------
sgroup : Symbol or None
The children of the head node. If the symbol has no
inputs then ``None`` will be returned.
"""
handle = SymbolHandle()
check_call(_LIB.MXSymbolGetChildren(
self.handle, ctypes.byref(handle)))
ret = Symbol(handle=handle)
if len(ret.list_outputs()) == 0:
return None
return ret
def list_arguments(self):
"""Lists all the arguments in the symbol.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> c.list_arguments
['a', 'b']
Returns
-------
args : list of string
List containing the names of all the arguments required to compute the symbol.
"""
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListArguments(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size.value)]
def list_outputs(self):
"""Lists all the outputs in the symbol.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> c.list_outputs()
['_plus12_output']
Returns
-------
list of str
List of all the outputs.
For most symbols, this list contains only the name of this symbol.
For symbol groups, this is a list with the names of all symbols
in the group.
"""
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListOutputs(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size.value)]
def list_auxiliary_states(self):
"""Lists all the auxiliary states in the symbol.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> c.list_auxiliary_states()
[]
Example of auxiliary states in `BatchNorm`.
>>> data = mx.symbol.Variable('data')
>>> weight = mx.sym.Variable(name='fc1_weight')
>>> fc1 = mx.symbol.FullyConnected(data = data, weight=weight, name='fc1', num_hidden=128)
>>> fc2 = mx.symbol.BatchNorm(fc1, name='batchnorm0')
>>> fc2.list_auxiliary_states()
['batchnorm0_moving_mean', 'batchnorm0_moving_var']
Returns
-------
aux_states : list of str
List of the auxiliary states in input symbol.
Notes
-----
Auxiliary states are special states of symbols that do not correspond to an argument,
and are not updated by gradient descent. Common examples of auxiliary states
include the `moving_mean` and `moving_variance` in `BatchNorm`.
Most operators do not have auxiliary states.
"""
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListAuxiliaryStates(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size.value)]
def list_inputs(self):
"""Lists all arguments and auxiliary states of this Symbol.
Returns
-------
inputs : list of str
List of all inputs.
Examples
--------
>>> bn = mx.sym.BatchNorm(name='bn')
>>> bn.list_arguments()
['bn_data', 'bn_gamma', 'bn_beta']
>>> bn.list_auxiliary_states()
['bn_moving_mean', 'bn_moving_var']
>>> bn.list_inputs()
['bn_data', 'bn_gamma', 'bn_beta', 'bn_moving_mean', 'bn_moving_var']
"""
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.NNSymbolListInputNames(
self.handle, 0, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size.value)]
def infer_type(self, *args, **kwargs):
"""Infers the type of all arguments and all outputs, given the known types
for some arguments.
This function takes the known types of some arguments in either positional way
or keyword argument way as input. It returns a tuple of `None` values
if there is not enough information to deduce the missing types.
Inconsistencies in the known types will cause an error to be raised.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> arg_types, out_types, aux_types = c.infer_type(a='float32')
>>> arg_types
[<type 'numpy.float32'>, <type 'numpy.float32'>]
>>> out_types
[<type 'numpy.float32'>]
>>> aux_types
[]
Parameters
----------
*args :
Type of known arguments in a positional way.
Unknown type can be marked as None.
**kwargs :
Keyword arguments of known types.
Returns
-------
arg_types : list of numpy.dtype or None
List of argument types.
The order is same as the order of list_arguments().
out_types : list of numpy.dtype or None
List of output types.
The order is same as the order of list_outputs().
aux_types : list of numpy.dtype or None
List of auxiliary state types.
The order is same as the order of list_auxiliary_states().
"""
# pylint: disable=too-many-locals
if len(args) != 0 and len(kwargs) != 0:
raise ValueError('Can only specify known argument \
types either by positional or kwargs way.')
sdata = []
if len(args) != 0:
keys = None
for s in args:
if s is not None:
s = _numpy.dtype(s).type
if s not in _DTYPE_NP_TO_MX:
raise TypeError('Argument need to be one of ' + str(_DTYPE_NP_TO_MX))
sdata.append(_DTYPE_NP_TO_MX[s])
else:
sdata.append(-1)
else:
keys = []
for k, v in kwargs.items():
v = _numpy.dtype(v).type
if v in _DTYPE_NP_TO_MX:
keys.append(c_str(k))
sdata.append(_DTYPE_NP_TO_MX[v])
arg_type_size = mx_uint()
arg_type_data = ctypes.POINTER(ctypes.c_int)()
out_type_size = mx_uint()
out_type_data = ctypes.POINTER(ctypes.c_int)()
aux_type_size = mx_uint()
aux_type_data = ctypes.POINTER(ctypes.c_int)()
complete = ctypes.c_int()
check_call(_LIB.MXSymbolInferType(
self.handle,
mx_uint(len(sdata)),
c_array(ctypes.c_char_p, keys),
c_array(ctypes.c_int, sdata),
ctypes.byref(arg_type_size),
ctypes.byref(arg_type_data),
ctypes.byref(out_type_size),
ctypes.byref(out_type_data),
ctypes.byref(aux_type_size),
ctypes.byref(aux_type_data),
ctypes.byref(complete)))
if complete.value != 0:
arg_types = [
_DTYPE_MX_TO_NP[arg_type_data[i]] for i in range(arg_type_size.value)]
out_types = [
_DTYPE_MX_TO_NP[out_type_data[i]] for i in range(out_type_size.value)]
aux_types = [
_DTYPE_MX_TO_NP[aux_type_data[i]] for i in range(aux_type_size.value)]
return (arg_types, out_types, aux_types)
else:
return (None, None, None)
# pylint: enable=too-many-locals
def infer_shape(self, *args, **kwargs):
"""Infers the shapes of all arguments and all outputs given the known shapes of
some arguments.
This function takes the known shapes of some arguments in either positional way
or keyword argument way as input. It returns a tuple of `None` values
if there is not enough information to deduce the missing shapes.
Example usage:
----------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> arg_shapes, out_shapes, aux_shapes = c.infer_shape(a=(3,3))
>>> arg_shapes
[(3L, 3L), (3L, 3L)]
>>> out_shapes
[(3L, 3L)]
>>> aux_shapes
[]
>>> c.infer_shape(a=(0,3)) # 0s in shape means unknown dimensions. So, returns None.
(None, None, None)
Inconsistencies in the known shapes will cause an error to be raised.
See the following example:
>>> data = mx.sym.Variable('data')
>>> out = mx.sym.FullyConnected(data=data, name='fc1', num_hidden=1000)
>>> out = mx.sym.Activation(data=out, act_type='relu')
>>> out = mx.sym.FullyConnected(data=out, name='fc2', num_hidden=10)
>>> weight_shape= (1, 100)
>>> data_shape = (100, 100)
>>> out.infer_shape(data=data_shape, fc1_weight=weight_shape)
Error in operator fc1: Shape inconsistent, Provided=(1,100), inferred shape=(1000,100)
Parameters
----------
*args :
Shape of arguments in a positional way.
Unknown shape can be marked as None.
**kwargs :
Keyword arguments of the known shapes.
Returns
-------
arg_shapes : list of tuple or None
List of argument shapes.
The order is same as the order of list_arguments().
out_shapes : list of tuple or None
List of output shapes.
The order is same as the order of list_outputs().
aux_shapes : list of tuple or None
List of auxiliary state shapes.
The order is same as the order of list_auxiliary_states().
"""
try:
res = self._infer_shape_impl(False, *args, **kwargs)
if res[1] is None:
arg_shapes, _, _ = self._infer_shape_impl(True, *args, **kwargs)
arg_names = self.list_arguments()
unknowns = []
for name, shape in zip(arg_names, arg_shapes):
if not shape or not _numpy.prod(shape):
if len(unknowns) >= 10:
unknowns.append('...')
break
unknowns.append('%s: %s' % (name, str(shape)))
warnings.warn(
"Cannot decide shape for the following arguments " +
"(0s in shape means unknown dimensions). " +
"Consider providing them as input:\n\t" +
"\n\t".join(unknowns), stacklevel=2)
return res
except MXNetError:
print("infer_shape error. Arguments:")
for i, arg in enumerate(args):
print(" #%d: %s" % (i, arg))
for k, v in kwargs.items():
print(" %s: %s" % (k, v))
raise
def infer_shape_partial(self, *args, **kwargs):
"""Infers the shape partially.
This functions works the same way as `infer_shape`,
except that this function can return partial results.
In the following example, information about fc2 is not available. So, `infer_shape`
will return a tuple of `None` values but `infer_shape_partial` will return partial values.
Example usage:
----------
>>> data = mx.sym.Variable('data')
>>> prev = mx.sym.Variable('prev')
>>> fc1 = mx.sym.FullyConnected(data=data, name='fc1', num_hidden=128)
>>> fc2 = mx.sym.FullyConnected(data=prev, name='fc2', num_hidden=128)
>>> out = mx.sym.Activation(data=mx.sym.elemwise_add(fc1, fc2), act_type='relu')
>>> out.list_arguments()
['data', 'fc1_weight', 'fc1_bias', 'prev', 'fc2_weight', 'fc2_bias']
>>> out.infer_shape(data=(10,64))
(None, None, None)
>>> out.infer_shape_partial(data=(10,64))
([(10L, 64L), (128L, 64L), (128L,), (), (), ()], [(10L, 128L)], [])
>>> # infers shape if you give information about fc2
>>> out.infer_shape(data=(10,64), prev=(10,128))
([(10L, 64L), (128L, 64L), (128L,), (10L, 128L), (128L, 128L), (128L,)], [(10L, 128L)], [])
Parameters
----------
*args :
Shape of arguments in a positional way.
Unknown shape can be marked as None
**kwargs :
Keyword arguments of known shapes.
Returns
-------
arg_shapes : list of tuple or None
List of argument shapes.
The order is same as the order of list_arguments().
out_shapes : list of tuple or None
List of output shapes.
The order is same as the order of list_outputs().
aux_shapes : list of tuple or None
List of auxiliary state shapes.
The order is same as the order of list_auxiliary_states().
"""
return self._infer_shape_impl(True, *args, **kwargs)
def _infer_shape_impl(self, partial, *args, **kwargs):
"""The actual implementation for calling shape inference API."""
# pylint: disable=too-many-locals
if len(args) != 0 and len(kwargs) != 0:
raise ValueError('Can only specify known argument \
shapes either by positional or kwargs way.')
sdata = []
indptr = [0]
if len(args) != 0:
keys = None
for i, s in enumerate(args):
if s is not None:
if not isinstance(s, tuple):
raise TypeError("Arguments need to be shapes (tuple), "
"but argument %d is %s." % (i, type(s)))
sdata.extend(s)
indptr.append(len(sdata))
else:
keys = []
for k, v in kwargs.items():
if not isinstance(v, tuple):
raise TypeError("Arguments need to be shapes (tuple), "
"but '%s' is %s." % (k, type(v)))
keys.append(c_str(k))
sdata.extend(v)
indptr.append(len(sdata))
arg_shape_size = mx_uint()
arg_shape_ndim = ctypes.POINTER(mx_uint)()
arg_shape_data = ctypes.POINTER(ctypes.POINTER(mx_uint))()
out_shape_size = mx_uint()
out_shape_ndim = ctypes.POINTER(mx_uint)()
out_shape_data = ctypes.POINTER(ctypes.POINTER(mx_uint))()
aux_shape_size = mx_uint()
aux_shape_ndim = ctypes.POINTER(mx_uint)()
aux_shape_data = ctypes.POINTER(ctypes.POINTER(mx_uint))()
complete = ctypes.c_int()
if partial:
infer_func = _LIB.MXSymbolInferShapePartial
else:
infer_func = _LIB.MXSymbolInferShape
check_call(infer_func(
self.handle,
mx_uint(len(indptr) - 1),
c_array(ctypes.c_char_p, keys),
c_array(mx_uint, indptr),
c_array(mx_uint, sdata),
ctypes.byref(arg_shape_size),
ctypes.byref(arg_shape_ndim),
ctypes.byref(arg_shape_data),
ctypes.byref(out_shape_size),
ctypes.byref(out_shape_ndim),
ctypes.byref(out_shape_data),
ctypes.byref(aux_shape_size),
ctypes.byref(aux_shape_ndim),
ctypes.byref(aux_shape_data),
ctypes.byref(complete)))
if complete.value != 0:
arg_shapes = [
tuple(arg_shape_data[i][:arg_shape_ndim[i]]) for i in range(arg_shape_size.value)]
out_shapes = [
tuple(out_shape_data[i][:out_shape_ndim[i]]) for i in range(out_shape_size.value)]
aux_shapes = [
tuple(aux_shape_data[i][:aux_shape_ndim[i]]) for i in range(aux_shape_size.value)]
return (arg_shapes, out_shapes, aux_shapes)
else:
return (None, None, None)
# pylint: enable=too-many-locals
def debug_str(self):
"""Gets a debug string of symbol.
It contains Symbol output, variables and operators in the computation graph
with their inputs, variables and attributes.
Returns
-------
string
Debug string of the symbol.
Examples
--------
>>> a = mx.sym.Variable('a')
>>> b = mx.sym.sin(a)
>>> c = 2 * a + b
>>> d = mx.sym.FullyConnected(data=c, num_hidden=10)
>>> d.debug_str()
>>> print d.debug_str()
Symbol Outputs:
output[0]=fullyconnected0(0)
Variable:a
--------------------
Op:_mul_scalar, Name=_mulscalar0
Inputs:
arg[0]=a(0) version=0
Attrs:
scalar=2
--------------------
Op:sin, Name=sin0
Inputs:
arg[0]=a(0) version=0
--------------------
Op:elemwise_add, Name=_plus0
Inputs:
arg[0]=_mulscalar0(0)
arg[1]=sin0(0)
Variable:fullyconnected0_weight
Variable:fullyconnected0_bias
--------------------
Op:FullyConnected, Name=fullyconnected0
Inputs:
arg[0]=_plus0(0)
arg[1]=fullyconnected0_weight(0) version=0
arg[2]=fullyconnected0_bias(0) version=0
Attrs:
num_hidden=10
"""
debug_str = ctypes.c_char_p()
check_call(_LIB.MXSymbolPrint(
self.handle, ctypes.byref(debug_str)))
return py_str(debug_str.value)
def save(self, fname):
"""Saves symbol to a file.
You can also use pickle to do the job if you only work on python.
The advantage of `load`/`save` functions is that the file contents are language agnostic.
This means the model saved by one language binding can be loaded by a different
language binding of `MXNet`.
You also get the benefit of being able to directly load/save from cloud storage(S3, HDFS).
Parameters
----------
fname : str
The name of the file.
- "s3://my-bucket/path/my-s3-symbol"
- "hdfs://my-bucket/path/my-hdfs-symbol"
- "/path-to/my-local-symbol"
See Also
--------
symbol.load : Used to load symbol from file.
"""
if not isinstance(fname, string_types):
raise TypeError('fname need to be string')
check_call(_LIB.MXSymbolSaveToFile(self.handle, c_str(fname)))
def tojson(self):
"""Saves symbol to a JSON string.
See Also
--------
symbol.load_json : Used to load symbol from JSON string.
"""
json_str = ctypes.c_char_p()
check_call(_LIB.MXSymbolSaveToJSON(self.handle, ctypes.byref(json_str)))
return py_str(json_str.value)
@staticmethod
def _get_ndarray_inputs(arg_key, args, arg_names, allow_missing):
"""Helper function to get NDArray lists handles from various inputs.
Parameters
----------
arg_key : str
The name of argument, used for error message.
args : list of NDArray or dict of str to NDArray
Input arguments to the symbols.
If type is list of NDArray, the position is in the same order of arg_names.
If type is dict of str to NDArray, then it maps the name of arguments
to the corresponding NDArray,
args_names : list of string
List of argument names.
allow_missing : boolean
Whether missing argument is allowed.
When allowed, the missing handle will be set to None(null)
Returns
-------
handles : list of NDArrayHandle
The positional list of NDArrayHandles generated from input.
"""
# setup args
arg_handles = []
arg_arrays = []
if isinstance(args, list):
if len(args) != len(arg_names):
raise ValueError('Length of %s does not match the number of arguments' % arg_key)
for narr in args:
if not isinstance(narr, NDArray):
raise TypeError('Only accept list of NDArrays or dict of str to NDArray')
arg_handles.append(narr.handle)
arg_arrays = args
elif isinstance(args, dict):
for name in arg_names:
if name in args:
narr = args[name]
if not isinstance(narr, NDArray):
raise TypeError('Only accept list of NDArrays or dict of str to NDArray')
arg_handles.append(narr.handle)
arg_arrays.append(narr)
else:
if allow_missing:
arg_handles.append(None)
arg_arrays.append(None)
else:
raise ValueError('key `%s` is missing in `%s`' % (name, arg_key))
else:
raise TypeError('Only accept list of NDArrays or dict of str to NDArray')
return c_array(NDArrayHandle, arg_handles), arg_arrays
def simple_bind(self, ctx, grad_req='write', type_dict=None, group2ctx=None,
shared_arg_names=None, shared_exec=None, shared_buffer=None, **kwargs):
"""Bind current symbol to get an executor, allocate all the arguments needed.
Allows specifying data types.
This function simplifies the binding procedure. You need to specify only input data shapes.
Before binding the executor, the function allocates arguments and auxiliary states
that were not explicitly specified. Allows specifying data types.
Example usage:
----------
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.FullyConnected(x, num_hidden=4)
>>> exe = y.simple_bind(mx.cpu(), x=(5,4), grad_req='null')
>>> exe.forward()
[<NDArray 5x4 @cpu(0)>]
>>> exe.outputs[0].asnumpy()
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)
>>> exe.arg_arrays
[<NDArray 5x4 @cpu(0)>, <NDArray 4x4 @cpu(0)>, <NDArray 4 @cpu(0)>]
>>> exe.grad_arrays
[<NDArray 5x4 @cpu(0)>, <NDArray 4x4 @cpu(0)>, <NDArray 4 @cpu(0)>]
Parameters
----------
ctx : Context
The device context the generated executor to run on.
grad_req: string
{'write', 'add', 'null'}, or list of str or dict of str to str, optional
To specify how we should update the gradient to the `args_grad`.
- 'write' means every time gradient is written to specified `args_grad` NDArray.
- 'add' means every time gradient is added to the specified NDArray.
- 'null' means no action is taken, the gradient may not be calculated.
type_dict : Dict of str->numpy.dtype
Input type dictionary, name->dtype
group2ctx : Dict of string to mx.Context
The dict mapping the `ctx_group` attribute to the context assignment.
shared_arg_names : List of string
The argument names whose `NDArray` of shared_exec can be reused for initializing
the current executor.
shared_exec : Executor
The executor whose arg_arrays, arg_arrays, grad_arrays, and aux_arrays can be
reused for initializing the current executor.
shared_buffer : Dict of string to `NDArray`
The dict mapping argument names to the `NDArray` that can be reused for initializing
the current executor. This buffer will be checked for reuse if one argument name
of the current executor is not found in `shared_arg_names`.
kwargs : Dict of str->shape
Input shape dictionary, name->shape
Returns
-------
executor : mxnet.Executor
The generated executor
"""
num_provided_arg_types = 0
provided_arg_type_names = ctypes.POINTER(ctypes.c_char_p)() # provided type argument names
provided_arg_type_data = ctypes.POINTER(mx_uint)() # provided types
if type_dict is not None:
provided_arg_type_names = []
provided_arg_type_data = []
for k, v in type_dict.items():
v = _numpy.dtype(v).type
if v in _DTYPE_NP_TO_MX:
provided_arg_type_names.append(c_str(k))
provided_arg_type_data.append(ctypes.c_int(_DTYPE_NP_TO_MX[v]))
num_provided_arg_types = mx_uint(len(provided_arg_type_names))
provided_arg_type_names = c_array(ctypes.c_char_p, provided_arg_type_names)
provided_arg_type_data = c_array(ctypes.c_int, provided_arg_type_data)
provided_arg_shape_data = [] # shape data
# argument shape index in sdata,
# e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg
provided_arg_shape_idx = [0]
provided_arg_shape_names = [] # provided argument names
for k, v in kwargs.items():
# if k not in listed_arguments and k not in listed_aux_states:
# raise ValueError('arg name %s is not valid', k)
if isinstance(v, tuple):
provided_arg_shape_names.append(c_str(k))
provided_arg_shape_data.extend(v)
provided_arg_shape_idx.append(len(provided_arg_shape_data))
provided_req_type_list_len = 0
provided_grad_req_types = ctypes.POINTER(ctypes.c_char_p)()
provided_grad_req_names = ctypes.POINTER(ctypes.c_char_p)()
if grad_req is not None:
if isinstance(grad_req, string_types):
# use provided_req_type_list_len = 0 to indicate this situation
provided_req_type_list_len = 0
provided_grad_req_types = [c_str(grad_req)]
elif isinstance(grad_req, list):
if len(grad_req) == 0:
raise RuntimeError('grad_req in simple_bind cannot be an empty list')
provided_grad_req_types = [c_str(item) for item in grad_req]
provided_req_type_list_len = len(provided_grad_req_types)
elif isinstance(grad_req, dict):
if len(grad_req) == 0:
raise RuntimeError('grad_req in simple_bind cannot be an empty dict')
provided_grad_req_names = []
provided_grad_req_types = []
for k, v in grad_req.items():
provided_grad_req_names.append(c_str(k))
provided_grad_req_types.append(c_str(v))
provided_grad_req_names = c_array(ctypes.c_char_p, provided_grad_req_names)
provided_req_type_list_len = len(provided_grad_req_types)
provided_grad_req_types = c_array(ctypes.c_char_p, provided_grad_req_types)
num_ctx_map_keys = mx_uint(0)
ctx_map_keys = ctypes.POINTER(ctypes.c_char_p)()
ctx_map_dev_types = ctypes.POINTER(ctypes.c_int)()
ctx_map_dev_ids = ctypes.POINTER(ctypes.c_int)()
if group2ctx is not None:
ctx_map_keys = []
ctx_map_dev_types = []
ctx_map_dev_ids = []
for key, val in group2ctx.items():
ctx_map_keys.append(c_str(key))
ctx_map_dev_types.append(ctypes.c_int(val.device_typeid))
ctx_map_dev_ids.append(ctypes.c_int(val.device_id))
num_ctx_map_keys = mx_uint(len(ctx_map_keys))
ctx_map_keys = c_array(ctypes.c_char_p, ctx_map_keys)
ctx_map_dev_types = c_array(ctypes.c_int, ctx_map_dev_types)
ctx_map_dev_ids = c_array(ctypes.c_int, ctx_map_dev_ids)
# prepare param names
shared_arg_name_list = []
if shared_arg_names is not None:
if not isinstance(shared_arg_names, list):
raise ValueError('shared_arg_names in simple_bind must be a list or None')
shared_arg_name_list = [c_str(name) for name in shared_arg_names]
# prepare shared_buffer
if shared_buffer is None:
shared_buffer_len = ctypes.c_int(-1)
shared_buffer_names = ctypes.POINTER(ctypes.c_char_p)()
shared_buffer_handles = ctypes.POINTER(NDArrayHandle)()
else:
if not isinstance(shared_buffer, dict):
raise ValueError('shared_buffer in simple_bind must be dict or None')
shared_buffer_names = []
shared_buffer_handles = []
for k, v in shared_buffer.items():
shared_buffer_names.append(c_str(k))
shared_buffer_handles.append(v.handle)
shared_buffer_names = c_array(ctypes.c_char_p, shared_buffer_names)
shared_buffer_len = ctypes.c_int(len(shared_buffer_handles))
shared_buffer_handles = c_array(NDArrayHandle, shared_buffer_handles)
updated_shared_buffer_names = ctypes.POINTER(ctypes.c_char_p)()
updated_shared_buffer_handles = ctypes.POINTER(NDArrayHandle)()
# prepare shared_exec_handle
shared_exec_handle = shared_exec.handle if shared_exec is not None else ExecutorHandle()
# prepare current executor handle
exe_handle = ExecutorHandle()
# prepare current executor's in_args, arg_grads, and aux_states
num_in_args = ctypes.c_uint()
in_arg_handles = ctypes.POINTER(NDArrayHandle)()
arg_grad_handles = ctypes.POINTER(NDArrayHandle)()
num_aux_states = ctypes.c_uint()
aux_state_handles = ctypes.POINTER(NDArrayHandle)()
try:
check_call(_LIB.MXExecutorSimpleBind(self.handle,
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
num_ctx_map_keys,
ctx_map_keys,
ctx_map_dev_types,
ctx_map_dev_ids,
mx_uint(provided_req_type_list_len),
provided_grad_req_names,
provided_grad_req_types,
mx_uint(len(provided_arg_shape_names)),
c_array(ctypes.c_char_p, provided_arg_shape_names),
c_array(mx_uint, provided_arg_shape_data),
c_array(mx_uint, provided_arg_shape_idx),
num_provided_arg_types,
provided_arg_type_names,
provided_arg_type_data,
mx_uint(len(shared_arg_name_list)),
c_array(ctypes.c_char_p, shared_arg_name_list),
ctypes.byref(shared_buffer_len),
shared_buffer_names,
shared_buffer_handles,
ctypes.byref(updated_shared_buffer_names),
ctypes.byref(updated_shared_buffer_handles),
ctypes.byref(num_in_args),
ctypes.byref(in_arg_handles),
ctypes.byref(arg_grad_handles),
ctypes.byref(num_aux_states),
ctypes.byref(aux_state_handles),
shared_exec_handle,
ctypes.byref(exe_handle)))
except MXNetError as e:
error_msg = "simple_bind error. Arguments:\n"
for k, v in kwargs.items():
error_msg += "%s: %s\n" % (k, v)
error_msg += "%s" % e
raise RuntimeError(error_msg)
# update shared_buffer
if shared_buffer is not None:
for i in range(shared_buffer_len.value):
k = py_str(updated_shared_buffer_names[i])
v = NDArray(NDArrayHandle(updated_shared_buffer_handles[i]))
shared_buffer[k] = v
# create in_args, arg_grads, and aux_states for the current executor
arg_arrays = [NDArray(NDArrayHandle(in_arg_handles[i])) for i in range(num_in_args.value)]
grad_arrays = [NDArray(NDArrayHandle(arg_grad_handles[i]))
if arg_grad_handles[i] is not None
else None for i in range(num_in_args.value)]
aux_arrays = [NDArray(NDArrayHandle(aux_state_handles[i]))
for i in range(num_aux_states.value)]
executor = Executor(exe_handle, self, ctx, grad_req, group2ctx)
executor.arg_arrays = arg_arrays
executor.grad_arrays = grad_arrays
executor.aux_arrays = aux_arrays
return executor
def bind(self, ctx, args, args_grad=None, grad_req='write',
aux_states=None, group2ctx=None, shared_exec=None):
"""Binds the current symbol to an executor and returns it.
We first declare the computation and then bind to the data to run.
This function returns an executor which provides method `forward()` method for evaluation
and a `outputs()` method to get all the results.
Example usage:
----------
>>> a = mx.sym.Variable('a')
>>> b = mx.sym.Variable('b')
>>> c = a + b
<Symbol _plus1>
>>> ex = c.bind(ctx=mx.cpu(), args={'a' : mx.nd.ones([2,3]), 'b' : mx.nd.ones([2,3])})
>>> ex.forward()
[<NDArray 2x3 @cpu(0)>]
>>> ex.outputs[0].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
Parameters
----------
ctx : Context
The device context the generated executor to run on.
args : list of NDArray or dict of str to NDArray
Input arguments to the symbol.
- If the input type is a list of `NDArray`, the order should be same as the order
of `list_arguments()`.
- If the input type is a dict of str to `NDArray`, then it maps the name of arguments
to the corresponding `NDArray`.
- In either case, all the arguments must be provided.
args_grad : list of NDArray or dict of str to `NDArray`, optional
When specified, `args_grad` provides NDArrays to hold
the result of gradient value in backward.
- If the input type is a list of `NDArray`, the order should be same as the order
of `list_arguments()`.
- If the input type is a dict of str to `NDArray`, then it maps the name of arguments
to the corresponding NDArray.
- When the type is a dict of str to `NDArray`, one only need to provide the dict
for required argument gradient.
Only the specified argument gradient will be calculated.
grad_req : {'write', 'add', 'null'}, or list of str or dict of str to str, optional
To specify how we should update the gradient to the `args_grad`.
- 'write' means everytime gradient is write to specified `args_grad` `NDArray`.
- 'add' means everytime gradient is add to the specified NDArray.
- 'null' means no action is taken, the gradient may not be calculated.
aux_states : list of `NDArray`, or dict of str to `NDArray`, optional
Input auxiliary states to the symbol, only needed when the output of
`list_auxiliary_states()` is not empty.
- If the input type is a list of `NDArray`, the order should be same as the order
of `list_auxiliary_states()`.
- If the input type is a dict of str to `NDArray`, then it maps the name of
`auxiliary_states` to the corresponding `NDArray`,
- In either case, all the auxiliary states need to be provided.
group2ctx : Dict of string to mx.Context
The dict mapping the `ctx_group` attribute to the context assignment.
shared_exec : mx.executor.Executor
Executor to share memory with. This is intended for runtime reshaping, variable length
sequences, etc. The returned executor shares state with `shared_exec`, and should not be
used in parallel with it.
Returns
-------
executor : Executor
The generated executor
Notes
-----
Auxiliary states are the special states of symbols that do not correspond
to an argument, and do not have gradient but are still useful
for the specific operations. Common examples of auxiliary states include
the `moving_mean` and `moving_variance` states in `BatchNorm`.
Most operators do not have auxiliary states and in those cases,
this parameter can be safely ignored.
One can give up gradient by using a dict in `args_grad` and only specify
gradient they interested in.
"""
# pylint: disable=too-many-locals, too-many-branches
if not isinstance(ctx, Context):
raise TypeError("Context type error")
listed_arguments = self.list_arguments()
args_handle, args = self._get_ndarray_inputs('args', args, listed_arguments, False)
# setup args gradient
if args_grad is None:
args_grad_handle = c_array(NDArrayHandle, [None] * len(args))
else:
args_grad_handle, args_grad = self._get_ndarray_inputs(
'args_grad', args_grad, listed_arguments, True)
if aux_states is None:
aux_states = []
aux_args_handle, aux_states = self._get_ndarray_inputs(
'aux_states', aux_states, self.list_auxiliary_states(), False)
# setup requirements
if isinstance(grad_req, string_types):
if grad_req not in _GRAD_REQ_MAP:
raise ValueError('grad_req must be in %s' % str(_GRAD_REQ_MAP))
reqs_array = c_array(
mx_uint,
[mx_uint(_GRAD_REQ_MAP[grad_req])] * len(listed_arguments))
elif isinstance(grad_req, list):
reqs_array = c_array(mx_uint, [mx_uint(_GRAD_REQ_MAP[item]) for item in grad_req])
elif isinstance(grad_req, dict):
req_array = []
for name in listed_arguments:
if name in grad_req:
req_array.append(mx_uint(_GRAD_REQ_MAP[grad_req[name]]))
else:
req_array.append(mx_uint(0))
reqs_array = c_array(mx_uint, req_array)
ctx_map_keys = []
ctx_map_dev_types = []
ctx_map_dev_ids = []
if group2ctx:
for key, val in group2ctx.items():
ctx_map_keys.append(c_str(key))
ctx_map_dev_types.append(ctypes.c_int(val.device_typeid))
ctx_map_dev_ids.append(ctypes.c_int(val.device_id))
handle = ExecutorHandle()
shared_handle = shared_exec.handle if shared_exec is not None else ExecutorHandle()
check_call(_LIB.MXExecutorBindEX(self.handle,
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
mx_uint(len(ctx_map_keys)),
c_array(ctypes.c_char_p, ctx_map_keys),
c_array(ctypes.c_int, ctx_map_dev_types),
c_array(ctypes.c_int, ctx_map_dev_ids),
mx_uint(len(args)),
args_handle,
args_grad_handle,
reqs_array,
mx_uint(len(aux_states)),
aux_args_handle,
shared_handle,
ctypes.byref(handle)))
executor = Executor(handle, self, ctx, grad_req, group2ctx)
executor.arg_arrays = args
executor.grad_arrays = args_grad
executor.aux_arrays = aux_states
return executor
def grad(self, wrt):
"""Gets the autodiff of current symbol.
This function can only be used if current symbol is a loss function.
.. note:: This function is currently not implemented.
Parameters
----------
wrt : Array of String
keyword arguments of the symbol that the gradients are taken.
Returns
-------
grad : Symbol
A gradient Symbol with returns to be the corresponding gradients.
"""
handle = SymbolHandle()
c_wrt = c_array(ctypes.c_char_p, [c_str(key) for key in wrt])
check_call(_LIB.MXSymbolGrad(self.handle,
mx_uint(len(wrt)),
c_wrt,
ctypes.byref(handle)))
return Symbol(handle)
# pylint: enable= no-member
def eval(self, ctx=cpu(), **kwargs):
"""Evaluates a symbol given arguments.
The `eval` method combines a call to `bind` (which returns an executor)
with a call to `forward` (executor method).
For the common use case, where you might repeatedly evaluate with same arguments,
eval is slow.
In that case, you should call `bind` once and then repeatedly call forward.
This function allows simpler syntax for less cumbersome introspection.
Example usage:
----------
>>> a = mx.sym.Variable('a')
>>> b = mx.sym.Variable('b')
>>> c = a + b
>>> ex = c.eval(ctx = mx.cpu(), a = mx.nd.ones([2,3]), b = mx.nd.ones([2,3]))
>>> ex
[<NDArray 2x3 @cpu(0)>]
>>> ex[0].asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
Parameters
----------
ctx : Context
The device context the generated executor to run on.
kwargs : Keyword arguments of type `NDArray`
Input arguments to the symbol. All the arguments must be provided.
Returns
----------
result : a list of NDArrays corresponding to the values taken by each symbol when
evaluated on given args. When called on a single symbol (not a group),
the result will be a list with one element.
"""
return self.bind(ctx, kwargs).forward()
def reshape(self, shape):
"""Shorthand for mxnet.sym.reshape.
Parameters
----------
shape : tuple of int
The new shape should not change the array size, namely
``np.prod(new_shape)`` should be equal to ``np.prod(self.shape)``.
One shape dimension can be -1. In this case, the value is inferred
from the length of the array and remaining dimensions.
Returns
-------
Symbol
A reshaped symbol.
"""
return reshape(self, shape=shape)
def var(name, attr=None, shape=None, lr_mult=None, wd_mult=None, dtype=None, init=None, **kwargs):
"""Creates a symbolic variable with specified name.
Example usage:
----------
>>> data = mx.sym.Variable('data', attr={'a': 'b'})
>>> data
<Symbol data>
Parameters
----------
name : str
Variable name.
attr : Dict of strings
Additional attributes to set on the variable. Format {string : string}.
shape : tuple
The shape of a variable. If specified, this will be used during the shape inference.
If one has specified a different shape for this variable using
a keyword argument when calling shape inference, this shape information will be ignored.
lr_mult : float
The learning rate multiplier for input variable.
wd_mult : float
Weight decay multiplier for input variable.
dtype : str or numpy.dtype
The dtype for input variable. If not specified, this value will be inferred.
init : initializer (mxnet.init.*)
Initializer for this variable to (optionally) override the default initializer.
kwargs : Additional attribute variables
Additional attributes must start and end with double underscores.
Returns
-------
variable : Symbol
A symbol corresponding to an input to the computation graph.
"""
if not isinstance(name, string_types):
raise TypeError('Expect a string for variable `name`')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateVariable(c_str(name), ctypes.byref(handle)))
ret = Symbol(handle)
attr = AttrScope.current.get(attr)
attr = {} if attr is None else attr
if shape is not None:
attr['__shape__'] = str(shape)
if lr_mult is not None:
attr['__lr_mult__'] = str(lr_mult)
if wd_mult is not None:
attr['__wd_mult__'] = str(wd_mult)
if dtype is not None:
attr['__dtype__'] = str(_DTYPE_NP_TO_MX[_numpy.dtype(dtype).type])
if init is not None:
if not isinstance(init, string_types):
init = init.dumps()
attr['__init__'] = init
for k, v in kwargs.items():
if k.startswith('__') and k.endswith('__'):
attr[k] = str(v)
else:
raise ValueError('Attribute name=%s is not supported.'
' Additional attributes must start and end with double underscores,'
' e.g, __yourattr__' % k)
ret._set_attr(**attr)
return ret
# for back compatibility
Variable = var
def Group(symbols):
"""Creates a symbol that contains a collection of other symbols, grouped together.
Example usage:
----------
>>> a = mx.sym.Variable('a')
>>> b = mx.sym.Variable('b')
>>> mx.sym.Group([a,b])
<Symbol Grouped>
Parameters
----------
symbols : list
List of symbols to be grouped.
Returns
-------
sym : Symbol
A group symbol.
"""
ihandles = []
for sym in symbols:
if not isinstance(sym, Symbol):
raise TypeError('Expected a list of symbols as input')
ihandles.append(sym.handle)
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateGroup(
mx_uint(len(ihandles)),
c_array(SymbolHandle, ihandles), ctypes.byref(handle)))
return Symbol(handle)
def load(fname):
"""Loads symbol from a JSON file.
You can also use pickle to do the job if you only work on python.
The advantage of load/save is the file is language agnostic.
This means the file saved using save can be loaded by other language binding of mxnet.
You also get the benefit being able to directly load/save from cloud storage(S3, HDFS).
Parameters
----------
fname : str
The name of the file, examples:
- `s3://my-bucket/path/my-s3-symbol`
- `hdfs://my-bucket/path/my-hdfs-symbol`
- `/path-to/my-local-symbol`
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
Symbol.save : Used to save symbol into file.
"""
if not isinstance(fname, string_types):
raise TypeError('fname need to be string')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromFile(c_str(fname), ctypes.byref(handle)))
return Symbol(handle)
def load_json(json_str):
"""Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
Symbol.tojson : Used to save symbol into json string.
"""
if not isinstance(json_str, string_types):
raise TypeError('fname required to be string')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
return Symbol(handle)
# pylint: disable=no-member
# pylint: disable=redefined-builtin
def pow(base, exp):
"""Returns element-wise result of base element raised to powers from exp element.
Both inputs can be Symbol or scalar number.
Broadcasting is not supported. Use `broadcast_pow` instead.
Parameters
---------
base : Symbol or scalar
The base symbol
exp : Symbol or scalar
The exponent symbol
Returns
-------
Symbol or scalar
The bases in x raised to the exponents in y.
Examples
--------
>>> mx.sym.pow(2, 3)
8
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.Variable('y')
>>> z = mx.sym.pow(x, 2)
>>> z.eval(x=mx.nd.array([1,2]))[0].asnumpy()
array([ 1., 4.], dtype=float32)
>>> z = mx.sym.pow(3, y)
>>> z.eval(y=mx.nd.array([2,3]))[0].asnumpy()
array([ 9., 27.], dtype=float32)
>>> z = mx.sym.pow(x, y)
>>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([2,3]))[0].asnumpy()
array([ 9., 64.], dtype=float32)
"""
if isinstance(base, Symbol) and isinstance(exp, Symbol):
return _internal._Power(base, exp)
if isinstance(base, Symbol) and isinstance(exp, Number):
return _internal._PowerScalar(base, scalar=exp)
if isinstance(base, Number) and isinstance(exp, Symbol):
return _internal._RPowerScalar(exp, scalar=base)
if isinstance(base, Number) and isinstance(exp, Number):
return base**exp
else:
raise TypeError('types (%s, %s) not supported' % (str(type(base)), str(type(exp))))
# pylint: disable=no-member
# pylint: disable=redefined-builtin
def maximum(left, right):
"""Returns element-wise maximum of the input elements.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First symbol to be compared.
right : Symbol or scalar
Second symbol to be compared.
Returns
-------
Symbol or scalar
The element-wise maximum of the input symbols.
Examples
--------
>>> mx.sym.maximum(2, 3.5)
3.5
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.Variable('y')
>>> z = mx.sym.maximum(x, 4)
>>> z.eval(x=mx.nd.array([3,5,2,10]))[0].asnumpy()
array([ 4., 5., 4., 10.], dtype=float32)
>>> z = mx.sym.maximum(x, y)
>>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy()
array([ 10., 4.], dtype=float32)
"""
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Maximum(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._MaximumScalar(left, scalar=right)
if isinstance(left, Number) and isinstance(right, Symbol):
return _internal._MaximumScalar(right, scalar=left)
if isinstance(left, Number) and isinstance(right, Number):
return left if left > right else right
else:
raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right))))
# pylint: disable=no-member
# pylint: disable=redefined-builtin
def minimum(left, right):
"""Returns element-wise minimum of the input elements.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First symbol to be compared.
right : Symbol or scalar
Second symbol to be compared.
Returns
-------
Symbol or scalar
The element-wise minimum of the input symbols.
Examples
--------
>>> mx.sym.minimum(2, 3.5)
2
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.Variable('y')
>>> z = mx.sym.minimum(x, 4)
>>> z.eval(x=mx.nd.array([3,5,2,10]))[0].asnumpy()
array([ 3., 4., 2., 4.], dtype=float32)
>>> z = mx.sym.minimum(x, y)
>>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy()
array([ 3., 2.], dtype=float32)
"""
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Minimum(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._MinimumScalar(left, scalar=right)
if isinstance(left, Number) and isinstance(right, Symbol):
return _internal._MinimumScalar(right, scalar=left)
if isinstance(left, Number) and isinstance(right, Number):
return left if left < right else right
else:
raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right))))
# pylint: disable=no-member
# pylint: disable=redefined-builtin
def hypot(left, right):
"""Given the "legs" of a right triangle, returns its hypotenuse.
Equivalent to :math:`\\sqrt(left^2 + right^2)`, element-wise.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First leg of the triangle(s).
right : Symbol or scalar
Second leg of the triangle(s).
Returns
-------
Symbol or scalar
The hypotenuse of the triangle(s)
Examples
--------
>>> mx.sym.hypot(3, 4)
5.0
>>> x = mx.sym.Variable('x')
>>> y = mx.sym.Variable('y')
>>> z = mx.sym.hypot(x, 4)
>>> z.eval(x=mx.nd.array([3,5,2]))[0].asnumpy()
array([ 5., 6.40312433, 4.47213602], dtype=float32)
>>> z = mx.sym.hypot(x, y)
>>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy()
array([ 10.44030666, 4.47213602], dtype=float32)
"""
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Hypot(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._HypotScalar(left, scalar=right)
if isinstance(left, Number) and isinstance(right, Symbol):
return _internal._HypotScalar(right, scalar=left)
if isinstance(left, Number) and isinstance(right, Number):
return _numpy.hypot(left, right)
else:
raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right))))
def zeros(shape, dtype=None, **kwargs):
"""Returns a new symbol of given shape and type, filled with zeros.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol.
"""
if dtype is None:
dtype = _numpy.float32
return _internal._zeros(shape=shape, dtype=dtype, **kwargs)
def ones(shape, dtype=None, **kwargs):
"""Returns a new symbol of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol
"""
if dtype is None:
dtype = _numpy.float32
return _internal._ones(shape=shape, dtype=dtype, **kwargs)
def arange(start, stop=None, step=1.0, repeat=1, name=None, dtype=None):
"""Returns evenly spaced values within a given interval.
Parameters
----------
start : number
Start of interval. The interval includes this value. The default start value is 0.
stop : number, optional
End of interval. The interval does not include this value.
step : number, optional
Spacing between values.
repeat : int, optional
"The repeating time of all elements.
E.g repeat=3, the element a will be repeated three times --> a, a, a.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol
"""
if dtype is None:
dtype = _numpy.float32
return _internal._arange(start=start, stop=stop, step=step, repeat=repeat,
name=name, dtype=dtype)
def _make_atomic_symbol_function(handle, name):
"""Create an atomic symbol function by handle and funciton name."""
real_name = ctypes.c_char_p()
desc = ctypes.c_char_p()
num_args = mx_uint()
arg_names = ctypes.POINTER(ctypes.c_char_p)()
arg_types = ctypes.POINTER(ctypes.c_char_p)()
arg_descs = ctypes.POINTER(ctypes.c_char_p)()
key_var_num_args = ctypes.c_char_p()
ret_type = ctypes.c_char_p()
check_call(_LIB.MXSymbolGetAtomicSymbolInfo(
handle, ctypes.byref(real_name), ctypes.byref(desc),
ctypes.byref(num_args),
ctypes.byref(arg_names),
ctypes.byref(arg_types),
ctypes.byref(arg_descs),
ctypes.byref(key_var_num_args),
ctypes.byref(ret_type)))
narg = int(num_args.value)
arg_names = [py_str(arg_names[i]) for i in range(narg)]
arg_types = [py_str(arg_types[i]) for i in range(narg)]
func_name = name
key_var_num_args = py_str(key_var_num_args.value)
ret_type = py_str(ret_type.value) if ret_type.value is not None else ''
doc_str = _build_doc(func_name,
py_str(desc.value),
arg_names,
arg_types,
[py_str(arg_descs[i]) for i in range(narg)],
key_var_num_args,
ret_type)
dtype_name = None
arr_name = None
ndsignature = []
signature = []
ndarg_names = []
kwarg_names = []
for i in range(narg):
name, atype = arg_names[i], arg_types[i]
if name == 'dtype':
dtype_name = name
signature.append('%s=_Null'%name)
elif atype.startswith('NDArray') or atype.startswith('Symbol'):
assert not arr_name, \
"Op can only have one argument with variable " \
"size and it must be the last argument."
if atype.endswith('[]'):
ndsignature.append('*%s'%name)
arr_name = name
else:
ndsignature.append('%s=None'%name)
ndarg_names.append(name)
else:
signature.append('%s=_Null'%name)
kwarg_names.append(name)
#signature.append('is_train=False')
signature.append('name=None')
signature.append('attr=None')
signature.append('out=None')
signature.append('**kwargs')
signature = ndsignature + signature
code = []
if arr_name:
code.append("""
def %s(*%s, **kwargs):"""%(func_name, arr_name))
code.append("""
sym_args = []
for i in {}:
assert isinstance(i, SymbolBase), \\
"Positional arguments must be Symbol instances, " \\
"but got %s"%str(i)
sym_args.append(i)""".format(arr_name))
if dtype_name is not None:
code.append("""
if '%s' in kwargs:
kwargs['%s'] = _numpy.dtype(kwargs['%s']).name"""%(
dtype_name, dtype_name, dtype_name))
code.append("""
attr = kwargs.pop('attr', None)
kwargs.update(AttrScope.current.get(attr))
name = kwargs.pop('name', None)
name = NameManager.current.get(name, '%s')
_ = kwargs.pop('out', None)
keys = []
vals = []
sym_kwargs = dict()
for k, v in kwargs.items():
if isinstance(v, SymbolBase):
sym_kwargs[k] = v
else:
keys.append(k)
vals.append(v)"""%(func_name.lower()))
if key_var_num_args:
code.append("""
if '%s' not in kwargs:
keys.append('%s')
vals.append(len(sym_args) + len(sym_kwargs))"""%(
key_var_num_args, key_var_num_args))
code.append("""
return _symbol_creator(%d, sym_args, sym_kwargs, keys, vals, name)"""%(
handle.value))
else:
code.append("""
def %s(%s):
kwargs.update(AttrScope.current.get(attr))
sym_kwargs = dict()
keys = []
vals = []"""%(func_name, ', '.join(signature)))
code.append("""
for k, v in kwargs.items():
if isinstance(v, SymbolBase):
sym_kwargs[k] = v
else:
keys.append(k)
vals.append(v)""")
# NDArray args
for name in ndarg_names: # pylint: disable=redefined-argument-from-local
code.append("""
if {name} is not None:
assert isinstance({name}, SymbolBase), \\
"Argument {name} must be Symbol instances, but got %s"%str({name})
sym_kwargs['{name}'] = {name}""".format(name=name))
# kwargs
for name in kwarg_names: # pylint: disable=redefined-argument-from-local
code.append("""
if %s is not _Null:
keys.append('%s')
vals.append(%s)"""%(name, name, name))
# dtype
if dtype_name is not None:
code.append("""
if %s is not _Null:
keys.append('%s')
vals.append(_numpy.dtype(%s).name)"""%(dtype_name, dtype_name, dtype_name))
code.append("""
name = NameManager.current.get(name, '%s')
return _symbol_creator(%d, None, sym_kwargs, keys, vals, name)"""%(
func_name.lower(), handle.value))
local = {}
exec(''.join(code), None, local) # pylint: disable=exec-used
symbol_function = local[func_name]
symbol_function.__name__ = func_name
symbol_function.__doc__ = doc_str
symbol_function.__module__ = 'mxnet.symbol'
return symbol_function
def _init_symbol_module(symbol_class, root_namespace):
"""List and add all the atomic symbol functions to current module."""
_set_symbol_class(symbol_class)
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = []
for i in range(size.value):
op_names.append(py_str(plist[i]))
module_obj = _sys.modules["%s.symbol" % root_namespace]
module_internal = _sys.modules["%s._symbol_internal" % root_namespace]
module_contrib = _sys.modules["%s.contrib.symbol" % root_namespace]
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
function = _make_atomic_symbol_function(hdl, name)
if function.__name__.startswith('_contrib_'):
function.__name__ = function.__name__[9:]
function.__module__ = 'mxnet.contrib.symbol'
setattr(module_contrib, function.__name__, function)
elif function.__name__.startswith('_'):
setattr(module_internal, function.__name__, function)
else:
setattr(module_obj, function.__name__, function)
# Initialize the atomic symbol in startups
_init_symbol_module(Symbol, "mxnet")
|
[] |
[] |
[
"MXNET_ENFORCE_CYTHON",
"MXNET_ENABLE_CYTHON"
] |
[]
|
["MXNET_ENFORCE_CYTHON", "MXNET_ENABLE_CYTHON"]
|
python
| 2 | 0 | |
cmd/pitr/recoverer/recoverer.go
|
package recoverer
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"time"
"github.com/percona/percona-xtradb-cluster-operator/cmd/pitr/pxc"
"github.com/percona/percona-xtradb-cluster-operator/cmd/pitr/storage"
"github.com/pkg/errors"
)
type Recoverer struct {
db *pxc.PXC
recoverTime string
storage storage.Storage
pxcUser string
pxcPass string
recoverType RecoverType
pxcServiceName string
binlogs []string
gtidSet string
startGTID string
recoverFlag string
recoverEndTime time.Time
gtid string
}
type Config struct {
PXCServiceName string `env:"PXC_SERVICE,required"`
PXCUser string `env:"PXC_USER,required"`
PXCPass string `env:"PXC_PASS,required"`
BackupStorage BackupS3
RecoverTime string `env:"PITR_DATE"`
RecoverType string `env:"PITR_RECOVERY_TYPE,required"`
GTID string `env:"PITR_GTID"`
BinlogStorage BinlogS3
}
type BackupS3 struct {
Endpoint string `env:"ENDPOINT" envDefault:"s3.amazonaws.com"`
AccessKeyID string `env:"ACCESS_KEY_ID,required"`
AccessKey string `env:"SECRET_ACCESS_KEY,required"`
Region string `env:"DEFAULT_REGION,required"`
BackupDest string `env:"S3_BUCKET_URL,required"`
}
type BinlogS3 struct {
Endpoint string `env:"BINLOG_S3_ENDPOINT" envDefault:"s3.amazonaws.com"`
AccessKeyID string `env:"BINLOG_ACCESS_KEY_ID,required"`
AccessKey string `env:"BINLOG_SECRET_ACCESS_KEY,required"`
Region string `env:"BINLOG_S3_REGION,required"`
BucketURL string `env:"BINLOG_S3_BUCKET_URL,required"`
}
func (c *Config) Verify() {
if len(c.BackupStorage.Endpoint) == 0 {
c.BackupStorage.Endpoint = "s3.amazonaws.com"
}
if len(c.BinlogStorage.Endpoint) == 0 {
c.BinlogStorage.Endpoint = "s3.amazonaws.com"
}
}
type RecoverType string
func New(c Config) (*Recoverer, error) {
c.Verify()
bucket, prefix, err := getBucketAndPrefix(c.BinlogStorage.BucketURL)
if err != nil {
return nil, errors.Wrap(err, "get bucket and prefix")
}
s3, err := storage.NewS3(strings.TrimPrefix(strings.TrimPrefix(c.BinlogStorage.Endpoint, "https://"), "http://"), c.BinlogStorage.AccessKeyID, c.BinlogStorage.AccessKey, bucket, prefix, c.BinlogStorage.Region, strings.HasPrefix(c.BinlogStorage.Endpoint, "https"))
if err != nil {
return nil, errors.Wrap(err, "new storage manager")
}
startGTID, err := getStartGTIDSet(c.BackupStorage)
if err != nil {
return nil, errors.Wrap(err, "get start GTID")
}
return &Recoverer{
storage: s3,
recoverTime: c.RecoverTime,
pxcUser: c.PXCUser,
pxcPass: c.PXCPass,
pxcServiceName: c.PXCServiceName,
recoverType: RecoverType(c.RecoverType),
startGTID: startGTID,
gtid: c.GTID,
}, nil
}
func getBucketAndPrefix(bucketURL string) (bucket string, prefix string, err error) {
u, err := url.Parse(bucketURL)
if err != nil {
err = errors.Wrap(err, "parse url")
return bucket, prefix, err
}
path := strings.TrimPrefix(strings.TrimSuffix(u.Path, "/"), "/")
if u.IsAbs() && u.Scheme == "s3" {
bucket = u.Host
prefix = path + "/"
return bucket, prefix, err
}
bucketArr := strings.Split(path, "/")
if len(bucketArr) > 1 {
prefix = strings.TrimPrefix(path, bucketArr[0]+"/") + "/"
}
bucket = bucketArr[0]
if len(bucket) == 0 {
err = errors.Errorf("can't get bucket name from %s", bucketURL)
return bucket, prefix, err
}
return bucket, prefix, err
}
func getStartGTIDSet(c BackupS3) (string, error) {
bucketArr := strings.Split(c.BackupDest, "/")
if len(bucketArr) < 2 {
return "", errors.New("parsing bucket")
}
prefix := strings.TrimPrefix(c.BackupDest, bucketArr[0]+"/") + "/"
s3, err := storage.NewS3(strings.TrimPrefix(strings.TrimPrefix(c.Endpoint, "https://"), "http://"), c.AccessKeyID, c.AccessKey, bucketArr[0], prefix, c.Region, strings.HasPrefix(c.Endpoint, "https"))
if err != nil {
return "", errors.Wrap(err, "new storage manager")
}
listInfo, err := s3.ListObjects("xtrabackup_info")
if err != nil {
return "", errors.Wrapf(err, "list %s info fies", prefix)
}
if len(listInfo) == 0 {
return "", errors.New("no info files in backup")
}
sort.Strings(listInfo)
infoObj, err := s3.GetObject(listInfo[0])
if err != nil {
return "", errors.Wrapf(err, "get %s info", prefix)
}
lastGTID, err := getLastBackupGTID(infoObj)
if err != nil {
return "", errors.Wrap(err, "get last backup gtid")
}
return lastGTID, nil
}
const (
Latest RecoverType = "latest" // recover to the latest existing binlog
Date RecoverType = "date" // recover to exact date
Transaction RecoverType = "transaction" // recover to needed trunsaction
Skip RecoverType = "skip" // skip transactions
)
func (r *Recoverer) Run() error {
host, err := pxc.GetPXCFirstHost(r.pxcServiceName)
if err != nil {
return errors.Wrap(err, "get host")
}
r.db, err = pxc.NewPXC(host, r.pxcUser, r.pxcPass)
if err != nil {
return errors.Wrapf(err, "new manager with host %s", host)
}
err = r.setBinlogs()
if err != nil {
return errors.Wrap(err, "get binlog list")
}
switch r.recoverType {
case Skip:
r.recoverFlag = " --exclude-gtids=" + r.gtid
case Transaction:
r.recoverFlag = " --exclude-gtids=" + r.gtidSet
case Date:
r.recoverFlag = ` --stop-datetime="` + r.recoverTime + `"`
const format = "2006-01-02 15:04:05"
endTime, err := time.Parse(format, r.recoverTime)
if err != nil {
return errors.Wrap(err, "parse date")
}
r.recoverEndTime = endTime
case Latest:
default:
return errors.New("wrong recover type")
}
err = r.recover()
if err != nil {
return errors.Wrap(err, "recover")
}
return nil
}
func (r *Recoverer) recover() (err error) {
err = r.db.DropCollectorFunctions()
if err != nil {
return errors.Wrap(err, "drop collector funcs")
}
for _, binlog := range r.binlogs {
log.Println("working with", binlog)
if r.recoverType == Date {
binlogArr := strings.Split(binlog, "_")
if len(binlogArr) < 2 {
return errors.New("get timestamp from binlog name")
}
binlogTime, err := strconv.ParseInt(binlogArr[1], 10, 64)
if err != nil {
return errors.Wrap(err, "get binlog time")
}
if binlogTime > r.recoverEndTime.Unix() {
return nil
}
}
binlogObj, err := r.storage.GetObject(binlog)
if err != nil {
return errors.Wrap(err, "get obj")
}
err = os.Setenv("MYSQL_PWD", os.Getenv("PXC_PASS"))
if err != nil {
return errors.Wrap(err, "set mysql pwd env var")
}
cmdString := "mysqlbinlog" + r.recoverFlag + " - | mysql -h" + r.db.GetHost() + " -u" + r.pxcUser
cmd := exec.Command("sh", "-c", cmdString)
cmd.Stdin = binlogObj
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err = cmd.Run()
if err != nil {
return errors.Wrapf(err, "cmd run. stderr: %s, stdout: %s", errb.String(), outb.String())
}
}
return nil
}
func getLastBackupGTID(infoObj io.Reader) (string, error) {
content, err := getDecompressedContent(infoObj)
if err != nil {
return "", errors.Wrap(err, "get content")
}
return getGTIDFromContent(content)
}
func getGTIDFromContent(content []byte) (string, error) {
sep := []byte("GTID of the last")
startIndex := bytes.Index(content, sep)
if startIndex == -1 {
return "", errors.New("no gtid data in backup")
}
newOut := content[startIndex+len(sep):]
e := bytes.Index(newOut, []byte("'\n"))
if e == -1 {
return "", errors.New("can't find gtid data in backup")
}
se := bytes.Index(newOut, []byte("'"))
set := newOut[se+1 : e]
return string(set), nil
}
func getDecompressedContent(infoObj io.Reader) ([]byte, error) {
tmpDir := os.TempDir()
cmd := exec.Command("xbstream", "-x", "--decompress")
cmd.Dir = tmpDir
cmd.Stdin = infoObj
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err := cmd.Run()
if err != nil {
return nil, errors.Wrapf(err, "xbsream cmd run. stderr: %s, stdout: %s", &errb, &outb)
}
if errb.Len() > 0 {
return nil, errors.Errorf("run xbstream error: %s", &errb)
}
decContent, err := ioutil.ReadFile(tmpDir + "/xtrabackup_info")
if err != nil {
return nil, errors.Wrap(err, "read xtrabackup_info file")
}
return decContent, nil
}
func (r *Recoverer) setBinlogs() error {
list, err := r.storage.ListObjects("binlog_")
if err != nil {
return errors.Wrap(err, "list objects with prefix 'binlog_'")
}
reverse(list)
binlogs := []string{}
sourceID := strings.Split(r.startGTID, ":")[0]
for _, binlog := range list {
if strings.Contains(binlog, "-gtid-set") {
continue
}
infoObj, err := r.storage.GetObject(binlog + "-gtid-set")
if err != nil {
log.Println("Can't get binlog object with gtid set. Name:", binlog, "error", err)
continue
}
content, err := ioutil.ReadAll(infoObj)
if err != nil {
return errors.Wrapf(err, "read %s gtid-set object", binlog)
}
binlogGTIDSet := string(content)
if sourceID != strings.Split(binlogGTIDSet, ":")[0] {
continue
}
if len(r.gtid) > 0 && r.recoverType == Transaction {
subResult, err := r.db.SubtractGTIDSet(binlogGTIDSet, r.gtid)
if err != nil {
return errors.Wrapf(err, "check if '%s' is a subset of '%s", binlogGTIDSet, r.gtid)
}
if subResult != binlogGTIDSet {
set, err := getExtendGTIDSet(binlogGTIDSet, r.gtid)
if err != nil {
return errors.Wrap(err, "get gtid set for extend")
}
r.gtidSet = set
}
if len(r.gtidSet) == 0 {
continue
}
}
binlogs = append(binlogs, binlog)
subResult, err := r.db.SubtractGTIDSet(r.startGTID, binlogGTIDSet)
if err != nil {
return errors.Wrapf(err, "check if '%s' is a subset of '%s", r.startGTID, binlogGTIDSet)
}
if subResult != r.startGTID {
break
}
}
if len(binlogs) == 0 {
return errors.Errorf("no objects for prefix binlog_ or with source_id=%s", sourceID)
}
reverse(binlogs)
r.binlogs = binlogs
return nil
}
func getExtendGTIDSet(gtidSet, gtid string) (string, error) {
s := strings.Split(gtidSet, ":")
if len(s) < 2 {
return "", errors.Errorf("incorrect source in gtid set %s", gtidSet)
}
e := strings.Split(s[1], "-")
if len(e) < 2 {
return "", errors.Errorf("incorrect id range in %s", gtidSet)
}
gs := strings.Split(gtid, ":")
if len(gs) < 2 {
return "", errors.Errorf("incorrect source in gtid set %s", gtid)
}
es := strings.Split(gs[1], "-")
return gs[0] + ":" + es[0] + "-" + e[1], nil
}
func reverse(list []string) {
for i := len(list)/2 - 1; i >= 0; i-- {
opp := len(list) - 1 - i
list[i], list[opp] = list[opp], list[i]
}
}
|
[
"\"PXC_PASS\""
] |
[] |
[
"PXC_PASS"
] |
[]
|
["PXC_PASS"]
|
go
| 1 | 0 | |
ddtrace/tracer/option.go
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2019 Datadog, Inc.
package tracer
import (
"math"
"net"
"net/http"
"os"
"path/filepath"
"time"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/internal/globalconfig"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
)
// config holds the tracer configuration.
type config struct {
// debug, when true, writes details to logs.
debug bool
// serviceName specifies the name of this application.
serviceName string
// sampler specifies the sampler that will be used for sampling traces.
sampler Sampler
// agentAddr specifies the hostname and port of the agent where the traces
// are sent to.
agentAddr string
// globalTags holds a set of tags that will be automatically applied to
// all spans.
globalTags map[string]interface{}
// transport specifies the Transport interface which will be used to send data to the agent.
transport transport
// propagator propagates span context cross-process
propagator Propagator
// httpRoundTripper defines the http.RoundTripper used by the agent transport.
httpRoundTripper http.RoundTripper
// hostname is automatically assigned when the DD_TRACE_REPORT_HOSTNAME is set to true,
// and is added as a special tag to the root span of traces.
hostname string
// logger specifies the logger to use when printing errors. If not specified, the "log" package
// will be used.
logger ddtrace.Logger
// runtimeMetrics specifies whether collection of runtime metrics is enabled.
runtimeMetrics bool
// dogstatsdAddr specifies the address to connect for sending metrics to the
// Datadog Agent. If not set, it defaults to "localhost:8125" or to the
// combination of the environment variables DD_AGENT_HOST and DD_DOGSTATSD_PORT.
dogstatsdAddr string
}
// StartOption represents a function that can be provided as a parameter to Start.
type StartOption func(*config)
// defaults sets the default values for a config.
func defaults(c *config) {
c.serviceName = filepath.Base(os.Args[0])
c.sampler = NewAllSampler()
c.agentAddr = defaultAddress
statsdHost, statsdPort := "localhost", "8125"
if v := os.Getenv("DD_AGENT_HOST"); v != "" {
statsdHost = v
}
if v := os.Getenv("DD_DOGSTATSD_PORT"); v != "" {
statsdPort = v
}
c.dogstatsdAddr = net.JoinHostPort(statsdHost, statsdPort)
if os.Getenv("DD_TRACE_REPORT_HOSTNAME") == "true" {
var err error
c.hostname, err = os.Hostname()
if err != nil {
log.Warn("unable to look up hostname: %v", err)
}
}
if v := os.Getenv("DD_ENV"); v != "" {
WithEnv(v)(c)
}
}
// WithLogger sets logger as the tracer's error printer.
func WithLogger(logger ddtrace.Logger) StartOption {
return func(c *config) {
c.logger = logger
}
}
// WithPrioritySampling is deprecated, and priority sampling is enabled by default.
// When using distributed tracing, the priority sampling value is propagated in order to
// get all the parts of a distributed trace sampled.
// To learn more about priority sampling, please visit:
// https://docs.datadoghq.com/tracing/getting_further/trace_sampling_and_storage/#priority-sampling-for-distributed-tracing
func WithPrioritySampling() StartOption {
return func(c *config) {
// This is now enabled by default.
}
}
// WithDebugMode enables debug mode on the tracer, resulting in more verbose logging.
func WithDebugMode(enabled bool) StartOption {
return func(c *config) {
c.debug = enabled
}
}
// WithPropagator sets an alternative propagator to be used by the tracer.
func WithPropagator(p Propagator) StartOption {
return func(c *config) {
c.propagator = p
}
}
// WithServiceName sets the default service name to be used with the tracer.
func WithServiceName(name string) StartOption {
return func(c *config) {
c.serviceName = name
}
}
// WithAgentAddr sets the address where the agent is located. The default is
// localhost:8126. It should contain both host and port.
func WithAgentAddr(addr string) StartOption {
return func(c *config) {
c.agentAddr = addr
}
}
// WithEnv sets the environment to which all traces started by the tracer will be submitted.
// The default value is the environment variable DD_ENV, if it is set.
func WithEnv(env string) StartOption {
return WithGlobalTag(ext.Environment, env)
}
// WithGlobalTag sets a key/value pair which will be set as a tag on all spans
// created by tracer. This option may be used multiple times.
func WithGlobalTag(k string, v interface{}) StartOption {
return func(c *config) {
if c.globalTags == nil {
c.globalTags = make(map[string]interface{})
}
c.globalTags[k] = v
}
}
// WithSampler sets the given sampler to be used with the tracer. By default
// an all-permissive sampler is used.
func WithSampler(s Sampler) StartOption {
return func(c *config) {
c.sampler = s
}
}
// WithHTTPRoundTripper allows customizing the underlying HTTP transport for
// emitting spans. This is useful for advanced customization such as emitting
// spans to a unix domain socket. The default should be used in most cases.
func WithHTTPRoundTripper(r http.RoundTripper) StartOption {
return func(c *config) {
c.httpRoundTripper = r
}
}
// WithAnalytics allows specifying whether Trace Search & Analytics should be enabled
// for integrations.
func WithAnalytics(on bool) StartOption {
return func(cfg *config) {
if on {
globalconfig.SetAnalyticsRate(1.0)
} else {
globalconfig.SetAnalyticsRate(math.NaN())
}
}
}
// WithAnalyticsRate sets the global sampling rate for sampling APM events.
func WithAnalyticsRate(rate float64) StartOption {
return func(_ *config) {
if rate >= 0.0 && rate <= 1.0 {
globalconfig.SetAnalyticsRate(rate)
} else {
globalconfig.SetAnalyticsRate(math.NaN())
}
}
}
// WithRuntimeMetrics enables automatic collection of runtime metrics every 10 seconds.
func WithRuntimeMetrics() StartOption {
return func(cfg *config) {
cfg.runtimeMetrics = true
}
}
// WithDogstatsdAddress specifies the address to connect to for sending metrics
// to the Datadog Agent. If not set, it defaults to "localhost:8125" or to the
// combination of the environment variables DD_AGENT_HOST and DD_DOGSTATSD_PORT.
// This option is in effect when WithRuntimeMetrics is enabled.
func WithDogstatsdAddress(addr string) StartOption {
return func(cfg *config) {
cfg.dogstatsdAddr = addr
}
}
// StartSpanOption is a configuration option for StartSpan. It is aliased in order
// to help godoc group all the functions returning it together. It is considered
// more correct to refer to it as the type as the origin, ddtrace.StartSpanOption.
type StartSpanOption = ddtrace.StartSpanOption
// Tag sets the given key/value pair as a tag on the started Span.
func Tag(k string, v interface{}) StartSpanOption {
return func(cfg *ddtrace.StartSpanConfig) {
if cfg.Tags == nil {
cfg.Tags = map[string]interface{}{}
}
cfg.Tags[k] = v
}
}
// ServiceName sets the given service name on the started span. For example "http.server".
func ServiceName(name string) StartSpanOption {
return Tag(ext.ServiceName, name)
}
// ResourceName sets the given resource name on the started span. A resource could
// be an SQL query, a URL, an RPC method or something else.
func ResourceName(name string) StartSpanOption {
return Tag(ext.ResourceName, name)
}
// SpanType sets the given span type on the started span. Some examples in the case of
// the Datadog APM product could be "web", "db" or "cache".
func SpanType(name string) StartSpanOption {
return Tag(ext.SpanType, name)
}
// WithSpanID sets the SpanID on the started span, instead of using a random number.
// If there is no parent Span (eg from ChildOf), then the TraceID will also be set to the
// value given here.
func WithSpanID(id uint64) StartSpanOption {
return func(cfg *ddtrace.StartSpanConfig) {
cfg.SpanID = id
}
}
// ChildOf tells StartSpan to use the given span context as a parent for the
// created span.
func ChildOf(ctx ddtrace.SpanContext) StartSpanOption {
return func(cfg *ddtrace.StartSpanConfig) {
cfg.Parent = ctx
}
}
// StartTime sets a custom time as the start time for the created span. By
// default a span is started using the creation time.
func StartTime(t time.Time) StartSpanOption {
return func(cfg *ddtrace.StartSpanConfig) {
cfg.StartTime = t
}
}
// FinishOption is a configuration option for FinishSpan. It is aliased in order
// to help godoc group all the functions returning it together. It is considered
// more correct to refer to it as the type as the origin, ddtrace.FinishOption.
type FinishOption = ddtrace.FinishOption
// FinishTime sets the given time as the finishing time for the span. By default,
// the current time is used.
func FinishTime(t time.Time) FinishOption {
return func(cfg *ddtrace.FinishConfig) {
cfg.FinishTime = t
}
}
// WithError marks the span as having had an error. It uses the information from
// err to set tags such as the error message, error type and stack trace. It has
// no effect if the error is nil.
func WithError(err error) FinishOption {
return func(cfg *ddtrace.FinishConfig) {
cfg.Error = err
}
}
// NoDebugStack prevents any error presented using the WithError finishing option
// from generating a stack trace. This is useful in situations where errors are frequent
// and performance is critical.
func NoDebugStack() FinishOption {
return func(cfg *ddtrace.FinishConfig) {
cfg.NoDebugStack = true
}
}
// StackFrames limits the number of stack frames included into erroneous spans to n, starting from skip.
func StackFrames(n, skip uint) FinishOption {
if n == 0 {
return NoDebugStack()
}
return func(cfg *ddtrace.FinishConfig) {
cfg.StackFrames = n
cfg.SkipStackFrames = skip
}
}
|
[
"\"DD_AGENT_HOST\"",
"\"DD_DOGSTATSD_PORT\"",
"\"DD_TRACE_REPORT_HOSTNAME\"",
"\"DD_ENV\""
] |
[] |
[
"DD_AGENT_HOST",
"DD_DOGSTATSD_PORT",
"DD_ENV",
"DD_TRACE_REPORT_HOSTNAME"
] |
[]
|
["DD_AGENT_HOST", "DD_DOGSTATSD_PORT", "DD_ENV", "DD_TRACE_REPORT_HOSTNAME"]
|
go
| 4 | 0 | |
automation/licenses.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script extracts licensing info.
"""
import base64
import json
import os
import re
import subprocess
import sys
import traceback
import urllib.parse
import urllib.request
def get(url, cache, headers=None):
"""
Fetches the given URL (with reply caching & optional authorization)
"""
if url in cache:
return cache[url]
result = '{}'
for _ in range(10):
if headers is None:
request = urllib.request.Request(url)
else:
request = urllib.request.Request(url, headers=headers)
try:
reply = urllib.request.urlopen(request)
if reply.getcode() == 200:
result = reply.read().decode('utf-8')
break
except urllib.error.HTTPError:
print(traceback.format_exc(), file=sys.stderr)
print(f'Retrying for {url}', file=sys.stderr)
continue
except ssl.SSLEOFError:
print(traceback.format_exc(), file=sys.stderr)
print(f'Retrying for {url}', file=sys.stderr)
continue
cache[url] = result
return result
def authorization_credentials():
"""
Reads authorization credentials from environment variables
"""
user = os.environ.get('GH_API_USER')
token = os.environ.get('GH_API_TOKEN')
print(len(user), file=sys.stderr)
print(len(token), file=sys.stderr)
return (user, token)
def authorization_headers(user, token):
"""
Prepares authorization header for an API request
"""
if None in [user, token]:
return None
credentials = '%s:%s' % (user, token)
auth = base64.b64encode(credentials.encode('utf-8'))
headers = {'Authorization': 'Basic %s' % auth.decode('utf-8')}
return headers
def run(command, path):
"""
Runs a command in a given directory and returns its output
or its cached output
"""
if os.path.isdir(path):
process = subprocess.run(
command,
encoding='utf-8',
stdout=subprocess.PIPE,
cwd=path,
check=True)
return process.stdout
with open(path, 'r') as handle:
return handle.read()
def execute(suffix, directory):
"""
Executes licensing extraction script
"""
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
script = os.path.basename(sys.argv[0]).replace('.py', suffix)
script = os.path.join(base, 'automation', script)
command = f'python3 "{script}"'
source = os.path.join(base, directory)
os.system(f'{command} "{source}"')
def github_normalize(url):
"""
Normalizes GitHub URL
"""
if url is None:
return None
url = url.replace('https://www.', '')
url = url.replace('.git', '')
url = re.sub(r'git.*://', '', url)
url = url.replace('git@', '')
return f'https://{url}'
def github_account(normalized_url):
"""
Extracts account identifier from a GitHub repository URL
"""
if normalized_url is None:
return None
return normalized_url.split('/')[3]
def github_owner(account, cache, headers=None):
"""
Fetches the owner name of a GitHub account
"""
url = f'https://api.github.com/users/{account}'
profile = json.loads(get(url, cache, headers=headers))
profile_name = profile['name'] if 'name' in profile else account
return profile_name
def github_license(license_name, cache, headers=None):
"""
Fetches the license template via GitHub API
"""
license_name = urllib.parse.quote(license_name)
license_url = f'https://api.github.com/licenses/{license_name}'
license_description = json.loads(get(license_url, cache, headers=headers))
return license_description['body']
def github_repository_license(normalized_url, cache, headers=None):
"""
Fetches the licensing information of a GitHub repository
"""
url = normalized_url.replace(
'github.com', 'api.github.com/repos') + '/license'
return json.loads(get(url, cache, headers=headers))
def escape(text):
"""
Normalizes whitespace and escapes HTML tags
"""
replacements = {
'<': '<',
'>': '>',
'\t': ' ',
'\f': '',
'\v': '',
'\xA0': '',
'\x85': ''}
for key in replacements:
text = text.replace(key, replacements[key])
return text
if __name__ == '__main__':
execute('_go.py', 'core')
execute('_js.py', 'ui')
|
[] |
[] |
[
"GH_API_TOKEN",
"GH_API_USER"
] |
[]
|
["GH_API_TOKEN", "GH_API_USER"]
|
python
| 2 | 0 | |
core/core/xchainmg_test.go
|
package xchaincore
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"os/exec"
"testing"
"time"
"github.com/golang/protobuf/proto"
log "github.com/xuperchain/log15"
"github.com/xuperchain/xuperchain/core/common/config"
"github.com/xuperchain/xuperchain/core/global"
p2p_base "github.com/xuperchain/xuperchain/core/p2p/base"
p2p_factory "github.com/xuperchain/xuperchain/core/p2p/factory"
xuper_p2p "github.com/xuperchain/xuperchain/core/p2p/pb"
"github.com/xuperchain/xuperchain/core/pb"
"github.com/xuperchain/xuperchain/core/contract/kernel"
crypto_client "github.com/xuperchain/xuperchain/core/crypto/client"
"github.com/xuperchain/xuperchain/core/ledger"
"github.com/xuperchain/xuperchain/core/utxo"
)
const BobAddress = "dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN"
const BobPubkey = `{"Curvname":"P-256","X":74695617477160058757747208220371236837474210247114418775262229497812962582435,"Y":51348715319124770392993866417088542497927816017012182211244120852620959209571}`
const BobPrivateKey = `{"Curvname":"P-256","X":74695617477160058757747208220371236837474210247114418775262229497812962582435,"Y":51348715319124770392993866417088542497927816017012182211244120852620959209571,"D":29079635126530934056640915735344231956621504557963207107451663058887647996601}`
const DefaultKvEngine = "default"
var baseDir = os.Getenv("XCHAIN_ROOT")
func Init(t *testing.T) *XChainMG {
logger := log.New("module", "xchain")
logger.SetHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
cfg := config.NewNodeConfig()
l, _ := net.Listen("tcp", ":0")
port := l.Addr().(*net.TCPAddr).Port
l.Close()
t.Log("port: ", port)
cfg.P2p.Port = int32(port)
p2pService, p2pErr := p2p_factory.GetP2PServer("p2pv2", cfg.P2p, nil, nil)
t.Log("cfg: ", cfg.P2p)
if p2pErr != nil {
t.Error("new p2p server error ", p2pErr.Error())
}
xcmg := &XChainMG{}
cfg.Datapath = "../core/data/blockchain"
if err := xcmg.Init(logger, cfg, p2pService); err != nil {
t.Error("XChainMG init error ", err.Error())
}
return xcmg
}
func TestXChainMgBasic(t *testing.T) {
/*
c := exec.Command("sh", "-c", "../xchain-cli netUrl gen")
_, cmdErr := c.Output()
if cmdErr != nil {
t.Error("netUrl gen error ", cmdErr.Error())
}
*/
InitCreateBlockChain(t)
xcmg := Init(t)
defer func() {
if xcmg != nil {
xcmg.Stop()
defer os.RemoveAll(fmt.Sprintf("%s/core/data", baseDir))
}
}()
if xcmg == nil {
t.Error("create XChainMG error")
}
// test for Get
rootXCore := xcmg.Get("xuper")
if rootXCore == nil {
t.Error("expect not nil, but got ", rootXCore)
}
xcore := xcmg.Get("Dog")
if xcore != nil {
t.Error("expect nil, but got ", xcore)
}
// test for GetAll
bcs := xcmg.GetAll()
if len(bcs) != 1 {
t.Error("expect size but got ", len(bcs), "expect xuper xchain but got ", bcs[0])
}
// test for Start
xcmg.Start()
// test for CreateBlockChain
// create exist chain
xcore2, xcoreErr := xcmg.CreateBlockChain("xuper", []byte("todo"))
if xcoreErr != ErrBlockChainIsExist {
t.Error("expect ErrBlockChainIsExist, but got ", xcoreErr)
} else {
t.Log("xcore2: ", xcore2)
}
// create non exist chain
rootJs, _ := ioutil.ReadFile(fmt.Sprintf("%s/core/data/config", baseDir) + "/xuper.json")
xcore2, xcoreErr = xcmg.CreateBlockChain("dog", rootJs)
if xcoreErr != nil {
t.Error("create non exist chain error ", xcoreErr.Error())
} else {
defer os.RemoveAll(fmt.Sprintf("%s/core/data/blockchain/dog", baseDir))
t.Log("dog chain ", xcore2)
}
status := rootXCore.Status()
t.Log("xuper chain status ", status)
txReq := &pb.TxData{}
txReq.Bcname = "xuper"
txReq.FromAddr = BobAddress
txReq.FromPubkey = BobPubkey
txReq.FromScrkey = BobPrivateKey
txReq.Nonce = "nonce"
txReq.Timestamp = time.Now().UnixNano()
// tx_req.Desc = []byte("")
txReq.Account = []*pb.TxDataAccount{
{Address: BobAddress, Amount: "1"},
}
txReq.Header = &pb.Header{}
hd := &global.XContext{Timer: global.NewXTimer()}
txStatus := rootXCore.GenerateTx(txReq, hd)
t.Log("tx status ", txStatus)
ret, balErr := rootXCore.GetBalance(BobAddress)
if balErr != nil {
t.Error("get balance error ", balErr.Error())
} else {
t.Log("address ", BobAddress, " balance ", ret)
}
// test for GetFrozenBalance
ret, balErr = rootXCore.GetFrozenBalance(BobAddress)
if balErr != nil {
t.Error("get frozen balance error ", balErr.Error())
} else {
t.Log("address ", BobAddress, " frozen balance ", ret)
}
// test for GetConsType
consType := rootXCore.GetConsType()
if consType != "single" {
t.Error("expect consType is single, but got ", consType)
}
// test for GetDposCandidates
strArr, _ := rootXCore.GetDposCandidates()
if len(strArr) != 0 {
t.Error("expect 0 candidates, but got ", len(strArr))
}
// test for GetDposNominateRecords
strArr2, _ := rootXCore.GetDposNominateRecords(BobAddress)
if len(strArr2) != 0 {
t.Error("expect 0 moninate records, but got ", len(strArr2))
}
strArr3, _ := rootXCore.GetDposNominatedRecords(BobAddress)
if len(strArr3) != 0 {
t.Error("expect 0 moninated records, but got ", len(strArr3))
}
strArr4, _ := rootXCore.GetDposVoteRecords(BobAddress)
if len(strArr4) != 0 {
t.Error("expect 0 vote records, but got ", len(strArr4))
}
strArr5, _ := rootXCore.GetDposVotedRecords(BobAddress)
if len(strArr5) != 0 {
t.Error("expect 0 voted records, but got ", len(strArr4))
}
// test for GetCheckResults
proposers, _ := rootXCore.GetCheckResults(0)
if len(proposers) != 0 {
t.Error("expect 0 proposers, but got ", len(proposers))
}
// test for PostTx -> txStatus
reply, state := rootXCore.PostTx(txStatus, hd)
t.Log("postTx reply ", reply)
t.Log("postTx status ", state)
// test for QueryTx -> txStatus
result := rootXCore.QueryTx(txStatus)
t.Log("query non exist tx result ", result)
// query ok tx
ecdsaPk, pkErr := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if pkErr != nil {
t.Error("generate key error ", pkErr.Error())
}
t.Log("tip blockid ", rootXCore.Ledger.GetMeta().TipBlockid)
t.Log("tx ", txStatus.Tx)
block, formatBlockErr := rootXCore.Ledger.FormatBlock([]*pb.Transaction{txStatus.Tx},
[]byte(BobAddress),
ecdsaPk,
223456789,
0,
0,
rootXCore.Ledger.GetMeta().TipBlockid,
big.NewInt(1))
if formatBlockErr != nil {
t.Error("format block error", formatBlockErr.Error())
}
confirmStatus := rootXCore.Ledger.ConfirmBlock(block, false)
if !confirmStatus.Succ {
t.Error("confirm block error ", confirmStatus)
}
playErr := rootXCore.Utxovm.Play(block.Blockid)
if playErr != nil {
t.Error("utxo play error ", playErr.Error())
}
rootXCore.nodeMode = config.NodeModeFastSync
globalBlock := &pb.Block{
Header: &pb.Header{},
Bcname: "xuper",
Blockid: block.Blockid,
Status: pb.Block_TRUNK,
Block: block,
}
result = rootXCore.QueryTx(txStatus)
t.Log("query exist tx result ", result)
// test for GetNodeMode
nodeMode := rootXCore.GetNodeMode()
if nodeMode != config.NodeModeFastSync {
t.Error("expect FAST_SYNC, but got ", nodeMode)
}
// test for SendBlock
// sendblock exist block
sendBlockErr := rootXCore.SendBlock(globalBlock, hd)
if sendBlockErr != nil && sendBlockErr != ErrBlockExist {
t.Error("send block error ", sendBlockErr.Error())
}
// sendblock non exist block but trunk block
txReq.Nonce = "nonce1"
txReq.Timestamp = time.Now().UnixNano()
txStatus = rootXCore.GenerateTx(txReq, &global.XContext{Timer: global.NewXTimer()})
block, formatBlockErr = rootXCore.Ledger.FormatBlock([]*pb.Transaction{txStatus.Tx},
[]byte(BobAddress),
ecdsaPk,
223456789,
0,
0,
rootXCore.Ledger.GetMeta().TipBlockid,
big.NewInt(1))
if formatBlockErr != nil {
t.Error("format block error", formatBlockErr.Error())
}
block.Height = rootXCore.Ledger.GetMeta().TrunkHeight + 1
globalBlock = &pb.Block{
Header: &pb.Header{},
Bcname: "xuper",
Blockid: block.Blockid,
Status: pb.Block_TRUNK,
Block: block,
}
sendBlockErr = rootXCore.SendBlock(globalBlock, &global.XContext{Timer: global.NewXTimer()})
if sendBlockErr != nil {
t.Error("send block error ", sendBlockErr.Error())
return
}
status = rootXCore.Status()
t.Log("xuper chain status ", status)
// sendblock non exist block and no trunk block
txReq.Nonce = "nonce2"
txReq.Timestamp = time.Now().UnixNano()
txStatus = rootXCore.GenerateTx(txReq, &global.XContext{Timer: global.NewXTimer()})
block, formatBlockErr = rootXCore.Ledger.FormatBlock([]*pb.Transaction{txStatus.Tx},
[]byte(BobAddress),
ecdsaPk,
223456789,
0,
0,
rootXCore.Ledger.GetMeta().TipBlockid,
big.NewInt(1))
if formatBlockErr != nil {
t.Error("format block error", formatBlockErr.Error())
}
block.Height = rootXCore.Ledger.GetMeta().TrunkHeight + 1
globalBlock = &pb.Block{
Header: &pb.Header{},
Bcname: "xuper",
Blockid: block.Blockid,
Status: pb.Block_TRUNK,
Block: block,
}
// save in pending table
saveErr := rootXCore.Ledger.SavePendingBlock(globalBlock)
if saveErr != nil {
t.Error("save error ", saveErr.Error())
}
txReq.Nonce = "nonce3"
txReq.Timestamp = time.Now().UnixNano()
txStatus = rootXCore.GenerateTx(txReq, &global.XContext{Timer: global.NewXTimer()})
block2, formatBlockErr2 := rootXCore.Ledger.FormatBlock([]*pb.Transaction{txStatus.Tx},
[]byte(BobAddress),
ecdsaPk,
223456789,
0,
0,
globalBlock.Block.Blockid,
big.NewInt(1))
if formatBlockErr2 != nil {
t.Error("format block error", formatBlockErr.Error())
}
globalBlock = &pb.Block{
Header: &pb.Header{},
Bcname: "xuper",
Blockid: block2.Blockid,
Status: pb.Block_TRUNK,
Block: block2,
}
block2.Height = rootXCore.Ledger.GetMeta().TrunkHeight + 1
sendBlockErr = rootXCore.SendBlock(globalBlock, &global.XContext{Timer: global.NewXTimer()})
if sendBlockErr != nil {
t.Error("send block error ", sendBlockErr.Error())
}
// test for GetBlock
// get exist block
blockID := &pb.BlockID{
Header: &pb.Header{},
Bcname: "xuper",
Blockid: globalBlock.Blockid,
NeedContent: true,
}
existBlock := rootXCore.GetBlock(blockID)
if existBlock == nil {
t.Error("expect no nil, but got ", existBlock)
}
// get non exist block
blockID = &pb.BlockID{
Header: &pb.Header{},
Bcname: "dog",
Blockid: []byte("123456"),
NeedContent: true,
}
existBlock = rootXCore.GetBlock(blockID)
if existBlock.Status != pb.Block_NOEXIST {
t.Error("expect NOEXIST but got ", existBlock.Status)
}
// test for GetBlockChainStatus
blkStatus := &pb.BCStatus{
Header: &pb.Header{},
Bcname: "xuper",
}
out := rootXCore.GetBlockChainStatus(blkStatus)
t.Log("out: ", out)
out2 := rootXCore.ConfirmTipBlockChainStatus(blkStatus)
t.Log("out: ", out2)
// test for countGetBlockChainStatus
res, _ := p2p_base.NewXuperMessage(p2p_base.XuperMsgVersion2, "xuper", "123456789",
xuper_p2p.XuperMessage_GET_BLOCK_RES, nil, xuper_p2p.XuperMessage_CHECK_SUM_ERROR)
countGetBlockChainStatus([]*xuper_p2p.XuperMessage{res})
// test for countConfirmBlockRes
t.Log("state value ", countConfirmBlockRes([]*xuper_p2p.XuperMessage{res}))
t.Log("is accepted: ", rootXCore.syncConfirm(blkStatus))
res2, _ := rootXCore.syncForOnce()
t.Log("sync for once", res2)
rootXCore.doMiner()
// test fot BroadCastGetBlock
rootXCore.BroadCastGetBlock(blockID)
// test for xchainmg_net.go
// assemble POSTTX,SENDBLOCK,BATCHPOSTTX,
msgInfo, _ := proto.Marshal(txStatus)
t.Log("msg info ", msgInfo)
msgTmp, _ := p2p_base.NewXuperMessage(p2p_base.XuperMsgVersion1, "xuper", "123456", xuper_p2p.XuperMessage_POSTTX,
msgInfo, xuper_p2p.XuperMessage_NONE)
xcmg.msgChan <- msgTmp
//batch BatchPostTx
batchTxs := &pb.BatchTxs{
Header: &pb.Header{},
Txs: []*pb.TxStatus{txStatus},
}
t.Log("batchTxs: ", batchTxs)
msgInfos, _ := proto.Marshal(batchTxs)
msgsTmp, _ := p2p_base.NewXuperMessage(p2p_base.XuperMsgVersion1, "xuper", "123457", xuper_p2p.XuperMessage_BATCHPOSTTX,
msgInfos, xuper_p2p.XuperMessage_NONE)
xcmg.msgChan <- msgsTmp
sendBlockMsgInfo, _ := proto.Marshal(globalBlock)
sendBlockMsgTmp, _ := p2p_base.NewXuperMessage(p2p_base.XuperMsgVersion1, "xuper", "123458", xuper_p2p.XuperMessage_SENDBLOCK,
sendBlockMsgInfo, xuper_p2p.XuperMessage_NONE)
xcmg.msgChan <- sendBlockMsgTmp
}
func InitCreateBlockChain(t *testing.T) {
//defer os.RemoveAll(workSpace)
workSpace := fmt.Sprintf("%s/core/data/blockchain/xuper", baseDir)
os.RemoveAll(fmt.Sprintf("%s/core/data", baseDir))
cmd := fmt.Sprintf("cp -rf %s/data %s/core/", baseDir, baseDir)
fmt.Println(cmd)
c := exec.Command("sh", "-c", cmd)
_, cmdErr := c.Output()
if cmdErr != nil {
// t.Error("cp error ", cmdErr.Error())
}
os.RemoveAll(fmt.Sprintf("%s/core/data/blockchain/xuper/", baseDir))
ledger, err := ledger.NewLedger(workSpace, nil, nil, DefaultKvEngine, crypto_client.CryptoTypeDefault)
if err != nil {
t.Fatal(err)
}
defer ledger.Close()
kl := &kernel.Kernel{}
kLogger := log.New("module", "kernel")
kLogger.SetHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
kl.Init(workSpace, kLogger, nil, "xuper")
kl.SetNewChainWhiteList(map[string]bool{BobAddress: true})
/*
utxoVM, _ := utxo.MakeUtxoVM("xuper", ledger, workSpace, "", "", []byte(""), nil, 5000, 60, 500, nil, false, DefaultKvEngine, crypto_client.CryptoTypeDefault)
utxoVM.RegisterVM("kernel", kl, global.VMPrivRing0)*/
//创建链的时候分配财富
tx, err2 := utxo.GenerateRootTx([]byte(`
{
"version" : "1"
, "consensus" : {
"type" : "single",
"miner" : "dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN"
}
, "predistribution":[
{
"address" : "dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN"
, "quota" : "100000000000000000000"
}
]
, "maxblocksize" : "128"
, "period" : "3000"
, "award" : "428100000000"
, "decimals" : "8"
, "award_decay": {
"height_gap": 31536000,
"ratio": 1
}
}
`))
if err2 != nil {
t.Fatal(err2)
}
//defer utxoVM.Close()
block, _ := ledger.FormatRootBlock([]*pb.Transaction{tx})
confirmStatus := ledger.ConfirmBlock(block, true)
if !confirmStatus.Succ {
t.Fatal("confirm block fail")
}
utxoVM, _ := utxo.MakeUtxoVM("xuper", ledger, workSpace, "", "", []byte(""), nil, 5000, 60, 500, nil, false, DefaultKvEngine, crypto_client.CryptoTypeDefault)
utxoVM.RegisterVM("kernel", kl, global.VMPrivRing0)
defer utxoVM.Close()
playErr := utxoVM.Play(block.Blockid)
if playErr != nil {
t.Fatal(playErr)
}
c = exec.Command("sh", "-c", fmt.Sprintf("cp %s/core/data/config/xuper.json %s/core/data/blockchain/xuper/", baseDir, baseDir))
_, cmdErr = c.Output()
if cmdErr != nil {
t.Error("cp error ", cmdErr.Error())
}
}
|
[
"\"XCHAIN_ROOT\""
] |
[] |
[
"XCHAIN_ROOT"
] |
[]
|
["XCHAIN_ROOT"]
|
go
| 1 | 0 | |
ios/build/bots/scripts/result_sink_util.py
|
# Copyright 2020 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 atexit
import base64
import cgi
import json
import logging
import os
import requests
import sys
LOGGER = logging.getLogger(__name__)
# VALID_STATUSES is a list of valid status values for test_result['status'].
# The full list can be obtained at
# https://source.chromium.org/chromium/infra/infra/+/main:go/src/go.chromium.org/luci/resultdb/proto/v1/test_result.proto;drc=ca12b9f52b27f064b0fa47c39baa3b011ffa5790;l=151-174
VALID_STATUSES = {"PASS", "FAIL", "CRASH", "ABORT", "SKIP"}
def _compose_test_result(test_id,
status,
expected,
test_log=None,
tags=None,
file_artifacts=None):
"""Composes the test_result dict item to be posted to result sink.
Args:
test_id: (str) A unique identifier of the test in LUCI context.
status: (str) Status of the test. Must be one in |VALID_STATUSES|.
expected: (bool) Whether the status is expected.
test_log: (str) Log of the test. Optional.
tags: (list) List of tags. Each item in list should be a length 2 tuple of
string as ("key", "value"). Optional.
file_artifacts: (dict) IDs to abs paths mapping of existing files to
report as artifact.
Returns:
A dict of test results with input information, confirming to
https://source.chromium.org/chromium/infra/infra/+/main:go/src/go.chromium.org/luci/resultdb/sink/proto/v1/test_result.proto
"""
tags = tags or []
file_artifacts = file_artifacts or {}
assert status in VALID_STATUSES, (
'%s is not a valid status (one in %s) for ResultSink.' %
(status, VALID_STATUSES))
for tag in tags:
assert len(tag) == 2, 'Items in tags should be length 2 tuples of strings'
assert isinstance(tag[0], str) and isinstance(
tag[1], str), ('Items in'
'tags should be length 2 tuples of strings')
test_result = {
'testId': test_id,
'status': status,
'expected': expected,
'tags': [{
'key': key,
'value': value
} for (key, value) in tags],
'testMetadata': {
'name': test_id,
}
}
test_result['artifacts'] = {
name: {
'filePath': file_artifacts[name]
} for name in file_artifacts
}
if test_log:
message = ''
if sys.version_info.major < 3:
message = base64.b64encode(test_log)
else:
# Python3 b64encode takes and returns bytes. The result must be
# serializable in order for the eventual json.dumps to succeed
message = base64.b64encode(test_log.encode('utf-8')).decode('utf-8')
test_result['summaryHtml'] = '<text-artifact artifact-id="Test Log" />'
test_result['artifacts'].update({
'Test Log': {
'contents': message
},
})
if not test_result['artifacts']:
test_result.pop('artifacts')
return test_result
class ResultSinkClient(object):
"""Stores constants and handles posting to ResultSink."""
def __init__(self):
"""Initiates and stores constants to class."""
self.sink = None
luci_context_file = os.environ.get('LUCI_CONTEXT')
if not luci_context_file:
logging.warning('LUCI_CONTEXT not found in environment. ResultDB'
' integration disabled.')
return
with open(luci_context_file) as f:
self.sink = json.load(f).get('result_sink')
if not self.sink:
logging.warning('ResultSink constants not found in LUCI context.'
' ResultDB integration disabled.')
return
self.url = ('http://%s/prpc/luci.resultsink.v1.Sink/ReportTestResults' %
self.sink['address'])
self.headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'ResultSink %s' % self.sink['auth_token'],
}
self._session = requests.Session()
# Ensure session is closed at exit.
atexit.register(self.close)
logging.getLogger("requests").setLevel(logging.WARNING)
def close(self):
"""Closes the connection to result sink server."""
if not self.sink:
return
LOGGER.info('Closing connection with result sink server.')
# Reset to default logging level of test runner scripts.
logging.getLogger("requests").setLevel(logging.DEBUG)
self._session.close()
def post(self, test_id, status, expected, **kwargs):
"""Composes and posts a test and status to result sink.
Args:
test_id: (str) A unique identifier of the test in LUCI context.
status: (str) Status of the test. Must be one in |VALID_STATUSES|.
expected: (bool) Whether the status is expected.
**kwargs: Optional keyword args. Namely:
test_log: (str) Log of the test. Optional.
tags: (list) List of tags. Each item in list should be a length 2 tuple
of string as ("key", "value"). Optional.
file_artifacts: (dict) IDs to abs paths mapping of existing files to
report as artifact.
"""
if not self.sink:
return
self._post_test_result(
_compose_test_result(test_id, status, expected, **kwargs))
def _post_test_result(self, test_result):
"""Posts single test result to server.
This method assumes |self.sink| is not None.
Args:
test_result: (dict) Confirming to protocol defined in
https://source.chromium.org/chromium/infra/infra/+/main:go/src/go.chromium.org/luci/resultdb/sink/proto/v1/test_result.proto
"""
res = self._session.post(
url=self.url,
headers=self.headers,
data=json.dumps({'testResults': [test_result]}),
)
res.raise_for_status()
|
[] |
[] |
[
"LUCI_CONTEXT"
] |
[]
|
["LUCI_CONTEXT"]
|
python
| 1 | 0 | |
code/tflkafka/tflrepub.py
|
import time
import httplib2
import os
from urllib import urlencode
import json
from kafka import KafkaProducer
appid = os.getenv("TFL_APPID")
appkey = os.getenv("TFL_APPKEY")
print ("using", appid, appkey)
def call_get_arrivals(line):
h = httplib2.Http(disable_ssl_certificate_validation=True)
# h.add_credentials(intro_username, intro_password)
resp, content = h.request("https://api.tfl.gov.uk/Line/"+line+"/Arrivals?app_id="+appid+"&app_key="+appkey)
# print resp
try:
response=json.loads(content)
for i in response:
line = i['lineName']
trainNumber = i['vehicleId']
stationId = i['naptanId']
stationName = i['stationName']
expArrival = i['expectedArrival']
timestamp = i['timestamp']
tts = i['timeToStation']
data = dict(line=line, trainNumber = trainNumber, stationId = stationId, stationName=stationName, timestamp=timestamp, expArrival = expArrival, tts = tts)
# print data
producer.send("tfl", json.dumps(data))
except Exception as inst:
pass
lines = ["victoria","circle","district","northern","jubilee","piccadilly","metropolitan","bakerloo","central" ]
time.sleep(30) #wait for kafka
producer = KafkaProducer(bootstrap_servers='kafka.freo.me:9092')
while 1==1:
for line in lines:
call_get_arrivals(line)
time.sleep(1)
|
[] |
[] |
[
"TFL_APPKEY",
"TFL_APPID"
] |
[]
|
["TFL_APPKEY", "TFL_APPID"]
|
python
| 2 | 0 | |
src/lambda_function.py
|
import collections
import datetime
import gzip
import json
import logging
import os
import time
import urllib2
from base64 import b64decode
from StringIO import StringIO
# set logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# print correct response status code and return True if we need to retry
def shouldRetry(e):
if e.code == 400:
logger.error("Got 400 code from Logz.io. This means that some of your logs are too big, or badly formatted. response: {0}".format(e.reason))
elif e.code == 401:
logger.error("You are not authorized with Logz.io! Token OK? dropping logs...")
else:
logger.error("Got {0} while sending logs to Logz.io, response: {1}".format(e.code, e.reason))
return True
return False
# send in bulk JSONs object to logzio
def sendToLogzio(jsonStrLogsList,logzioUrl):
headers = {"Content-type": "application/json"}
maxRetries = 3
sleepBetweenRetries = 5
for currTry in reversed(xrange(maxRetries)):
request = urllib2.Request(logzioUrl, data='\n'.join(jsonStrLogsList), headers=headers)
try:
response = urllib2.urlopen(request)
statusCode = response.getcode()
logger.info("Successfully sent bulk of " + str(len(jsonStrLogsList)) + " logs to Logz.io!")
return
except (IOError) as e:
if (shouldRetry(e)):
logger.info("Failure is retriable - Trying {} more times".format(currTry))
time.sleep(sleepBetweenRetries)
else:
raise IOError("Failed to send logs")
raise RuntimeError("Retries attempts exhausted. Failed sending to Logz.io")
def extractAwsLogsData(event):
try:
logsDataDecoded = event['awslogs']['data'].decode('base64')
logsDataUnzipped = gzip.GzipFile(fileobj=StringIO(logsDataDecoded)).read()
logsDataDict = json.loads(logsDataUnzipped)
return logsDataDict
except ValueError as e:
logger.error("Got exception while loading json, message: {}".format(e))
raise ValueError("Exception: json loads")
def lambda_handler(event, context):
logzioUrl = "{0}/?token={1}&type={2}".format(os.environ['URL'], os.environ['TOKEN'], os.environ['TYPE'])
awsLogsData = extractAwsLogsData(event)
logger.info("About to send {} logs".format(len(awsLogsData['logEvents'])))
jsonStrLogsList =[]
for log in awsLogsData['logEvents']:
if not isinstance(log, collections.Mapping):
raise TypeError("Expected log inside logEvents to be a Dict but found another type")
if '@timestamp' not in log:
log['@timestamp'] = str(log['timestamp'])
log['logStream'] = awsLogsData['logStream']
log['messageType'] = awsLogsData['messageType']
log['owner'] = awsLogsData['owner']
log['logGroup'] = awsLogsData['logGroup']
jsonStrLogsList.append(json.dumps(log))
sendToLogzio(jsonStrLogsList,logzioUrl)
|
[] |
[] |
[
"URL",
"TYPE",
"TOKEN"
] |
[]
|
["URL", "TYPE", "TOKEN"]
|
python
| 3 | 0 | |
tests/testing_utilities.py
|
# _ __ _ ___ _ ___ _ _
# | |/ /_ _ __ _| |_ ___ __/ __| __ _| |___ _ __ ___| _ \ |_ _ __ _(_)_ _
# | ' <| '_/ _` | _/ _ (_-<__ \/ _` | / _ \ ' \/ -_) _/ | || / _` | | ' \
# |_|\_\_| \__,_|\__\___/__/___/\__,_|_\___/_|_|_\___|_| |_|\_,_\__, |_|_||_|
# |___/
# License: BSD License ; see LICENSE
#
# Main authors: Philipp Bucher (https://github.com/philbucher)
#
# this file contains helpers used in the tests
# set up testing environment (before anything else)
import initialize_testing_environment
# python imports
from pathlib import Path
import unittest
import os
from sys import version_info as py_version_info
from shutil import rmtree
# plugin imports
from kratos_salome_plugin import IsExecutedInSalome
from kratos_salome_plugin.salome_study_utilities import ResetStudy, GetNumberOfObjectsInStudy
# salome imports
import salome
# importing important modules
# not sure if the order is important, but this is how it is done in the dumped studies
import GEOM
from salome.geom import geomBuilder
import SMESH
from salome.smesh import smeshBuilder
def GetTestsPath() -> Path:
"""path to the "tests" folder"""
return Path(__file__).parent.absolute()
def GetTestsDir():
""" !!! DEPRECATED !!! """
return os.path.dirname(os.path.realpath(__file__))
def CheckIfKratosAvailable():
if "KRATOS_AVAILABLE" in os.environ:
# this is intended to be used in the CI
# there "try-except" might lead to an undiscovered failure
return (os.environ["KRATOS_AVAILABLE"] == "1")
else:
try:
import KratosMultiphysics
return True
except:
return False
def CheckIfApplicationsAvailable(*application_names):
raise Exception("This function is untested!")
if not CheckIfKratosAvailable():
return False
from KratosMultiphysics.kratos_utilities import CheckIfApplicationsAvailable
return CheckIfApplicationsAvailable(application_names)
def DeleteFileIfExisting(file_path: Path) -> None:
"""Delete a file if it exists"""
if file_path.is_file():
os.remove(str(file_path))
def DeleteDirectoryIfExisting(directory_path: Path) -> None:
"""Delete a directory if it exists"""
if directory_path.is_dir():
rmtree(directory_path)
def skipUnlessPythonVersionIsAtLeast(min_python_version, reason):
'''Skips the test if the test requires a newer version of Python
Note that this should only be used for functionalities that are used inside
of Salome, otherwise the minimum python version of the plugin is increased
'''
reason_for_skip = 'This test requires at least Python version {}, the current version is: ({},{},{}). Reason: {}'.format(min_python_version, py_version_info[0], py_version_info[1], py_version_info[2], reason)
return unittest.skipIf(min_python_version > py_version_info, reason_for_skip)
def CreateHDFStudyFile(file_name: str, *ignored_args) -> bool:
"""aux function for mocking salome.myStudy.SaveAs
it ignores arguments for multifile and mode (ascii or binary)
TODO do a type check on the "file_name"? => salome seems to only work with "str"
"""
if not file_name.endswith(".hdf"):
file_name+=".hdf"
with open(file_name, "w") as hdf_file:
hdf_file.write("This is a mocked hdf study file created during testing\n")
hdf_file.write("It should be deleted after testing\n")
return True
@unittest.skipUnless(initialize_testing_environment.PYQT_AVAILABLE, "Qt is not available")
class QtTestCase(unittest.TestCase): pass
@unittest.skipUnless(IsExecutedInSalome(), "This test can only be executed in Salome")
class SalomeTestCase(unittest.TestCase):
def setUp(self):
# initializing salome also creates a study.
# clearing the study in order to have a clean study for each test.
# This is much faster than re-launching salome for each test
self.study = salome.myStudy
ResetStudy()
self.assertEqual(GetNumberOfObjectsInStudy(), 0, msg="Resetting the study failed!")
self.geompy = geomBuilder.New()
self.smesh = smeshBuilder.New()
class SalomeTestCaseWithBox(SalomeTestCase):
# a test case that has a simple box with a tetra and hexa mesh as setup
def setUp(self):
super().setUp()
# creating geometry
O = self.geompy.MakeVertex(0, 0, 0)
OX = self.geompy.MakeVectorDXDYDZ(1, 0, 0)
OY = self.geompy.MakeVectorDXDYDZ(0, 1, 0)
OZ = self.geompy.MakeVectorDXDYDZ(0, 0, 1)
self.box = self.geompy.MakeBoxDXDYDZ(200, 200, 200)
[self.face_1, self.face_2] = self.geompy.SubShapes(self.box, [13, 23])
[self.edge_1, self.edge_2] = self.geompy.SubShapes(self.box, [18, 26])
self.group_faces = self.geompy.CreateGroup(self.box, self.geompy.ShapeType["FACE"])
self.geompy.UnionIDs(self.group_faces, [33, 31])
self.group_edges = self.geompy.CreateGroup(self.box, self.geompy.ShapeType["EDGE"])
self.geompy.UnionIDs(self.group_edges, [25, 12, 29, 22])
self.name_main_box = 'main_box'
self.geompy.addToStudy(self.box, self.name_main_box)
# creating mesh
self.mesh_tetra = self.smesh.Mesh(self.box)
Regular_1D = self.mesh_tetra.Segment()
Max_Size_1 = Regular_1D.MaxSize(60)
MEFISTO_2D = self.mesh_tetra.Triangle(algo=smeshBuilder.MEFISTO)
NETGEN_3D = self.mesh_tetra.Tetrahedron()
isDone = self.mesh_tetra.Compute()
self.assertTrue(isDone, msg="Tetra mesh could not be computed!")
self.name_main_mesh_tetra = 'main_mesh_tetra'
self.smesh.SetName(self.mesh_tetra.GetMesh(), self.name_main_mesh_tetra)
self.mesh_hexa = self.smesh.Mesh(self.box)
Regular_1D_1 = self.mesh_hexa.Segment()
Number_of_Segments_1 = Regular_1D_1.NumberOfSegments(8)
Quadrangle_2D = self.mesh_hexa.Quadrangle(algo=smeshBuilder.QUADRANGLE)
Hexa_3D = self.mesh_hexa.Hexahedron(algo=smeshBuilder.Hexa)
isDone = self.mesh_hexa.Compute()
self.assertTrue(isDone, msg="Hexa mesh could not be computed!")
self.name_main_mesh_hexa = 'main_mesh_hexa'
self.smesh.SetName(self.mesh_hexa.GetMesh(), self.name_main_mesh_hexa)
# adding 0D Elements
for i in range(10):
self.mesh_tetra.Add0DElement( i+1 )
self.group_tetra_0D_elements = self.mesh_tetra.CreateEmptyGroup(SMESH.ELEM0D, "subset_0D_elements") # type "SMESH._objref_SMESH_Group"
self.group_tetra_0D_elements.AddFrom(self.mesh_tetra.GetMesh())
for i in range(4):
self.mesh_tetra.Add0DElement( i+15 ) # those are only in the main-mesh
# adding Ball Elements
for i in range(6):
self.mesh_hexa.AddBall(i+1, i*6+1)
self.group_hexa_ball_elements = self.mesh_hexa.CreateEmptyGroup(SMESH.BALL, "subset_ball_elements") # type "SMESH._objref_SMESH_Group"
self.group_hexa_ball_elements.AddFrom(self.mesh_hexa.GetMesh())
for i in range(11):
self.mesh_hexa.AddBall(i+15, i+2) # those are only in the main-mesh
# creating more mesh groups
self.group_tetra_f1_nodes = self.mesh_tetra.GroupOnGeom(self.face_1,'face_1_nodes',SMESH.NODE) # type "SMESH._objref_SMESH_GroupOnGeom"
self.group_tetra_f1_faces = self.mesh_tetra.GroupOnGeom(self.face_1,'face_1_faces',SMESH.FACE) # type "SMESH._objref_SMESH_GroupOnGeom"
criteria = [self.smesh.GetCriterion(SMESH.EDGE, SMESH.FT_Length, SMESH.FT_LessThan, 150)]
filter_1 = self.smesh.GetFilterFromCriteria(criteria)
filter_1.SetMesh(self.mesh_hexa.GetMesh())
self.group_hexa_edges = self.mesh_hexa.GroupOnFilter( SMESH.EDGE, 'group_edges', filter_1) # type "SMESH._objref_SMESH_GroupOnFilter"
# using random names since they are not used so far
self.sub_mesh_tetra_f_1 = self.mesh_tetra.GetSubMesh( self.face_1, 'Sub-mesh_1' )
self.sub_mesh_tetra_f_2 = self.mesh_tetra.GetSubMesh( self.face_2, 'Sub-mesh_2' )
self.sub_mesh_tetra_e_1 = self.mesh_tetra.GetSubMesh( self.edge_1, 'Sub-mesh_3' )
self.sub_mesh_tetra_e_2 = self.mesh_tetra.GetSubMesh( self.edge_2, 'Sub-mesh_4' )
self.sub_mesh_tetra_g_1 = self.mesh_tetra.GetSubMesh( self.group_faces, 'Sub-mesh_5' )
self.sub_mesh_tetra_g_2 = self.mesh_tetra.GetSubMesh( self.group_edges, 'Sub-mesh_6' )
self.sub_mesh_hexa_f_1 = self.mesh_hexa.GetSubMesh( self.face_1, 'Sub-mesh_7' )
self.sub_mesh_hexa_f_2 = self.mesh_hexa.GetSubMesh( self.face_2, 'Sub-mesh_8' )
self.sub_mesh_hexa_e_1 = self.mesh_hexa.GetSubMesh( self.edge_1, 'Sub-mesh_9' )
self.sub_mesh_hexa_e_2 = self.mesh_hexa.GetSubMesh( self.edge_2, 'Sub-mesh_10' )
self.sub_mesh_hexa_g_1 = self.mesh_hexa.GetSubMesh( self.group_faces, 'Sub-mesh_11' )
self.name_mesh_group = "name_mesh_group"
self.sub_mesh_hexa_g_2 = self.mesh_hexa.GetSubMesh( self.group_edges, self.name_mesh_group )
class SalomeTestCaseCantilever2D(SalomeTestCase):
# a test case that has a simple 2D cantilever
def setUp(self):
super().setUp()
debug = False
# creating geometry
self.O = self.geompy.MakeVertex(0, 0, 0)
self.OX = self.geompy.MakeVectorDXDYDZ(1, 0, 0)
self.OY = self.geompy.MakeVectorDXDYDZ(0, 1, 0)
self.OZ = self.geompy.MakeVectorDXDYDZ(0, 0, 1)
self.Vertex_1 = self.geompy.MakeVertex(0, 0, 0)
self.Vertex_2 = self.geompy.MakeVertex(5, 0, 0)
self.Vertex_3 = self.geompy.MakeVertex(5, 1, 0)
self.Vertex_4 = self.geompy.MakeVertex(0, 1, 0)
self.Line_1 = self.geompy.MakeLineTwoPnt(self.Vertex_1, self.Vertex_2)
self.Line_2 = self.geompy.MakeLineTwoPnt(self.Vertex_2, self.Vertex_3)
self.Line_3 = self.geompy.MakeLineTwoPnt(self.Vertex_3, self.Vertex_4)
self.Line_4 = self.geompy.MakeLineTwoPnt(self.Vertex_4, self.Vertex_1)
self.Face_1 = self.geompy.MakeFaceWires([self.Line_1, self.Line_2, self.Line_3, self.Line_4], 1)
[self.Neumann,self.Dirichlet] = self.geompy.SubShapes(self.Face_1, [6, 10])
# publish geometry ( only in debug)
if debug:
self.geompy.addToStudy( self.O, 'O' )
self.geompy.addToStudy( self.OX, 'OX' )
self.geompy.addToStudy( self.OY, 'OY' )
self.geompy.addToStudy( self.OZ, 'OZ' )
self.geompy.addToStudy( self.Vertex_1, 'Vertex_1' )
self.geompy.addToStudy( self.Vertex_2, 'Vertex_2' )
self.geompy.addToStudy( self.Vertex_3, 'Vertex_3' )
self.geompy.addToStudy( self.Vertex_4, 'Vertex_4' )
self.geompy.addToStudy( self.Line_1, 'Line_1' )
self.geompy.addToStudy( self.Line_2, 'Line_2' )
self.geompy.addToStudy( self.Line_3, 'Line_3' )
self.geompy.addToStudy( self.Line_4, 'Line_4' )
self.geompy.addToStudy( self.Face_1, 'domain' )
self.geompy.addToStudyInFather( self.Face_1, self.Neumann, 'Neumann' )
self.geompy.addToStudyInFather( self.Face_1, self.Dirichlet, 'Dirichlet' )
# creating mesh
self.smeshObj_1 = self.smesh.CreateHypothesis('MaxLength')
self.smeshObj_2 = self.smesh.CreateHypothesis('NumberOfSegments')
self.domain_mesh = self.smesh.Mesh(self.Face_1)
self.Regular_1D = self.domain_mesh.Segment()
self.Local_Length_1 = self.Regular_1D.LocalLength(1,None,1e-07)
self.Quadrangle_2D = self.domain_mesh.Quadrangle(algo=smeshBuilder.QUADRANGLE)
self.Local_Length_1.SetLength( 0.2 )
self.Local_Length_1.SetPrecision( 1e-07 )
isDone = self.domain_mesh.Compute()
self.assertTrue(isDone, msg="Mesh could not be computed!")
self.neumann_mesh = self.domain_mesh.GetSubMesh( self.Neumann, 'neumann' )
self.dirichlet_mesh = self.domain_mesh.GetSubMesh( self.Dirichlet, 'dirichlet' )
if debug:
self.smesh.SetName(self.Regular_1D.GetAlgorithm(), 'Regular_1D')
self.smesh.SetName(self.Quadrangle_2D.GetAlgorithm(), 'Quadrangle_2D')
self.smesh.SetName(self.Local_Length_1, 'Local Length_1')
self.smesh.SetName(self.domain_mesh.GetMesh(), 'domain_mesh')
self.smesh.SetName(self.dirichlet_mesh, 'dirichlet')
self.smesh.SetName(self.neumann_mesh, 'neumann')
salome.myStudy.SaveAs("SalomeTestCaseCantilever2D.hdf", False, False) # args: use_multifile, use_acsii
def CompareMdpaWithReferenceFile(mdpa_file_name, test_case):
"""This function compares two mdpa files"""
def GetFileLines(ref_mdpa_file, other_mdpa_file):
"""This function reads the reference and the output file
It returns the lines read from both files and also compares
if they contain the same numer of lines
"""
# check if files are valid
err_msg = 'The specified reference file name "'
err_msg += ref_mdpa_file
err_msg += '" is not valid!'
test_case.assertTrue(os.path.isfile(ref_mdpa_file), msg=err_msg)
err_msg = 'The specified output file name "'
err_msg += other_mdpa_file
err_msg += '" is not valid!'
test_case.assertTrue(os.path.isfile(other_mdpa_file), msg=err_msg)
# "readlines" adds a newline at the end of the line,
# which will be removed with rstrip afterwards
with open(ref_mdpa_file,'r') as ref_file:
lines_ref = ref_file.readlines()
with open(other_mdpa_file,'r') as out_file:
lines_out = out_file.readlines()
# removing trailing newline AND whitespaces (beginning & end) than can mess with the comparison
# furthermore convert tabs to spaces
lines_ref = [line.rstrip().lstrip().replace("\t", " ") for line in lines_ref]
lines_out = [line.rstrip().lstrip().replace("\t", " ") for line in lines_out]
num_lines_ref = len(lines_ref)
num_lines_out = len(lines_out)
err_msg = "Files have different number of lines!"
err_msg += "\nNum Lines Reference File: " + str(num_lines_ref)
err_msg += "\nNum Lines Other File: " + str(num_lines_out)
test_case.assertEqual(num_lines_ref, num_lines_out, msg=err_msg)
return lines_ref, lines_out
def CompareNodes(lines_ref, lines_out, line_index):
line_index += 1 # skip the "Begin" line
while not lines_ref[line_index].split(" ")[0] == "End":
line_ref_splitted = lines_ref[line_index].split(" ")
line_out_splitted = lines_out[line_index].split(" ")
test_case.assertEqual(len(line_ref_splitted), len(line_out_splitted), msg="Line {}: Node format is not correct!".format(line_index+1))
# compare node Id
test_case.assertEqual(int(line_ref_splitted[0]), int(line_out_splitted[0]), msg="Line {}: Node Ids do not match!".format(line_index+1))
# compare node coordinates
for i in range(1,4):
ref_coord = float(line_ref_splitted[i])
out_coord = float(line_out_splitted[i])
test_case.assertAlmostEqual(ref_coord, out_coord, msg="Line {}: Node Coordinates do not match!".format(line_index+1))
line_index += 1
return line_index+1
def CompareGeometricalObjects(lines_ref, lines_out, line_index):
# compare entity types (Elements or Conditions)
test_case.assertEqual(lines_ref[line_index], lines_out[line_index])
line_index += 1 # skip the "Begin" line
while not lines_ref[line_index].split(" ")[0] == "End":
line_ref_splitted = lines_ref[line_index].split(" ")
line_out_splitted = lines_out[line_index].split(" ")
test_case.assertListEqual(line_ref_splitted, line_out_splitted)
line_index += 1
return line_index+1
def CompareSubModelParts(lines_ref, lines_out, line_index):
while not lines_ref[line_index].split(" ")[0] == "End":
if lines_ref[line_index].startswith("Begin SubModelPartData"):
line_index = CompareKeyValueData(lines_ref, lines_out, line_index)
test_case.assertEqual(lines_ref[line_index], lines_out[line_index])
line_index += 1
test_case.assertEqual(lines_ref[line_index+1], lines_out[line_index+1]) # compare "End" line
return line_index+1
def CompareEntityValues(line_ref_splitted, line_out_splitted, line_index):
test_case.assertEqual(len(line_ref_splitted), len(line_out_splitted), msg="Line {}: Data format is not correct!".format(line_index+1))
# compare data key
test_case.assertEqual(line_ref_splitted[0], line_out_splitted[0], msg="Line {}: Data Keys do not match!".format(line_index+1))
# compare data value
if len(line_ref_splitted) == 2: # normal key-value pair
try: # check if the value can be converted to float
val_ref = float(line_ref_splitted[1])
val_is_float = True
except ValueError:
val_is_float = False
if val_is_float:
val_ref = float(line_ref_splitted[1])
val_out = float(line_out_splitted[1])
test_case.assertAlmostEqual(val_ref, val_out, msg="Line {}: Value does not match!".format(line_index+1))
else:
test_case.assertEqual(line_ref_splitted[1], line_out_splitted[1], msg="Line {}: Value does not match!".format(line_index+1))
elif len(line_ref_splitted) == 3: # vector or matrix
def StripLeadingAndEndingCharacter(the_string):
# e.g. "[12]" => "12"
return the_string[1:-1]
def ReadValues(the_string):
the_string = the_string.replace("(", "").replace(")", "")
return [float(s) for s in the_string.split(",")]
def ReadVector(line_with_vector_splitted):
size_vector = int(StripLeadingAndEndingCharacter(line_with_vector_splitted[1]))
test_case.assertGreater(size_vector, 0)
values_vector = ReadValues(line_with_vector_splitted[2])
test_case.assertEqual(size_vector, len(values_vector))
return size_vector, values_vector
def ReadMatrix(line_with_matrix_splitted):
# "serializes" the values which is ok for testing
# only thing that cannot be properly tested this way is the num of rows & cols
# however probably not worth the effort
sizes_as_string = StripLeadingAndEndingCharacter(line_with_matrix_splitted[1])
sizes_splitted = sizes_as_string.split(",")
test_case.assertEqual(len(sizes_splitted), 2)
num_rows = int(sizes_splitted[0])
num_cols = int(sizes_splitted[1])
test_case.assertGreater(num_rows, 0)
test_case.assertGreater(num_cols, 0)
values_matrix = ReadValues(line_with_matrix_splitted[2])
test_case.assertEqual(len(values_matrix), num_rows*num_cols)
return num_rows, num_cols, values_matrix
if "," in line_ref_splitted[1]: # matrix
num_rows_ref, num_cols_ref, vals_mat_ref = ReadMatrix(line_ref_splitted)
num_rows_out, num_cols_out, vals_mat_out = ReadMatrix(line_out_splitted)
test_case.assertEqual(num_rows_ref, num_rows_out)
test_case.assertEqual(num_cols_ref, num_cols_out)
for val_ref, val_out in zip(vals_mat_ref, vals_mat_out):
test_case.assertAlmostEqual(val_ref, val_out)
else: # vector
size_vec_ref, vals_vec_ref = ReadVector(line_ref_splitted)
size_vec_out, vals_vec_out = ReadVector(line_out_splitted)
test_case.assertEqual(size_vec_ref, size_vec_out)
for val_ref, val_out in zip(vals_vec_ref, vals_vec_out):
test_case.assertAlmostEqual(val_ref, val_out)
else:
raise Exception("Line {}: Data Value has too many entries!".format(line_index+1))
def CompareEntitiyData(lines_ref, lines_out, line_index):
test_case.assertEqual(lines_ref[line_index], lines_out[line_index])
is_nodal_data = ("Nodal" in lines_ref[line_index])
line_index += 1 # skip the "Begin" line
while not lines_ref[line_index].split(" ")[0] == "End":
line_ref_splitted = lines_ref[line_index].split(" ")
line_out_splitted = lines_out[line_index].split(" ")
if is_nodal_data:
# removing the "fixity"
line_ref_splitted.pop(1)
line_out_splitted.pop(1)
CompareEntityValues(line_ref_splitted, line_out_splitted, line_index)
line_index += 1
return line_index+1
def CompareKeyValueData(lines_ref, lines_out, line_index):
# compare entity types (Elements or Conditions)
ref_type = lines_ref[line_index].split(" ")[1]
out_type = lines_out[line_index].split(" ")[1]
test_case.assertEqual(ref_type, out_type, msg="Line {}: Types do not match!".format(line_index+1))
line_index += 1 # skip the "Begin" line
while not lines_ref[line_index].split(" ")[0] == "End":
line_ref_splitted = lines_ref[line_index].split(" ")
line_out_splitted = lines_out[line_index].split(" ")
CompareEntityValues(line_ref_splitted, line_out_splitted, line_index)
line_index += 1
return line_index+1
def CompareMdpaFiles(ref_mdpa_file, other_mdpa_file):
lines_ref, lines_out = GetFileLines(ref_mdpa_file, other_mdpa_file)
line_index = 0
while line_index < len(lines_ref):
ref_line_splitted = lines_ref[line_index].split(" ")
if lines_ref[line_index].startswith("//"):
if line_index > 0: # skip first line as this contains the date and time
test_case.assertEqual(lines_ref[line_index], lines_out[line_index])
line_index += 1
elif ref_line_splitted[0] == "Begin":
comparison_type = ref_line_splitted[1]
if comparison_type == "Nodes":
line_index = CompareNodes(lines_ref, lines_out, line_index)
elif comparison_type == "Elements" or comparison_type == "Conditions":
line_index = CompareGeometricalObjects(lines_ref, lines_out, line_index)
elif comparison_type in ["SubModelPart", "SubModelPartNodes", "SubModelPartElements", "SubModelPartConditions"]:
line_index = CompareSubModelParts(lines_ref, lines_out, line_index)
elif comparison_type in ["NodalData", "ElementalData", "ConditionalData"]:
line_index = CompareEntitiyData(lines_ref, lines_out, line_index)
elif comparison_type in ["Properties", "ModelPartData", "SubModelPartData"]:
line_index = CompareKeyValueData(lines_ref, lines_out, line_index)
else:
raise Exception('Comparison for "{}" not implemented!'.format(comparison_type))
else:
line_index += 1
if not mdpa_file_name.endswith(".mdpa"):
mdpa_file_name += ".mdpa"
# the naming has to follow a certain style!
ref_file_name = os.path.join(GetTestsDir(), "mdpa_ref_files", "ref_"+mdpa_file_name)
CompareMdpaFiles(ref_file_name, mdpa_file_name)
os.remove(mdpa_file_name) # remove file (only done if test is successful!)
def CheckModelPartHierarchie(model_part, hierarchie, test_case):
"""Checking if the hierarchie of a ModelPart matches the expected one
This is intended to check larger models, where it is not feasible
save large mdpa-files as references
the hierarchie is a dict with the structure of the ModelPart. E.g.:
{
"name_model_part" : {
"nodes": 15
"elements": 11
"conditions": 5
"properties": 2,
"sub_model_parts" : {
"domain" : {
"nodes": 15,
"elements" : 11,
"properties" :1
"sub_model_parts" : {
"sub_domain" : {
"nodes" : 3,
"elements" : 2
}
}
},
"boundary" : {
"nodes": 6
"conditions" : 5,
"properties" : 1
}
}
}
}
}
"""
def CheckModelPartHierarchieNumbers(smp, smp_hierarchie):
exp_num = smp_hierarchie.get("nodes", 0)
test_case.assertEqual(smp.NumberOfNodes(), exp_num, msg='ModelPart "{}" is expected to have {} nodes but has {}'.format(smp.FullName(), exp_num, smp.NumberOfNodes()))
exp_num = smp_hierarchie.get("elements", 0)
test_case.assertEqual(smp.NumberOfElements(), exp_num, msg='ModelPart "{}" is expected to have {} elements but has {}'.format(smp.FullName(), exp_num, smp.NumberOfElements()))
exp_num = smp_hierarchie.get("conditions", 0)
test_case.assertEqual(smp.NumberOfConditions(), exp_num, msg='ModelPart "{}" is expected to have {} conditions but has {}'.format(smp.FullName(), exp_num, smp.NumberOfConditions()))
exp_num = smp_hierarchie.get("properties", 0)
test_case.assertEqual(smp.NumberOfProperties(), exp_num, msg='ModelPart "{}" is expected to have {} properties but has {}'.format(smp.FullName(), exp_num, smp.NumberOfProperties()))
if "sub_model_parts" in smp_hierarchie:
smp_hierarchie = smp_hierarchie["sub_model_parts"]
for name_smp in smp_hierarchie:
test_case.assertTrue(smp.HasSubModelPart(name_smp), msg='ModelPart "{}" does not have SubModelPart with name "{}"'.format(smp.FullName(), name_smp))
CheckModelPartHierarchieNumbers(smp.GetSubModelPart(name_smp), smp_hierarchie[name_smp])
# check name of MainModelPart
test_case.assertEqual(len(hierarchie), 1)
name_main_model_part = hierarchie.__iter__().__next__()
test_case.assertEqual(model_part.Name, name_main_model_part)
CheckModelPartHierarchieNumbers(model_part, hierarchie[name_main_model_part])
class ModelPartForTests:
"""auxiliary functions for creating entities in ModelParts for testing purposes
Names of the entities are compatible with Kratos
"""
@staticmethod
def CreateNodes(mp):
for i in range(8):
mp.CreateNewNode(i+1, i**1.1, i*2.2, 2.6)
@staticmethod
def CreateNodesAndLineElements(mp):
for i in range(6):
mp.CreateNewNode(i+1, 0.0, 0.0, 0.0) # coordinates do not matter here
props_1 = mp.CreateNewProperties(1)
props_2 = mp.CreateNewProperties(15)
for i in range(10):
if i%3 == 0:
props = props_2
else:
props = props_1
mp.CreateNewElement("Element2D2N", i+1, [i%3+1,i%6+1], props)
@staticmethod
def CreateNodesAndTriangleConditions(mp):
for i in range(6):
mp.CreateNewNode(i+1, 0.0, 0.0, 0.0) # coordinates do not matter here
props_1 = mp.CreateNewProperties(1)
props_2 = mp.CreateNewProperties(15)
for i in range(17):
if i%5 == 0:
props = props_2
else:
props = props_1
mp.CreateNewCondition("SurfaceCondition3D3N", i+1, [i%3+1,i%6+1,i%2+1], props)
|
[] |
[] |
[
"KRATOS_AVAILABLE"
] |
[]
|
["KRATOS_AVAILABLE"]
|
python
| 1 | 0 | |
integration/testcmd/gotest/uinit/gotest.go
|
// Copyright 2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/u-root/u-root/pkg/mount"
"golang.org/x/sys/unix"
)
func walkTests(testRoot string, fn func(string, string)) error {
return filepath.Walk(testRoot, func(path string, info os.FileInfo, err error) error {
if !info.Mode().IsRegular() || !strings.HasSuffix(path, ".test") || err != nil {
return nil
}
t2, err := filepath.Rel(testRoot, path)
if err != nil {
return err
}
pkgName := filepath.Dir(t2)
fn(path, pkgName)
return nil
})
}
// Mount a vfat volume and run the tests within.
func main() {
if err := os.MkdirAll("/testdata", 0755); err != nil {
log.Fatalf("Couldn't create testdata: %v", err)
}
var (
mp *mount.MountPoint
err error
)
if os.Getenv("UROOT_USE_9P") == "1" {
mp, err = mount.Mount("tmpdir", "/testdata", "9p", "", 0)
} else {
mp, err = mount.Mount("/dev/sda1", "/testdata", "vfat", "", unix.MS_RDONLY)
}
if err != nil {
log.Fatalf("Failed to mount test directory: %v", err)
}
defer mp.Unmount(0) //nolint:errcheck
walkTests("/testdata/tests", func(path, pkgName string) {
ctx, cancel := context.WithTimeout(context.Background(), 25000*time.Millisecond)
defer cancel()
r, w, err := os.Pipe()
if err != nil {
log.Printf("Failed to get pipe: %v", err)
return
}
cmd := exec.CommandContext(ctx, path, "-test.v")
cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr
// Write to stdout for humans, write to w for the JSON converter.
//
// The test collector will gobble up JSON for statistics, and
// print non-JSON for humans to consume.
cmd.Stdout = io.MultiWriter(os.Stdout, w)
// Start test in its own dir so that testdata is available as a
// relative directory.
cmd.Dir = filepath.Dir(path)
if err := cmd.Start(); err != nil {
log.Printf("Failed to start %v: %v", path, err)
return
}
j := exec.CommandContext(ctx, "test2json", "-t", "-p", pkgName)
j.Stdin = r
j.Stdout, cmd.Stderr = os.Stdout, os.Stderr
if err := j.Start(); err != nil {
log.Printf("Failed to start test2json: %v", err)
return
}
// Don't do anything if the test fails. The log collector will
// deal with it. ¯\_(ツ)_/¯
cmd.Wait()
// Close the pipe so test2json will quit.
w.Close()
j.Wait()
})
log.Printf("GoTest Done")
unix.Reboot(unix.LINUX_REBOOT_CMD_POWER_OFF)
}
|
[
"\"UROOT_USE_9P\""
] |
[] |
[
"UROOT_USE_9P"
] |
[]
|
["UROOT_USE_9P"]
|
go
| 1 | 0 | |
blocks/df.go
|
package blocks
import (
"os"
"os/exec"
"strings"
"fmt"
"strconv"
pgu "github.com/luketpickering/gobar/pangoutils"
)
type DiskFreeBlock struct {
homedir string
df_str string
}
func (b *DiskFreeBlock) Update() {
df_out, df_err := exec.Command("df", "--output=pcent", b.homedir).Output()
if df_err != nil {
return
}
splits := strings.Fields(string(df_out))
if len(splits) < 2 {
return
}
df_pc, _ := strconv.Atoi(strings.TrimRight(splits[1],"%"))
if df_pc > 90 {
b.df_str = pgu.NewPangoStrU(fmt.Sprintf(" \uf0a0 %v%% ",df_pc)).SetBGColor(pgu.Red).SetFGColor(pgu.DarkGrey).String()
} else if df_pc > 80 {
b.df_str = pgu.NewPangoStrU(fmt.Sprintf(" \uf0a0 %v%% ",df_pc)).SetFGColor(pgu.Orange).String()
} else {
b.df_str = fmt.Sprintf(" \uf0a0 %v%% ",df_pc)
}
}
func (b *DiskFreeBlock) ToBlock() Block {
out_b := NewPangoBlock()
out_b.full_text = b.df_str
out_b.min_width = " \uf0a0 100% "
return out_b
}
func (b *DiskFreeBlock) Check() bool {
_, err := exec.LookPath("df")
if err != nil {
return false
}
b.homedir = os.Getenv("HOME")
return true
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
main.go
|
package main
import (
"database/sql"
"github.com/brianglass/english_bible"
alexa "github.com/brianglass/go-alexa/skillserver"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/cors"
"log"
"net/http"
"os"
"time"
)
const (
// This is about the middle of the country including Hawaii and Alaska
// Folks on the east coast won't much care after midnight and the folks in
// Hawaii will have the day change happen at 9pm. That's not ideal, but my
// guess is that most people won't be using the service after 9pm.
TimeZone = "America/Los_Angeles"
)
var (
TZ *time.Location
AlexaAppId = os.Getenv("ALEXA_APP_ID")
)
func init() {
var e error
TZ, e = time.LoadLocation(TimeZone)
if e != nil {
TZ = time.UTC
log.Printf("Error loading '%s' timezone, using UTC.", TimeZone)
}
}
func main() {
var ocadb, bibledb *sql.DB
var e error
// Open up all the requisite databases
if ocadb, e = sql.Open("sqlite3", "oca_calendar.db"); e != nil {
log.Printf("Got error opening database: %#v. Exiting.", e)
os.Exit(1)
}
defer ocadb.Close()
if bibledb, e = sql.Open("sqlite3", "english.db"); e != nil {
log.Printf("Got error opening database: %#v. Exiting.", e)
os.Exit(1)
}
defer bibledb.Close()
bible := english_bible.NewBible(bibledb)
// Setup HTTP routers
router := mux.NewRouter()
// Google health check expects to to receive a response for /. Do not delete.
router.HandleFunc("/", healthHandler)
router.HandleFunc("/healthz", healthHandler)
ocaRouter := router.PathPrefix("/api/oca").Subrouter()
NewCalendarServer(ocaRouter, ocadb, false, true, bible, "OCA")
rocorRouter := router.PathPrefix("/api/rocor").Subrouter()
NewCalendarServer(rocorRouter, ocadb, true, true, bible, "ROCOR") // Apparently Rocor now does the Lukan jump
// Setup Alexa skill
apps := map[string]interface{}{
"/echo/": NewSkill(AlexaAppId, ocadb, false, true, bible, TZ),
}
alexa.Init(apps, router.NewRoute().Subrouter())
// Setup middleware
router.Use(cors.Default().Handler)
router.Use(handlers.CompressHandler)
router.Use(logHeaderMiddleware)
// Launch the HTTP server
http.ListenAndServe(":8080", handlers.CombinedLoggingHandler(os.Stdout, router))
}
func healthHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/plain")
writer.WriteHeader(http.StatusOK)
writer.Write([]byte("ok"))
}
func logHeaderMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
log.Println(request.Header)
next.ServeHTTP(writer, request)
})
}
|
[
"\"ALEXA_APP_ID\""
] |
[] |
[
"ALEXA_APP_ID"
] |
[]
|
["ALEXA_APP_ID"]
|
go
| 1 | 0 | |
repl/cli/cli.go
|
// Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Read Eval Print Loop for CLI
package cli
import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"github.com/go-python/gpython/py"
"github.com/go-python/gpython/repl"
"github.com/peterh/liner"
)
const HistoryFileName = ".gpyhistory"
// homeDirectory finds the home directory or returns ""
func homeDirectory() string {
usr, err := user.Current()
if err == nil {
return usr.HomeDir
}
// Fall back to reading $HOME - work around user.Current() not
// working for cross compiled binaries on OSX.
// https://github.com/golang/go/issues/6376
return os.Getenv("HOME")
}
// Holds state for readline services
type readline struct {
*liner.State
repl *repl.REPL
historyFile string
module *py.Module
prompt string
}
// newReadline creates a new instance of readline
func newReadline(repl *repl.REPL) *readline {
rl := &readline{
State: liner.NewLiner(),
repl: repl,
}
home := homeDirectory()
if home != "" {
rl.historyFile = filepath.Join(home, HistoryFileName)
}
rl.SetTabCompletionStyle(liner.TabPrints)
rl.SetWordCompleter(rl.Completer)
return rl
}
// readHistory reads the history into the term
func (rl *readline) ReadHistory() error {
f, err := os.Open(rl.historyFile)
if err != nil {
return err
}
defer f.Close()
_, err = rl.State.ReadHistory(f)
if err != nil {
return err
}
return nil
}
// writeHistory writes the history from the term
func (rl *readline) WriteHistory() error {
f, err := os.OpenFile(rl.historyFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
defer f.Close()
_, err = rl.State.WriteHistory(f)
if err != nil {
return err
}
return nil
}
// Close the readline and write history
func (rl *readline) Close() error {
err := rl.State.Close()
if err != nil {
return err
}
if rl.historyFile != "" {
err := rl.WriteHistory()
if err != nil {
return err
}
}
return nil
}
// Completer takes the currently edited line with the cursor
// position and returns the completion candidates for the partial word
// to be completed. If the line is "Hello, wo!!!" and the cursor is
// before the first '!', ("Hello, wo!!!", 9) is passed to the
// completer which may returns ("Hello, ", {"world", "Word"}, "!!!")
// to have "Hello, world!!!".
func (rl *readline) Completer(line string, pos int) (head string, completions []string, tail string) {
return rl.repl.Completer(line, pos)
}
// SetPrompt sets the current terminal prompt
func (rl *readline) SetPrompt(prompt string) {
rl.prompt = prompt
}
// Print prints the output
func (rl *readline) Print(out string) {
_, _ = os.Stdout.WriteString(out + "\n")
}
// RunREPL starts the REPL loop
func RunREPL() {
repl := repl.New()
rl := newReadline(repl)
repl.SetUI(rl)
defer rl.Close()
err := rl.ReadHistory()
if err != nil {
fmt.Printf("Failed to open history: %v\n", err)
}
fmt.Printf("Gpython 3.4.0\n")
for {
line, err := rl.Prompt(rl.prompt)
if err != nil {
if err == io.EOF {
fmt.Printf("\n")
break
}
fmt.Printf("Problem reading line: %v\n", err)
continue
}
if line != "" {
rl.AppendHistory(line)
}
rl.repl.Run(line)
}
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
main.go
|
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/Plloi/Junior/commands"
"github.com/Plloi/pdb-cmdr/pkg/router"
"github.com/Plloi/pdb-pokemon/pkg/pokemon"
"github.com/bwmarrin/discordgo"
"github.com/joho/godotenv"
log "github.com/sirupsen/logrus"
)
// Variables used for command line parameters
var (
Token string
Router *router.CommandRouter
SAL *commands.SAL
)
func init() {
flag.StringVar(&Token, "t", "", "Bot Discord Token")
flag.Parse()
log.SetLevel(log.DebugLevel)
godotenv.Load()
if Token == "" {
Token = os.Getenv("DISCORD_TOKEN")
}
}
func main() {
log.Info("Starting up")
// Create a new Discord session using the provided bot token.
if Token == "" {
log.Error("Token Required for bot usage")
os.Exit(1)
}
dg, err := discordgo.New("Bot " + Token)
if err != nil {
fmt.Println("error creating Discord session,", err)
return
}
Router = router.NewCommandRouter()
Router.DefaultPrefix = "pj!"
Router.RegisterCommand("prefix", "Sets the bot command prefix (Admin Locked)", Router.SetPrefix)
// Register router's command handler for message events.
dg.AddHandler(Router.HandleCommand)
log.Info("Importing commands module")
commands.Setup(Router)
log.Info("Loading Pokemon Module")
pokemon.Setup(Router)
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
fmt.Println("error opening connection,", err)
return
}
// Wait here until CTRL-C or other term signal is received.
log.Info("Bot is now running")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// Cleanly close down the Discord session.
dg.Close()
}
|
[
"\"DISCORD_TOKEN\""
] |
[] |
[
"DISCORD_TOKEN"
] |
[]
|
["DISCORD_TOKEN"]
|
go
| 1 | 0 | |
src/cmd/linuxkit/push_vcenter.go
|
package main
import (
"context"
"flag"
"fmt"
"os"
"path"
"path/filepath"
"strings"
log "github.com/Sirupsen/logrus"
)
// Process the push arguments and execute push
func pushVCenter(args []string) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var newVM vmConfig
flags := flag.NewFlagSet("vCenter", flag.ExitOnError)
invoked := filepath.Base(os.Args[0])
flags.Usage = func() {
fmt.Printf("USAGE: %s push vcenter [options] path \n\n", invoked)
fmt.Printf("'path' specifies the full path of an ISO image. It will be pushed to a vCenter cluster.\n")
fmt.Printf("Options:\n\n")
flags.PrintDefaults()
}
newVM.vCenterURL = flags.String("url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
newVM.dsName = flags.String("datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the image")
newVM.networkName = flags.String("network", os.Getenv("VCNETWORK"), "The network label the VM will use")
newVM.vSphereHost = flags.String("hostname", os.Getenv("VCHOST"), "The server that will host the image")
newVM.path = flags.String("path", "", "Path to a specific image")
newVM.vmFolder = flags.String("folder", "", "A folder on the datastore to push the image too")
if err := flags.Parse(args); err != nil {
log.Fatalln("Unable to parse args")
}
remArgs := flags.Args()
if len(remArgs) == 0 {
fmt.Printf("Please specify the path to the image to push\n")
flags.Usage()
os.Exit(1)
}
*newVM.path = remArgs[0]
// Ensure an iso has been passed to the vCenter push Command
if !strings.HasSuffix(*newVM.path, ".iso") {
log.Fatalln("Please specify an '.iso' file")
}
// Test any passed in files before uploading image
checkFile(*newVM.path)
// Connect to VMware vCenter and return the values needed to upload image
c, dss, _, _, _, _ := vCenterConnect(ctx, newVM)
// Create a folder from the uploaded image name if needed
if *newVM.vmFolder == "" {
*newVM.vmFolder = strings.TrimSuffix(path.Base(*newVM.path), ".iso")
}
// The CreateFolder method isn't necessary as the *newVM.vmname will be created automatically
uploadFile(c, newVM, dss)
}
|
[
"\"VCURL\"",
"\"VCDATASTORE\"",
"\"VCNETWORK\"",
"\"VCHOST\""
] |
[] |
[
"VCNETWORK",
"VCHOST",
"VCDATASTORE",
"VCURL"
] |
[]
|
["VCNETWORK", "VCHOST", "VCDATASTORE", "VCURL"]
|
go
| 4 | 0 | |
test/e2e/autoscaling/cluster_size_autoscaling.go
|
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package autoscaling
import (
"fmt"
"io/ioutil"
"math"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"k8s.io/api/core/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
schedulingv1 "k8s.io/api/scheduling/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
clientset "k8s.io/client-go/kubernetes"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/test/e2e/framework"
e2elog "k8s.io/kubernetes/test/e2e/framework/log"
e2enode "k8s.io/kubernetes/test/e2e/framework/node"
"k8s.io/kubernetes/test/e2e/scheduling"
testutils "k8s.io/kubernetes/test/utils"
imageutils "k8s.io/kubernetes/test/utils/image"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
"k8s.io/klog"
)
const (
defaultTimeout = 3 * time.Minute
resizeTimeout = 5 * time.Minute
manualResizeTimeout = 6 * time.Minute
scaleUpTimeout = 5 * time.Minute
scaleUpTriggerTimeout = 2 * time.Minute
scaleDownTimeout = 20 * time.Minute
podTimeout = 2 * time.Minute
nodesRecoverTimeout = 5 * time.Minute
rcCreationRetryTimeout = 4 * time.Minute
rcCreationRetryDelay = 20 * time.Second
makeSchedulableTimeout = 10 * time.Minute
makeSchedulableDelay = 20 * time.Second
freshStatusLimit = 20 * time.Second
gkeUpdateTimeout = 15 * time.Minute
gkeNodepoolNameKey = "cloud.google.com/gke-nodepool"
disabledTaint = "DisabledForAutoscalingTest"
criticalAddonsOnlyTaint = "CriticalAddonsOnly"
newNodesForScaledownTests = 2
unhealthyClusterThreshold = 4
caNoScaleUpStatus = "NoActivity"
caOngoingScaleUpStatus = "InProgress"
timestampFormat = "2006-01-02 15:04:05 -0700 MST"
expendablePriorityClassName = "expendable-priority"
highPriorityClassName = "high-priority"
gpuLabel = "cloud.google.com/gke-accelerator"
)
var _ = SIGDescribe("Cluster size autoscaling [Slow]", func() {
f := framework.NewDefaultFramework("autoscaling")
var c clientset.Interface
var nodeCount int
var coreCount int64
var memAllocatableMb int
var originalSizes map[string]int
ginkgo.BeforeEach(func() {
c = f.ClientSet
framework.SkipUnlessProviderIs("gce", "gke")
originalSizes = make(map[string]int)
sum := 0
for _, mig := range strings.Split(framework.TestContext.CloudConfig.NodeInstanceGroup, ",") {
size, err := framework.GroupSize(mig)
framework.ExpectNoError(err)
ginkgo.By(fmt.Sprintf("Initial size of %s: %d", mig, size))
originalSizes[mig] = size
sum += size
}
// Give instances time to spin up
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, sum, scaleUpTimeout))
nodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
nodeCount = len(nodes.Items)
coreCount = 0
for _, node := range nodes.Items {
quantity := node.Status.Allocatable[v1.ResourceCPU]
coreCount += quantity.Value()
}
ginkgo.By(fmt.Sprintf("Initial number of schedulable nodes: %v", nodeCount))
gomega.Expect(nodeCount).NotTo(gomega.BeZero())
mem := nodes.Items[0].Status.Allocatable[v1.ResourceMemory]
memAllocatableMb = int((&mem).Value() / 1024 / 1024)
gomega.Expect(nodeCount).Should(gomega.Equal(sum))
if framework.ProviderIs("gke") {
val, err := isAutoscalerEnabled(5)
framework.ExpectNoError(err)
if !val {
err = enableAutoscaler("default-pool", 3, 5)
framework.ExpectNoError(err)
}
}
})
ginkgo.AfterEach(func() {
framework.SkipUnlessProviderIs("gce", "gke")
ginkgo.By(fmt.Sprintf("Restoring initial size of the cluster"))
setMigSizes(originalSizes)
expectedNodes := 0
for _, size := range originalSizes {
expectedNodes += size
}
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, expectedNodes, scaleDownTimeout))
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
framework.ExpectNoError(err)
s := time.Now()
makeSchedulableLoop:
for start := time.Now(); time.Since(start) < makeSchedulableTimeout; time.Sleep(makeSchedulableDelay) {
for _, n := range nodes.Items {
err = makeNodeSchedulable(c, &n, true)
switch err.(type) {
case CriticalAddonsOnlyError:
continue makeSchedulableLoop
default:
framework.ExpectNoError(err)
}
}
break
}
klog.Infof("Made nodes schedulable again in %v", time.Since(s).String())
})
ginkgo.It("shouldn't increase cluster size if pending pod is too large [Feature:ClusterSizeAutoscalingScaleUp]", func() {
ginkgo.By("Creating unschedulable pod")
ReserveMemory(f, "memory-reservation", 1, int(1.1*float64(memAllocatableMb)), false, defaultTimeout)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ginkgo.By("Waiting for scale up hoping it won't happen")
// Verify that the appropriate event was generated
eventFound := false
EventsLoop:
for start := time.Now(); time.Since(start) < scaleUpTimeout; time.Sleep(20 * time.Second) {
ginkgo.By("Waiting for NotTriggerScaleUp event")
events, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(metav1.ListOptions{})
framework.ExpectNoError(err)
for _, e := range events.Items {
if e.InvolvedObject.Kind == "Pod" && e.Reason == "NotTriggerScaleUp" && strings.Contains(e.Message, "it wouldn't fit if a new node is added") {
ginkgo.By("NotTriggerScaleUp event found")
eventFound = true
break EventsLoop
}
}
}
gomega.Expect(eventFound).Should(gomega.Equal(true))
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size <= nodeCount }, time.Second))
})
simpleScaleUpTest := func(unready int) {
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout, unready))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
}
ginkgo.It("should increase cluster size if pending pods are small [Feature:ClusterSizeAutoscalingScaleUp]",
func() { simpleScaleUpTest(0) })
gpuType := os.Getenv("TESTED_GPU_TYPE")
ginkgo.It(fmt.Sprintf("Should scale up GPU pool from 0 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
framework.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 0)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet()
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(0))
ginkgo.By("Schedule a pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount+1 }, scaleUpTimeout))
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(1))
})
ginkgo.It(fmt.Sprintf("Should scale up GPU pool from 1 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
framework.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 1)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet()
ginkgo.By("Schedule a single pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 2))
defer disableAutoscaler(gpuPoolName, 0, 2)
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(1))
ginkgo.By("Scale GPU deployment")
framework.ScaleRC(f.ClientSet, f.ScalesGetter, f.Namespace.Name, "gpu-pod-rc", 2, true)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount+2 }, scaleUpTimeout))
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(2))
})
ginkgo.It(fmt.Sprintf("Should not scale GPU pool up if pod does not require GPUs [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
framework.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 0)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet()
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(0))
ginkgo.By("Schedule bunch of pods beyond point of filling default pool but do not request any GPUs")
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout))
// Expect gpu pool to stay intact
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(0))
})
ginkgo.It(fmt.Sprintf("Should scale down GPU pool from 1 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
framework.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 1)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet()
ginkgo.By("Schedule a single pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(1))
ginkgo.By("Remove the only POD requiring GPU")
framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, scaleDownTimeout))
gomega.Expect(len(getPoolNodes(f, gpuPoolName))).Should(gomega.Equal(0))
})
ginkgo.It("should increase cluster size if pending pods are small and one node is broken [Feature:ClusterSizeAutoscalingScaleUp]",
func() {
framework.TestUnderTemporaryNetworkFailure(c, "default", getAnyNode(c), func() { simpleScaleUpTest(1) })
})
ginkgo.It("shouldn't trigger additional scale-ups during processing scale-up [Feature:ClusterSizeAutoscalingScaleUp]", func() {
// Wait for the situation to stabilize - CA should be running and have up-to-date node readiness info.
status, err := waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.ready == s.target && s.ready <= nodeCount
}, scaleUpTriggerTimeout)
framework.ExpectNoError(err)
unmanagedNodes := nodeCount - status.ready
ginkgo.By("Schedule more pods than can fit and wait for cluster to scale-up")
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
status, err = waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.status == caOngoingScaleUpStatus
}, scaleUpTriggerTimeout)
framework.ExpectNoError(err)
target := status.target
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("Expect no more scale-up to be happening after all pods are scheduled")
// wait for a while until scale-up finishes; we cannot read CA status immediately
// after pods are scheduled as status config map is updated by CA once every loop iteration
status, err = waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.status == caNoScaleUpStatus
}, 2*freshStatusLimit)
framework.ExpectNoError(err)
if status.target != target {
klog.Warningf("Final number of nodes (%v) does not match initial scale-up target (%v).", status.target, target)
}
gomega.Expect(status.timestamp.Add(freshStatusLimit).Before(time.Now())).Should(gomega.Equal(false))
gomega.Expect(status.status).Should(gomega.Equal(caNoScaleUpStatus))
gomega.Expect(status.ready).Should(gomega.Equal(status.target))
gomega.Expect(len(framework.GetReadySchedulableNodesOrDie(f.ClientSet).Items)).Should(gomega.Equal(status.target + unmanagedNodes))
})
ginkgo.It("should increase cluster size if pending pods are small and there is another node pool that is not autoscaled [Feature:ClusterSizeAutoscalingScaleUp]", func() {
framework.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
// We wait for nodes to become schedulable to make sure the new nodes
// will be returned by getPoolNodes below.
framework.ExpectNoError(framework.WaitForAllNodesSchedulable(c, resizeTimeout))
klog.Infof("Not enabling cluster autoscaler for the node pool (on purpose).")
ginkgo.By("Getting memory available on new nodes, so we can account for it when creating RC")
nodes := getPoolNodes(f, extraPoolName)
gomega.Expect(len(nodes)).Should(gomega.Equal(extraNodes))
extraMemMb := 0
for _, node := range nodes {
mem := node.Status.Allocatable[v1.ResourceMemory]
extraMemMb += int((&mem).Value() / 1024 / 1024)
}
ginkgo.By("Reserving 0.1x more memory than the cluster holds to trigger scale up")
totalMemoryReservation := int(1.1 * float64(nodeCount*memAllocatableMb+extraMemMb))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ReserveMemory(f, "memory-reservation", 100, totalMemoryReservation, false, defaultTimeout)
// Verify, that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+extraNodes+1 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
ginkgo.It("should disable node pool autoscaling [Feature:ClusterSizeAutoscalingScaleUp]", func() {
framework.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 1, 2))
framework.ExpectNoError(disableAutoscaler(extraPoolName, 1, 2))
})
ginkgo.It("should increase cluster size if pods are pending due to host port conflict [Feature:ClusterSizeAutoscalingScaleUp]", func() {
scheduling.CreateHostPortPods(f, "host-port", nodeCount+2, false)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "host-port")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+2 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
ginkgo.It("should increase cluster size if pods are pending due to pod anti-affinity [Feature:ClusterSizeAutoscalingScaleUp]", func() {
pods := nodeCount
newPods := 2
labels := map[string]string{
"anti-affinity": "yes",
}
ginkgo.By("starting a pod with anti-affinity on each node")
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("scheduling extra pods with anti-affinity to existing ones")
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, newPods, "extra-pod", labels, labels))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "extra-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should increase cluster size if pod requesting EmptyDir volume is pending [Feature:ClusterSizeAutoscalingScaleUp]", func() {
ginkgo.By("creating pods")
pods := nodeCount
newPods := 1
labels := map[string]string{
"anti-affinity": "yes",
}
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
ginkgo.By("waiting for all pods before triggering scale up")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("creating a pod requesting EmptyDir")
framework.ExpectNoError(runVolumeAntiAffinityPods(f, f.Namespace.Name, newPods, "extra-pod", labels, labels, emptyDirVolumes))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "extra-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should increase cluster size if pod requesting volume is pending [Feature:ClusterSizeAutoscalingScaleUp]", func() {
framework.SkipUnlessProviderIs("gce", "gke")
volumeLabels := labels.Set{
framework.VolumeSelectorKey: f.Namespace.Name,
}
selector := metav1.SetAsLabelSelector(volumeLabels)
ginkgo.By("creating volume & pvc")
diskName, err := framework.CreatePDWithRetry()
framework.ExpectNoError(err)
pvConfig := framework.PersistentVolumeConfig{
NamePrefix: "gce-",
Labels: volumeLabels,
PVSource: v1.PersistentVolumeSource{
GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{
PDName: diskName,
FSType: "ext3",
ReadOnly: false,
},
},
Prebind: nil,
}
emptyStorageClass := ""
pvcConfig := framework.PersistentVolumeClaimConfig{
Selector: selector,
StorageClassName: &emptyStorageClass,
}
pv, pvc, err := framework.CreatePVPVC(c, pvConfig, pvcConfig, f.Namespace.Name, false)
framework.ExpectNoError(err)
framework.ExpectNoError(framework.WaitOnPVandPVC(c, f.Namespace.Name, pv, pvc))
defer func() {
errs := framework.PVPVCCleanup(c, f.Namespace.Name, pv, pvc)
if len(errs) > 0 {
framework.Failf("failed to delete PVC and/or PV. Errors: %v", utilerrors.NewAggregate(errs))
}
pv, pvc = nil, nil
if diskName != "" {
framework.ExpectNoError(framework.DeletePDWithRetry(diskName))
}
}()
ginkgo.By("creating pods")
pods := nodeCount
labels := map[string]string{
"anti-affinity": "yes",
}
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer func() {
framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
klog.Infof("RC and pods not using volume deleted")
}()
ginkgo.By("waiting for all pods before triggering scale up")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("creating a pod requesting PVC")
pvcPodName := "pvc-pod"
newPods := 1
volumes := buildVolumes(pv, pvc)
framework.ExpectNoError(runVolumeAntiAffinityPods(f, f.Namespace.Name, newPods, pvcPodName, labels, labels, volumes))
defer func() {
framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, pvcPodName)
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
}()
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should add node to the particular mig [Feature:ClusterSizeAutoscalingScaleUp]", func() {
labelKey := "cluster-autoscaling-test.special-node"
labelValue := "true"
ginkgo.By("Finding the smallest MIG")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
if minSize == 0 {
newSizes := make(map[string]int)
for mig, size := range originalSizes {
newSizes[mig] = size
}
newSizes[minMig] = 1
setMigSizes(newSizes)
}
removeLabels := func(nodesToClean sets.String) {
ginkgo.By("Removing labels from nodes")
for node := range nodesToClean {
framework.RemoveLabelOffNode(c, node, labelKey)
}
}
nodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
nodesSet := sets.NewString(nodes...)
defer removeLabels(nodesSet)
ginkgo.By(fmt.Sprintf("Annotating nodes of the smallest MIG(%s): %v", minMig, nodes))
for node := range nodesSet {
framework.AddOrUpdateLabelOnNode(c, node, labelKey, labelValue)
}
scheduling.CreateNodeSelectorPods(f, "node-selector", minSize+1, map[string]string{labelKey: labelValue}, false)
ginkgo.By("Waiting for new node to appear and annotating it")
framework.WaitForGroupSize(minMig, int32(minSize+1))
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout))
newNodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
newNodesSet := sets.NewString(newNodes...)
newNodesSet.Delete(nodes...)
if len(newNodesSet) > 1 {
ginkgo.By(fmt.Sprintf("Spotted following new nodes in %s: %v", minMig, newNodesSet))
klog.Infof("Usually only 1 new node is expected, investigating")
klog.Infof("Kubectl:%s\n", framework.RunKubectlOrDie("get", "nodes", "-o", "json"))
if output, err := exec.Command("gcloud", "compute", "instances", "list",
"--project="+framework.TestContext.CloudConfig.ProjectID,
"--zone="+framework.TestContext.CloudConfig.Zone).Output(); err == nil {
klog.Infof("Gcloud compute instances list: %s", output)
} else {
klog.Errorf("Failed to get instances list: %v", err)
}
for newNode := range newNodesSet {
if output, err := execCmd("gcloud", "compute", "instances", "describe",
newNode,
"--project="+framework.TestContext.CloudConfig.ProjectID,
"--zone="+framework.TestContext.CloudConfig.Zone).Output(); err == nil {
klog.Infof("Gcloud compute instances describe: %s", output)
} else {
klog.Errorf("Failed to get instances describe: %v", err)
}
}
// TODO: possibly remove broken node from newNodesSet to prevent removeLabel from crashing.
// However at this moment we DO WANT it to crash so that we don't check all test runs for the
// rare behavior, but only the broken ones.
}
ginkgo.By(fmt.Sprintf("New nodes: %v\n", newNodesSet))
registeredNodes := sets.NewString()
for nodeName := range newNodesSet {
node, err := f.ClientSet.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err == nil && node != nil {
registeredNodes.Insert(nodeName)
} else {
klog.Errorf("Failed to get node %v: %v", nodeName, err)
}
}
ginkgo.By(fmt.Sprintf("Setting labels for registered new nodes: %v", registeredNodes.List()))
for node := range registeredNodes {
framework.AddOrUpdateLabelOnNode(c, node, labelKey, labelValue)
}
defer removeLabels(registeredNodes)
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "node-selector"))
})
ginkgo.It("should scale up correct target pool [Feature:ClusterSizeAutoscalingScaleUp]", func() {
framework.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 1, 2))
defer disableAutoscaler(extraPoolName, 1, 2)
extraPods := extraNodes + 1
totalMemoryReservation := int(float64(extraPods) * 1.5 * float64(memAllocatableMb))
ginkgo.By(fmt.Sprintf("Creating rc with %v pods too big to fit default-pool but fitting extra-pool", extraPods))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ReserveMemory(f, "memory-reservation", extraPods, totalMemoryReservation, false, defaultTimeout)
// Apparently GKE master is restarted couple minutes after the node pool is added
// reseting all the timers in scale down code. Adding 5 extra minutes to workaround
// this issue.
// TODO: Remove the extra time when GKE restart is fixed.
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes+1, scaleUpTimeout+5*time.Minute))
})
simpleScaleDownTest := func(unready int) {
cleanup, err := addKubeSystemPdbs(f)
defer cleanup()
framework.ExpectNoError(err)
ginkgo.By("Manually increase cluster size")
increasedSize := 0
newSizes := make(map[string]int)
for key, val := range originalSizes {
newSizes[key] = val + 2 + unready
increasedSize += val + 2 + unready
}
setMigSizes(newSizes)
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size >= increasedSize }, manualResizeTimeout, unready))
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout, unready))
}
ginkgo.It("should correctly scale down after a node is not needed [Feature:ClusterSizeAutoscalingScaleDown]",
func() { simpleScaleDownTest(0) })
ginkgo.It("should correctly scale down after a node is not needed and one node is broken [Feature:ClusterSizeAutoscalingScaleDown]",
func() {
framework.TestUnderTemporaryNetworkFailure(c, "default", getAnyNode(c), func() { simpleScaleDownTest(1) })
})
ginkgo.It("should correctly scale down after a node is not needed when there is non autoscaled pool[Feature:ClusterSizeAutoscalingScaleDown]", func() {
framework.SkipUnlessProviderIs("gke")
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-1", 3)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= increasedSize+extraNodes }, scaleUpTimeout))
ginkgo.By("Some node should be removed")
// Apparently GKE master is restarted couple minutes after the node pool is added
// reseting all the timers in scale down code. Adding 10 extra minutes to workaround
// this issue.
// TODO: Remove the extra time when GKE restart is fixed.
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize+extraNodes }, scaleDownTimeout+10*time.Minute))
})
ginkgo.It("should be able to scale down when rescheduling a pod is required and pdb allows for it[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 1, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("shouldn't be able to scale down when rescheduling a pod is required, but pdb doesn't allow drain[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 1, 0, func(increasedSize int) {
ginkgo.By("No nodes should be removed")
time.Sleep(scaleDownTimeout)
nodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
gomega.Expect(len(nodes.Items)).Should(gomega.Equal(increasedSize))
})
})
ginkgo.It("should be able to scale down by draining multiple pods one by one as dictated by pdb[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 2, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("should be able to scale down by draining system pods with pdb[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, "kube-system", 2, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("Should be able to scale a node group up from 0[Feature:ClusterSizeAutoscalingScaleUp]", func() {
// Provider-specific setup
if framework.ProviderIs("gke") {
// GKE-specific setup
ginkgo.By("Add a new node pool with 0 nodes and min size 0")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 0)
defer deleteNodePool(extraPoolName)
framework.ExpectNoError(enableAutoscaler(extraPoolName, 0, 1))
defer disableAutoscaler(extraPoolName, 0, 1)
} else {
// on GCE, run only if there are already at least 2 node groups
framework.SkipUnlessAtLeast(len(originalSizes), 2, "At least 2 node groups are needed for scale-to-0 tests")
ginkgo.By("Manually scale smallest node group to 0")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
framework.ExpectNoError(framework.ResizeGroup(minMig, int32(0)))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount-minSize, resizeTimeout))
}
ginkgo.By("Make remaining nodes unschedulable")
nodes, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
for _, node := range nodes.Items {
err = makeNodeUnschedulable(f.ClientSet, &node)
defer func(n v1.Node) {
makeNodeSchedulable(f.ClientSet, &n, false)
}(node)
framework.ExpectNoError(err)
}
ginkgo.By("Run a scale-up test")
ReserveMemory(f, "memory-reservation", 1, 100, false, 1*time.Second)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= len(nodes.Items)+1 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
// Scale to 0 test is split into two functions (for GKE & GCE.)
// The reason for it is that scenario is exactly the same,
// but setup & verification use different APIs.
//
// Scenario:
// (GKE only) add an extra node pool with size 1 & enable autoscaling for it
// (GCE only) find the smallest MIG & resize it to 1
// manually drain the single node from this node pool/MIG
// wait for cluster size to decrease
// verify the targeted node pool/MIG is of size 0
gkeScaleToZero := func() {
// GKE-specific setup
ginkgo.By("Add a new node pool with size 1 and min size 0")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 0, 1))
defer disableAutoscaler(extraPoolName, 0, 1)
ngNodes := getPoolNodes(f, extraPoolName)
gomega.Expect(len(ngNodes)).To(gomega.Equal(extraNodes))
for _, node := range ngNodes {
ginkgo.By(fmt.Sprintf("Target node for scale-down: %s", node.Name))
}
for _, node := range ngNodes {
drainNode(f, node)
}
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size <= nodeCount }, scaleDownTimeout))
// GKE-specific check
newSize := getPoolSize(f, extraPoolName)
gomega.Expect(newSize).Should(gomega.Equal(0))
}
gceScaleToZero := func() {
// non-GKE only
ginkgo.By("Find smallest node group and manually scale it to a single node")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
framework.ExpectNoError(framework.ResizeGroup(minMig, int32(1)))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount-minSize+1, resizeTimeout))
ngNodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
gomega.Expect(len(ngNodes) == 1).To(gomega.BeTrue())
node, err := f.ClientSet.CoreV1().Nodes().Get(ngNodes[0], metav1.GetOptions{})
ginkgo.By(fmt.Sprintf("Target node for scale-down: %s", node.Name))
framework.ExpectNoError(err)
// this part is identical
drainNode(f, node)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < nodeCount-minSize+1 }, scaleDownTimeout))
// non-GKE only
newSize, err := framework.GroupSize(minMig)
framework.ExpectNoError(err)
gomega.Expect(newSize).Should(gomega.Equal(0))
}
ginkgo.It("Should be able to scale a node group down to 0[Feature:ClusterSizeAutoscalingScaleDown]", func() {
if framework.ProviderIs("gke") { // In GKE, we can just add a node pool
gkeScaleToZero()
} else if len(originalSizes) >= 2 {
gceScaleToZero()
} else {
framework.Skipf("At least 2 node groups are needed for scale-to-0 tests")
}
})
ginkgo.It("Shouldn't perform scale up operation and should list unhealthy status if most of the cluster is broken[Feature:ClusterSizeAutoscalingScaleUp]", func() {
clusterSize := nodeCount
for clusterSize < unhealthyClusterThreshold+1 {
clusterSize = manuallyIncreaseClusterSize(f, originalSizes)
}
// If new nodes are disconnected too soon, they'll be considered not started
// instead of unready, and cluster won't be considered unhealthy.
//
// More precisely, Cluster Autoscaler compares last transition time of
// several readiness conditions to node create time. If it's within
// 2 minutes, it'll assume node is just starting and not unhealthy.
//
// Nodes become ready in less than 1 minute after being created,
// so waiting extra 2 minutes before breaking them (which triggers
// readiness condition transition) should be sufficient, while
// making no assumptions about minimal node startup time.
time.Sleep(2 * time.Minute)
ginkgo.By("Block network connectivity to some nodes to simulate unhealthy cluster")
nodesToBreakCount := int(math.Ceil(math.Max(float64(unhealthyClusterThreshold), 0.5*float64(clusterSize))))
nodes, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
gomega.Expect(nodesToBreakCount <= len(nodes.Items)).To(gomega.BeTrue())
nodesToBreak := nodes.Items[:nodesToBreakCount]
// TestUnderTemporaryNetworkFailure only removes connectivity to a single node,
// and accepts func() callback. This is expanding the loop to recursive call
// to avoid duplicating TestUnderTemporaryNetworkFailure
var testFunction func()
testFunction = func() {
if len(nodesToBreak) > 0 {
ntb := &nodesToBreak[0]
nodesToBreak = nodesToBreak[1:]
framework.TestUnderTemporaryNetworkFailure(c, "default", ntb, testFunction)
} else {
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, defaultTimeout)
defer framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
time.Sleep(scaleUpTimeout)
currentNodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
e2elog.Logf("Currently available nodes: %v, nodes available at the start of test: %v, disabled nodes: %v", len(currentNodes.Items), len(nodes.Items), nodesToBreakCount)
gomega.Expect(len(currentNodes.Items)).Should(gomega.Equal(len(nodes.Items) - nodesToBreakCount))
status, err := getClusterwideStatus(c)
e2elog.Logf("Clusterwide status: %v", status)
framework.ExpectNoError(err)
gomega.Expect(status).Should(gomega.Equal("Unhealthy"))
}
}
testFunction()
// Give nodes time to recover from network failure
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, len(nodes.Items), nodesRecoverTimeout))
})
ginkgo.It("shouldn't scale up when expendable pod is created [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize+1 pods allocating 0.7 allocatable on present nodes. One more node will have to be created.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", nodeCount+1, int(float64(nodeCount+1)*float64(0.7)*float64(memAllocatableMb)), false, time.Second, expendablePriorityClassName)
defer cleanupFunc()
ginkgo.By(fmt.Sprintf("Waiting for scale up hoping it won't happen, sleep for %s", scaleUpTimeout.String()))
time.Sleep(scaleUpTimeout)
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, time.Second))
})
ginkgo.It("should scale up when non expendable pod is created [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize+1 pods allocating 0.7 allocatable on present nodes. One more node will have to be created.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", nodeCount+1, int(float64(nodeCount+1)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, highPriorityClassName)
defer cleanupFunc()
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size > nodeCount }, time.Second))
})
ginkgo.It("shouldn't scale up when expendable pod is preempted [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc1 := ReserveMemoryWithPriority(f, "memory-reservation1", nodeCount, int(float64(nodeCount)*float64(0.7)*float64(memAllocatableMb)), true, defaultTimeout, expendablePriorityClassName)
defer cleanupFunc1()
// Create nodesCountAfterResize pods allocating 0.7 allocatable on present nodes - one pod per node. Pods created here should preempt pods created above.
cleanupFunc2 := ReserveMemoryWithPriority(f, "memory-reservation2", nodeCount, int(float64(nodeCount)*float64(0.7)*float64(memAllocatableMb)), true, defaultTimeout, highPriorityClassName)
defer cleanupFunc2()
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, time.Second))
})
ginkgo.It("should scale down when expendable pod is running [Feature:ClusterSizeAutoscalingScaleDown]", func() {
defer createPriorityClasses(f)()
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
// Create increasedSize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", increasedSize, int(float64(increasedSize)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, expendablePriorityClassName)
defer cleanupFunc()
ginkgo.By("Waiting for scale down")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, scaleDownTimeout))
})
ginkgo.It("shouldn't scale down when non expendable pod is running [Feature:ClusterSizeAutoscalingScaleDown]", func() {
defer createPriorityClasses(f)()
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
// Create increasedSize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", increasedSize, int(float64(increasedSize)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, highPriorityClassName)
defer cleanupFunc()
ginkgo.By(fmt.Sprintf("Waiting for scale down hoping it won't happen, sleep for %s", scaleDownTimeout.String()))
time.Sleep(scaleDownTimeout)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == increasedSize }, time.Second))
})
})
func installNvidiaDriversDaemonSet() {
ginkgo.By("Add daemonset which installs nvidia drivers")
// the link differs from one in GKE documentation; discussed with @mindprince this one should be used
framework.RunKubectlOrDie("apply", "-f", "https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/daemonset.yaml")
}
func execCmd(args ...string) *exec.Cmd {
klog.Infof("Executing: %s", strings.Join(args, " "))
return exec.Command(args[0], args[1:]...)
}
func runDrainTest(f *framework.Framework, migSizes map[string]int, namespace string, podsPerNode, pdbSize int, verifyFunction func(int)) {
increasedSize := manuallyIncreaseClusterSize(f, migSizes)
nodes, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
numPods := len(nodes.Items) * podsPerNode
testID := string(uuid.NewUUID()) // So that we can label and find pods
labelMap := map[string]string{"test_id": testID}
framework.ExpectNoError(runReplicatedPodOnEachNode(f, nodes.Items, namespace, podsPerNode, "reschedulable-pods", labelMap, 0))
defer framework.DeleteRCAndWaitForGC(f.ClientSet, namespace, "reschedulable-pods")
ginkgo.By("Create a PodDisruptionBudget")
minAvailable := intstr.FromInt(numPods - pdbSize)
pdb := &policyv1beta1.PodDisruptionBudget{
ObjectMeta: metav1.ObjectMeta{
Name: "test_pdb",
Namespace: namespace,
},
Spec: policyv1beta1.PodDisruptionBudgetSpec{
Selector: &metav1.LabelSelector{MatchLabels: labelMap},
MinAvailable: &minAvailable,
},
}
_, err = f.ClientSet.PolicyV1beta1().PodDisruptionBudgets(namespace).Create(pdb)
defer func() {
f.ClientSet.PolicyV1beta1().PodDisruptionBudgets(namespace).Delete(pdb.Name, &metav1.DeleteOptions{})
}()
framework.ExpectNoError(err)
verifyFunction(increasedSize)
}
func getGkeAPIEndpoint() string {
gkeAPIEndpoint := os.Getenv("CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER")
if gkeAPIEndpoint == "" {
gkeAPIEndpoint = "https://test-container.sandbox.googleapis.com"
}
if strings.HasSuffix(gkeAPIEndpoint, "/") {
gkeAPIEndpoint = gkeAPIEndpoint[:len(gkeAPIEndpoint)-1]
}
return gkeAPIEndpoint
}
func getGKEURL(apiVersion string, suffix string) string {
out, err := execCmd("gcloud", "auth", "print-access-token").Output()
framework.ExpectNoError(err)
token := strings.Replace(string(out), "\n", "", -1)
return fmt.Sprintf("%s/%s/%s?access_token=%s",
getGkeAPIEndpoint(),
apiVersion,
suffix,
token)
}
func getGKEClusterURL(apiVersion string) string {
if isRegionalCluster() {
// TODO(bskiba): Use locations API for all clusters once it's graduated to v1.
return getGKEURL(apiVersion, fmt.Sprintf("projects/%s/locations/%s/clusters/%s",
framework.TestContext.CloudConfig.ProjectID,
framework.TestContext.CloudConfig.Region,
framework.TestContext.CloudConfig.Cluster))
}
return getGKEURL(apiVersion, fmt.Sprintf("projects/%s/zones/%s/clusters/%s",
framework.TestContext.CloudConfig.ProjectID,
framework.TestContext.CloudConfig.Zone,
framework.TestContext.CloudConfig.Cluster))
}
func getCluster(apiVersion string) (string, error) {
resp, err := http.Get(getGKEClusterURL(apiVersion))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("error: %s %s", resp.Status, body)
}
return string(body), nil
}
func isAutoscalerEnabled(expectedMaxNodeCountInTargetPool int) (bool, error) {
apiVersion := "v1"
if isRegionalCluster() {
apiVersion = "v1beta1"
}
strBody, err := getCluster(apiVersion)
if err != nil {
return false, err
}
if strings.Contains(strBody, "\"maxNodeCount\": "+strconv.Itoa(expectedMaxNodeCountInTargetPool)) {
return true, nil
}
return false, nil
}
func getClusterLocation() string {
if isRegionalCluster() {
return "--region=" + framework.TestContext.CloudConfig.Region
}
return "--zone=" + framework.TestContext.CloudConfig.Zone
}
func getGcloudCommandFromTrack(commandTrack string, args []string) []string {
command := []string{"gcloud"}
if commandTrack == "beta" || commandTrack == "alpha" {
command = append(command, commandTrack)
}
command = append(command, args...)
command = append(command, getClusterLocation())
command = append(command, "--project="+framework.TestContext.CloudConfig.ProjectID)
return command
}
func getGcloudCommand(args []string) []string {
track := ""
if isRegionalCluster() {
track = "beta"
}
return getGcloudCommandFromTrack(track, args)
}
func isRegionalCluster() bool {
// TODO(bskiba): Use an appropriate indicator that the cluster is regional.
return framework.TestContext.CloudConfig.MultiZone
}
func enableAutoscaler(nodePool string, minCount, maxCount int) error {
klog.Infof("Using gcloud to enable autoscaling for pool %s", nodePool)
args := []string{"container", "clusters", "update", framework.TestContext.CloudConfig.Cluster,
"--enable-autoscaling",
"--min-nodes=" + strconv.Itoa(minCount),
"--max-nodes=" + strconv.Itoa(maxCount),
"--node-pool=" + nodePool}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Errorf("Failed config update result: %s", output)
return fmt.Errorf("Failed to enable autoscaling: %v", err)
}
klog.Infof("Config update result: %s", output)
var finalErr error
for startTime := time.Now(); startTime.Add(gkeUpdateTimeout).After(time.Now()); time.Sleep(30 * time.Second) {
val, err := isAutoscalerEnabled(maxCount)
if err == nil && val {
return nil
}
finalErr = err
}
return fmt.Errorf("autoscaler not enabled, last error: %v", finalErr)
}
func disableAutoscaler(nodePool string, minCount, maxCount int) error {
klog.Infof("Using gcloud to disable autoscaling for pool %s", nodePool)
args := []string{"container", "clusters", "update", framework.TestContext.CloudConfig.Cluster,
"--no-enable-autoscaling",
"--node-pool=" + nodePool}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Errorf("Failed config update result: %s", output)
return fmt.Errorf("Failed to disable autoscaling: %v", err)
}
klog.Infof("Config update result: %s", output)
var finalErr error
for startTime := time.Now(); startTime.Add(gkeUpdateTimeout).After(time.Now()); time.Sleep(30 * time.Second) {
val, err := isAutoscalerEnabled(maxCount)
if err == nil && !val {
return nil
}
finalErr = err
}
return fmt.Errorf("autoscaler still enabled, last error: %v", finalErr)
}
func addNodePool(name string, machineType string, numNodes int) {
args := []string{"container", "node-pools", "create", name, "--quiet",
"--machine-type=" + machineType,
"--num-nodes=" + strconv.Itoa(numNodes),
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Creating node-pool %s: %s", name, output)
framework.ExpectNoError(err, string(output))
}
func addGpuNodePool(name string, gpuType string, gpuCount int, numNodes int) {
args := []string{"beta", "container", "node-pools", "create", name, "--quiet",
"--accelerator", "type=" + gpuType + ",count=" + strconv.Itoa(gpuCount),
"--num-nodes=" + strconv.Itoa(numNodes),
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Creating node-pool %s: %s", name, output)
framework.ExpectNoError(err, string(output))
}
func deleteNodePool(name string) {
klog.Infof("Deleting node pool %s", name)
args := []string{"container", "node-pools", "delete", name, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
err := wait.ExponentialBackoff(
wait.Backoff{Duration: 1 * time.Minute, Factor: float64(3), Steps: 3},
func() (bool, error) {
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Warningf("Error deleting nodegroup - error:%v, output: %s", err, output)
return false, nil
}
klog.Infof("Node-pool deletion output: %s", output)
return true, nil
})
framework.ExpectNoError(err)
}
func getPoolNodes(f *framework.Framework, poolName string) []*v1.Node {
nodes := make([]*v1.Node, 0, 1)
nodeList := framework.GetReadyNodesIncludingTaintedOrDie(f.ClientSet)
for _, node := range nodeList.Items {
if node.Labels[gkeNodepoolNameKey] == poolName {
nodes = append(nodes, &node)
}
}
return nodes
}
// getPoolInitialSize returns the initial size of the node pool taking into
// account that it may span multiple zones. In that case, node pool consists of
// multiple migs all containing initialNodeCount nodes.
func getPoolInitialSize(poolName string) int {
// get initial node count
args := []string{"container", "node-pools", "describe", poolName, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster,
"--format=value(initialNodeCount)"}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Node-pool initial size: %s", output)
framework.ExpectNoError(err, string(output))
fields := strings.Fields(string(output))
gomega.Expect(len(fields)).Should(gomega.Equal(1))
size, err := strconv.ParseInt(fields[0], 10, 64)
framework.ExpectNoError(err)
// get number of node pools
args = []string{"container", "node-pools", "describe", poolName, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster,
"--format=value(instanceGroupUrls)"}
output, err = execCmd(getGcloudCommand(args)...).CombinedOutput()
framework.ExpectNoError(err, string(output))
nodeGroupCount := len(strings.Split(string(output), ";"))
return int(size) * nodeGroupCount
}
func getPoolSize(f *framework.Framework, poolName string) int {
size := 0
nodeList := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
for _, node := range nodeList.Items {
if node.Labels[gkeNodepoolNameKey] == poolName {
size++
}
}
return size
}
func reserveMemory(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, selector map[string]string, tolerations []v1.Toleration, priorityClassName string) func() error {
ginkgo.By(fmt.Sprintf("Running RC which reserves %v MB of memory", megabytes))
request := int64(1024 * 1024 * megabytes / replicas)
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: f.Namespace.Name,
Timeout: timeout,
Image: imageutils.GetPauseImageName(),
Replicas: replicas,
MemRequest: request,
NodeSelector: selector,
Tolerations: tolerations,
PriorityClassName: priorityClassName,
}
for start := time.Now(); time.Since(start) < rcCreationRetryTimeout; time.Sleep(rcCreationRetryDelay) {
err := framework.RunRC(*config)
if err != nil && strings.Contains(err.Error(), "Error creating replication controller") {
klog.Warningf("Failed to create memory reservation: %v", err)
continue
}
if expectRunning {
framework.ExpectNoError(err)
}
return func() error {
return framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, id)
}
}
framework.Failf("Failed to reserve memory within timeout")
return nil
}
// ReserveMemoryWithPriority creates a replication controller with pods with priority that, in summation,
// request the specified amount of memory.
func ReserveMemoryWithPriority(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, priorityClassName string) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, nil, nil, priorityClassName)
}
// ReserveMemoryWithSelectorAndTolerations creates a replication controller with pods with node selector that, in summation,
// request the specified amount of memory.
func ReserveMemoryWithSelectorAndTolerations(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, selector map[string]string, tolerations []v1.Toleration) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, selector, tolerations, "")
}
// ReserveMemory creates a replication controller with pods that, in summation,
// request the specified amount of memory.
func ReserveMemory(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, nil, nil, "")
}
// WaitForClusterSizeFunc waits until the cluster size matches the given function.
func WaitForClusterSizeFunc(c clientset.Interface, sizeFunc func(int) bool, timeout time.Duration) error {
return WaitForClusterSizeFuncWithUnready(c, sizeFunc, timeout, 0)
}
// WaitForClusterSizeFuncWithUnready waits until the cluster size matches the given function and assumes some unready nodes.
func WaitForClusterSizeFuncWithUnready(c clientset.Interface, sizeFunc func(int) bool, timeout time.Duration, expectedUnready int) error {
for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
klog.Warningf("Failed to list nodes: %v", err)
continue
}
numNodes := len(nodes.Items)
// Filter out not-ready nodes.
e2enode.Filter(nodes, func(node v1.Node) bool {
return e2enode.IsConditionSetAsExpected(&node, v1.NodeReady, true)
})
numReady := len(nodes.Items)
if numNodes == numReady+expectedUnready && sizeFunc(numNodes) {
klog.Infof("Cluster has reached the desired size")
return nil
}
klog.Infof("Waiting for cluster with func, current size %d, not ready nodes %d", numNodes, numNodes-numReady)
}
return fmt.Errorf("timeout waiting %v for appropriate cluster size", timeout)
}
func waitForCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interface, tolerateUnreadyCount int) error {
var notready []string
for start := time.Now(); time.Now().Before(start.Add(scaleUpTimeout)); time.Sleep(20 * time.Second) {
pods, err := c.CoreV1().Pods(f.Namespace.Name).List(metav1.ListOptions{})
if err != nil {
return fmt.Errorf("failed to get pods: %v", err)
}
notready = make([]string, 0)
for _, pod := range pods.Items {
ready := false
for _, c := range pod.Status.Conditions {
if c.Type == v1.PodReady && c.Status == v1.ConditionTrue {
ready = true
}
}
// Failed pods in this context generally mean that they have been
// double scheduled onto a node, but then failed a constraint check.
if pod.Status.Phase == v1.PodFailed {
klog.Warningf("Pod has failed: %v", pod)
}
if !ready && pod.Status.Phase != v1.PodFailed {
notready = append(notready, pod.Name)
}
}
if len(notready) <= tolerateUnreadyCount {
klog.Infof("sufficient number of pods ready. Tolerating %d unready", tolerateUnreadyCount)
return nil
}
klog.Infof("Too many pods are not ready yet: %v", notready)
}
klog.Info("Timeout on waiting for pods being ready")
klog.Info(framework.RunKubectlOrDie("get", "pods", "-o", "json", "--all-namespaces"))
klog.Info(framework.RunKubectlOrDie("get", "nodes", "-o", "json"))
// Some pods are still not running.
return fmt.Errorf("Too many pods are still not running: %v", notready)
}
func waitForAllCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interface) error {
return waitForCaPodsReadyInNamespace(f, c, 0)
}
func getAnyNode(c clientset.Interface) *v1.Node {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
klog.Errorf("Failed to get node list: %v", err)
return nil
}
if len(nodes.Items) == 0 {
klog.Errorf("No nodes")
return nil
}
return &nodes.Items[0]
}
func setMigSizes(sizes map[string]int) bool {
madeChanges := false
for mig, desiredSize := range sizes {
currentSize, err := framework.GroupSize(mig)
framework.ExpectNoError(err)
if desiredSize != currentSize {
ginkgo.By(fmt.Sprintf("Setting size of %s to %d", mig, desiredSize))
err = framework.ResizeGroup(mig, int32(desiredSize))
framework.ExpectNoError(err)
madeChanges = true
}
}
return madeChanges
}
func drainNode(f *framework.Framework, node *v1.Node) {
ginkgo.By("Make the single node unschedulable")
makeNodeUnschedulable(f.ClientSet, node)
ginkgo.By("Manually drain the single node")
podOpts := metav1.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, node.Name).String()}
pods, err := f.ClientSet.CoreV1().Pods(metav1.NamespaceAll).List(podOpts)
framework.ExpectNoError(err)
for _, pod := range pods.Items {
err = f.ClientSet.CoreV1().Pods(pod.Namespace).Delete(pod.Name, metav1.NewDeleteOptions(0))
framework.ExpectNoError(err)
}
}
func makeNodeUnschedulable(c clientset.Interface, node *v1.Node) error {
ginkgo.By(fmt.Sprintf("Taint node %s", node.Name))
for j := 0; j < 3; j++ {
freshNode, err := c.CoreV1().Nodes().Get(node.Name, metav1.GetOptions{})
if err != nil {
return err
}
for _, taint := range freshNode.Spec.Taints {
if taint.Key == disabledTaint {
return nil
}
}
freshNode.Spec.Taints = append(freshNode.Spec.Taints, v1.Taint{
Key: disabledTaint,
Value: "DisabledForTest",
Effect: v1.TaintEffectNoSchedule,
})
_, err = c.CoreV1().Nodes().Update(freshNode)
if err == nil {
return nil
}
if !errors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to taint node, retries left: %v", 3-j)
}
return fmt.Errorf("Failed to taint node in allowed number of retries")
}
// CriticalAddonsOnlyError implements the `error` interface, and signifies the
// presence of the `CriticalAddonsOnly` taint on the node.
type CriticalAddonsOnlyError struct{}
func (CriticalAddonsOnlyError) Error() string {
return fmt.Sprintf("CriticalAddonsOnly taint found on node")
}
func makeNodeSchedulable(c clientset.Interface, node *v1.Node, failOnCriticalAddonsOnly bool) error {
ginkgo.By(fmt.Sprintf("Remove taint from node %s", node.Name))
for j := 0; j < 3; j++ {
freshNode, err := c.CoreV1().Nodes().Get(node.Name, metav1.GetOptions{})
if err != nil {
return err
}
var newTaints []v1.Taint
for _, taint := range freshNode.Spec.Taints {
if failOnCriticalAddonsOnly && taint.Key == criticalAddonsOnlyTaint {
return CriticalAddonsOnlyError{}
}
if taint.Key != disabledTaint {
newTaints = append(newTaints, taint)
}
}
if len(newTaints) == len(freshNode.Spec.Taints) {
return nil
}
freshNode.Spec.Taints = newTaints
_, err = c.CoreV1().Nodes().Update(freshNode)
if err == nil {
return nil
}
if !errors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to taint node, retries left: %v", 3-j)
}
return fmt.Errorf("Failed to remove taint from node in allowed number of retries")
}
// ScheduleAnySingleGpuPod schedules a pod which requires single GPU of any type
func ScheduleAnySingleGpuPod(f *framework.Framework, id string) error {
return ScheduleGpuPod(f, id, "", 1)
}
// ScheduleGpuPod schedules a pod which requires a given number of gpus of given type
func ScheduleGpuPod(f *framework.Framework, id string, gpuType string, gpuLimit int64) error {
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: f.Namespace.Name,
Timeout: 3 * scaleUpTimeout, // spinning up GPU node is slow
Image: imageutils.GetPauseImageName(),
Replicas: 1,
GpuLimit: gpuLimit,
Labels: map[string]string{"requires-gpu": "yes"},
}
if gpuType != "" {
config.NodeSelector = map[string]string{gpuLabel: gpuType}
}
err := framework.RunRC(*config)
if err != nil {
return err
}
return nil
}
// Create an RC running a given number of pods with anti-affinity
func runAntiAffinityPods(f *framework.Framework, namespace string, pods int, id string, podLabels, antiAffinityLabels map[string]string) error {
config := &testutils.RCConfig{
Affinity: buildAntiAffinity(antiAffinityLabels),
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: scaleUpTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: pods,
Labels: podLabels,
}
err := framework.RunRC(*config)
if err != nil {
return err
}
_, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(id, metav1.GetOptions{})
if err != nil {
return err
}
return nil
}
func runVolumeAntiAffinityPods(f *framework.Framework, namespace string, pods int, id string, podLabels, antiAffinityLabels map[string]string, volumes []v1.Volume) error {
config := &testutils.RCConfig{
Affinity: buildAntiAffinity(antiAffinityLabels),
Volumes: volumes,
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: scaleUpTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: pods,
Labels: podLabels,
}
err := framework.RunRC(*config)
if err != nil {
return err
}
_, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(id, metav1.GetOptions{})
if err != nil {
return err
}
return nil
}
var emptyDirVolumes = []v1.Volume{
{
Name: "empty-volume",
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
},
}
func buildVolumes(pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim) []v1.Volume {
return []v1.Volume{
{
Name: pv.Name,
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: pvc.Name,
ReadOnly: false,
},
},
},
}
}
func buildAntiAffinity(labels map[string]string) *v1.Affinity {
return &v1.Affinity{
PodAntiAffinity: &v1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchLabels: labels,
},
TopologyKey: "kubernetes.io/hostname",
},
},
},
}
}
// Create an RC running a given number of pods on each node without adding any constraint forcing
// such pod distribution. This is meant to create a bunch of underutilized (but not unused) nodes
// with pods that can be rescheduled on different nodes.
// This is achieved using the following method:
// 1. disable scheduling on each node
// 2. create an empty RC
// 3. for each node:
// 3a. enable scheduling on that node
// 3b. increase number of replicas in RC by podsPerNode
func runReplicatedPodOnEachNode(f *framework.Framework, nodes []v1.Node, namespace string, podsPerNode int, id string, labels map[string]string, memRequest int64) error {
ginkgo.By("Run a pod on each node")
for _, node := range nodes {
err := makeNodeUnschedulable(f.ClientSet, &node)
defer func(n v1.Node) {
makeNodeSchedulable(f.ClientSet, &n, false)
}(node)
if err != nil {
return err
}
}
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: defaultTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: 0,
Labels: labels,
MemRequest: memRequest,
}
err := framework.RunRC(*config)
if err != nil {
return err
}
rc, err := f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(id, metav1.GetOptions{})
if err != nil {
return err
}
for i, node := range nodes {
err = makeNodeSchedulable(f.ClientSet, &node, false)
if err != nil {
return err
}
// Update replicas count, to create new pods that will be allocated on node
// (we retry 409 errors in case rc reference got out of sync)
for j := 0; j < 3; j++ {
*rc.Spec.Replicas = int32((i + 1) * podsPerNode)
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Update(rc)
if err == nil {
break
}
if !errors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to scale RC, retries left: %v", 3-j)
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(id, metav1.GetOptions{})
if err != nil {
return err
}
}
err = wait.PollImmediate(5*time.Second, podTimeout, func() (bool, error) {
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(id, metav1.GetOptions{})
if err != nil || rc.Status.ReadyReplicas < int32((i+1)*podsPerNode) {
return false, nil
}
return true, nil
})
if err != nil {
return fmt.Errorf("failed to coerce RC into spawning a pod on node %s within timeout", node.Name)
}
err = makeNodeUnschedulable(f.ClientSet, &node)
if err != nil {
return err
}
}
return nil
}
// Increase cluster size by newNodesForScaledownTests to create some unused nodes
// that can be later removed by cluster autoscaler.
func manuallyIncreaseClusterSize(f *framework.Framework, originalSizes map[string]int) int {
ginkgo.By("Manually increase cluster size")
increasedSize := 0
newSizes := make(map[string]int)
for key, val := range originalSizes {
newSizes[key] = val + newNodesForScaledownTests
increasedSize += val + newNodesForScaledownTests
}
setMigSizes(newSizes)
checkClusterSize := func(size int) bool {
if size >= increasedSize {
return true
}
resized := setMigSizes(newSizes)
if resized {
klog.Warning("Unexpected node group size while waiting for cluster resize. Setting size to target again.")
}
return false
}
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet, checkClusterSize, manualResizeTimeout))
return increasedSize
}
// Try to get clusterwide health from CA status configmap.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getClusterwideStatus(c clientset.Interface) (string, error) {
configMap, err := c.CoreV1().ConfigMaps("kube-system").Get("cluster-autoscaler-status", metav1.GetOptions{})
if err != nil {
return "", err
}
status, ok := configMap.Data["status"]
if !ok {
return "", fmt.Errorf("Status information not found in configmap")
}
matcher, err := regexp.Compile("Cluster-wide:\\s*\n\\s*Health:\\s*([A-Za-z]+)")
if err != nil {
return "", err
}
result := matcher.FindStringSubmatch(status)
if len(result) < 2 {
return "", fmt.Errorf("Failed to parse CA status configmap, raw status: %v", status)
}
return result[1], nil
}
type scaleUpStatus struct {
status string
ready int
target int
timestamp time.Time
}
// Try to get timestamp from status.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getStatusTimestamp(status string) (time.Time, error) {
timestampMatcher, err := regexp.Compile("Cluster-autoscaler status at \\s*([0-9\\-]+ [0-9]+:[0-9]+:[0-9]+\\.[0-9]+ \\+[0-9]+ [A-Za-z]+)")
if err != nil {
return time.Time{}, err
}
timestampMatch := timestampMatcher.FindStringSubmatch(status)
if len(timestampMatch) < 2 {
return time.Time{}, fmt.Errorf("Failed to parse CA status timestamp, raw status: %v", status)
}
timestamp, err := time.Parse(timestampFormat, timestampMatch[1])
if err != nil {
return time.Time{}, err
}
return timestamp, nil
}
// Try to get scaleup statuses of all node groups.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getScaleUpStatus(c clientset.Interface) (*scaleUpStatus, error) {
configMap, err := c.CoreV1().ConfigMaps("kube-system").Get("cluster-autoscaler-status", metav1.GetOptions{})
if err != nil {
return nil, err
}
status, ok := configMap.Data["status"]
if !ok {
return nil, fmt.Errorf("Status information not found in configmap")
}
timestamp, err := getStatusTimestamp(status)
if err != nil {
return nil, err
}
matcher, err := regexp.Compile("s*ScaleUp:\\s*([A-Za-z]+)\\s*\\(ready=([0-9]+)\\s*cloudProviderTarget=([0-9]+)\\s*\\)")
if err != nil {
return nil, err
}
matches := matcher.FindAllStringSubmatch(status, -1)
if len(matches) < 1 {
return nil, fmt.Errorf("Failed to parse CA status configmap, raw status: %v", status)
}
result := scaleUpStatus{
status: caNoScaleUpStatus,
ready: 0,
target: 0,
timestamp: timestamp,
}
for _, match := range matches {
if match[1] == caOngoingScaleUpStatus {
result.status = caOngoingScaleUpStatus
}
newReady, err := strconv.Atoi(match[2])
if err != nil {
return nil, err
}
result.ready += newReady
newTarget, err := strconv.Atoi(match[3])
if err != nil {
return nil, err
}
result.target += newTarget
}
klog.Infof("Cluster-Autoscaler scale-up status: %v (%v, %v)", result.status, result.ready, result.target)
return &result, nil
}
func waitForScaleUpStatus(c clientset.Interface, cond func(s *scaleUpStatus) bool, timeout time.Duration) (*scaleUpStatus, error) {
var finalErr error
var status *scaleUpStatus
err := wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {
status, finalErr = getScaleUpStatus(c)
if finalErr != nil {
return false, nil
}
if status.timestamp.Add(freshStatusLimit).Before(time.Now()) {
// stale status
finalErr = fmt.Errorf("Status too old")
return false, nil
}
return cond(status), nil
})
if err != nil {
err = fmt.Errorf("Failed to find expected scale up status: %v, last status: %v, final err: %v", err, status, finalErr)
}
return status, err
}
// This is a temporary fix to allow CA to migrate some kube-system pods
// TODO: Remove this when the PDB is added for some of those components
func addKubeSystemPdbs(f *framework.Framework) (func(), error) {
ginkgo.By("Create PodDisruptionBudgets for kube-system components, so they can be migrated if required")
var newPdbs []string
cleanup := func() {
var finalErr error
for _, newPdbName := range newPdbs {
ginkgo.By(fmt.Sprintf("Delete PodDisruptionBudget %v", newPdbName))
err := f.ClientSet.PolicyV1beta1().PodDisruptionBudgets("kube-system").Delete(newPdbName, &metav1.DeleteOptions{})
if err != nil {
// log error, but attempt to remove other pdbs
klog.Errorf("Failed to delete PodDisruptionBudget %v, err: %v", newPdbName, err)
finalErr = err
}
}
if finalErr != nil {
framework.Failf("Error during PodDisruptionBudget cleanup: %v", finalErr)
}
}
type pdbInfo struct {
label string
minAvailable int
}
pdbsToAdd := []pdbInfo{
{label: "kube-dns", minAvailable: 1},
{label: "kube-dns-autoscaler", minAvailable: 0},
{label: "metrics-server", minAvailable: 0},
{label: "kubernetes-dashboard", minAvailable: 0},
{label: "glbc", minAvailable: 0},
}
for _, pdbData := range pdbsToAdd {
ginkgo.By(fmt.Sprintf("Create PodDisruptionBudget for %v", pdbData.label))
labelMap := map[string]string{"k8s-app": pdbData.label}
pdbName := fmt.Sprintf("test-pdb-for-%v", pdbData.label)
minAvailable := intstr.FromInt(pdbData.minAvailable)
pdb := &policyv1beta1.PodDisruptionBudget{
ObjectMeta: metav1.ObjectMeta{
Name: pdbName,
Namespace: "kube-system",
},
Spec: policyv1beta1.PodDisruptionBudgetSpec{
Selector: &metav1.LabelSelector{MatchLabels: labelMap},
MinAvailable: &minAvailable,
},
}
_, err := f.ClientSet.PolicyV1beta1().PodDisruptionBudgets("kube-system").Create(pdb)
newPdbs = append(newPdbs, pdbName)
if err != nil {
return cleanup, err
}
}
return cleanup, nil
}
func createPriorityClasses(f *framework.Framework) func() {
priorityClasses := map[string]int32{
expendablePriorityClassName: -15,
highPriorityClassName: 1000,
}
for className, priority := range priorityClasses {
_, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(&schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: className}, Value: priority})
if err != nil {
klog.Errorf("Error creating priority class: %v", err)
}
gomega.Expect(err == nil || errors.IsAlreadyExists(err)).To(gomega.Equal(true))
}
return func() {
for className := range priorityClasses {
err := f.ClientSet.SchedulingV1().PriorityClasses().Delete(className, nil)
if err != nil {
klog.Errorf("Error deleting priority class: %v", err)
}
}
}
}
|
[
"\"TESTED_GPU_TYPE\"",
"\"CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER\""
] |
[] |
[
"CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER",
"TESTED_GPU_TYPE"
] |
[]
|
["CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER", "TESTED_GPU_TYPE"]
|
go
| 2 | 0 | |
operations/patch_util.go
|
package operations
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"text/template"
"time"
"github.com/evergreen-ci/evergreen/model"
"github.com/evergreen-ci/evergreen/model/patch"
"github.com/evergreen-ci/evergreen/rest/client"
restmodel "github.com/evergreen-ci/evergreen/rest/model"
"github.com/evergreen-ci/utility"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
"github.com/pkg/errors"
)
// Above this size, the user must explicitly use --large to submit the patch (or confirm)
const largePatchThreshold = 1024 * 1024 * 16
// This is the template used to render a patch's summary in a human-readable output format.
var patchDisplayTemplate = template.Must(template.New("patch").Parse(`
ID : {{.Patch.Id.Hex}}
Created : {{.Patch.CreateTime}}
Description : {{if .Patch.Description}}{{.Patch.Description}}{{else}}<none>{{end}}
Build : {{.Link}}
Status : {{.Patch.Status}}
{{if .ShowFinalized}} Finalized : {{if .Patch.Activated}}Yes{{else}}No{{end}}{{end}}
{{if .ShowSummary}}
Summary :
{{range .Patch.Patches}}{{if not (eq .ModuleName "") }}Module:{{.ModuleName}}{{end}}
Base Commit : {{.Githash}}
{{range .PatchSet.Summary}}+{{.Additions}} -{{.Deletions}} {{.Name}}
{{end}}
{{end}}
{{end}}
`))
type localDiff struct {
fullPatch string
patchSummary string
log string
base string
}
type patchParams struct {
Project string
Alias string
Variants []string
Tasks []string
SyncBuildVariants []string
SyncTasks []string
SyncStatuses []string
SyncTimeout time.Duration
Description string
SkipConfirm bool
Finalize bool
Browse bool
Large bool
ShowSummary bool
Uncommitted bool
PreserveCommits bool
Ref string
BackportOf patch.BackportInfo
TriggerAliases []string
Parameters []patch.Parameter
}
type patchSubmission struct {
projectName string
patchData string
description string
base string
alias string
variants []string
tasks []string
syncBuildVariants []string
syncTasks []string
syncStatuses []string
syncTimeout time.Duration
finalize bool
parameters []patch.Parameter
triggerAliases []string
backportOf patch.BackportInfo
}
func (p *patchParams) createPatch(ac *legacyClient, diffData *localDiff) (*patch.Patch, error) {
patchSub := patchSubmission{
projectName: p.Project,
patchData: diffData.fullPatch,
description: p.Description,
base: diffData.base,
variants: p.Variants,
tasks: p.Tasks,
alias: p.Alias,
syncBuildVariants: p.SyncBuildVariants,
syncTasks: p.SyncTasks,
syncStatuses: p.SyncStatuses,
syncTimeout: p.SyncTimeout,
finalize: p.Finalize,
backportOf: p.BackportOf,
parameters: p.Parameters,
triggerAliases: p.TriggerAliases,
}
newPatch, err := ac.PutPatch(patchSub)
if err != nil {
return nil, err
}
return newPatch, nil
}
func (p *patchParams) validateSubmission(diffData *localDiff) error {
if err := validatePatchSize(diffData, p.Large); err != nil {
return err
}
if !p.SkipConfirm && len(diffData.fullPatch) == 0 {
if !confirm("Patch submission is empty. Continue? (y/n)", true) {
return errors.New("patch aborted")
}
} else if !p.SkipConfirm && diffData.patchSummary != "" {
grip.Info(diffData.patchSummary)
if diffData.log != "" {
grip.Info(diffData.log)
}
if !confirm("This is a summary of the patch to be submitted. Continue? (y/n):", true) {
return errors.New("patch aborted")
}
}
return nil
}
func (p *patchParams) displayPatch(conf *ClientSettings, newPatch *patch.Patch) error {
patchDisp, err := getPatchDisplay(newPatch, p.ShowSummary, conf.UIServerHost)
if err != nil {
return err
}
grip.Info("Patch successfully created.")
grip.Info(patchDisp)
if p.Browse {
browserCmd, err := findBrowserCommand()
if err != nil || len(browserCmd) == 0 {
grip.Warningf("cannot find browser command: %s", err)
return nil
}
browserCmd = append(browserCmd, newPatch.GetURL(conf.UIServerHost))
cmd := exec.Command(browserCmd[0], browserCmd[1:]...)
return cmd.Run()
}
return nil
}
func findBrowserCommand() ([]string, error) {
browser := os.Getenv("BROWSER")
if browser != "" {
return []string{browser}, nil
}
switch runtime.GOOS {
case "darwin":
return []string{"open"}, nil
case "windows":
return []string{"cmd", "/c", "start"}, nil
default:
candidates := []string{"xdg-open", "gnome-open", "x-www-browser", "firefox",
"opera", "mozilla", "netscape"}
for _, b := range candidates {
path, err := exec.LookPath(b)
if err == nil {
return []string{path}, nil
}
}
}
return nil, errors.New("unable to find a web browser, try setting $BROWSER")
}
// Performs validation for patch or patch-file
func (p *patchParams) validatePatchCommand(ctx context.Context, conf *ClientSettings, ac *legacyClient, comm client.Communicator) (*model.ProjectRef, error) {
if err := p.loadProject(conf); err != nil {
grip.Warningf("warning - failed to set default project: %v\n", err)
}
if err := p.loadAlias(conf); err != nil {
grip.Warningf("warning - failed to set default alias: %v\n", err)
}
if err := p.loadVariants(conf); err != nil {
grip.Warningf("warning - failed to set default variants: %v\n", err)
}
if err := p.loadTasks(conf); err != nil {
grip.Warningf("warning - failed to set default tasks: %v\n", err)
}
if err := p.loadParameters(conf); err != nil {
grip.Warningf("warning - failed to set default parameters: %v\n", err)
}
if err := p.loadTriggerAliases(conf); err != nil {
grip.Warningf("warning - failed to set default trigger aliases: %v\n", err)
}
if p.Uncommitted || conf.UncommittedChanges {
p.Ref = ""
}
// Validate the project exists
ref, err := ac.GetProjectRef(p.Project)
if err != nil {
if apiErr, ok := err.(APIError); ok && apiErr.code == http.StatusNotFound {
err = errors.Errorf("%s \nRun `evergreen list --projects` to see all valid projects", err)
}
return nil, err
}
// Validate the alias exists
if p.Alias != "" {
validAlias := false
aliases, err := comm.ListAliases(ctx, ref.Id)
if err != nil {
return nil, errors.Wrap(err, "error contacting API server")
}
for _, alias := range aliases {
if alias.Alias == p.Alias {
validAlias = true
break
}
}
if !validAlias {
return nil, errors.Errorf("%s is not a valid alias", p.Alias)
}
}
// Validate trigger aliases exist
if len(p.TriggerAliases) > 0 {
validTriggerAliases, err := comm.ListPatchTriggerAliases(ctx, p.Project)
if err != nil {
return nil, errors.Wrap(err, "error fetching trigger aliases")
}
for _, alias := range p.TriggerAliases {
if !utility.StringSliceContains(validTriggerAliases, alias) {
return nil, errors.Errorf("Trigger alias '%s' is not defined for project '%s'. Valid aliases are %v", alias, p.Project, validTriggerAliases)
}
}
}
if (len(p.Tasks) == 0 || len(p.Variants) == 0) && p.Alias == "" && p.Finalize {
return ref, errors.Errorf("Need to specify at least one task/variant or alias when finalizing.")
}
return ref, nil
}
func (p *patchParams) loadProject(conf *ClientSettings) error {
if p.Project == "" {
p.Project = conf.FindDefaultProject()
} else {
if conf.FindDefaultProject() == "" &&
!p.SkipConfirm && confirm(fmt.Sprintf("Make %s your default project?", p.Project), true) {
conf.SetDefaultProject(p.Project)
if err := conf.Write(""); err != nil {
grip.Warning(message.WrapError(err, message.Fields{
"message": "failed to set default project",
"project": p.Project,
}))
}
}
}
if p.Project == "" {
return errors.New("Need to specify a project")
}
return nil
}
// Sets the patch's alias to either the passed in option or the default
func (p *patchParams) loadAlias(conf *ClientSettings) error {
// If somebody passed an --alias
if p.Alias != "" {
// Check if there's an alias as the default, and if not, ask to save the cl one
defaultAlias := conf.FindDefaultAlias(p.Project)
if defaultAlias == "" && !p.SkipConfirm &&
confirm(fmt.Sprintf("Set %v as the default alias for project '%v'?",
p.Alias, p.Project), false) {
conf.SetDefaultAlias(p.Project, p.Alias)
if err := conf.Write(""); err != nil {
return err
}
}
} else if len(p.Variants) == 0 || len(p.Tasks) == 0 {
// No --alias or variant/task pair was passed, use the default
p.Alias = conf.FindDefaultAlias(p.Project)
}
return nil
}
func (p *patchParams) loadVariants(conf *ClientSettings) error {
if len(p.Variants) != 0 {
defaultVariants := conf.FindDefaultVariants(p.Project)
if len(defaultVariants) == 0 && !p.SkipConfirm &&
confirm(fmt.Sprintf("Set %v as the default variants for project '%v'?",
p.Variants, p.Project), false) {
conf.SetDefaultVariants(p.Project, p.Variants...)
if err := conf.Write(""); err != nil {
return err
}
}
} else if p.Alias == "" {
p.Variants = conf.FindDefaultVariants(p.Project)
}
return nil
}
func (p *patchParams) loadParameters(conf *ClientSettings) error {
defaultParameters := conf.FindDefaultParameters(p.Project)
if len(p.Parameters) != 0 {
if len(defaultParameters) == 0 && !p.SkipConfirm &&
confirm(fmt.Sprintf("Set %v as the default parameters for project '%v'?",
p.Parameters, p.Project), false) {
conf.SetDefaultParameters(p.Project, p.Parameters)
if err := conf.Write(""); err != nil {
return err
}
}
} else {
p.Parameters = defaultParameters
}
return nil
}
func (p *patchParams) loadTriggerAliases(conf *ClientSettings) error {
defaultAliases := conf.FindDefaultTriggerAliases(p.Project)
if len(p.TriggerAliases) != 0 {
if len(defaultAliases) == 0 && !p.SkipConfirm &&
confirm(fmt.Sprintf("Set %v as the default trigger aliases for project '%v'?",
p.TriggerAliases, p.Project), false) {
conf.SetDefaultTriggerAliases(p.Project, p.TriggerAliases)
if err := conf.Write(""); err != nil {
return err
}
}
} else {
p.TriggerAliases = defaultAliases
}
return nil
}
func (p *patchParams) loadTasks(conf *ClientSettings) error {
if len(p.Tasks) != 0 {
defaultTasks := conf.FindDefaultTasks(p.Project)
if len(defaultTasks) == 0 && !p.SkipConfirm &&
confirm(fmt.Sprintf("Set %v as the default tasks for project '%v'?",
p.Tasks, p.Project), false) {
conf.SetDefaultTasks(p.Project, p.Tasks...)
if err := conf.Write(""); err != nil {
return err
}
}
} else if p.Alias == "" {
p.Tasks = conf.FindDefaultTasks(p.Project)
}
return nil
}
func (p *patchParams) getDescription() string {
if p.Description != "" {
return p.Description
}
description := ""
if !p.SkipConfirm {
description = prompt("Enter a description for this patch (optional):")
}
if description == "" {
var err error
description, err = getDefaultDescription()
if err != nil {
grip.Error(err)
}
}
return description
}
// Returns an error if the diff is greater than the system limit, or if it's above the large
// patch threhsold and allowLarge is not set.
func validatePatchSize(diff *localDiff, allowLarge bool) error {
patchLen := len(diff.fullPatch)
if patchLen > patch.SizeLimit {
return errors.Errorf("Patch is greater than the system limit (%v > %v bytes).", patchLen, patch.SizeLimit)
} else if patchLen > largePatchThreshold && !allowLarge {
return errors.Errorf("Patch is larger than the default threshold (%v > %v bytes).\n"+
"To allow submitting this patch, use the --large flag.", patchLen, largePatchThreshold)
}
// Patch is small enough and/or allowLarge is true, so no error
return nil
}
// getPatchDisplay returns a human-readable summary representation of a patch object
// which can be written to the terminal.
func getPatchDisplay(p *patch.Patch, summarize bool, uiHost string) (string, error) {
var out bytes.Buffer
err := patchDisplayTemplate.Execute(&out, struct {
Patch *patch.Patch
ShowSummary bool
ShowFinalized bool
Link string
}{
Patch: p,
ShowSummary: summarize,
ShowFinalized: p.IsCommitQueuePatch(),
Link: p.GetURL(uiHost),
})
if err != nil {
return "", err
}
return out.String(), nil
}
func getAPIPatchDisplay(apiPatch *restmodel.APIPatch, summarize bool, uiHost string) (string, error) {
servicePatchIface, err := apiPatch.ToService()
if err != nil {
return "", errors.Wrap(err, "can't convert patch to service")
}
servicePatch, ok := servicePatchIface.(patch.Patch)
if !ok {
return "", errors.New("service patch is not a Patch")
}
return getPatchDisplay(&servicePatch, summarize, uiHost)
}
func isCommitRange(commits string) bool {
return strings.Contains(commits, "..")
}
func formatCommitRange(commits string) string {
if commits == "" {
return commits
}
if isCommitRange(commits) {
return commits
}
return fmt.Sprintf("%s^!", commits)
}
func getFeatureBranch(ref, commits string) string {
if ref != "" {
return ref
}
if commits != "" {
// if one commit, this returns just that commit, else the first commit in the range
return strings.Split(commits, "..")[0]
}
return "HEAD"
}
func isValidCommitsFormat(commits string) error {
errToReturn := errors.New("Invalid commit format: verify input is of the form `<hash1> OR `<hash1>..<hash2>` (where hash1 is an ancestor of hash2)")
if commits == "" || !isCommitRange(commits) {
return nil
}
commitsList := strings.Split(commits, "..")
if len(commitsList) != 2 { // extra check
return errToReturn
}
if _, err := gitIsAncestor(commitsList[0], strings.Trim(commitsList[1], ".")); err != nil {
// suppressing given error bc it's not helpful
return errToReturn
}
return nil
}
func confirmUncommittedChanges(preserveCommits, includeUncommitedChanges bool) (bool, error) {
uncommittedChanges, err := gitUncommittedChanges()
if err != nil {
return false, errors.Wrap(err, "can't test for uncommitted changes")
}
if !uncommittedChanges {
return true, nil
}
if preserveCommits {
return confirm("Uncommitted changes are omitted from patches when commits are preserved. Continue? (y/N)", false), nil
}
if !includeUncommitedChanges {
return confirm(fmt.Sprintf(`Uncommitted changes are omitted from patches by default.
Use the '--%s, -u' flag or set 'patch_uncommitted_changes: true' in your ~/.evergreen.yml file to include uncommitted changes.
Continue? (Y/n)`, uncommittedChangesFlag), true), nil
}
return true, nil
}
// loadGitData inspects the current git working directory and returns a patch and its summary.
// The branch argument is used to determine where to generate the merge base from, and any extra
// arguments supplied are passed directly in as additional args to git diff.
func loadGitData(branch, ref, commits string, format bool, extraArgs ...string) (*localDiff, error) {
// branch@{upstream} refers to the branch that the branch specified by branchname is set to
// build on top of. This allows automatically detecting a branch based on the correct remote,
// if the user's repo is a fork, for example. This also works with a commit hash, if given.
// In the case a range is passed, we only need one commit to determine the base, so we use the first commit.
// For details see: https://git-scm.com/docs/gitrevisions
mergeBase, err := gitMergeBase(branch+"@{upstream}", ref, commits)
if err != nil {
return nil, errors.Wrap(err, "Error getting merge base")
}
statArgs := []string{"--stat"}
if len(extraArgs) > 0 {
statArgs = append(statArgs, extraArgs...)
}
stat, err := gitDiff(mergeBase, ref, commits, statArgs...)
if err != nil {
return nil, errors.Wrap(err, "Error getting diff summary")
}
log, err := gitLog(mergeBase, ref, commits)
if err != nil {
return nil, errors.Wrap(err, "git log")
}
var fullPatch string
if format {
fullPatch, err = gitFormatPatch(mergeBase, ref, commits)
if err != nil {
return nil, errors.Wrap(err, "Error getting formatted patch")
}
} else {
if !utility.StringSliceContains(extraArgs, "--binary") {
extraArgs = append(extraArgs, "--binary")
}
fullPatch, err = gitDiff(mergeBase, ref, commits, extraArgs...)
if err != nil {
return nil, errors.Wrap(err, "Error getting patch")
}
}
return &localDiff{fullPatch, stat, log, mergeBase}, nil
}
// gitMergeBase runs "git merge-base <branch1> <branch2>" (where branch2 can optionally be a githash)
// and returns the resulting githash as string
func gitMergeBase(branch1, ref, commits string) (string, error) {
branch2 := getFeatureBranch(ref, commits)
cmd := exec.Command("git", "merge-base", branch1, branch2)
out, err := cmd.CombinedOutput()
if err != nil {
return "", errors.Wrapf(err, "'git merge-base %s %s' failed: %s (%s)", branch1, branch2, out, err)
}
return strings.TrimSpace(string(out)), err
}
func gitIsAncestor(commit1, commit2 string) (string, error) {
args := []string{"--is-ancestor", commit1, commit2}
return gitCmd("merge-base", args...)
}
// gitDiff runs "git diff <base> <ref> <commits> <diffargs ...>" and returns the output of the command as a string,
// where ref and commits are mutually exclusive (and not required)
func gitDiff(base string, ref, commits string, diffArgs ...string) (string, error) {
args := []string{base}
if commits != "" {
args = []string{formatCommitRange(commits)}
}
if ref != "" {
args = append(args, ref)
}
args = append(args, "--no-ext-diff")
args = append(args, diffArgs...)
return gitCmd("diff", args...)
}
func gitFormatPatch(base string, ref, commits string) (string, error) {
revisionRange := fmt.Sprintf("%s..%s", base, ref)
if commits != "" {
revisionRange = formatCommitRange(commits)
}
return gitCmd("format-patch", "--keep-subject", "--no-signature", "--stdout", "--no-ext-diff", "--binary", revisionRange)
}
// getLog runs "git log <base>...<ref> or uses the commit range given
func gitLog(base, ref, commits string) (string, error) {
revisionRange := fmt.Sprintf("%s...%s", base, ref)
if commits != "" {
revisionRange = formatCommitRange(commits)
}
return gitCmd("log", revisionRange, "--oneline")
}
func gitCommitMessages(base, ref, commits string) (string, error) {
input := fmt.Sprintf("%s@{upstream}..%s", base, ref)
if commits != "" {
input = formatCommitRange(commits)
}
args := []string{"--no-show-signature", "--pretty=format:%s", "--reverse", input}
msg, err := gitCmd("log", args...)
if err != nil {
return "", errors.Wrap(err, "can't get messages")
}
// separate multiple commits with <-
msg = strings.TrimSpace(msg)
msg = strings.Replace(msg, "\n", " <- ", -1)
return msg, nil
}
// assumes base includes @{upstream}
func gitLastCommitMessage() (string, error) {
args := []string{"HEAD", "--no-show-signature", "--pretty=format:%s", "-n 1"}
return gitCmd("log", args...)
}
func gitBranch() (string, error) {
args := []string{"--abbrev-ref", "HEAD"}
return gitCmd("rev-parse", args...)
}
func getDefaultDescription() (string, error) {
desc, err := gitLastCommitMessage()
if err != nil {
return "", errors.Wrap(err, "Couldn't get last commit message")
}
branch, err := gitBranch()
if err != nil {
return "", errors.Wrap(err, "Couldn't get branch name")
}
branch = strings.TrimSpace(branch)
if strings.HasPrefix(desc, branch) {
return desc, nil
}
return fmt.Sprintf("%s: %s", branch, desc), nil
}
func gitCommitCount(base, ref, commits string) (int, error) {
input := fmt.Sprintf("%s@{upstream}..%s", base, ref)
if commits != "" {
input = formatCommitRange(commits)
}
out, err := gitCmd("rev-list", input, "--count")
if err != nil {
return 0, errors.Wrap(err, "can't get commit count")
}
count, err := strconv.Atoi(strings.TrimSpace(out))
if err != nil {
return 0, errors.Wrapf(err, "'%s' is not an integer", out)
}
return count, nil
}
func gitUncommittedChanges() (bool, error) {
args := "--porcelain"
out, err := gitCmd("status", args)
if err != nil {
return false, errors.Wrap(err, "can't run git status")
}
return len(out) != 0, nil
}
func diffToMbox(diffData *localDiff, subject string) (string, error) {
if len(diffData.fullPatch) == 0 {
return "", nil
}
metadata, err := getGitConfigMetadata()
if err != nil {
grip.Error(errors.Wrap(err, "Problem getting git metadata. Patch will be ineligible to be enqueued on the commit queue."))
return diffData.fullPatch, nil
}
metadata.Subject = subject
return addMetadataToDiff(diffData, metadata)
}
func addMetadataToDiff(diffData *localDiff, metadata GitMetadata) (string, error) {
mboxTemplate := template.Must(template.New("mbox").Parse(`From 72899681697bc4c45b1dae2c97c62e2e7e5d597b Mon Sep 17 00:00:00 2001
From: {{.Metadata.Username}} <{{.Metadata.Email}}>
Date: {{.Metadata.CurrentTime}}
Subject: {{.Metadata.Subject}}
---
{{.DiffStat}}
{{.DiffContent}}
--
{{.Metadata.GitVersion}}
`))
out := bytes.Buffer{}
err := mboxTemplate.Execute(&out, struct {
Metadata GitMetadata
DiffStat string
DiffContent string
}{
Metadata: metadata,
DiffStat: diffData.log,
DiffContent: diffData.fullPatch,
})
if err != nil {
return "", errors.Wrap(err, "problem executing mbox template")
}
return out.String(), nil
}
type GitMetadata struct {
Username string
Email string
CurrentTime string
GitVersion string
Subject string
}
func getGitConfigMetadata() (GitMetadata, error) {
var err error
metadata := GitMetadata{}
username, err := gitCmd("config", "user.name")
if err != nil {
return metadata, errors.Wrap(err, "can't get git user.name")
}
metadata.Username = strings.TrimSpace(username)
email, err := gitCmd("config", "user.email")
if err != nil {
return metadata, errors.Wrap(err, "can't get git user.email")
}
metadata.Email = strings.TrimSpace(email)
metadata.CurrentTime = time.Now().Format(time.RFC1123Z)
// We need just the version number, but git gives it as part of a larger string.
// Parse the version number out of the version string.
versionString, err := gitCmd("version")
if err != nil {
return metadata, errors.Wrap(err, "can't get git version")
}
versionString = strings.TrimSpace(versionString)
metadata.GitVersion, err = parseGitVersion(versionString)
if err != nil {
return metadata, errors.Wrap(err, "can't get git version")
}
return metadata, nil
}
func parseGitVersion(version string) (string, error) {
matches := regexp.MustCompile(`^git version ` +
// capture the version major.minor(.patch(.build(.etc...)))
`(\w+(?:\.\w+)+)` +
// match and discard Apple git's addition to the version string
`(?: \(Apple Git-[\w\.]+\))?$`,
).FindStringSubmatch(version)
if len(matches) != 2 {
return "", errors.Errorf("can't parse git version number from version string '%s'", version)
}
return matches[1], nil
}
func gitCmd(cmdName string, gitArgs ...string) (string, error) {
args := make([]string, 0, 1+len(gitArgs))
args = append(args, cmdName)
args = append(args, gitArgs...)
cmd := exec.Command("git", args...)
out, err := cmd.CombinedOutput()
if err != nil {
return "", errors.Errorf("'git %s' failed with err %s", strings.Join(args, " "), err)
}
return string(out), nil
}
|
[
"\"BROWSER\""
] |
[] |
[
"BROWSER"
] |
[]
|
["BROWSER"]
|
go
| 1 | 0 | |
cli/diagnose_cmd.go
|
/*
* Copyright (c) 2021 Michael Morris. All Rights Reserved.
*
* Licensed under the MIT license (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* https://github.com/mmmorris1975/aws-runas/blob/master/LICENSE
*
* 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.
*/
package cli
import (
"context"
"encoding/binary"
"fmt"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/mmmorris1975/aws-runas/config"
"github.com/urfave/cli/v2"
"gopkg.in/ini.v1"
"math"
"net"
"net/http"
"os"
"strings"
"time"
)
const diagDesc = `Check the configuration of the given 'profile_name' argument to see if there are
any inconsistencies which may prevent the program from functioning properly.`
var diagCmd = &cli.Command{
Name: "diagnose",
Aliases: []string{"diag"},
Usage: diagFlag.Usage,
ArgsUsage: "[profile_name]",
Description: diagDesc,
BashComplete: bashCompleteProfile,
Action: func(ctx *cli.Context) error {
log.Debug("Diagnostics")
_, cfg, err := resolveConfig(ctx, 1)
if err != nil {
return err
}
if len(cfg.ProfileName) < 1 {
log.Warning("No profile specified, will only check default section. Provide a profile name for more validation")
cfg.ProfileName = awsconfig.DefaultSharedConfigProfile
}
checkEnv()
checkRegion(cfg.Region)
checkProfileCfg(cfg)
checkTime()
printConfig(cfg)
return nil
},
}
func printConfig(cfg *config.AwsConfig) {
fmt.Printf("PROFILE: %s\n", cfg.ProfileName)
fmt.Printf("REGION: %s\n", cfg.Region)
fmt.Printf("SOURCE PROFILE: %s\n", cfg.SrcProfile)
fmt.Printf("SESSION TOKEN DURATION: %s\n", cfg.SessionTokenDuration)
fmt.Printf("MFA SERIAL: %s\n", cfg.MfaSerial)
fmt.Printf("ROLE ARN: %s\n", cfg.RoleArn)
fmt.Printf("EXTERNAL ID: %s\n", cfg.ExternalId)
fmt.Printf("ASSUME ROLE CREDENTIAL DURATION: %s\n", cfg.CredentialsDuration)
if len(cfg.SamlUrl) > 0 {
fmt.Printf("SAML ENDPOINT URL: %s\n", cfg.SamlUrl)
fmt.Printf("SAML USERNAME: %s\n", cfg.SamlUsername)
fmt.Printf("JUMP ROLE ARN: %s\n", cfg.JumpRoleArn)
}
if len(cfg.WebIdentityUrl) > 0 {
fmt.Printf("WEB IDENTITY ENDPOINT URL: %s\n", cfg.WebIdentityUrl)
fmt.Printf("WEB IDENTITY CLIENT ID: %s\n", cfg.WebIdentityClientId)
fmt.Printf("WEB IDENTITY REDIRECT URI: %s\n", cfg.WebIdentityRedirectUri)
fmt.Printf("WEB IDENTITY USERNAME: %s\n", cfg.WebIdentityUsername)
fmt.Printf("JUMP ROLE ARN: %s\n", cfg.JumpRoleArn)
}
}
func checkEnv() {
envAk := os.Getenv("AWS_ACCESS_KEY_ID")
envSt := os.Getenv("AWS_SESSION_TOKEN")
if len(envAk) > 0 && len(envSt) > 0 {
if strings.HasPrefix(envAk, "AKIA") {
log.Error("detected static access key env var along with session token env var, this is invalid")
} else {
log.Info("environment variables appear sane")
}
}
}
func checkRegion(region string) {
// Check that region is set
if len(region) < 1 {
log.Error("region is not set, it must be specified in the config file or as an environment variable")
} else {
log.Info("region is configured in profile or environment variable")
}
}
func checkProfileCfg(cfg *config.AwsConfig) {
if len(cfg.SamlUrl) > 0 && len(cfg.WebIdentityUrl) > 0 {
log.Error("found SAML and Web Identity (OIDC) endpoint urls set, this is invalid")
}
if len(cfg.ProfileName) > 0 {
if len(cfg.SamlUrl) > 0 || len(cfg.WebIdentityUrl) > 0 {
checkExternalProviderConfig(cfg)
} else {
checkIamConfig(cfg)
}
}
}
func checkExternalProviderConfig(cfg *config.AwsConfig) {
if len(cfg.RoleArn) < 1 {
log.Error("role_arn is a required parameter when using external identity providers")
}
if len(cfg.SamlUrl) > 0 {
checkProvider(cfg.SamlUrl)
} else {
checkProvider(cfg.WebIdentityUrl)
if len(cfg.WebIdentityClientId) < 1 || len(cfg.WebIdentityRedirectUri) < 1 {
log.Error("missing web_identity_client_id and/or web_identity_redirect_uri configuration")
}
}
}
func checkIamConfig(cfg *config.AwsConfig) {
// iam profile checks
var cfgCreds bool
if len(cfg.RoleArn) > 0 {
if len(cfg.SrcProfile) < 1 || cfg.SourceProfile() == nil {
log.Errorf("missing source_profile configuration for profile '%s'", cfg.ProfileName)
return
}
// source_profile name must exist in the credentials file when using IAM profiles
cfgCreds = checkCredentialProfile(cfg.SrcProfile)
} else {
// not a profile with a role, must have matching section in creds file
cfgCreds = checkCredentialProfile(cfg.ProfileName)
}
// check for profile creds and env var creds at the same time
envAk := os.Getenv("AWS_ACCESS_KEY_ID")
if cfgCreds && len(envAk) > 0 {
log.Error("detected AWS credential environment variables and profile credentials, this may confuse aws-runas")
} else {
log.Info("credentials appear sane")
}
}
func checkProvider(url string) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodHead, url, http.NoBody) //nolint:gosec
if err != nil {
log.Errorf("error creating http request: %v", err)
return
}
var res *http.Response
res, err = http.DefaultClient.Do(req)
if err != nil {
log.Errorf("error communicating with external provider endpoint: %v", err)
}
defer res.Body.Close()
// default http client chases redirects automatically
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusMethodNotAllowed {
log.Warningf("http status %s when communicating with external provider endpoint", res.Status)
}
}
func checkCredentialProfile(profile string) bool {
src := awsconfig.DefaultSharedCredentialsFilename()
if v, ok := os.LookupEnv("AWS_SHARED_CREDENTIALS_FILE"); ok {
src = v
}
f, err := ini.Load(src)
if err != nil {
log.Errorf("error loading credentials file: %v", err)
return false
}
s, err := f.GetSection(profile)
if err != nil {
log.Errorf("error loading profile credentials: %v", err)
return false
}
if !s.HasKey("aws_access_key_id") || !s.HasKey("aws_secret_access_key") {
log.Errorf("incomplete or missing credentials for profile '%s'", profile)
return false
}
log.Info("profile credentials appear sane")
return true
}
func checkTime() {
// AWS requires that the timestamp in API requests be within 5 minutes of the time at
// the service endpoint. Ensure our local clock is within 5 minutes of an NTP source
maxDrift := 5 * time.Minute
warnDrift := 3 * time.Minute
nTime, err := ntpTime()
if err != nil {
log.Errorf("error checking ntp: %v", err)
return
}
tLocal := time.Now()
drift := nTime.Sub(tLocal)
log.Debugf("ntp: %+v, local: %+v, drift: %+v", nTime.Unix(), tLocal.Unix(), drift)
switch d := math.Abs(drift.Seconds()); {
case d >= maxDrift.Seconds():
log.Errorf("Local time drift is more than %v, AWS API requests will be rejected", maxDrift.Truncate(time.Minute))
case d > warnDrift.Seconds():
log.Warningf("Local time drift is more than %v seconds, check system time", warnDrift.Truncate(time.Minute))
default:
log.Info("system time is within spec")
}
}
func ntpTime() (time.Time, error) {
var t time.Time
var err error
deadlineDuration := 200 * time.Millisecond
gotResponse := false
for !gotResponse {
if deadlineDuration > 10*time.Second {
return time.Time{}, fmt.Errorf("retry attempt limit exceeded")
}
t, err = fetchTime(deadlineDuration)
if err != nil {
switch e := err.(type) {
case *net.OpError:
if e.Timeout() || e.Temporary() {
deadlineDuration = (deadlineDuration * 3) / 2
log.Debugf("Retryable error %v, deadline duration %v", e, deadlineDuration)
continue
} else {
return t, e
}
default:
return t, e
}
}
gotResponse = true
}
return t, nil
}
// REF: https://medium.com/learning-the-go-programming-language/lets-make-an-ntp-client-in-go-287c4b9a969f.
func fetchTime(deadline time.Duration) (time.Time, error) {
// epoch times between NTP and Unix time are offset by this much
// REF: https://tools.ietf.org/html/rfc5905#section-6 (Figure 4)
var ntpUnixOffsetSec uint32 = 2208988800
c, err := net.Dial("udp", "pool.ntp.org:123")
if err != nil {
return time.Time{}, err
}
defer c.Close()
if deadline > 0 {
if err = c.SetReadDeadline(time.Now().Add(deadline)); err != nil {
return time.Time{}, err
}
}
// NTPv3 client request packet
if err = binary.Write(c, binary.BigEndian, &ntpPacket{Settings: 0x1B}); err != nil {
return time.Time{}, err
}
resp := new(ntpPacket)
if err = binary.Read(c, binary.BigEndian, resp); err != nil {
return time.Time{}, err
}
return time.Unix(int64(resp.TxTimeSec-ntpUnixOffsetSec), (int64(resp.TxTimeFrac)*1e9)>>32), nil
}
type ntpPacket struct {
Settings uint8 // leap yr indicator, ver number, and mode
Stratum uint8 // stratum of local clock
Poll int8 // poll exponent
Precision int8 // precision exponent
RootDelay uint32 // root delay
RootDispersion uint32 // root dispersion
ReferenceID uint32 // reference id
RefTimeSec uint32 // reference timestamp sec
RefTimeFrac uint32 // reference timestamp fractional
OrigTimeSec uint32 // origin time secs
OrigTimeFrac uint32 // origin time fractional
RxTimeSec uint32 // receive time secs
RxTimeFrac uint32 // receive time frac
TxTimeSec uint32 // transmit time secs
TxTimeFrac uint32 // transmit time frac
}
|
[
"\"AWS_ACCESS_KEY_ID\"",
"\"AWS_SESSION_TOKEN\"",
"\"AWS_ACCESS_KEY_ID\""
] |
[] |
[
"AWS_SESSION_TOKEN",
"AWS_ACCESS_KEY_ID"
] |
[]
|
["AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID"]
|
go
| 2 | 0 | |
cmd/echo-server/main.go
|
package main
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/gorilla/websocket"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Echo server listening on port %s.\n", port)
err := http.ListenAndServe(
":"+port,
h2c.NewHandler(
http.HandlerFunc(handler),
&http2.Server{},
),
)
if err != nil {
panic(err)
}
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(*http.Request) bool {
return true
},
}
func handler(wr http.ResponseWriter, req *http.Request) {
if os.Getenv("LOG_HTTP_BODY") != "" {
fmt.Printf("-------- %s | %s %s\n", req.RemoteAddr, req.Method, req.URL)
buf := &bytes.Buffer{}
buf.ReadFrom(req.Body)
if buf.Len() != 0 {
w := hex.Dumper(os.Stdout)
w.Write(buf.Bytes())
w.Close()
}
// Replace original body with buffered version so it's still sent to the
// browser.
req.Body.Close()
req.Body = ioutil.NopCloser(
bytes.NewReader(buf.Bytes()),
)
} else {
fmt.Printf("%s | %s %s\n", req.RemoteAddr, req.Method, req.URL)
}
if websocket.IsWebSocketUpgrade(req) {
serveWebSocket(wr, req)
} else if req.URL.Path == "/.ws" {
wr.Header().Add("Content-Type", "text/html")
wr.WriteHeader(200)
io.WriteString(wr, websocketHTML)
} else {
serveHTTP(wr, req)
}
}
func serveWebSocket(wr http.ResponseWriter, req *http.Request) {
connection, err := upgrader.Upgrade(wr, req, nil)
if err != nil {
fmt.Printf("%s | %s\n", req.RemoteAddr, err)
return
}
defer connection.Close()
fmt.Printf("%s | upgraded to websocket\n", req.RemoteAddr)
var message []byte
host, err := os.Hostname()
if err == nil {
message = []byte(fmt.Sprintf("Request served by %s", host))
} else {
message = []byte(fmt.Sprintf("Server hostname unknown: %s", err.Error()))
}
err = connection.WriteMessage(websocket.TextMessage, message)
if err == nil {
var messageType int
for {
messageType, message, err = connection.ReadMessage()
if err != nil {
break
}
if messageType == websocket.TextMessage {
fmt.Printf("%s | txt | %s\n", req.RemoteAddr, message)
} else {
fmt.Printf("%s | bin | %d byte(s)\n", req.RemoteAddr, len(message))
}
err = connection.WriteMessage(messageType, message)
if err != nil {
break
}
}
}
if err != nil {
fmt.Printf("%s | %s\n", req.RemoteAddr, err)
}
}
func serveHTTP(wr http.ResponseWriter, req *http.Request) {
wr.Header().Add("Content-Type", "text/plain")
wr.WriteHeader(200)
host, err := os.Hostname()
if err == nil {
fmt.Fprintf(wr, "Request served by %s\n\n", host)
} else {
fmt.Fprintf(wr, "Server hostname unknown: %s\n\n", err.Error())
}
fmt.Fprintf(wr, "%s %s %s\n", req.Proto, req.Method, req.URL)
fmt.Fprintln(wr, "")
fmt.Fprintf(wr, "Host: %s\n", req.Host)
for key, values := range req.Header {
for _, value := range values {
fmt.Fprintf(wr, "%s: %s\n", key, value)
}
}
fmt.Fprintln(wr, "")
io.Copy(wr, req.Body)
}
|
[
"\"PORT\"",
"\"LOG_HTTP_BODY\""
] |
[] |
[
"PORT",
"LOG_HTTP_BODY"
] |
[]
|
["PORT", "LOG_HTTP_BODY"]
|
go
| 2 | 0 | |
ably/ablytest/sandbox.go
|
package ablytest
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path"
"time"
"github.com/ably/ably-go/ably"
)
type Key struct {
ID string `json:"id,omitempty"`
ScopeID string `json:"scopeId,omitempty"`
Status int `json:"status,omitempty"`
Type int `json:"type,omitempty"`
Value string `json:"value,omitempty"`
Created int `json:"created,omitempty"`
Modified int `json:"modified,omitempty"`
RawCapability string `json:"capability,omitempty"`
Expires int `json:"expired,omitempty"`
Privileged bool `json:"privileged,omitempty"`
}
func (k *Key) Capability() ably.Capability {
c, _ := ably.ParseCapability(k.RawCapability)
return c
}
type Namespace struct {
ID string `json:"id"`
Created int `json:"created,omitempty"`
Modified int `json:"modified,omitempty"`
Persisted bool `json:"persisted,omitempty"`
}
type Presence struct {
ClientID string `json:"clientId"`
Data string `json:"data"`
Encoding string `json:"encoding,omitempty"`
}
type Channel struct {
Name string `json:"name"`
Presence []Presence `json:"presence,omitempty"`
}
type Connection struct {
Name string `json:"name"`
Key string `json:"key"`
}
type Config struct {
ID string `json:"id,omitempty"`
AppID string `json:"appId,omitempty"`
AccountID string `json:"accountId,omitempty"`
Status int `json:"status,omitempty"`
Created int `json:"created,omitempty"`
Modified int `json:"modified,omitempty"`
TLSOnly bool `json:"tlsOnly,omitempty"`
Labels string `json:"labels,omitempty"`
Keys []Key `json:"keys"`
Namespaces []Namespace `json:"namespaces"`
Channels []Channel `json:"channels"`
Connections []Connection `json:"connections,omitempty"`
}
func DefaultConfig() *Config {
return &Config{
Keys: []Key{
{},
},
Namespaces: []Namespace{
{ID: "persisted", Persisted: true},
},
Channels: []Channel{
{
Name: "persisted:presence_fixtures",
Presence: []Presence{
{ClientID: "client_bool", Data: "true"},
{ClientID: "client_int", Data: "true"},
{ClientID: "client_string", Data: "true"},
{ClientID: "client_json", Data: `{"test": "This is a JSONObject clientData payload"}`},
},
},
},
}
}
type Sandbox struct {
Config *Config
Environment string
client *http.Client
}
func NewRealtimeClient(opts *ably.ClientOptions) (*Sandbox, *ably.RealtimeClient) {
app := MustSandbox(nil)
client, err := ably.NewRealtimeClient(app.Options(opts))
if err != nil {
panic(nonil(err, app.Close()))
}
return app, client
}
func NewRestClient(opts *ably.ClientOptions) (*Sandbox, *ably.RestClient) {
app := MustSandbox(nil)
client, err := ably.NewRestClient(app.Options(opts))
if err != nil {
panic(nonil(err, app.Close()))
}
return app, client
}
func MustSandbox(config *Config) *Sandbox {
app, err := NewSandbox(nil)
if err != nil {
panic(err)
}
return app
}
func NewSandbox(config *Config) (*Sandbox, error) {
return NewSandboxWIthEnv(config, Environment)
}
func NewSandboxWIthEnv(config *Config, env string) (*Sandbox, error) {
app := &Sandbox{
Config: config,
Environment: env,
client: NewHTTPClient(),
}
if app.Config == nil {
app.Config = DefaultConfig()
}
p, err := json.Marshal(app.Config)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", app.URL("apps"), bytes.NewReader(p))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := app.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
err := errors.New(http.StatusText(resp.StatusCode))
if p, e := ioutil.ReadAll(resp.Body); e == nil && len(p) != 0 {
err = fmt.Errorf("request error: %s (%q)", err, p)
}
return nil, err
}
if err := json.NewDecoder(resp.Body).Decode(app.Config); err != nil {
return nil, err
}
return app, nil
}
func (app *Sandbox) Close() error {
req, err := http.NewRequest("DELETE", app.URL("apps", app.Config.AppID), nil)
if err != nil {
return err
}
req.SetBasicAuth(app.KeyParts())
resp, err := app.client.Do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode > 299 {
return errors.New(http.StatusText(resp.StatusCode))
}
return nil
}
func (app *Sandbox) NewRealtimeClient(opts ...*ably.ClientOptions) *ably.RealtimeClient {
client, err := ably.NewRealtimeClient(app.Options(opts...))
if err != nil {
panic("ably.NewRealtimeClient failed: " + err.Error())
}
return client
}
func (app *Sandbox) KeyParts() (name, secret string) {
return app.Config.AppID + "." + app.Config.Keys[0].ID, app.Config.Keys[0].Value
}
func (app *Sandbox) Key() string {
name, secret := app.KeyParts()
return name + ":" + secret
}
func (app *Sandbox) Options(opts ...*ably.ClientOptions) *ably.ClientOptions {
type transportHijacker interface {
Hijack(http.RoundTripper) http.RoundTripper
}
appOpts := &ably.ClientOptions{
Environment: app.Environment,
HTTPClient: NewHTTPClient(),
NoBinaryProtocol: NoBinaryProtocol,
Logger: DefaultLogger,
AuthOptions: ably.AuthOptions{
Key: app.Key(),
},
}
opt := MergeOptions(append([]*ably.ClientOptions{{}}, opts...)...)
// If opts want to record round trips inject the recording transport
// via TransportHijacker interface.
if appOpts.HTTPClient != nil && opt.HTTPClient != nil {
if hijacker, ok := opt.HTTPClient.Transport.(transportHijacker); ok {
appOpts.HTTPClient.Transport = hijacker.Hijack(appOpts.HTTPClient.Transport)
opt.HTTPClient = nil
}
}
appOpts = MergeOptions(appOpts, opt)
return appOpts
}
func (app *Sandbox) URL(paths ...string) string {
return "https://" + app.Environment + "-rest.ably.io/" + path.Join(paths...)
}
func NewHTTPClient() *http.Client {
const timeout = time.Minute
return &http.Client{
Timeout: timeout,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: timeout,
KeepAlive: timeout,
}).Dial,
TLSHandshakeTimeout: timeout,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: os.Getenv("HTTP_PROXY") != "",
},
},
}
}
func NewHTTPClientNoKeepAlive() *http.Client {
const timeout = time.Minute
return &http.Client{
Timeout: timeout,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: timeout,
}).Dial,
TLSHandshakeTimeout: timeout,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: os.Getenv("HTTP_PROXY") != "",
},
},
}
}
|
[
"\"HTTP_PROXY\"",
"\"HTTP_PROXY\""
] |
[] |
[
"HTTP_PROXY"
] |
[]
|
["HTTP_PROXY"]
|
go
| 1 | 0 | |
core/__init__.py
|
import os
from flask import Flask
try:
from core import local_settings as settings
except ImportError:
from core import settings
__version__ = '1.0.0'
def create_app():
"""
This function creates application with predefined settings that depends on
environment variable of a system.
:return: application
"""
application = Flask(
__name__,
template_folder=settings.TEMPLATE_DIR,
static_folder=settings.STATIC_DIR
)
environment = os.environ.get('APP_ENV', 'dev')
environments = {
'dev': settings.Dev,
'prod': settings.Prod
}
if environment in environments:
application.config.from_object(environments[environment])
else:
raise EnvironmentError('Application variable has not been specified.')
# Register blueprints
from app.views import app_bp
application.register_blueprint(app_bp)
return application
|
[] |
[] |
[
"APP_ENV"
] |
[]
|
["APP_ENV"]
|
python
| 1 | 0 | |
handlers/utils/utils.go
|
package utils
import (
"os"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt"
)
// TokenMetadata struct to describe metadata in JWT.
type TokenMetadata struct {
Expires int64
Username string
UserID uint
}
// ExtractTokenMetadata func to extract metadata from JWT.
func ExtractTokenMetadata(c *fiber.Ctx) (*TokenMetadata, error) {
token, err := verifyToken(c)
if err != nil {
return nil, err
}
// Setting and checking token and credentials.
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid {
// Expires time.
expires := int64(claims["exp"].(float64))
username := string(claims["username"].(string))
user_id := uint(claims["user_id"].(float64))
return &TokenMetadata{
Expires: expires,
Username: username,
UserID: user_id,
}, nil
}
return nil, err
}
func extractToken(c *fiber.Ctx) string {
bearToken := c.Get("Authorization")
// Normally Authorization HTTP header.
onlyToken := strings.Split(bearToken, " ")
if len(onlyToken) == 2 {
return onlyToken[1]
}
return ""
}
func verifyToken(c *fiber.Ctx) (*jwt.Token, error) {
tokenString := extractToken(c)
token, err := jwt.Parse(tokenString, jwtKeyFunc)
if err != nil {
return nil, err
}
return token, nil
}
func jwtKeyFunc(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET_KEY")), nil
}
|
[
"\"JWT_SECRET_KEY\""
] |
[] |
[
"JWT_SECRET_KEY"
] |
[]
|
["JWT_SECRET_KEY"]
|
go
| 1 | 0 | |
Bookkeeper/wsgi.py
|
"""
WSGI config for Bookkeeper project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Bookkeeper.settings")
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
web/app/logout/logout.go
|
package logout
import (
"net/http"
"net/url"
"os"
"github.com/gin-gonic/gin"
)
// Handler for our logout.
func Handler(ctx *gin.Context) {
logoutUrl, err := url.Parse("https://" + os.Getenv("AUTH0_DOMAIN") + "/v2/logout")
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}
scheme := "http"
if ctx.Request.TLS != nil {
scheme = "https"
}
returnTo, err := url.Parse(scheme + "://" + ctx.Request.Host)
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}
parameters := url.Values{}
parameters.Add("returnTo", returnTo.String())
parameters.Add("client_id", os.Getenv("AUTH0_CLIENT_ID"))
logoutUrl.RawQuery = parameters.Encode()
ctx.Redirect(http.StatusTemporaryRedirect, logoutUrl.String())
}
|
[
"\"AUTH0_DOMAIN\"",
"\"AUTH0_CLIENT_ID\""
] |
[] |
[
"AUTH0_DOMAIN",
"AUTH0_CLIENT_ID"
] |
[]
|
["AUTH0_DOMAIN", "AUTH0_CLIENT_ID"]
|
go
| 2 | 0 | |
rest/authentication/authentication_handles_test.go
|
package authentication
import (
"github.com/maxdobeck/gatekeeper/models"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
// An HTTP test to ensure a login request is rejected if the credentials are wrong
func TestLoginBadCredentials(t *testing.T) {
bodyReader := strings.NewReader(`{"email": "[email protected]", "password": "wrongPassword"}`)
req, err := http.NewRequest("POST", "/login", bodyReader)
if err != nil {
t.Fatal("Problem making our login req. ", err)
}
w := httptest.NewRecorder()
Login(w, req)
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 401 {
t.Fail()
}
log.Debug(resp.StatusCode)
log.Debug(resp.Header.Get("Content-Type"))
log.Debug(string(body))
}
// Test the Login command with a valid set of credentials
func TestLoginGoodCredentials(t *testing.T) {
models.ConnToDB(os.Getenv("PGURL"))
_, delErr := models.Db.Query("DELETE FROM members WHERE email like '[email protected]'")
log.Info(delErr)
valid := models.NewMember{
Name: "Valid Test Member",
Email: "[email protected]",
Email2: "[email protected]",
Password: "superduper",
Password2: "superduper",
}
models.CreateMember(&valid)
bodyReader := strings.NewReader(`{"email": "[email protected]", "password": "superduper"}`)
req, err := http.NewRequest("POST", "/login", bodyReader)
if err != nil {
t.Fatal("Problem logging in ", err)
}
w := httptest.NewRecorder()
Login(w, req)
resp := w.Result()
log.Info(resp.StatusCode)
if resp.StatusCode != 200 {
t.Fail()
}
}
|
[
"\"PGURL\""
] |
[] |
[
"PGURL"
] |
[]
|
["PGURL"]
|
go
| 1 | 0 | |
vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go
|
// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
// +build go1.6,!go1.7
package codec
import "os"
var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") != "0"
|
[
"\"GO15VENDOREXPERIMENT\""
] |
[] |
[
"GO15VENDOREXPERIMENT"
] |
[]
|
["GO15VENDOREXPERIMENT"]
|
go
| 1 | 0 | |
vendor/github.com/docker/docker/pkg/archive/archive_test.go
|
package archive // import "github.com/docker/docker/pkg/archive"
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/ioutils"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
var tmp string
func init() {
tmp = "/tmp/"
if runtime.GOOS == "windows" {
tmp = os.Getenv("TEMP") + `\`
}
}
var defaultArchiver = NewDefaultArchiver()
func defaultTarUntar(src, dst string) error {
return defaultArchiver.TarUntar(src, dst)
}
func defaultUntarPath(src, dst string) error {
return defaultArchiver.UntarPath(src, dst)
}
func defaultCopyFileWithTar(src, dst string) (err error) {
return defaultArchiver.CopyFileWithTar(src, dst)
}
func defaultCopyWithTar(src, dst string) error {
return defaultArchiver.CopyWithTar(src, dst)
}
func TestIsArchivePathDir(t *testing.T) {
cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if IsArchivePath(tmp + "archivedir") {
t.Fatalf("Incorrectly recognised directory as an archive")
}
}
func TestIsArchivePathInvalidFile(t *testing.T) {
cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1024 count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if IsArchivePath(tmp + "archive") {
t.Fatalf("Incorrectly recognised invalid tar path as archive")
}
if IsArchivePath(tmp + "archive.gz") {
t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
}
}
func TestIsArchivePathTar(t *testing.T) {
whichTar := "tar"
cmdStr := fmt.Sprintf("touch /tmp/archivedata && %s -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz", whichTar)
cmd := exec.Command("sh", "-c", cmdStr)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if !IsArchivePath(tmp + "/archive") {
t.Fatalf("Did not recognise valid tar path as archive")
}
if !IsArchivePath(tmp + "archive.gz") {
t.Fatalf("Did not recognise valid compressed tar path as archive")
}
}
func testDecompressStream(t *testing.T, ext, compressCommand string) io.Reader {
cmd := exec.Command("sh", "-c",
fmt.Sprintf("touch /tmp/archive && %s /tmp/archive", compressCommand))
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create an archive file for test : %s.", output)
}
filename := "archive." + ext
archive, err := os.Open(tmp + filename)
if err != nil {
t.Fatalf("Failed to open file %s: %v", filename, err)
}
defer archive.Close()
r, err := DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress %s: %v", filename, err)
}
if _, err = ioutil.ReadAll(r); err != nil {
t.Fatalf("Failed to read the decompressed stream: %v ", err)
}
if err = r.Close(); err != nil {
t.Fatalf("Failed to close the decompressed stream: %v ", err)
}
return r
}
func TestDecompressStreamGzip(t *testing.T) {
testDecompressStream(t, "gz", "gzip -f")
}
func TestDecompressStreamBzip2(t *testing.T) {
testDecompressStream(t, "bz2", "bzip2 -f")
}
func TestDecompressStreamXz(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Xz not present in msys2")
}
testDecompressStream(t, "xz", "xz -f")
}
func TestCompressStreamXzUnsupported(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()
_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestCompressStreamBzip2Unsupported(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()
_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestCompressStreamInvalid(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()
_, err = CompressStream(dest, -1)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestExtensionInvalid(t *testing.T) {
compression := Compression(-1)
output := compression.Extension()
if output != "" {
t.Fatalf("The extension of an invalid compression should be an empty string.")
}
}
func TestExtensionUncompressed(t *testing.T) {
compression := Uncompressed
output := compression.Extension()
if output != "tar" {
t.Fatalf("The extension of an uncompressed archive should be 'tar'.")
}
}
func TestExtensionBzip2(t *testing.T) {
compression := Bzip2
output := compression.Extension()
if output != "tar.bz2" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
}
}
func TestExtensionGzip(t *testing.T) {
compression := Gzip
output := compression.Extension()
if output != "tar.gz" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
}
}
func TestExtensionXz(t *testing.T) {
compression := Xz
output := compression.Extension()
if output != "tar.xz" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
}
}
func TestCmdStreamLargeStderr(t *testing.T) {
cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
out, err := cmdStream(cmd, nil)
if err != nil {
t.Fatalf("Failed to start command: %s", err)
}
errCh := make(chan error)
go func() {
_, err := io.Copy(ioutil.Discard, out)
errCh <- err
}()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("Command should not have failed (err=%.100s...)", err)
}
case <-time.After(5 * time.Second):
t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
}
}
func TestCmdStreamBad(t *testing.T) {
// TODO Windows: Figure out why this is failing in CI but not locally
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows CI machines")
}
badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
out, err := cmdStream(badCmd, nil)
if err != nil {
t.Fatalf("Failed to start command: %s", err)
}
if output, err := ioutil.ReadAll(out); err == nil {
t.Fatalf("Command should have failed")
} else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
t.Fatalf("Wrong error value (%s)", err)
} else if s := string(output); s != "hello\n" {
t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
}
}
func TestCmdStreamGood(t *testing.T) {
cmd := exec.Command("sh", "-c", "echo hello; exit 0")
out, err := cmdStream(cmd, nil)
if err != nil {
t.Fatal(err)
}
if output, err := ioutil.ReadAll(out); err != nil {
t.Fatalf("Command should not have failed (err=%s)", err)
} else if s := string(output); s != "hello\n" {
t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
}
}
func TestUntarPathWithInvalidDest(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
assert.NilError(t, err)
defer os.RemoveAll(tempFolder)
invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
// Create a src file
srcFile := filepath.Join(tempFolder, "src")
tarFile := filepath.Join(tempFolder, "src.tar")
os.Create(srcFile)
os.Create(invalidDestFolder) // being a file (not dir) should cause an error
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
assert.NilError(t, err)
err = defaultUntarPath(tarFile, invalidDestFolder)
if err == nil {
t.Fatalf("UntarPath with invalid destination path should throw an error.")
}
}
func TestUntarPathWithInvalidSrc(t *testing.T) {
dest, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer os.RemoveAll(dest)
err = defaultUntarPath("/invalid/path", dest)
if err == nil {
t.Fatalf("UntarPath with invalid src path should throw an error.")
}
}
func TestUntarPath(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
assert.NilError(t, err)
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(filepath.Join(tmpFolder, "src"))
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
assert.NilError(t, err)
err = defaultUntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
}
expectedFile := filepath.Join(destFolder, srcFileU)
_, err = os.Stat(expectedFile)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
// Do the same test as above but with the destination as file, it should fail
func TestUntarPathWithDestinationFile(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(filepath.Join(tmpFolder, "src"))
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
destFile := filepath.Join(tmpFolder, "dest")
_, err = os.Create(destFile)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
err = defaultUntarPath(tarFile, destFile)
if err == nil {
t.Fatalf("UntarPath should throw an error if the destination if a file")
}
}
// Do the same test as above but with the destination folder already exists
// and the destination file is a directory
// It's working, see https://github.com/docker/docker/issues/10040
func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(srcFile)
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatalf("Fail to create the destination folder")
}
// Let's create a folder that will has the same path as the extracted file (from tar)
destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
err = os.MkdirAll(destSrcFileAsFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = defaultUntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
}
}
func TestCopyWithTarInvalidSrc(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
destFolder := filepath.Join(tempFolder, "dest")
invalidSrc := filepath.Join(tempFolder, "doesnotexists")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyWithTar(invalidSrc, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
srcFolder := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyWithTar(srcFolder, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
}
// Test CopyWithTar with a file as src
func TestCopyWithTarSrcFile(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(src, []byte("content"), 0777)
err = defaultCopyWithTar(src, dest)
if err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
// FIXME Check the content
if err != nil {
t.Fatalf("Destination file should be the same as the source.")
}
}
// Test CopyWithTar with a folder as src
func TestCopyWithTarSrcFolder(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, filepath.Join("src", "folder"))
err = os.MkdirAll(src, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
err = defaultCopyWithTar(src, dest)
if err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
// FIXME Check the content (the file inside)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestCopyFileWithTarInvalidSrc(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempFolder)
destFolder := filepath.Join(tempFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatal(err)
}
invalidFile := filepath.Join(tempFolder, "doesnotexists")
err = defaultCopyFileWithTar(invalidFile, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
defer os.RemoveAll(tempFolder)
srcFile := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
_, err = os.Create(srcFile)
if err != nil {
t.Fatal(err)
}
err = defaultCopyFileWithTar(srcFile, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
// FIXME Test the src file and content
}
func TestCopyFileWithTarSrcFolder(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, "srcfolder")
err = os.MkdirAll(src, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyFileWithTar(src, dest)
if err == nil {
t.Fatalf("CopyFileWithTar should throw an error with a folder.")
}
}
func TestCopyFileWithTarSrcFile(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(src, []byte("content"), 0777)
err = defaultCopyWithTar(src, dest+"/")
if err != nil {
t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestTarFiles(t *testing.T) {
// TODO Windows: Figure out how to port this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
// try without hardlinks
if err := checkNoChanges(1000, false); err != nil {
t.Fatal(err)
}
// try with hardlinks
if err := checkNoChanges(1000, true); err != nil {
t.Fatal(err)
}
}
func checkNoChanges(fileNum int, hardlinks bool) error {
srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
if err != nil {
return err
}
defer os.RemoveAll(srcDir)
destDir, err := ioutil.TempDir("", "docker-test-destDir")
if err != nil {
return err
}
defer os.RemoveAll(destDir)
_, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
if err != nil {
return err
}
err = defaultTarUntar(srcDir, destDir)
if err != nil {
return err
}
changes, err := ChangesDirs(destDir, srcDir)
if err != nil {
return err
}
if len(changes) > 0 {
return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
}
return nil
}
func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
archive, err := TarWithOptions(origin, options)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
buf := make([]byte, 10)
if _, err := archive.Read(buf); err != nil {
return nil, err
}
wrap := io.MultiReader(bytes.NewReader(buf), archive)
detectedCompression := DetectCompression(buf)
compression := options.Compression
if detectedCompression.Extension() != compression.Extension() {
return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
}
tmp, err := ioutil.TempDir("", "docker-test-untar")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmp)
if err := Untar(wrap, tmp, nil); err != nil {
return nil, err
}
if _, err := os.Stat(tmp); err != nil {
return nil, err
}
return ChangesDirs(origin, tmp)
}
func TestTarUntar(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(origin)
if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
t.Fatal(err)
}
for _, c := range []Compression{
Uncompressed,
Gzip,
} {
changes, err := tarUntar(t, origin, &TarOptions{
Compression: c,
ExcludePatterns: []string{"3"},
})
if err != nil {
t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
}
if len(changes) != 1 || changes[0].Path != "/3" {
t.Fatalf("Unexpected differences after tarUntar: %v", changes)
}
}
}
func TestTarWithOptionsChownOptsAlwaysOverridesIdPair(t *testing.T) {
origin, err := ioutil.TempDir("", "docker-test-tar-chown-opt")
assert.NilError(t, err)
defer os.RemoveAll(origin)
filePath := filepath.Join(origin, "1")
err = ioutil.WriteFile(filePath, []byte("hello world"), 0700)
assert.NilError(t, err)
idMaps := []idtools.IDMap{
0: {
ContainerID: 0,
HostID: 0,
Size: 65536,
},
1: {
ContainerID: 0,
HostID: 100000,
Size: 65536,
},
}
cases := []struct {
opts *TarOptions
expectedUID int
expectedGID int
}{
{&TarOptions{ChownOpts: &idtools.IDPair{UID: 1337, GID: 42}}, 1337, 42},
{&TarOptions{ChownOpts: &idtools.IDPair{UID: 100001, GID: 100001}, UIDMaps: idMaps, GIDMaps: idMaps}, 100001, 100001},
{&TarOptions{ChownOpts: &idtools.IDPair{UID: 0, GID: 0}, NoLchown: false}, 0, 0},
{&TarOptions{ChownOpts: &idtools.IDPair{UID: 1, GID: 1}, NoLchown: true}, 1, 1},
{&TarOptions{ChownOpts: &idtools.IDPair{UID: 1000, GID: 1000}, NoLchown: true}, 1000, 1000},
}
for _, testCase := range cases {
reader, err := TarWithOptions(filePath, testCase.opts)
assert.NilError(t, err)
tr := tar.NewReader(reader)
defer reader.Close()
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
assert.NilError(t, err)
assert.Check(t, is.Equal(hdr.Uid, testCase.expectedUID), "Uid equals expected value")
assert.Check(t, is.Equal(hdr.Gid, testCase.expectedGID), "Gid equals expected value")
}
}
}
func TestTarWithOptions(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
t.Fatal(err)
}
if _, err := ioutil.TempDir(origin, "folder"); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(origin)
if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
t.Fatal(err)
}
cases := []struct {
opts *TarOptions
numChanges int
}{
{&TarOptions{IncludeFiles: []string{"1"}}, 2},
{&TarOptions{ExcludePatterns: []string{"2"}}, 1},
{&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
{&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
{&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
}
for _, testCase := range cases {
changes, err := tarUntar(t, origin, testCase.opts)
if err != nil {
t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
}
if len(changes) != testCase.numChanges {
t.Errorf("Expected %d changes, got %d for %+v:",
testCase.numChanges, len(changes), testCase.opts)
}
}
}
// Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
// use PAX Global Extended Headers.
// Failing prevents the archives from being uncompressed during ADD
func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil, false)
if err != nil {
t.Fatal(err)
}
}
// Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
// Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
func TestUntarUstarGnuConflict(t *testing.T) {
f, err := os.Open("testdata/broken.tar")
if err != nil {
t.Fatal(err)
}
defer f.Close()
found := false
tr := tar.NewReader(f)
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
t.Fatal(err)
}
if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
found = true
break
}
}
if !found {
t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
}
}
func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
fileData := []byte("fooo")
for n := 0; n < numberOfFiles; n++ {
fileName := fmt.Sprintf("file-%d", n)
if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil {
return 0, err
}
if makeLinks {
if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
return 0, err
}
}
}
totalSize := numberOfFiles * len(fileData)
return totalSize, nil
}
func BenchmarkTarUntar(b *testing.B) {
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, false)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(origin)
defer os.RemoveAll(tempDir)
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := defaultTarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func BenchmarkTarUntarWithLinks(b *testing.B) {
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, true)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(origin)
defer os.RemoveAll(tempDir)
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := defaultTarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func TestUntarInvalidFilenames(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Passes but hits breakoutError: platform and architecture is not supported")
}
for i, headers := range [][]*tar.Header{
{
{
Name: "../victim/dotdot",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{
{
// Note the leading slash
Name: "/../victim/slash-dotdot",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarHardlinkToSymlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{
{
Name: "symlink1",
Typeflag: tar.TypeSymlink,
Linkname: "regfile",
Mode: 0644,
},
{
Name: "symlink2",
Typeflag: tar.TypeLink,
Linkname: "symlink1",
Mode: 0644,
},
{
Name: "regfile",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidHardlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeLink,
Linkname: "../victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeLink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try reading victim/hello (hardlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // Try reading victim/hello (hardlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // Try removing victim directory (hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidSymlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeSymlink,
Linkname: "../victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeSymlink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try reading victim/hello (symlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (symlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // try removing victim directory (symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try writing to victim/newdir/newfile with a symlink in the path
{
// this header needs to be before the next one, or else there is an error
Name: "dir/loophole",
Typeflag: tar.TypeSymlink,
Linkname: "../../victim",
Mode: 0755,
},
{
Name: "dir/loophole/newdir/newfile",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestTempArchiveCloseMultipleTimes(t *testing.T) {
reader := ioutil.NopCloser(strings.NewReader("hello"))
tempArchive, err := NewTempArchive(reader, "")
assert.NilError(t, err)
buf := make([]byte, 10)
n, err := tempArchive.Read(buf)
assert.NilError(t, err)
if n != 5 {
t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
}
for i := 0; i < 3; i++ {
if err = tempArchive.Close(); err != nil {
t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
}
}
}
func TestReplaceFileTarWrapper(t *testing.T) {
filesInArchive := 20
testcases := []struct {
doc string
filename string
modifier TarModifierFunc
expected string
fileCount int
}{
{
doc: "Modifier creates a new file",
filename: "newfile",
modifier: createModifier(t),
expected: "the new content",
fileCount: filesInArchive + 1,
},
{
doc: "Modifier replaces a file",
filename: "file-2",
modifier: createOrReplaceModifier,
expected: "the new content",
fileCount: filesInArchive,
},
{
doc: "Modifier replaces the last file",
filename: fmt.Sprintf("file-%d", filesInArchive-1),
modifier: createOrReplaceModifier,
expected: "the new content",
fileCount: filesInArchive,
},
{
doc: "Modifier appends to a file",
filename: "file-3",
modifier: appendModifier,
expected: "fooo\nnext line",
fileCount: filesInArchive,
},
}
for _, testcase := range testcases {
sourceArchive, cleanup := buildSourceArchive(t, filesInArchive)
defer cleanup()
resultArchive := ReplaceFileTarWrapper(
sourceArchive,
map[string]TarModifierFunc{testcase.filename: testcase.modifier})
actual := readFileFromArchive(t, resultArchive, testcase.filename, testcase.fileCount, testcase.doc)
assert.Check(t, is.Equal(testcase.expected, actual), testcase.doc)
}
}
// TestPrefixHeaderReadable tests that files that could be created with the
// version of this package that was built with <=go17 are still readable.
func TestPrefixHeaderReadable(t *testing.T) {
// https://gist.github.com/stevvooe/e2a790ad4e97425896206c0816e1a882#file-out-go
var testFile = []byte("\x1f\x8b\x08\x08\x44\x21\x68\x59\x00\x03\x74\x2e\x74\x61\x72\x00\x4b\xcb\xcf\x67\xa0\x35\x30\x80\x00\x86\x06\x10\x47\x01\xc1\x37\x40\x00\x54\xb6\xb1\xa1\xa9\x99\x09\x48\x25\x1d\x40\x69\x71\x49\x62\x91\x02\xe5\x76\xa1\x79\x84\x21\x91\xd6\x80\x72\xaf\x8f\x82\x51\x30\x0a\x46\x36\x00\x00\xf0\x1c\x1e\x95\x00\x06\x00\x00")
tmpDir, err := ioutil.TempDir("", "prefix-test")
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
err = Untar(bytes.NewReader(testFile), tmpDir, nil)
assert.NilError(t, err)
baseName := "foo"
pth := strings.Repeat("a", 100-len(baseName)) + "/" + baseName
_, err = os.Lstat(filepath.Join(tmpDir, pth))
assert.NilError(t, err)
}
func buildSourceArchive(t *testing.T, numberOfFiles int) (io.ReadCloser, func()) {
srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
assert.NilError(t, err)
_, err = prepareUntarSourceDirectory(numberOfFiles, srcDir, false)
assert.NilError(t, err)
sourceArchive, err := TarWithOptions(srcDir, &TarOptions{})
assert.NilError(t, err)
return sourceArchive, func() {
os.RemoveAll(srcDir)
sourceArchive.Close()
}
}
func createOrReplaceModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
return &tar.Header{
Mode: 0600,
Typeflag: tar.TypeReg,
}, []byte("the new content"), nil
}
func createModifier(t *testing.T) TarModifierFunc {
return func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
assert.Check(t, is.Nil(content))
return createOrReplaceModifier(path, header, content)
}
}
func appendModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
buffer := bytes.Buffer{}
if content != nil {
if _, err := buffer.ReadFrom(content); err != nil {
return nil, nil, err
}
}
buffer.WriteString("\nnext line")
return &tar.Header{Mode: 0600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil
}
func readFileFromArchive(t *testing.T, archive io.ReadCloser, name string, expectedCount int, doc string) string {
destDir, err := ioutil.TempDir("", "docker-test-destDir")
assert.NilError(t, err)
defer os.RemoveAll(destDir)
err = Untar(archive, destDir, nil)
assert.NilError(t, err)
files, _ := ioutil.ReadDir(destDir)
assert.Check(t, is.Len(files, expectedCount), doc)
content, err := ioutil.ReadFile(filepath.Join(destDir, name))
assert.Check(t, err)
return string(content)
}
func TestDisablePigz(t *testing.T) {
_, err := exec.LookPath("unpigz")
if err != nil {
t.Log("Test will not check full path when Pigz not installed")
}
os.Setenv("MOBY_DISABLE_PIGZ", "true")
defer os.Unsetenv("MOBY_DISABLE_PIGZ")
r := testDecompressStream(t, "gz", "gzip -f")
// For the bufio pool
outsideReaderCloserWrapper := r.(*ioutils.ReadCloserWrapper)
// For the context canceller
contextReaderCloserWrapper := outsideReaderCloserWrapper.Reader.(*ioutils.ReadCloserWrapper)
assert.Equal(t, reflect.TypeOf(contextReaderCloserWrapper.Reader), reflect.TypeOf(&gzip.Reader{}))
}
func TestPigz(t *testing.T) {
r := testDecompressStream(t, "gz", "gzip -f")
// For the bufio pool
outsideReaderCloserWrapper := r.(*ioutils.ReadCloserWrapper)
// For the context canceller
contextReaderCloserWrapper := outsideReaderCloserWrapper.Reader.(*ioutils.ReadCloserWrapper)
_, err := exec.LookPath("unpigz")
if err == nil {
t.Log("Tested whether Pigz is used, as it installed")
assert.Equal(t, reflect.TypeOf(contextReaderCloserWrapper.Reader), reflect.TypeOf(&io.PipeReader{}))
} else {
t.Log("Tested whether Pigz is not used, as it not installed")
assert.Equal(t, reflect.TypeOf(contextReaderCloserWrapper.Reader), reflect.TypeOf(&gzip.Reader{}))
}
}
|
[
"\"TEMP\""
] |
[] |
[
"TEMP"
] |
[]
|
["TEMP"]
|
go
| 1 | 0 | |
main.go
|
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/gin-gonic/gin"
"os"
"strconv"
"time"
)
type Timer struct {
TimerId string
StartTime int64
Now int64
Seconds int
SecondsRemaining int
}
type TimerDatabase struct {
Db *dynamodb.DynamoDB
Region string
TableName string
}
func makeTimerDatabase() *TimerDatabase {
region := os.Getenv("REGION")
config := &aws.Config{Region: aws.String(region)}
return &TimerDatabase{
Db: dynamodb.New(session.New(), config),
Region: os.Getenv("REGION"),
TableName: os.Getenv("TABLE_NAME"),
}
}
func (timers *TimerDatabase) Find(timerId string) (*Timer, error) {
response, err := timers.Db.GetItem(&dynamodb.GetItemInput{
TableName: aws.String(timers.TableName),
Key: map[string]*dynamodb.AttributeValue{
"Timer": {
S: aws.String(timerId),
},
},
})
if err != nil {
fmt.Println(err)
return nil, err
}
if response == nil || response.Item == nil {
return nil, nil
}
startTime, err := strconv.ParseInt(*response.Item["StartTime"].N, 10, 64)
if err != nil {
return nil, err
}
seconds, err := strconv.Atoi(*response.Item["Seconds"].N)
if err != nil {
return nil, err
}
now := time.Now().Unix()
secondsRemaining := int(startTime + int64(seconds) - now)
return &Timer{
TimerId: *response.Item["Timer"].S,
StartTime: startTime,
Seconds: seconds,
Now: now,
SecondsRemaining: secondsRemaining,
}, nil
}
func (timers *TimerDatabase) Set(timerId string, seconds int) (*Timer, error) {
startTime := time.Now().Unix()
startTimeString := strconv.FormatInt(startTime, 10)
secondsString := strconv.Itoa(seconds)
_, err := timers.Db.PutItem(&dynamodb.PutItemInput{
TableName: aws.String(timers.TableName),
Item: map[string]*dynamodb.AttributeValue{
"Timer": {
S: aws.String(timerId),
},
"StartTime": {
N: aws.String(startTimeString),
},
"Seconds": {
N: aws.String(secondsString),
},
},
})
if err != nil {
fmt.Println(err)
return nil, err
}
return &Timer{
TimerId: timerId,
StartTime: startTime,
Now: startTime,
Seconds: seconds,
SecondsRemaining: seconds,
}, nil
}
func healthCheck(c *gin.Context) {
c.JSON(200, gin.H{"Status": "OK"})
}
func checkTimer(timers *TimerDatabase) func(c *gin.Context) {
return func(c *gin.Context) {
timer, err := timers.Find(c.Param("timer"))
if err != nil {
c.JSON(500, gin.H{
"Message": "Internal error",
})
return
}
if timer == nil {
c.JSON(404, gin.H{
"Message": "Timer not found",
})
return
}
if timer.SecondsRemaining < 0 {
c.JSON(504, gin.H{
"Message": "Timer expired",
})
return
}
c.JSON(200, timer)
}
}
func setTimer(timers *TimerDatabase) func(c *gin.Context) {
return func(c *gin.Context) {
seconds, err := strconv.Atoi(c.Param("seconds"))
if err != nil {
c.JSON(400, gin.H{
"Message": "Invalid number of seconds",
})
return
}
timer, err := timers.Set(c.Param("timer"), seconds)
if err != nil {
c.JSON(500, gin.H{
"Message": "Internal error",
})
return
}
c.JSON(200, timer)
}
}
func main() {
timers := makeTimerDatabase()
r := gin.Default()
r.GET("/", healthCheck)
r.GET("/:timer", checkTimer(timers))
r.GET("/:timer/:seconds", setTimer(timers))
r.Run()
}
|
[
"\"REGION\"",
"\"REGION\"",
"\"TABLE_NAME\""
] |
[] |
[
"TABLE_NAME",
"REGION"
] |
[]
|
["TABLE_NAME", "REGION"]
|
go
| 2 | 0 | |
voice/fairseq_g2p.py
|
"""
This module converts words to a format usable by the FairseqGraphemeToPhoneme
class and contains t he FairseqGraphemeToPhoneme class.
The FairseqGraphemeToPhoneme class uses fairseq models to get the phonetic
transcriptions of words.
These models are based off the sigmorph Icelandic g2p models.
"""
# Copyright (c) Judy Y. Fong <[email protected]>
#
# This g2p source code is licensed under the GPL-2.0 License found in the
# LICENSE file in the root directory of this source tree.
import os
import fairseq
import torch
from fairseq.models.transformer import TransformerModel
# Function to change 'hlaupa' to 'h l a u p a' etc
def words2spaced(normal_words):
"""
Change normal words to words with spaces between letters
e.g. hlaupa to h l a u p a
"""
separated = []
for word in normal_words:
separated.append(' '.join(char for char in word))
return separated
class FairseqGraphemeToPhoneme:
"""
The Fairseq_graphemetophoneme class uses fairseq models to get the phonetic
transcriptions of words.
These models are based off othe sigmorph Icelandic g2p models.
"""
def __init__(self):
self.possible_dialects = ['standard', 'north', 'north_east', 'south']
self.dialect_models = {}
model_dir = os.getenv("G2P_MODEL_DIR", "/app/fairseq_g2p/")
""" Select the paths based on dialect """
for dialect in self.possible_dialects:
data_dir = model_dir + '/data-bin/' + dialect
checkpoint_file = model_dir + '/checkpoints/' + dialect + \
'-256-.3-s-s/checkpoint_last.pt'
self.dialect_models[dialect] = \
TransformerModel.from_pretrained(data_dir, checkpoint_file)
def examples(self):
"""
Print out examples of the output from fairseq g2p models from grammatek
"""
# Process phrase to work with g2p functioon
# TODO: remove punctuation because it affects the output
# phrase = 'Velkomin til íslands.'
# phrase = 'Velkomin til íslands'
phrase = 'What is up Charlie Zinger Queen'
# Change a phrase to a list of words with .split()
phrase_spaced = words2spaced(phrase.split())
# Process words to work with g2p function
h_l_a_u_p_a = words2spaced(['hlaupa'])
processed = words2spaced(
['Hlaupa', 'derp', 'orð', 'hrafn', 'daginn', 'Akureyri', 'banki']
)
# works with c, w, q, and z
# g2p works with lowercased and capital letters
# NOTE: punctuation just gives random output so shouldn't allow it to
# be passed to self.dialect_models[dialect].translate()
dialect = "standard"
print(self.dialect_models[dialect].translate(h_l_a_u_p_a))
# ['l_0 9i: p a']
print(self.dialect_models[dialect].translate(processed))
# ['l_0 9i: p a', 't E r_0 p']
print(self.dialect_models[dialect].translate(phrase_spaced))
# ['c E l k_h O m I n', 't_h I: l', 'i s t l a n t s']
print('\nnorth')
print(self.dialect_models["north"].translate(processed))
print('\nnorth east')
print(self.dialect_models["north_east"].translate(processed))
print('\nsouth')
print(self.dialect_models["south"].translate(processed))
# ['hlaupa','orð', 'derp']
def pronounce(self, word_list, dialect='standard'):
"""
Take in a normal word list and return pronunciation objects
Apply phonemes based on dialect
"""
w_o_r_d_l_i_s_t = words2spaced(word_list)
if dialect in self.possible_dialects:
word_phones = \
self.dialect_models[dialect].translate(w_o_r_d_l_i_s_t)
fairseq_response = []
for (phones, word) in zip(word_phones, word_list):
fairseq_response.append({
"word": word,
"results": [
{"pronunciation": phones}
]
})
return fairseq_response
raise ValueError("There is no matching dialect g2p model.")
|
[] |
[] |
[
"G2P_MODEL_DIR"
] |
[]
|
["G2P_MODEL_DIR"]
|
python
| 1 | 0 | |
httpd/handlers/stripeGetPriceConfig.go
|
package handlers
import (
"net/http"
"os"
"soci-backend/httpd/utils"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/price"
)
// StripeGetPriceConfig create a new subscription with fixed price for user
func StripeGetPriceConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
SendResponse(w, utils.MakeError("you can only GET to the price config route"), http.StatusMethodNotAllowed)
return
}
params := &stripe.PriceListParams{
LookupKeys: stripe.StringSlice([]string{"sample_basic", "sample_premium"}),
}
prices := make([]*stripe.Price, 0)
i := price.List(params)
for i.Next() {
prices = append(prices, i.Price())
}
output := map[string]interface{}{
"publishableKey": os.Getenv("STRIPE_PUBLISHABLE_KEY"),
"prices": prices,
}
SendResponse(w, output, 200)
}
|
[
"\"STRIPE_PUBLISHABLE_KEY\""
] |
[] |
[
"STRIPE_PUBLISHABLE_KEY"
] |
[]
|
["STRIPE_PUBLISHABLE_KEY"]
|
go
| 1 | 0 | |
src/back/myServer/asgi.py
|
"""
ASGI config for myServer project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myServer.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
automobile/register/register_model.py
|
"""
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates and to vendors to perform work on your behalf)
through distribution, network access, service agreement, lease, rental, or
otherwise. This license does not purport to express any claim of ownership over
data you may have shared with Microsoft in the creation of the Software Code.
Unless applicable law gives you more rights, Microsoft reserves all other
rights not expressly granted herein, whether by implication, estoppel or
otherwise.
THE SOFTWARE CODE 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
MICROSOFT OR ITS LICENSORS 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 THE SOFTWARE CODE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import json
import os
import sys
import argparse
import traceback
import joblib
from azureml.core import Run, Experiment, Workspace, Dataset
from azureml.core.model import Model as AMLModel
def main():
run = Run.get_context()
if (run.id.startswith('OfflineRun')):
from dotenv import load_dotenv
# For local development, set values in this section
load_dotenv()
workspace_name = os.environ.get("WORKSPACE_NAME")
experiment_name = os.environ.get("EXPERIMENT_NAME")
resource_group = os.environ.get("RESOURCE_GROUP")
subscription_id = os.environ.get("SUBSCRIPTION_ID")
# run_id useful to query previous runs
run_id = "bd184a18-2ac8-4951-8e78-e290bef3b012"
aml_workspace = Workspace.get(
name=workspace_name,
subscription_id=subscription_id,
resource_group=resource_group
)
ws = aml_workspace
exp = Experiment(ws, experiment_name)
else:
ws = run.experiment.workspace
exp = run.experiment
run_id = 'amlcompute'
parser = argparse.ArgumentParser("register")
parser.add_argument(
"--run_id",
type=str,
help="Training run ID",
)
parser.add_argument(
"--model_name",
type=str,
help="Name of the Model",
default="automobile_model.pkl",
)
parser.add_argument(
"--step_input",
type=str,
help=("input from previous steps")
)
args = parser.parse_args()
if (args.run_id is not None):
run_id = args.run_id
if (run_id == 'amlcompute'):
run_id = run.parent.id
model_name = args.model_name
model_path = args.step_input
print("Getting registration parameters")
# Load the registration parameters from the parameters file
with open("parameters.json") as f:
pars = json.load(f)
try:
register_args = pars["registration"]
except KeyError:
print("Could not load registration values from file")
register_args = {"tags": []}
model_tags = {}
for tag in register_args["tags"]:
try:
mtag = run.parent.get_metrics()[tag]
model_tags[tag] = mtag
except KeyError:
print(f"Could not find {tag} metric on parent run.")
# load the model
print("Loading model from " + model_path)
model_file = os.path.join(model_path, model_name)
model = joblib.load(model_file)
parent_tags = run.parent.get_tags()
try:
build_id = parent_tags["BuildId"]
except KeyError:
build_id = None
print("BuildId tag not found on parent run.")
print(f"Tags present: {parent_tags}")
try:
build_uri = parent_tags["BuildUri"]
except KeyError:
build_uri = None
print("BuildUri tag not found on parent run.")
print(f"Tags present: {parent_tags}")
if (model is not None):
dataset_id = parent_tags["dataset_id"]
if (build_id is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id)
elif (build_uri is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id)
else:
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id,
build_uri)
else:
print("Model not found. Skipping model registration.")
sys.exit(0)
def model_already_registered(model_name, exp, run_id):
model_list = AMLModel.list(exp.workspace, name=model_name, run_id=run_id)
if len(model_list) >= 1:
e = ("Model name:", model_name, "in workspace",
exp.workspace, "with run_id ", run_id, "is already registered.")
print(e)
raise Exception(e)
else:
print("Model is not registered for this run.")
def register_aml_model(
model_path,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id: str = 'none',
build_uri=None
):
try:
tagsValue = {"area": "automobile",
"run_id": run_id,
"experiment_name": exp.name}
tagsValue.update(model_tags)
if (build_id != 'none'):
model_already_registered(model_name, exp, run_id)
tagsValue["BuildId"] = build_id
if (build_uri is not None):
tagsValue["BuildUri"] = build_uri
model = AMLModel.register(
workspace=exp.workspace,
model_name=model_name,
model_path=model_path,
tags=tagsValue,
datasets=[('training data',
Dataset.get_by_id(exp.workspace, dataset_id))])
os.chdir("..")
print(
"Model registered: {} \nModel Description: {} "
"\nModel Version: {}".format(
model.name, model.description, model.version
)
)
except Exception:
traceback.print_exc(limit=None, file=None, chain=True)
print("Model registration failed")
raise
if __name__ == '__main__':
main()
|
[] |
[] |
[
"SUBSCRIPTION_ID",
"RESOURCE_GROUP",
"WORKSPACE_NAME",
"EXPERIMENT_NAME"
] |
[]
|
["SUBSCRIPTION_ID", "RESOURCE_GROUP", "WORKSPACE_NAME", "EXPERIMENT_NAME"]
|
python
| 4 | 0 | |
src/hidreader/hidreader.java
|
package hidreader;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import com.nordicid.nurapi.NurApi;
import com.nordicid.nurapi.NurApiException;
import com.nordicid.nurapi.NurApiListener;
import com.nordicid.nurapi.NurApiSocketTransport;
import com.nordicid.nurapi.NurEventAutotune;
import com.nordicid.nurapi.NurEventClientInfo;
import com.nordicid.nurapi.NurEventDeviceInfo;
import com.nordicid.nurapi.NurEventEpcEnum;
import com.nordicid.nurapi.NurEventFrequencyHop;
import com.nordicid.nurapi.NurEventIOChange;
import com.nordicid.nurapi.NurEventInventory;
import com.nordicid.nurapi.NurEventNxpAlarm;
import com.nordicid.nurapi.NurEventProgrammingProgress;
import com.nordicid.nurapi.NurEventTagTrackingChange;
import com.nordicid.nurapi.NurEventTagTrackingData;
import com.nordicid.nurapi.NurEventTraceTag;
import com.nordicid.nurapi.NurEventTriggeredRead;
import com.nordicid.nurapi.NurRespInventory;
import com.nordicid.nurapi.NurTag;
import com.nordicid.nurapi.NurTagStorage;
import com.nordicid.tdt.*;
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.internal.websocket.Base64;
import org.eclipse.paho.client.mqttv3.internal.websocket.Base64.Base64Encoder;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.nio.channels.FileChannel;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.NameValuePair;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.entity.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class hidreader {
private static MqttClient mosquClient = null;
private static MqttMessage message = new MqttMessage();
private static String topicctl = "/hidreader/ctl";
private static String topicsave = "/hidreader/savesettings";
private static String topicev = "/hidreader/events";
private static String broker = "tcp://127.0.0.1:1883";
private static String clientId = "hidreader";
private static String lastStatus = "N/A";
private static SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
private static NurApi mApi = new NurApi();
static class NotifiedTag {
public String epc;
public Date firstSeen;
public Date lastSeen;
}
private static HashMap<String, NotifiedTag> mNotifiedTags = new HashMap<String, NotifiedTag>();
private static void log(String str)
{
System.out.println(dateFmt.format(new Date()) + ": " + str);
}
// Init and connect to mqtt broker
private static void initMqtt()
{
if (mosquClient != null && mosquClient.isConnected())
return;
try {
if (mosquClient == null) {
mosquClient = new MqttClient(broker, clientId);
mosquClient.setCallback(mqttCallbacks);
}
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setMaxInflight(100);
log("Connecting to broker: " + broker);
mosquClient.connect(connOpts);
log("Connected to broker");
int qos = 0;
mosquClient.subscribe(topicctl, qos);
mosquClient.subscribe(topicsave, qos);
}
catch (Exception me) {
log("Cannot connect MQTT: " + me.getMessage());
}
}
// Publish message to specific topic (catch by e.g. browser client)
private static void publishMessage(String content, String topic)
{
if (mosquClient == null || !mosquClient.isConnected())
return;
try {
message.setPayload(content.getBytes());
mosquClient.publish(topic, message);
//log("publishMessage() " + content + " topic " + topic);
}
catch (Exception me) {
log("Cannot publish MQTT: " + me.getMessage());
try {
mosquClient.disconnect();
} catch (Exception e) { }
}
}
// Publish status event
private static void publishStatus(String status)
{
lastStatus = status;
log("publishStatus() " + status);
String statusJson = "{ \"type\": \"status\", \"msg\": \""+status+"\" }";
publishMessage(statusJson, topicev);
}
private static void publishEvent(String msg)
{
log("publishEvent() " + msg);
msg = msg.replace("\"", "\\\"");
String statusJson = "{ \"type\": \"event\", \"msg\": \""+msg+"\" }";
publishMessage(statusJson, topicev);
}
/**
* Unescapes a string that contains standard Java escape sequences.
* <ul>
* <li><strong>\b \f \n \r \t \" \'</strong> :
* BS, FF, NL, CR, TAB, double and single quote.</li>
* <li><strong>\X \XX \XXX</strong> : Octal character
* specification (0 - 377, 0x00 - 0xFF).</li>
* <li><strong>\uXXXX</strong> : Hexadecimal based Unicode character.</li>
* </ul>
*
* @param st
* A string optionally containing standard java escape sequences.
* @return The translated string.
*/
private static String unescapeJavaString(String st) {
StringBuilder sb = new StringBuilder(st.length());
for (int i = 0; i < st.length(); i++) {
char ch = st.charAt(i);
if (ch == '\\') {
char nextChar = (i == st.length() - 1) ? '\\' : st
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= st.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + st.charAt(i + 2) + st.charAt(i + 3)
+ st.charAt(i + 4) + st.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
private static void SendToSocket(String str) throws IOException
{
Socket socket = null;
try {
socket = new Socket(outputAddress, (int)outputPort);
OutputStream outstream = (OutputStream) socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.print(str);
out.flush();
out.close();
outstream.close();
} catch (UnknownHostException e) {
publishEvent("SendToSocket failed: " + e.getMessage());
} finally {
if(socket != null)
socket.close();
}
}
private static void SendHTTPPost(String str) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, ClientProtocolException, IOException
{
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
//allow self-signed certificates by default, feel free to modify to fit your requirements
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
String encoding = Base64.encode(postUser + ":" + postPwd);
HttpPost httpPost = new HttpPost(outputAddress);
if(postAuth == true)
httpPost.addHeader("Authorization", "Basic " + encoding);
if(postHeader == 0)
{
StringEntity params = new StringEntity(str);
httpPost.setEntity(params);
httpPost.addHeader("content-type", "application/json");
log("Posting JSON");
}
else
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(postKey, str));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
httpPost.addHeader("content-type", "multipart/form-data");
}
CloseableHttpResponse response = httpClient.execute(httpPost);
}
private static String getReplStr(String replStr, NurTag t)
{
if (replStr.startsWith("EPC")) {
return t.getEpcString();
}
else if (replStr.startsWith("ANTID")) {
return Integer.toString(t.getAntennaId());
}
else if (replStr.startsWith("RSSI")) {
return Integer.toString(t.getRssi());
}
else if (replStr.startsWith("SRSSI")) {
return Integer.toString(t.getScaledRssi());
}
else if (replStr.startsWith("FREQ")) {
return Integer.toString(t.getFreq());
}
else if (replStr.startsWith("URI")) {
try
{
return new EPCTagEngine(t.getEpcString()).buildTagEAN();
}
catch(Exception e)
{
return t.getEpcString();
}
}
return null;
}
private static String replaceOne(String str, NurTag t, String replStr, int startPos, int endPos, int []nextPos)
{
String repl = getReplStr(replStr, t);
if (repl == null)
{
int curly = replStr.indexOf('{');
if (curly != -1) {
nextPos[0] = startPos + curly;
} else {
nextPos[0] = endPos;
}
return str;
}
final Pattern pattern = Pattern.compile(":(.*?)\\Z");
final Matcher matcher = pattern.matcher(replStr);
int stripLen = 0;
if (matcher.find()) {
try {
stripLen = Integer.parseInt(matcher.group(1));
if (stripLen < 0) {
repl = repl.substring(repl.length() + stripLen);
} else {
repl = repl.substring(0, stripLen);
}
} catch (Exception e) {
e.printStackTrace();
}
}
String ret = str.substring(0, startPos);
ret += repl;
nextPos[0] = ret.length();
ret += str.substring(endPos);
return ret;
}
private static String replaceAll(String str, NurTag t)
{
Pattern pattern = Pattern.compile("\\{(.+?)\\}");
int []nextPos = new int[1];
nextPos[0] = 0;
int maxLoops = 1000;
while (maxLoops-- > 0)
{
Matcher matcher = pattern.matcher(str);
if (matcher.find(nextPos[0])) {
str = replaceOne(str, t, matcher.group(1), matcher.start(), matcher.end(), nextPos);
} else {
break;
}
}
return str;
}
private static void notifyTag(NurTag t)
{
log("notifyTag() " + t.getEpcString() + "; outputType " + outputType);
try {
String str = replaceAll(outputFormat, t);
// log("Notify tag: " + str);
publishEvent("Notify tag: " + str);
if (outputType == 1)
{
str = unescapeJavaString(str);
FileWriter file = new FileWriter("/dev/uartRoute");
file.write(str);
file.flush();
file.close();
}
else if(outputType == 2)
{
SendToSocket(str);
}
else if(outputType == 3)
{
SendHTTPPost(str);
}
}
catch (Exception e)
{
publishEvent("notifyTag failed, stopping inventory. Exception: " + e.toString());
publishMessage("stop", topicctl);
e.printStackTrace();
}
}
static boolean newTagsAdded = false;
private static void handleNewTags()
{
Date now = new Date();
newTagsAdded = false;
synchronized (mApi.getStorage())
{
for (int n=0; n<mApi.getStorage().size(); n++)
{
NurTag t = mApi.getStorage().get(n);
if (mNotifiedTags.containsKey(t.getEpcString())) {
mNotifiedTags.get(t.getEpcString()).lastSeen = now;
} else {
newTagsAdded = true;
NotifiedTag notifiedTag = new NotifiedTag();
notifiedTag.epc = t.getEpcString();
notifiedTag.firstSeen = now;
notifiedTag.lastSeen = now;
mNotifiedTags.put(t.getEpcString(), notifiedTag);
notifyTag(t);
}
}
mApi.getStorage().clear();
}
}
// Publish inventoried tags
private static void publishTags()
{
newTagsAdded = false;
houseKeeping();
Date now = new Date();
JSONObject tagsJson = new JSONObject();
JSONArray tagsList = new JSONArray();
Iterator it = mNotifiedTags.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
NotifiedTag notifiedTag = (NotifiedTag)pair.getValue();
JSONObject tagJson = new JSONObject();
tagJson.put("epc", notifiedTag.epc);
tagJson.put("firstSeen", notifiedTag.firstSeen.getTime());
tagJson.put("lastSeen", now.getTime() - notifiedTag.lastSeen.getTime());
tagsList.add(tagJson);
}
tagsJson.put("type", "tags");
tagsJson.put("tags", tagsList);
publishMessage(tagsJson.toString(), topicev);
}
private static boolean houseKeeping()
{
boolean ret = false;
Date now = new Date();
Iterator it = mNotifiedTags.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
NotifiedTag notifiedTag = (NotifiedTag)pair.getValue();
if ((now.getTime()-notifiedTag.lastSeen.getTime())/1000 >= notifyUniqueTime) {
log("Expired tag: " + notifiedTag.epc);
publishEvent("Expired tag: " + notifiedTag.epc);
it.remove();
ret = true;
}
}
return ret;
}
// Connect nur reader over TCP/IP
private static boolean connectNurIP(String addr, int port)
{
try {
mApi.setTransport(new NurApiSocketTransport(addr, port));
mApi.connect();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
static String settingsFile = System.getenv("HOME") + "/../frontend/settings.json";
static String outputFormat = "{EPC}\\n";
static long txLevel = 0;
static long notifyUniqueTime = 3600;
static long outputType = 0;
static String outputAddress = "";
static long outputPort = 80;
static long postHeader = 0;
static String postKey = "";
static String postUser = "";
static String postPwd = "";
static Boolean postAuth = false;
static JSONObject getSettingsJsonObject()
{
JSONObject obj = new JSONObject();
obj.put("outputFormat", outputFormat);
obj.put("txLevel", txLevel);
obj.put("notifyUniqueTime", notifyUniqueTime);
obj.put("outputType", outputType);
obj.put("outputAddress", outputAddress);
obj.put("outputPort", outputPort);
obj.put("postHeader", postHeader);
obj.put("postKey", postKey);
obj.put("postUser", postUser);
obj.put("postPwd", postPwd);
obj.put("postAuth", postAuth);
log("getSettingsJsonObject: " + postUser);
return obj;
}
static void saveSettings()
{
try {
JSONObject obj = getSettingsJsonObject();
log("saveSettings " + obj.get("postUser"));
FileWriter file = new FileWriter(settingsFile);
file.write(obj.toJSONString());
file.flush();
log("SAVED:");
log(obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
static void publishSettings()
{
JSONObject obj = new JSONObject();
obj.put("type", "settings");
obj.put("settings", getSettingsJsonObject());
publishMessage(obj.toString(), topicev);
}
static void loadSettings(String jsonData)
{
try {
JSONParser parser = new JSONParser();
Object obj;
if (jsonData.length() == 0) {
obj = parser.parse(new FileReader(settingsFile));
} else {
obj = parser.parse(jsonData);
}
JSONObject jsonObject = (JSONObject) obj;
if (jsonObject.containsKey("outputFormat"))
outputFormat = (String) jsonObject.get("outputFormat");
if (jsonObject.containsKey("txLevel"))
txLevel = (Long) jsonObject.get("txLevel");
if (jsonObject.containsKey("notifyUniqueTime"))
notifyUniqueTime = (Long) jsonObject.get("notifyUniqueTime");
if (jsonObject.containsKey("outputType"))
outputType = (Long) jsonObject.get("outputType");
if (jsonObject.containsKey("outputAddress"))
outputAddress = (String) jsonObject.get("outputAddress");
if (jsonObject.containsKey("outputPort"))
outputPort = (Long) jsonObject.get("outputPort");
if(jsonObject.containsKey("postHeader"))
postHeader = (Long) jsonObject.get("postHeader");
if(jsonObject.containsKey("postKey"))
postKey = (String) jsonObject.get("postKey");
if(jsonObject.containsKey("postUser"))
postUser = (String) jsonObject.get("postUser");
if(jsonObject.containsKey("postPwd"))
postPwd = (String) jsonObject.get("postPwd");
if(jsonObject.containsKey("postAuth"))
postAuth = (Boolean) jsonObject.get("postAuth");
log("loadSettings: " + postUser);
log("LOADED:");
log(jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
try {
if (mApi.isConnected()) {
mApi.setSetupTxLevel((int)txLevel);
}
} catch (Exception ex)
{ }
}
public static void main(String[] args) {
log("hidreader main enter; NurApi v" + mApi.getFileVersion());
loadSettings("");
saveSettings();
// Set listener for NurApi
mApi.setListener(new NurApiListener() {
@Override
public void triggeredReadEvent(NurEventTriggeredRead arg0) {
// TODO Auto-generated method stub
}
@Override
public void traceTagEvent(NurEventTraceTag arg0) {
// TODO Auto-generated method stub
}
@Override
public void programmingProgressEvent(NurEventProgrammingProgress arg0) {
// TODO Auto-generated method stub
}
@Override
public void logEvent(int arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void inventoryStreamEvent(NurEventInventory arg0) {
// Got some tags
if(arg0.tagsAdded != 0)
{
handleNewTags();
}
if (arg0.stopped)
{
// Restart stream
//log("Restart inventory stream");
try {
mApi.startInventoryStream();
} catch (Exception e)
{
publishStatus("error " + e.getMessage());
}
}
}
@Override
public void inventoryExtendedStreamEvent(NurEventInventory arg0) {
// TODO Auto-generated method stub
}
@Override
public void frequencyHopEvent(NurEventFrequencyHop arg0) {
// TODO Auto-generated method stub
}
@Override
public void disconnectedEvent() {
// TODO Auto-generated method stub
}
@Override
public void deviceSearchEvent(NurEventDeviceInfo arg0) {
// TODO Auto-generated method stub
}
@Override
public void debugMessageEvent(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void connectedEvent() {
try {
mApi.setSetupTxLevel((int)txLevel);
} catch (Exception ex)
{ }
}
@Override
public void clientDisconnectedEvent(NurEventClientInfo arg0) {
// TODO Auto-generated method stub
}
@Override
public void clientConnectedEvent(NurEventClientInfo arg0) {
// TODO Auto-generated method stub
}
@Override
public void bootEvent(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void IOChangeEvent(NurEventIOChange arg0) {
// TODO Auto-generated method stub
}
@Override
public void autotuneEvent(NurEventAutotune arg0) {
// TODO Auto-generated method stub
}
@Override
public void epcEnumEvent(NurEventEpcEnum arg0) {
// TODO Auto-generated method stub
}
@Override
public void nxpEasAlarmEvent(NurEventNxpAlarm arg0) {
// TODO Auto-generated method stub
}
@Override
public void tagTrackingChangeEvent(NurEventTagTrackingChange arg0) {
// TODO Auto-generated method stub
}
@Override
public void tagTrackingScanEvent(NurEventTagTrackingData arg0) {
// TODO Auto-generated method stub
}
});
while (true)
{
try {
Thread.sleep(1000);
} catch (Exception e)
{
break;
}
// init mqtt for sending the results
initMqtt();
if (!mApi.isConnected())
{
if (!connectNurIP("localhost", 4333))
{
publishStatus("noconn");
continue;
}
else
{
try {
mApi.startInventoryStream();
publishStatus("running");
} catch (Exception e)
{
publishStatus("error " + e.getMessage());
}
//publishStatus("idle");
}
}
else
{
if (houseKeeping() || newTagsAdded) {
publishTags();
}
}
}
log("hidreader main leave");
}
/****************************************************************/
/* Methods to implement the MqttCallback interface */
/****************************************************************/
private static MqttCallback mqttCallbacks = new MqttCallback()
{
/**
* @see MqttCallback#connectionLost(Throwable)
*/
@Override
public void connectionLost(Throwable cause) {
// Called when the connection to the server has been lost.
// An application may choose to implement reconnection
// logic at this point. This sample simply exits.
log("Connection to " + broker + " lost!" + cause);
}
/**
* @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Called when a message has been delivered to the
// server. The token passed in here is the same one
// that was passed to or returned from the original call to publish.
// This allows applications to perform asynchronous
// delivery without blocking until delivery completes.
//
// This sample demonstrates asynchronous deliver and
// uses the token.waitForCompletion() call in the main thread which
// blocks until the delivery has completed.
// Additionally the deliveryComplete method will be called if
// the callback is set on the client
//
// If the connection to the server breaks before delivery has completed
// delivery of a message will complete after the client has re-connected.
// The getPendingTokens method will provide tokens for any messages
// that are still to be delivered.
}
/**
* @see MqttCallback#messageArrived(String, MqttMessage)
*/
@Override
public void messageArrived(String topic, MqttMessage message) throws MqttException {
// Called when a message arrives from the server that matches any
// subscription made by the client
String msg = new String(message.getPayload());
log("messageArrived() Topic:\t" + topic + " Message:\t" + msg);
if (topic.equals(topicsave)) {
loadSettings(msg);
saveSettings();
publishEvent("Settings saved");
publishSettings();
return;
}
if (msg.equals("getTags"))
{
publishTags();
}
else if (msg.equals("getSettings"))
{
try {
publishSettings();
} catch(Exception e)
{
publishStatus("error " + e.getMessage());
}
}
else if (msg.equals("resetSettings"))
{
try {
Files.delete(Paths.get(settingsFile));
} catch(Exception e)
{
}
try {
outputFormat = "{EPC}\\n";
txLevel = 0;
notifyUniqueTime = 3600;
outputType = 0;
saveSettings();
publishSettings();
} catch(Exception e)
{
publishStatus("error " + e.getMessage());
}
}
else if (msg.equals("status"))
{
publishStatus(lastStatus);
}
else if (msg.equals("clear"))
{
try {
mNotifiedTags.clear();
publishEvent("Cleared");
publishTags();
} catch(Exception e)
{
publishStatus("error " + e.getMessage());
}
}
else if (msg.equals("stop"))
{
try {
mApi.stopInventoryStream();
publishStatus("idle");
} catch(Exception e)
{
publishStatus("error " + e.getMessage());
}
}
else if (msg.equals("start"))
{
try {
mApi.startInventoryStream();
publishStatus("running");
} catch(Exception e)
{
publishStatus("error " + e.getMessage());
}
}
}
};
/****************************************************************/
/* End of MqttCallback methods */
/****************************************************************/
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
java
| 1 | 0 | |
text2error/edits/generators/random/mlm/abc/model.py
|
from typing import * # pylint: disable=wildcard-import,unused-wildcard-import
from abc import abstractmethod
import random
import functools
import os
from transformers import AutoModelWithLMHead
from transformers import PreTrainedModel
from transformers.tokenization_utils import BatchEncoding
from .tokenizer import MaskedLMRandomTextEditsGeneratorWithTokenizer
from .....edit import TextEdit
from ......utils.cache import KeyedSingletonLoader
class MaskedLMRandomTextEditsGeneratorWithModel(
MaskedLMRandomTextEditsGeneratorWithTokenizer
):
# pylint: disable=too-few-public-methods
models_cache = KeyedSingletonLoader()
def __init__(
self,
model_name: str = "bert-base-cased",
device: Optional[str] = None,
rng: Optional[random.Random] = None,
edits_num: Optional[Union[int, Callable[[int, Optional[int]], int]]] = None,
) -> None:
super().__init__(model_name, rng, edits_num)
self.device = device
self.model = self.__load_model(self.model_name, device=self.device)
def __del__(self) -> None:
super().__del__()
self.__unload_model(self.model_name, device=self.device)
@abstractmethod
def generate(self, text: str) -> List[TextEdit]:
... # pragma: no cover
def _model_encode(self, text: str) -> BatchEncoding:
encoding = self.tokenizer.encode_plus(
text,
add_special_tokens=True,
return_special_tokens_mask=True,
return_tensors="pt",
)
# TODO: Handle overflowing elements for long sentences.
return encoding
@classmethod
def __load_model(
cls, model_name: str, device: Optional[str] = None
) -> PreTrainedModel:
key = model_name + "-" + str(device)
model_provider = functools.partial(
cls.__load_transformers_model, model_name, device=device
)
return cls.models_cache.load(key, model_provider)
@classmethod
def __unload_model(cls, model_name: str, device: Optional[str] = None) -> None:
key = model_name + "-" + str(device)
cls.models_cache.unload(key)
@classmethod
def __load_transformers_model(
cls, model_name: str, **kwargs: Any
) -> PreTrainedModel:
cache_dir = os.environ.get("TRANSFORMERS_CACHE_DIR", ".transformers_cache")
model = AutoModelWithLMHead.from_pretrained(model_name, cache_dir=cache_dir)
if not model.__class__.__name__.endswith("ForMaskedLM"):
raise ValueError("The model provided is not a Masked LM: %s" % model_name)
if "device" in kwargs:
model = model.to(kwargs.get("device"))
model.eval()
return model
|
[] |
[] |
[
"TRANSFORMERS_CACHE_DIR"
] |
[]
|
["TRANSFORMERS_CACHE_DIR"]
|
python
| 1 | 0 | |
cmd/zelus-benchmark/main.go
|
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"strings"
"sync/atomic"
"time"
"github.com/orkunkaraduman/zelus/pkg/client"
"github.com/orkunkaraduman/zelus/pkg/protocol"
)
func main() {
fmt.Printf("zelus-benchmark\n\n")
pp := os.Getenv("PPROF")
if pp != "" {
go func() {
log.Fatalln(http.ListenAndServe(pp, nil))
}()
}
var err error
ca := newCmdArgs(os.Stdout)
err = ca.Parse(os.Args[1:])
if err != nil {
os.Exit(2)
}
defer func() {
if e, ok := recover().(error); ok {
fmt.Println("Error:", e.Error())
fmt.Println("")
os.Exit(1)
}
fmt.Println("")
}()
fmt.Printf("Connecting clients to server...\n")
protocol.BufferSize = 1 * 1024 * 1024
client.ConnBufferSize = 1 * 1024 * 1024
cls := make([]*client.Client, ca.Clients)
closeFunc := func() {
for _, cl := range cls {
if cl == nil {
continue
}
cl.Close()
}
}
defer closeFunc()
sigIntCh := make(chan os.Signal, 1)
signal.Notify(sigIntCh, os.Interrupt)
go func() {
<-sigIntCh
closeFunc()
}()
for i := range cls {
if ca.Socket == "" {
cls[i], err = client.New("tcp", ca.Hostname)
} else {
cls[i], err = client.New("unix", ca.Socket)
}
if err != nil {
panic(err)
}
}
fmt.Printf("Preparing...\n\n")
brChs := make([]chan benchmarkResult, ca.Clients)
for i := range brChs {
brChs[i] = make(chan benchmarkResult)
}
keys := make([]string, ca.Requests)
for i := range keys {
keys[i] = fmt.Sprintf("%s%d", ca.Prefix, i)
}
fmt.Printf("Number of clients: %d\nNumber of requests: %d\n\n\n", ca.Clients, ca.Requests)
numberOfRequests := int(ca.Requests)
requestsPerClient := int(ca.Requests / ca.Clients)
tests := strings.Split(strings.ToUpper(ca.Tests), ",")
err = nil
for err == nil {
for _, test := range tests {
test = strings.TrimSpace(test)
count := int64(0)
n, m := 0, numberOfRequests-requestsPerClient*len(cls)
for i := range cls {
l := requestsPerClient
if m > 0 {
l++
m--
}
switch test {
case "SET":
go set(cls[i], keys[n:n+l], int(ca.Multi), int(ca.Datasize), brChs[i], &count)
case "GET":
go get(cls[i], keys[n:n+l], int(ca.Multi), int(ca.Datasize), brChs[i], &count)
case "DEL":
go del(cls[i], keys[n:n+l], int(ca.Multi), int(ca.Datasize), brChs[i], &count)
default:
panic(fmt.Errorf("test %s is unknown", test))
}
n += l
}
startTm := time.Now()
lastCount := int64(0)
lastNs := startTm.UnixNano()
tk := time.NewTicker(1 * time.Second)
go func() {
for now := range tk.C {
ns := now.UnixNano()
currCount := atomic.LoadInt64(&count)
fmt.Printf("%12d/%d: %d req/s\n",
count,
len(keys),
1000000000*(currCount-lastCount)/(ns-lastNs),
)
lastCount = currCount
lastNs = ns
}
}()
fmt.Printf("Test %s started.\n", test)
tbr := benchmarkResult{}
for _, brCh := range brChs {
br := <-brCh
if err == nil {
err = br.err
}
tbr.count += br.count
tbr.duration += br.duration
}
tk.Stop()
runtime.Gosched()
ns := tbr.duration.Nanoseconds() / int64(len(cls))
fmt.Printf("\n Number of requests: %d/%d (%.2f%%)\n Avarage duration: %v\n Requests per second: %d\n\n\n",
tbr.count,
numberOfRequests,
float64(100*tbr.count)/float64(numberOfRequests),
time.Duration(ns),
1000000000*tbr.count/ns,
)
if err != nil {
break
}
}
if !ca.Loop {
break
}
}
}
|
[
"\"PPROF\""
] |
[] |
[
"PPROF"
] |
[]
|
["PPROF"]
|
go
| 1 | 0 | |
serverless-vpc-access/cloudfunction/test/main.py
|
import os
import json
import requests
def query_url():
ip = os.environ["HTTP_ENDPOINT"]
url = f'http://{ip}/'
response = requests.get(url)
return json.dumps(dict(url=url,
status=response.status_code,
headers=dict(response.headers),
env=dict(os.environ)),
indent=4,
sort_keys=True)
def main(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
request_json = request.get_json()
if request.args and 'message' in request.args and request.args.get('message') == 'call_nginx':
return query_url()
elif request_json and 'message' in request_json:
return request_json['message']
if __name__ == "__main__":
print(query_url())
|
[] |
[] |
[
"HTTP_ENDPOINT"
] |
[]
|
["HTTP_ENDPOINT"]
|
python
| 1 | 0 | |
src/capabilities/launch_manager.py
|
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Open Source Robotics Foundation, Inc. nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Author: William Woodall <[email protected]>
"""This module manages the launching of capabilities"""
from __future__ import print_function
import copy
import os
import subprocess
import sys
import threading
import rospy
from capabilities.msg import CapabilityEvent
def which(program):
"""Custom versions of the ``which`` built-in shell command
Searches the pathes in the ``PATH`` environment variable for a given
executable name. It returns the full path to the first instance of the
executable found or None if it was not found.
:param program: name of the executable to find
:type program: str
:returns: Full path to the first instance of the executable, or None
:rtype: str or None
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ.get('PATH', os.defpath).split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
_this_dir = os.path.dirname(__file__)
_placeholder_script = os.path.join(_this_dir, 'placeholder_script')
_nodelet_manager_launch_file = os.path.join(_this_dir, 'capability_server_nodelet_manager.launch')
_special_nodelet_manager_capability = '!!nodelet_manager'
class LaunchManager(object):
"""Manages multiple launch files which implement capabilities"""
__roslaunch_exec = which('roslaunch')
__python_exec = which('python')
def __init__(self, quiet=False, screen=False, nodelet_manager_name=None):
self.__running_launch_files_lock = threading.Lock()
with self.__running_launch_files_lock:
self.__running_launch_files = {}
self.__outputs = [sys.stdout]
self.__event_publisher = rospy.Publisher("~events", CapabilityEvent, queue_size=1000)
self.__event_subscriber = rospy.Subscriber(
"~events", CapabilityEvent, self.handle_capability_events)
self.stopping = False
self.__quiet = quiet
self.__screen = screen
name = rospy.get_namespace()
name += "" if name.startswith('/') else "/"
name += nodelet_manager_name if nodelet_manager_name else rospy.get_name().split('/')[-1] + '_nodelet_manager'
self.__nodelet_manager_name = name
self.__start_nodelet_manager()
@property
def nodelet_manager_name(self):
return self.__nodelet_manager_name
def stop(self):
"""Stops the launch manager, also stopping any running launch files"""
if self.stopping:
return # pragma: no cover
with self.__running_launch_files_lock:
# Incase the other thread tried the lock before this thread updated
# the self.stopping variable, check it again.
if self.stopping:
return # pragma: no cover
self.stopping = True
for pid in self.__running_launch_files: # pragma: no cover
try:
self.__stop_by_pid(pid)
except RuntimeError as exc:
if "launch file with PID" not in "{0}".format(exc):
raise # Re-raise
def __stop_by_pid(self, pid):
if pid not in self.__running_launch_files:
raise RuntimeError("No running launch file with PID of '{0}'".format(pid))
proc, thread, _, _ = self.__running_launch_files[pid]
if proc.poll() is None:
proc.terminate()
proc.wait()
thread.join()
def stop_capability_provider(self, pid):
"""Stops the launch file for a capability provider, by pid
:param pid: process ID of the launch file process that be stopped.
:type pid: int
"""
with self.__running_launch_files_lock:
self.__stop_by_pid(pid)
def handle_capability_events(self, msg):
"""Callback for events recieved on the events topic
Only handles TERMINDATED events, all other events are discarded.
:param msg: ROS message recieved on the events topic
:type msg: :py:class:`capabilities.msgs.CapabilityEvent`
"""
if msg.type == msg.SERVER_READY:
return
if msg.type != msg.TERMINATED:
return
with self.__running_launch_files_lock:
if msg.pid in self.__running_launch_files:
del self.__running_launch_files[msg.pid]
def run_capability_provider(self, provider, provider_path):
"""Runs a given capability provider by launching its launch file
:param provider: provider that should be launched
:type provider: :py:class:`capabilities.specs.provider.CapabilityProvider`
:param provider_path: path which the provider spec file is located at
:type provider_path: str
"""
if os.path.isfile(provider_path):
provider_path = os.path.dirname(provider_path)
if provider.launch_file is None:
launch_file = None
rospy.loginfo("Provider '{0}' does not have a launch file, running a placeholder."
.format(provider.name))
else:
launch_file = os.path.join(provider_path, provider.launch_file)
self.run_launch_file(launch_file, provider)
def run_launch_file(self, launch_file, provider, manager=False):
with self.__running_launch_files_lock:
if launch_file is not None and launch_file in [x[3] for x in self.__running_launch_files.values()]:
raise RuntimeError("Launch file at '{0}' is already running."
.format(launch_file))
if launch_file is None:
cmd = [self.__python_exec, _placeholder_script]
else:
if self.__screen:
cmd = [self.__roslaunch_exec, '--screen', launch_file]
else:
cmd = [self.__roslaunch_exec, launch_file]
if manager:
cmd.append("capability_server_nodelet_manager_name:=" + self.__nodelet_manager_name.split('/')[-1])
else:
cmd.append("capability_server_nodelet_manager_name:=" + self.__nodelet_manager_name)
if self.__quiet:
env = copy.deepcopy(os.environ)
env['PYTHONUNBUFFERED'] = 'x'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
else:
proc = subprocess.Popen(cmd)
thread = self.__start_communication_thread(proc)
msg = CapabilityEvent()
msg.header.stamp = rospy.Time.now()
msg.capability = provider.implements
msg.provider = provider.name
msg.pid = proc.pid
msg.type = msg.LAUNCHED
self.__running_launch_files[proc.pid] = [
proc, thread, provider, launch_file
]
self.__event_publisher.publish(msg)
thread.start()
def __start_nodelet_manager(self):
class MockProvider:
implements = _special_nodelet_manager_capability
name = rospy.get_name().lstrip('/')
provider = MockProvider()
launch_file = _nodelet_manager_launch_file
self.run_launch_file(launch_file, provider, manager=True)
def __start_communication_thread(self, proc):
return threading.Thread(target=self.__monitor_process, args=(proc,))
def __monitor_process(self, proc):
try:
with self.__running_launch_files_lock:
if proc.pid not in self.__running_launch_files:
raise RuntimeError("Unknown process id: " + str(proc.pid))
provider = self.__running_launch_files[proc.pid][2]
if proc.stdout is not None:
while proc.returncode is None:
try:
for line in iter(proc.stdout.readline, ''):
for output in self.__outputs:
output.write(line)
except KeyboardInterrupt: # pragma: no cover
pass
proc.poll()
else:
proc.wait()
msg = CapabilityEvent()
msg.header.stamp = rospy.Time.now()
msg.capability = provider.implements
msg.provider = provider.name
msg.type = msg.TERMINATED
msg.pid = proc.pid
self.__event_publisher.publish(msg)
except Exception as exc:
rospy.logerr('{0}: {1}'.format(exc.__class__.__name__, str(exc)))
raise
assert LaunchManager._LaunchManager__roslaunch_exec is not None, "'roslaunch' executable not found"
|
[] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
python
| 1 | 0 | |
tabnine-vim/third_party/ycmd/update_clang.py
|
#!/usr/bin/env python
# Passing an environment variable containing unicode literals to a subprocess
# on Windows and Python2 raises a TypeError. Since there is no unicode
# string in this script, we don't import unicode_literals to avoid the issue.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import subprocess
import contextlib
import os
import os.path as p
import platform
import shutil
import sys
import tempfile
import tarfile
import hashlib
from distutils.spawn import find_executable
try:
import lzma
except:
from backports import lzma
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
sys.path.insert( 0, os.path.join( DIR_OF_THIS_SCRIPT, 'ycmd' ) )
from ycmd import server_utils
server_utils.SetUpPythonPath()
# Not installing aliases from python-future; it's unreliable and slow.
from builtins import * # noqa
from future.utils import iteritems
import argparse
import requests
from io import BytesIO
def OnWindows():
return platform.system() == 'Windows'
def OnMac():
return platform.system() == 'Darwin'
LLVM_DOWNLOAD_DATA = {
'win32': {
'format': 'nsis',
'llvm_package': 'LLVM-{llvm_version}-{os_name}.exe',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'bin', 'libclang.dll' ),
os.path.join( 'lib', 'libclang.lib' ),
]
},
'win64': {
'format': 'nsis',
'llvm_package': 'LLVM-{llvm_version}-{os_name}.exe',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'bin', 'libclang.dll' ),
os.path.join( 'lib', 'libclang.lib' ),
]
},
'x86_64-apple-darwin': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.dylib' )
]
},
'x86_64-linux-gnu-ubuntu-14.04': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.so' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.1}' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.3}' )
]
},
'i386-unknown-freebsd-10': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.so' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.1}' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.3}' )
]
},
'amd64-unknown-freebsd-10': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.so' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.1}' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.3}' )
]
},
'aarch64-linux-gnu': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.so' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.1}' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.3}' )
]
},
'armv7a-linux-gnueabihf': {
'format': 'lzma',
'llvm_package': 'clang+llvm-{llvm_version}-{os_name}.tar.xz',
'ycmd_package': 'libclang-{llvm_version}-{os_name}.tar.bz2',
'files_to_copy': [
os.path.join( 'lib', 'libclang.so' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.1}' ),
os.path.join( 'lib', 'libclang.so.{llvm_version:.3}' )
]
},
}
@contextlib.contextmanager
def TemporaryDirectory():
temp_dir = tempfile.mkdtemp()
try:
yield temp_dir
finally:
shutil.rmtree( temp_dir )
def DownloadClangLicense( version, destination ):
print( 'Downloading license...' )
request = requests.get(
'https://releases.llvm.org/{version}/LICENSE.TXT'.format( version=version ),
stream = True )
request.raise_for_status()
file_name = os.path.join( destination, 'LICENSE.TXT' )
with open( file_name, 'wb' ) as f:
f.write( request.content )
request.close()
return file_name
def Download( url ):
print( 'Downloading {}'.format( url.rsplit( '/', 1 )[ -1 ] ) )
request = requests.get( url, stream=True )
request.raise_for_status()
content = request.content
request.close()
return content
def ExtractLZMA( compressed_data, destination ):
uncompressed_data = BytesIO( lzma.decompress( compressed_data ) )
with tarfile.TarFile( fileobj=uncompressed_data, mode='r' ) as tar_file:
a_member = tar_file.getmembers()[ 0 ]
tar_file.extractall( destination )
# Determine the directory name
return os.path.join( destination,
a_member.name.split( os.path.sep )[ 0 ] )
def Extract7Z( llvm_package, archive, destination ):
# Extract with appropriate tool
if OnWindows():
# The winreg module is named _winreg on Python 2.
try:
import winreg
except ImportError:
import _winreg as winreg
with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\7-Zip' ) as key:
executable = os.path.join( winreg.QueryValueEx( key, "Path" )[ 0 ],
'7z.exe' )
elif OnMac():
executable = '/Applications/Keka.app/Contents/Resources/keka7z'
else:
# On Linux, p7zip 16.02 is required.
executable = find_executable( '7z' )
command = [
executable,
'-y',
'x',
archive,
'-o' + destination
]
# Silence 7-Zip output.
subprocess.check_call( command, stdout = subprocess.PIPE )
return destination
def MakeBundle( files_to_copy,
license_file_name,
source_dir,
bundle_file_name,
hashes,
version ):
archive_name = os.path.basename( bundle_file_name )
print( 'Bundling files to {}'.format( archive_name ) )
with tarfile.open( name=bundle_file_name, mode='w:bz2' ) as tar_file:
tar_file.add( license_file_name, arcname='LICENSE.TXT' )
for file_name in files_to_copy:
arcname = file_name.format( llvm_version = version )
name = os.path.join( source_dir, arcname )
if not os.path.exists( name ):
raise RuntimeError( 'File {} does not exist.'.format( name ) )
tar_file.add( name = name, arcname = arcname )
sys.stdout.write( 'Calculating checksum: ' )
with open( bundle_file_name, 'rb' ) as f:
hashes[ archive_name ] = hashlib.sha256( f.read() ).hexdigest()
print( hashes[ archive_name ] )
def UploadBundleToBintray( user_name,
api_token,
os_name,
version,
bundle_file_name ):
print( 'Uploading to bintray...' )
with open( bundle_file_name, 'rb' ) as bundle:
request = requests.put(
'https://api.bintray.com/content/{subject}/{repo}/{file_path}'.format(
subject = user_name,
repo = 'libclang',
file_path = os.path.basename( bundle_file_name ) ),
data = bundle,
auth = ( user_name, api_token ),
headers = {
'X-Bintray-Package': 'libclang',
'X-Bintray-Version': version,
'X-Bintray-Publish': 1,
'X-Bintray-Override': 1,
} )
request.raise_for_status()
def ParseArguments():
parser = argparse.ArgumentParser()
parser.add_argument( 'version', action='store',
help = 'The LLVM version' )
parser.add_argument( '--bt-user', action='store',
help = 'Bintray user name. Defaults to environment '
'variable: YCMD_BINTRAY_USERNAME' )
parser.add_argument( '--bt-token', action='store',
help = 'Bintray api token. Defaults to environment '
'variable: YCMD_BINTRAY_API_TOKEN.' )
parser.add_argument( '--from-cache', action='store',
help = 'Use the clang packages from this dir. Useful '
'if releases.llvm.org is unreliable.' )
parser.add_argument( '--output-dir', action='store',
help = 'For testing, directory to put bundles in.' )
parser.add_argument( '--no-upload', action='store_true',
help = "For testing, just build the bundles; don't "
"upload to bintray. Useful with --output-dir." )
args = parser.parse_args()
if not args.bt_user:
if 'YCMD_BINTRAY_USERNAME' not in os.environ:
raise RuntimeError( 'ERROR: Must specify either --bt-user or '
'YCMD_BINTRAY_USERNAME in environment' )
args.bt_user = os.environ[ 'YCMD_BINTRAY_USERNAME' ]
if not args.bt_token:
if 'YCMD_BINTRAY_API_TOKEN' not in os.environ:
raise RuntimeError( 'ERROR: Must specify either --bt-token or '
'YCMD_BINTRAY_API_TOKEN in environment' )
args.bt_token = os.environ[ 'YCMD_BINTRAY_API_TOKEN' ]
return args
def PrepareBundleLZMA( cache_dir, llvm_package, download_url, temp_dir ):
package_dir = None
if cache_dir:
archive = os.path.join( cache_dir, llvm_package )
print( 'Extracting cached {}'.format( llvm_package ) )
try:
with open( archive, 'rb' ) as f:
package_dir = ExtractLZMA( f.read(), temp_dir )
except IOError:
pass
if not package_dir:
compressed_data = Download( download_url )
print( 'Extracting {}'.format( llvm_package ) )
package_dir = ExtractLZMA( compressed_data, temp_dir )
return package_dir
def PrepareBundleNSIS( cache_dir, llvm_package, download_url, temp_dir ):
if cache_dir:
archive = os.path.join( cache_dir, llvm_package )
print( 'Extracting cached {}'.format( llvm_package ) )
else:
compressed_data = Download( download_url )
archive = os.path.join( temp_dir, llvm_package )
with open( archive, 'wb' ) as f:
f.write( compressed_data )
print( 'Extracting {}'.format( llvm_package ) )
return Extract7Z( llvm_package, archive, temp_dir )
def BundleAndUpload( args, temp_dir, output_dir, os_name, download_data,
license_file_name, hashes ):
llvm_package = download_data[ 'llvm_package' ].format(
os_name = os_name,
llvm_version = args.version )
ycmd_package = download_data[ 'ycmd_package' ].format(
os_name = os_name,
llvm_version = args.version )
download_url = (
'https://releases.llvm.org/{llvm_version}/{llvm_package}'.format(
llvm_version = args.version,
llvm_package = llvm_package ) )
ycmd_package_file = os.path.join( output_dir, ycmd_package )
if download_data[ 'format' ] == 'lzma':
package_dir = PrepareBundleLZMA( args.from_cache,
llvm_package,
download_url,
temp_dir )
elif download_data[ 'format' ] == 'nsis':
package_dir = PrepareBundleNSIS( args.from_cache,
llvm_package,
download_url,
temp_dir )
else:
raise AssertionError( 'Format not yet implemented: {}'.format(
download_data[ 'format' ] ) )
MakeBundle( download_data[ 'files_to_copy' ],
license_file_name,
package_dir,
ycmd_package_file,
hashes,
args.version )
if not args.no_upload:
UploadBundleToBintray( args.bt_user,
args.bt_token,
os_name,
args.version,
ycmd_package_file )
def Overwrite( src, dest ):
if os.path.exists( dest ):
shutil.rmtree( dest )
shutil.copytree( src, dest )
def UpdateClangHeaders( args, temp_dir ):
src_name = 'cfe-{version}.src'.format( version = args.version )
archive_name = src_name + '.tar.xz'
compressed_data = Download( 'https://releases.llvm.org/{version}/'
'{archive}'.format( version = args.version,
archive = archive_name ) )
print( 'Extracting {}'.format( archive_name ) )
src = ExtractLZMA( compressed_data, temp_dir )
print( 'Updating Clang headers...' )
includes_dir = os.path.join(
DIR_OF_THIS_SCRIPT, 'clang_includes', 'include' )
Overwrite( os.path.join( src, 'lib', 'Headers' ), includes_dir )
os.remove( os.path.join( includes_dir, 'CMakeLists.txt' ) )
Overwrite( os.path.join( src, 'include', 'clang-c' ),
os.path.join( DIR_OF_THIS_SCRIPT, 'cpp', 'llvm', 'include',
'clang-c' ) )
def Main():
args = ParseArguments()
output_dir = args.output_dir if args.output_dir else tempfile.mkdtemp()
try:
hashes = dict()
with TemporaryDirectory() as temp_dir:
license_file_name = DownloadClangLicense( args.version, temp_dir )
for os_name, download_data in iteritems( LLVM_DOWNLOAD_DATA ):
BundleAndUpload( args, temp_dir, output_dir, os_name, download_data,
license_file_name, hashes )
UpdateClangHeaders( args, temp_dir )
finally:
if not args.output_dir:
shutil.rmtree( output_dir )
for bundle_file_name, sha256 in iteritems( hashes ):
print( 'Checksum for {bundle_file_name}: {sha256}'.format(
bundle_file_name = bundle_file_name,
sha256 = sha256 ) )
if __name__ == "__main__":
Main()
|
[] |
[] |
[
"YCMD_BINTRAY_API_TOKEN'",
"YCMD_BINTRAY_USERNAME'"
] |
[]
|
["YCMD_BINTRAY_API_TOKEN'", "YCMD_BINTRAY_USERNAME'"]
|
python
| 2 | 0 | |
third_party/buildbot_slave_8_4/buildslave/scripts/logwatcher.py
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
from twisted.python.failure import Failure
from twisted.internet import defer, reactor, protocol, error
from twisted.protocols.basic import LineOnlyReceiver
class FakeTransport:
disconnecting = False
class BuildmasterTimeoutError(Exception):
pass
class BuildslaveTimeoutError(Exception):
pass
class ReconfigError(Exception):
pass
class BuildSlaveDetectedError(Exception):
pass
class TailProcess(protocol.ProcessProtocol):
def outReceived(self, data):
self.lw.dataReceived(data)
def errReceived(self, data):
print "ERR: '%s'" % (data,)
class LogWatcher(LineOnlyReceiver):
POLL_INTERVAL = 0.1
TIMEOUT_DELAY = 10.0
delimiter = os.linesep
def __init__(self, logfile):
self.logfile = logfile
self.in_reconfig = False
self.transport = FakeTransport()
self.pp = TailProcess()
self.pp.lw = self
self.processtype = "buildmaster"
self.timer = None
def start(self):
# If the log file doesn't exist, create it now.
if not os.path.exists(self.logfile):
open(self.logfile, 'a').close()
# return a Deferred that fires when the reconfig process has
# finished. It errbacks with TimeoutError if the finish line has not
# been seen within 10 seconds, and with ReconfigError if the error
# line was seen. If the logfile could not be opened, it errbacks with
# an IOError.
self.p = reactor.spawnProcess(self.pp, "/usr/bin/tail",
("tail", "-f", "-n", "0", self.logfile),
env=os.environ,
)
self.running = True
d = defer.maybeDeferred(self._start)
return d
def _start(self):
self.d = defer.Deferred()
self.timer = reactor.callLater(self.TIMEOUT_DELAY, self.timeout)
return self.d
def timeout(self):
self.timer = None
if self.processtype == "buildmaster":
e = BuildmasterTimeoutError()
else:
e = BuildslaveTimeoutError()
self.finished(Failure(e))
def finished(self, results):
try:
self.p.signalProcess("KILL")
except error.ProcessExitedAlready:
pass
if self.timer:
self.timer.cancel()
self.timer = None
self.running = False
self.in_reconfig = False
self.d.callback(results)
def lineReceived(self, line):
if not self.running:
return
if "Log opened." in line:
self.in_reconfig = True
if "loading configuration from" in line:
self.in_reconfig = True
if "Creating BuildSlave" in line:
self.processtype = "buildslave"
if self.in_reconfig:
print line
if "message from master: attached" in line:
return self.finished("buildslave")
if "I will keep using the previous config file" in line:
return self.finished(Failure(ReconfigError()))
if "configuration update complete" in line:
return self.finished("buildmaster")
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
trychange.py
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Client-side script to send a try job to the try server. It communicates to
the try server by either writting to a svn/git repository or by directly
connecting to the server by HTTP.
"""
import contextlib
import datetime
import errno
import getpass
import itertools
import json
import logging
import optparse
import os
import posixpath
import re
import shutil
import sys
import tempfile
import urllib
import urllib2
import urlparse
import breakpad # pylint: disable=W0611
import fix_encoding
import gcl
import gclient_utils
import gerrit_util
import scm
import subprocess2
__version__ = '1.2'
# Constants
HELP_STRING = "Sorry, Tryserver is not available."
USAGE = r"""%prog [options]
Client-side script to send a try job to the try server. It communicates to
the try server by either writting to a svn repository or by directly connecting
to the server by HTTP."""
EPILOG = """
Examples:
Send a patch directly from rietveld:
%(prog)s -R codereview.chromium.org/1337
--email [email protected] --root src
Try a change against a particular revision:
%(prog)s -r 123
Try a change including changes to a sub repository:
%(prog)s -s third_party/WebKit
A git patch off a web site (git inserts a/ and b/) and fix the base dir:
%(prog)s --url http://url/to/patch.diff --patchlevel 1 --root src
Use svn to store the try job, specify an alternate email address and use a
premade diff file on the local drive:
%(prog)s --email [email protected]
--svn_repo svn://svn.chromium.org/chrome-try/try --diff foo.diff
Running only on a 'mac' slave with revision 123 and clobber first; specify
manually the 3 source files to use for the try job:
%(prog)s --bot mac --revision 123 --clobber -f src/a.cc -f src/a.h
-f include/b.h
"""
GIT_PATCH_DIR_BASENAME = os.path.join('git-try', 'patches-git')
GIT_BRANCH_FILE = 'ref'
_GIT_PUSH_ATTEMPTS = 3
def DieWithError(message):
print >> sys.stderr, message
sys.exit(1)
def RunCommand(args, error_ok=False, error_message=None, **kwargs):
try:
return subprocess2.check_output(args, shell=False, **kwargs)
except subprocess2.CalledProcessError, e:
if not error_ok:
DieWithError(
'Command "%s" failed.\n%s' % (
' '.join(args), error_message or e.stdout or ''))
return e.stdout
def RunGit(args, **kwargs):
"""Returns stdout."""
return RunCommand(['git'] + args, **kwargs)
class Error(Exception):
"""An error during a try job submission.
For this error, trychange.py does not display stack trace, only message
"""
class InvalidScript(Error):
def __str__(self):
return self.args[0] + '\n' + HELP_STRING
class NoTryServerAccess(Error):
def __str__(self):
return self.args[0] + '\n' + HELP_STRING
def Escape(name):
"""Escapes characters that could interfere with the file system or try job
parsing.
"""
return re.sub(r'[^\w#-]', '_', name)
class SCM(object):
"""Simplistic base class to implement one function: ProcessOptions."""
def __init__(self, options, path, file_list):
items = path.split('@')
assert len(items) <= 2
self.checkout_root = os.path.abspath(items[0])
items.append(None)
self.diff_against = items[1]
self.options = options
# Lazy-load file list from the SCM unless files were specified in options.
self._files = None
self._file_tuples = None
if file_list:
self._files = file_list
self._file_tuples = [('M', f) for f in self.files]
self.options.files = None
self.codereview_settings = None
self.codereview_settings_file = 'codereview.settings'
self.toplevel_root = None
def GetFileNames(self):
"""Return the list of files in the diff."""
return self.files
def GetCodeReviewSetting(self, key):
"""Returns a value for the given key for this repository.
Uses gcl-style settings from the repository.
"""
if gcl:
gcl_setting = gcl.GetCodeReviewSetting(key)
if gcl_setting != '':
return gcl_setting
if self.codereview_settings is None:
self.codereview_settings = {}
settings_file = self.ReadRootFile(self.codereview_settings_file)
if settings_file:
for line in settings_file.splitlines():
if not line or line.lstrip().startswith('#'):
continue
k, v = line.split(":", 1)
self.codereview_settings[k.strip()] = v.strip()
return self.codereview_settings.get(key, '')
def _GclStyleSettings(self):
"""Set default settings based on the gcl-style settings from the repository.
The settings in the self.options object will only be set if no previous
value exists (i.e. command line flags to the try command will override the
settings in codereview.settings).
"""
settings = {
'port': self.GetCodeReviewSetting('TRYSERVER_HTTP_PORT'),
'host': self.GetCodeReviewSetting('TRYSERVER_HTTP_HOST'),
'svn_repo': self.GetCodeReviewSetting('TRYSERVER_SVN_URL'),
'gerrit_url': self.GetCodeReviewSetting('TRYSERVER_GERRIT_URL'),
'git_repo': self.GetCodeReviewSetting('TRYSERVER_GIT_URL'),
'project': self.GetCodeReviewSetting('TRYSERVER_PROJECT'),
# Primarily for revision=auto
'revision': self.GetCodeReviewSetting('TRYSERVER_REVISION'),
'root': self.GetCodeReviewSetting('TRYSERVER_ROOT'),
'patchlevel': self.GetCodeReviewSetting('TRYSERVER_PATCHLEVEL'),
}
logging.info('\n'.join(['%s: %s' % (k, v)
for (k, v) in settings.iteritems() if v]))
for (k, v) in settings.iteritems():
# Avoid overwriting options already set using command line flags.
if v and getattr(self.options, k) is None:
setattr(self.options, k, v)
def AutomagicalSettings(self):
"""Determines settings based on supported code review and checkout tools.
"""
# Try to find gclient or repo root first.
if not self.options.no_search:
self.toplevel_root = gclient_utils.FindGclientRoot(self.checkout_root)
if self.toplevel_root:
logging.info('Found .gclient at %s' % self.toplevel_root)
else:
self.toplevel_root = gclient_utils.FindFileUpwards(
os.path.join('..', '.repo'), self.checkout_root)
if self.toplevel_root:
logging.info('Found .repo dir at %s'
% os.path.dirname(self.toplevel_root))
# Parse TRYSERVER_* settings from codereview.settings before falling back
# on setting self.options.root manually further down. Otherwise
# TRYSERVER_ROOT would never be used in codereview.settings.
self._GclStyleSettings()
if self.toplevel_root and not self.options.root:
assert os.path.abspath(self.toplevel_root) == self.toplevel_root
self.options.root = gclient_utils.PathDifference(self.toplevel_root,
self.checkout_root)
else:
self._GclStyleSettings()
def ReadRootFile(self, filename):
cur = self.checkout_root
root = self.toplevel_root or self.checkout_root
assert cur.startswith(root), (root, cur)
while cur.startswith(root):
filepath = os.path.join(cur, filename)
if os.path.isfile(filepath):
logging.info('Found %s at %s' % (filename, cur))
return gclient_utils.FileRead(filepath)
cur = os.path.dirname(cur)
logging.warning('Didn\'t find %s' % filename)
return None
def _SetFileTuples(self, file_tuples):
excluded = ['!', '?', 'X', ' ', '~']
def Excluded(f):
if f[0][0] in excluded:
return True
for r in self.options.exclude:
if re.search(r, f[1]):
logging.info('Ignoring "%s"' % f[1])
return True
return False
self._file_tuples = [f for f in file_tuples if not Excluded(f)]
self._files = [f[1] for f in self._file_tuples]
def CaptureStatus(self):
"""Returns the 'svn status' emulated output as an array of (status, file)
tuples."""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
@property
def files(self):
if self._files is None:
self._SetFileTuples(self.CaptureStatus())
return self._files
@property
def file_tuples(self):
if self._file_tuples is None:
self._SetFileTuples(self.CaptureStatus())
return self._file_tuples
class SVN(SCM):
"""Gathers the options and diff for a subversion checkout."""
def __init__(self, *args, **kwargs):
SCM.__init__(self, *args, **kwargs)
self.checkout_root = scm.SVN.GetCheckoutRoot(self.checkout_root)
if not self.options.email:
# Assumes the svn credential is an email address.
self.options.email = scm.SVN.GetEmail(self.checkout_root)
logging.info("SVN(%s)" % self.checkout_root)
def ReadRootFile(self, filename):
data = SCM.ReadRootFile(self, filename)
if data:
return data
# Try to search on the subversion repository for the file.
if not gcl:
return None
data = gcl.GetCachedFile(filename)
logging.debug('%s:\n%s' % (filename, data))
return data
def CaptureStatus(self):
return scm.SVN.CaptureStatus(None, self.checkout_root)
def GenerateDiff(self):
"""Returns a string containing the diff for the given file list.
The files in the list should either be absolute paths or relative to the
given root.
"""
return scm.SVN.GenerateDiff(self.files, self.checkout_root, full_move=True,
revision=self.diff_against)
class GIT(SCM):
"""Gathers the options and diff for a git checkout."""
def __init__(self, *args, **kwargs):
SCM.__init__(self, *args, **kwargs)
self.checkout_root = scm.GIT.GetCheckoutRoot(self.checkout_root)
if not self.options.name:
self.options.name = scm.GIT.GetPatchName(self.checkout_root)
if not self.options.email:
self.options.email = scm.GIT.GetEmail(self.checkout_root)
if not self.diff_against:
self.diff_against = scm.GIT.GetUpstreamBranch(self.checkout_root)
if not self.diff_against:
raise NoTryServerAccess(
"Unable to determine default branch to diff against. "
"Verify this branch is set up to track another"
"(via the --track argument to \"git checkout -b ...\"")
logging.info("GIT(%s)" % self.checkout_root)
def CaptureStatus(self):
return scm.GIT.CaptureStatus(
[],
self.checkout_root.replace(os.sep, '/'),
self.diff_against)
def GenerateDiff(self):
if RunGit(['diff-index', 'HEAD']):
print 'Cannot try with a dirty tree. You must commit locally first.'
return None
return scm.GIT.GenerateDiff(
self.checkout_root,
files=self.files,
full_move=True,
branch=self.diff_against)
def _ParseBotList(botlist, testfilter):
"""Parses bot configurations from a list of strings."""
bots = []
if testfilter:
for bot in itertools.chain.from_iterable(botspec.split(',')
for botspec in botlist):
tests = set()
if ':' in bot:
if bot.endswith(':compile'):
tests |= set(['compile'])
else:
raise ValueError(
'Can\'t use both --testfilter and --bot builder:test formats '
'at the same time')
bots.append((bot, tests))
else:
for botspec in botlist:
botname = botspec.split(':')[0]
tests = set()
if ':' in botspec:
tests |= set(filter(None, botspec.split(':')[1].split(',')))
bots.append((botname, tests))
return bots
def _ApplyTestFilter(testfilter, bot_spec):
"""Applies testfilter from CLI.
Specifying a testfilter strips off any builder-specified tests (except for
compile).
"""
if testfilter:
return [(botname, set(testfilter) | (tests & set(['compile'])))
for botname, tests in bot_spec]
else:
return bot_spec
def _GenTSBotSpec(checkouts, change, changed_files, options):
bot_spec = []
# Get try slaves from PRESUBMIT.py files if not specified.
# Even if the diff comes from options.url, use the local checkout for bot
# selection.
try:
import presubmit_support
root_presubmit = checkouts[0].ReadRootFile('PRESUBMIT.py')
if not change:
if not changed_files:
changed_files = checkouts[0].file_tuples
change = presubmit_support.Change(options.name,
'',
checkouts[0].checkout_root,
changed_files,
options.issue,
options.patchset,
options.email)
masters = presubmit_support.DoGetTryMasters(
change,
checkouts[0].GetFileNames(),
checkouts[0].checkout_root,
root_presubmit,
options.project,
options.verbose,
sys.stdout)
# Compatibility for old checkouts and bots that were on tryserver.chromium.
trybots = masters.get('tryserver.chromium', [])
# Compatibility for checkouts that are not using tryserver.chromium
# but are stuck with git-try or gcl-try.
if not trybots and len(masters) == 1:
trybots = masters.values()[0]
if trybots:
old_style = filter(lambda x: isinstance(x, basestring), trybots)
new_style = filter(lambda x: isinstance(x, tuple), trybots)
# _ParseBotList's testfilter is set to None otherwise it will complain.
bot_spec = _ApplyTestFilter(options.testfilter,
_ParseBotList(old_style, None))
bot_spec.extend(_ApplyTestFilter(options.testfilter, new_style))
except ImportError:
pass
return bot_spec
def _ParseSendChangeOptions(bot_spec, options):
"""Parse common options passed to _SendChangeHTTP, _SendChangeSVN and
_SendChangeGit.
"""
values = [
('user', options.user),
('name', options.name),
]
# A list of options to copy.
optional_values = (
'email',
'revision',
'root',
'patchlevel',
'issue',
'patchset',
'target',
'project',
)
for option_name in optional_values:
value = getattr(options, option_name)
if value:
values.append((option_name, value))
# Not putting clobber to optional_names
# because it used to have lower-case 'true'.
if options.clobber:
values.append(('clobber', 'true'))
for bot, tests in bot_spec:
values.append(('bot', ('%s:%s' % (bot, ','.join(tests)))))
return values
def _SendChangeHTTP(bot_spec, options):
"""Send a change to the try server using the HTTP protocol."""
if not options.host:
raise NoTryServerAccess('Please use the --host option to specify the try '
'server host to connect to.')
if not options.port:
raise NoTryServerAccess('Please use the --port option to specify the try '
'server port to connect to.')
values = _ParseSendChangeOptions(bot_spec, options)
values.append(('patch', options.diff))
url = 'http://%s:%s/send_try_patch' % (options.host, options.port)
logging.info('Sending by HTTP')
logging.info(''.join("%s=%s\n" % (k, v) for k, v in values))
logging.info(url)
logging.info(options.diff)
if options.dry_run:
return
try:
logging.info('Opening connection...')
connection = urllib2.urlopen(url, urllib.urlencode(values))
logging.info('Done')
except IOError, e:
logging.info(str(e))
if bot_spec and len(e.args) > 2 and e.args[2] == 'got a bad status line':
raise NoTryServerAccess('%s is unaccessible. Bad --bot argument?' % url)
else:
raise NoTryServerAccess('%s is unaccessible. Reason: %s' % (url,
str(e.args)))
if not connection:
raise NoTryServerAccess('%s is unaccessible.' % url)
logging.info('Reading response...')
response = connection.read()
logging.info('Done')
if response != 'OK':
raise NoTryServerAccess('%s is unaccessible. Got:\n%s' % (url, response))
PrintSuccess(bot_spec, options)
@contextlib.contextmanager
def _TempFilename(name, contents=None):
"""Create a temporary directory, append the specified name and yield.
In contrast to NamedTemporaryFile, does not keep the file open.
Deletes the file on __exit__.
"""
temp_dir = tempfile.mkdtemp(prefix=name)
try:
path = os.path.join(temp_dir, name)
if contents is not None:
with open(path, 'wb') as f:
f.write(contents)
yield path
finally:
shutil.rmtree(temp_dir, True)
@contextlib.contextmanager
def _PrepareDescriptionAndPatchFiles(description, options):
"""Creates temporary files with description and patch.
__enter__ called on the return value returns a tuple of patch_filename and
description_filename.
Args:
description: contents of description file.
options: patchset options object. Must have attributes: user,
name (of patch) and diff (contents of patch).
"""
current_time = str(datetime.datetime.now()).replace(':', '.')
patch_basename = '%s.%s.%s.diff' % (Escape(options.user),
Escape(options.name), current_time)
with _TempFilename('description', description) as description_filename:
with _TempFilename(patch_basename, options.diff) as patch_filename:
yield patch_filename, description_filename
def _SendChangeSVN(bot_spec, options):
"""Send a change to the try server by committing a diff file on a subversion
server."""
if not options.svn_repo:
raise NoTryServerAccess('Please use the --svn_repo option to specify the'
' try server svn repository to connect to.')
values = _ParseSendChangeOptions(bot_spec, options)
description = ''.join("%s=%s\n" % (k, v) for k, v in values)
logging.info('Sending by SVN')
logging.info(description)
logging.info(options.svn_repo)
logging.info(options.diff)
if options.dry_run:
return
with _PrepareDescriptionAndPatchFiles(description, options) as (
patch_filename, description_filename):
if sys.platform == "cygwin":
# Small chromium-specific issue here:
# git-try uses /usr/bin/python on cygwin but svn.bat will be used
# instead of /usr/bin/svn by default. That causes bad things(tm) since
# Windows' svn.exe has no clue about cygwin paths. Hence force to use
# the cygwin version in this particular context.
exe = "/usr/bin/svn"
else:
exe = "svn"
patch_dir = os.path.dirname(patch_filename)
command = [exe, 'import', '-q', patch_dir, options.svn_repo, '--file',
description_filename]
if scm.SVN.AssertVersion("1.5")[0]:
command.append('--no-ignore')
try:
subprocess2.check_call(command)
except subprocess2.CalledProcessError, e:
raise NoTryServerAccess(str(e))
PrintSuccess(bot_spec, options)
def _GetPatchGitRepo(git_url):
"""Gets a path to a Git repo with patches.
Stores patches in .git/git-try/patches-git directory, a git repo. If it
doesn't exist yet or its origin URL is different, cleans up and clones it.
If it existed before, then pulls changes.
Does not support SVN repo.
Returns a path to the directory with patches.
"""
git_dir = scm.GIT.GetGitDir(os.getcwd())
patch_dir = os.path.join(git_dir, GIT_PATCH_DIR_BASENAME)
logging.info('Looking for git repo for patches')
# Is there already a repo with the expected url or should we clone?
clone = True
if os.path.exists(patch_dir) and scm.GIT.IsInsideWorkTree(patch_dir):
existing_url = scm.GIT.Capture(
['config', '--local', 'remote.origin.url'],
cwd=patch_dir)
clone = existing_url != git_url
if clone:
if os.path.exists(patch_dir):
logging.info('Cleaning up')
shutil.rmtree(patch_dir, True)
logging.info('Cloning patch repo')
scm.GIT.Capture(['clone', git_url, GIT_PATCH_DIR_BASENAME], cwd=git_dir)
email = scm.GIT.GetEmail(cwd=os.getcwd())
scm.GIT.Capture(['config', '--local', 'user.email', email], cwd=patch_dir)
else:
if scm.GIT.IsWorkTreeDirty(patch_dir):
logging.info('Work dir is dirty: hard reset!')
scm.GIT.Capture(['reset', '--hard'], cwd=patch_dir)
logging.info('Updating patch repo')
scm.GIT.Capture(['pull', 'origin', 'master'], cwd=patch_dir)
return os.path.abspath(patch_dir)
def _SendChangeGit(bot_spec, options):
"""Sends a change to the try server by committing a diff file to a GIT repo.
Creates a temp orphan branch, commits patch.diff, creates a ref pointing to
that commit, deletes the temp branch, checks master out, adds 'ref' file
containing the name of the new ref, pushes master and the ref to the origin.
TODO: instead of creating a temp branch, use git-commit-tree.
"""
if not options.git_repo:
raise NoTryServerAccess('Please use the --git_repo option to specify the '
'try server git repository to connect to.')
values = _ParseSendChangeOptions(bot_spec, options)
comment_subject = '%s.%s' % (options.user, options.name)
comment_body = ''.join("%s=%s\n" % (k, v) for k, v in values)
description = '%s\n\n%s' % (comment_subject, comment_body)
logging.info('Sending by GIT')
logging.info(description)
logging.info(options.git_repo)
logging.info(options.diff)
if options.dry_run:
return
patch_dir = _GetPatchGitRepo(options.git_repo)
def patch_git(*args):
return scm.GIT.Capture(list(args), cwd=patch_dir)
def add_and_commit(filename, comment_filename):
patch_git('add', filename)
patch_git('commit', '-F', comment_filename)
assert scm.GIT.IsInsideWorkTree(patch_dir)
assert not scm.GIT.IsWorkTreeDirty(patch_dir)
with _PrepareDescriptionAndPatchFiles(description, options) as (
patch_filename, description_filename):
logging.info('Committing patch')
temp_branch = 'tmp_patch'
target_ref = 'refs/patches/%s/%s' % (
Escape(options.user),
os.path.basename(patch_filename).replace(' ','_'))
target_filename = os.path.join(patch_dir, 'patch.diff')
branch_file = os.path.join(patch_dir, GIT_BRANCH_FILE)
patch_git('checkout', 'master')
try:
# Try deleting an existing temp branch, if any.
try:
patch_git('branch', '-D', temp_branch)
logging.debug('Deleted an existing temp branch.')
except subprocess2.CalledProcessError:
pass
# Create a new branch and put the patch there.
patch_git('checkout', '--orphan', temp_branch)
patch_git('reset')
patch_git('clean', '-f')
shutil.copyfile(patch_filename, target_filename)
add_and_commit(target_filename, description_filename)
assert not scm.GIT.IsWorkTreeDirty(patch_dir)
# Create a ref and point it to the commit referenced by temp_branch.
patch_git('update-ref', target_ref, temp_branch)
# Delete the temp ref.
patch_git('checkout', 'master')
patch_git('branch', '-D', temp_branch)
# Update the branch file in the master.
def update_branch():
with open(branch_file, 'w') as f:
f.write(target_ref)
add_and_commit(branch_file, description_filename)
update_branch()
# Push master and target_ref to origin.
logging.info('Pushing patch')
for attempt in xrange(_GIT_PUSH_ATTEMPTS):
try:
patch_git('push', 'origin', 'master', target_ref)
except subprocess2.CalledProcessError as e:
is_last = attempt == _GIT_PUSH_ATTEMPTS - 1
if is_last:
raise NoTryServerAccess(str(e))
# Fetch, reset, update branch file again.
patch_git('fetch', 'origin')
patch_git('reset', '--hard', 'origin/master')
update_branch()
except subprocess2.CalledProcessError, e:
# Restore state.
patch_git('checkout', 'master')
patch_git('reset', '--hard', 'origin/master')
raise
PrintSuccess(bot_spec, options)
def _SendChangeGerrit(bot_spec, options):
"""Posts a try job to a Gerrit change.
Reads Change-Id from the HEAD commit, resolves the current revision, checks
that local revision matches the uploaded one, posts a try job in form of a
message, sets Tryjob-Request label to 1.
Gerrit message format: starts with !tryjob, optionally followed by a tryjob
definition in JSON format:
buildNames: list of strings specifying build names.
build_properties: a dict of build properties.
"""
logging.info('Sending by Gerrit')
if not options.gerrit_url:
raise NoTryServerAccess('Please use --gerrit_url option to specify the '
'Gerrit instance url to connect to')
gerrit_host = urlparse.urlparse(options.gerrit_url).hostname
logging.debug('Gerrit host: %s' % gerrit_host)
def GetChangeId(commmitish):
"""Finds Change-ID of the HEAD commit."""
CHANGE_ID_RGX = '^Change-Id: (I[a-f0-9]{10,})'
comment = scm.GIT.Capture(['log', '-1', commmitish, '--format=%b'],
cwd=os.getcwd())
change_id_match = re.search(CHANGE_ID_RGX, comment, re.I | re.M)
if not change_id_match:
raise Error('Change-Id was not found in the HEAD commit. Make sure you '
'have a Git hook installed that generates and inserts a '
'Change-Id into a commit message automatically.')
change_id = change_id_match.group(1)
return change_id
def FormatMessage():
# Build job definition.
job_def = {}
build_properties = {}
if options.testfilter:
build_properties['testfilter'] = options.testfilter
builderNames = [builder for builder, _ in bot_spec]
if builderNames:
job_def['builderNames'] = builderNames
if build_properties:
job_def['build_properties'] = build_properties
# Format message.
msg = '!tryjob'
if job_def:
msg = '%s %s' % (msg, json.dumps(job_def, sort_keys=True))
return msg
def PostTryjob(message):
logging.info('Posting gerrit message: %s' % message)
if not options.dry_run:
# Post a message and set TryJob=1 label.
try:
gerrit_util.SetReview(gerrit_host, change_id, msg=message,
labels={'Tryjob-Request': 1})
except gerrit_util.GerritError, e:
if e.http_status == 400:
raise Error(e.message)
else:
raise
head_sha = scm.GIT.Capture(['log', '-1', '--format=%H'], cwd=os.getcwd())
change_id = GetChangeId(head_sha)
try:
# Check that the uploaded revision matches the local one.
changes = gerrit_util.GetChangeCurrentRevision(gerrit_host, change_id)
except gerrit_util.GerritAuthenticationError, e:
raise NoTryServerAccess(e.message)
assert len(changes) <= 1, 'Multiple changes with id %s' % change_id
if not changes:
raise Error('A change %s was not found on the server. Was it uploaded?' %
change_id)
logging.debug('Found Gerrit change: %s' % changes[0])
if changes[0]['current_revision'] != head_sha:
raise Error('Please upload your latest local changes to Gerrit.')
# Post a try job.
message = FormatMessage()
PostTryjob(message)
change_url = urlparse.urljoin(options.gerrit_url,
'/#/c/%s' % changes[0]['_number'])
print('A tryjob was posted on change %s' % change_url)
def PrintSuccess(bot_spec, options):
if not options.dry_run:
text = 'Patch \'%s\' sent to try server' % options.name
if bot_spec:
text += ': %s' % ', '.join(
'%s:%s' % (b[0], ','.join(b[1])) for b in bot_spec)
print(text)
def GuessVCS(options, path, file_list):
"""Helper to guess the version control system.
NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't
support it yet.
This examines the path directory, guesses which SCM we're using, and
returns an instance of the appropriate class. Exit with an error if we can't
figure it out.
Returns:
A SCM instance. Exits if the SCM can't be guessed.
"""
__pychecker__ = 'no-returnvalues'
real_path = path.split('@')[0]
logging.info("GuessVCS(%s)" % path)
# Subversion has a .svn in all working directories.
if os.path.isdir(os.path.join(real_path, '.svn')):
return SVN(options, path, file_list)
# Git has a command to test if you're in a git tree.
# Try running it, but don't die if we don't have git installed.
try:
subprocess2.check_output(
['git', 'rev-parse', '--is-inside-work-tree'], cwd=real_path,
stderr=subprocess2.VOID)
return GIT(options, path, file_list)
except OSError, e:
if e.errno != errno.ENOENT:
raise
except subprocess2.CalledProcessError, e:
if e.returncode != errno.ENOENT and e.returncode != 128:
# ENOENT == 2 = they don't have git installed.
# 128 = git error code when not in a repo.
logging.warning('Unexpected error code: %s' % e.returncode)
raise
raise NoTryServerAccess(
( 'Could not guess version control system for %s.\n'
'Are you in a working copy directory?') % path)
def GetMungedDiff(path_diff, diff):
# Munge paths to match svn.
changed_files = []
for i in range(len(diff)):
if diff[i].startswith('--- ') or diff[i].startswith('+++ '):
new_file = posixpath.join(path_diff, diff[i][4:]).replace('\\', '/')
if diff[i].startswith('--- '):
file_path = new_file.split('\t')[0].strip()
if file_path.startswith('a/'):
file_path = file_path[2:]
changed_files.append(('M', file_path))
diff[i] = diff[i][0:4] + new_file
return (diff, changed_files)
class OptionParser(optparse.OptionParser):
def format_epilog(self, _):
"""Removes epilog formatting."""
return self.epilog or ''
def gen_parser(prog):
# Parse argv
parser = OptionParser(usage=USAGE, version=__version__, prog=prog)
parser.add_option("-v", "--verbose", action="count", default=0,
help="Prints debugging infos")
group = optparse.OptionGroup(parser, "Result and status")
group.add_option("-u", "--user", default=getpass.getuser(),
help="Owner user name [default: %default]")
group.add_option("-e", "--email",
default=os.environ.get('TRYBOT_RESULTS_EMAIL_ADDRESS',
os.environ.get('EMAIL_ADDRESS')),
help="Email address where to send the results. Use either "
"the TRYBOT_RESULTS_EMAIL_ADDRESS environment "
"variable or EMAIL_ADDRESS to set the email address "
"the try bots report results to [default: %default]")
group.add_option("-n", "--name",
help="Descriptive name of the try job")
group.add_option("--issue", type='int',
help="Update rietveld issue try job status")
group.add_option("--patchset", type='int',
help="Update rietveld issue try job status. This is "
"optional if --issue is used, In that case, the "
"latest patchset will be used.")
group.add_option("--dry_run", action='store_true',
help="Don't send the try job. This implies --verbose, so "
"it will print the diff.")
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Try job options")
group.add_option(
"-b", "--bot", action="append",
help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple "
"times to specify multiple builders. ex: "
"'-bwin_rel:ui_tests,webkit_unit_tests -bwin_layout'. See "
"the try server waterfall for the builders name and the tests "
"available. Can also be used to specify gtest_filter, e.g. "
"-bwin_rel:base_unittests:ValuesTest.*Value"))
group.add_option("-B", "--print_bots", action="store_true",
help="Print bots we would use (e.g. from PRESUBMIT.py)"
" and exit. Do not send patch. Like --dry_run"
" but less verbose.")
group.add_option("-r", "--revision",
help="Revision to use for the try job. If 'auto' is "
"specified, it is resolved to the revision a patch is "
"generated against (Git only). Default: the "
"revision will be determined by the try server; see "
"its waterfall for more info")
group.add_option("-c", "--clobber", action="store_true",
help="Force a clobber before building; e.g. don't do an "
"incremental build")
# TODO(maruel): help="Select a specific configuration, usually 'debug' or "
# "'release'"
group.add_option("--target", help=optparse.SUPPRESS_HELP)
group.add_option("--project",
help="Override which project to use. Projects are defined "
"server-side to define what default bot set to use")
group.add_option(
"-t", "--testfilter", action="append", default=[],
help=("Apply a testfilter to all the selected builders. Unless the "
"builders configurations are similar, use multiple "
"--bot <builder>:<test> arguments."))
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Patch to run")
group.add_option("-f", "--file", default=[], dest="files",
metavar="FILE", action="append",
help="Use many times to list the files to include in the "
"try, relative to the repository root")
group.add_option("--diff",
help="File containing the diff to try")
group.add_option("--url",
help="Url where to grab a patch, e.g. "
"http://example.com/x.diff")
group.add_option("-R", "--rietveld_url", default="codereview.appspot.com",
metavar="URL",
help="Has 2 usages, both refer to the rietveld instance: "
"Specify which code review patch to use as the try job "
"or rietveld instance to update the try job results "
"Default:%default")
group.add_option("--root",
help="Root to use for the patch; base subdirectory for "
"patch created in a subdirectory")
group.add_option("-p", "--patchlevel", type='int', metavar="LEVEL",
help="Used as -pN parameter to patch")
group.add_option("-s", "--sub_rep", action="append", default=[],
help="Subcheckout to use in addition. This is mainly "
"useful for gclient-style checkouts. In git, checkout "
"the branch with changes first. Use @rev or "
"@branch to specify the "
"revision/branch to diff against. If no @branch is "
"given the diff will be against the upstream branch. "
"If @branch then the diff is branch..HEAD. "
"All edits must be checked in.")
group.add_option("--no_search", action="store_true",
help=("Disable automatic search for gclient or repo "
"checkout root."))
group.add_option("-E", "--exclude", action="append",
default=['ChangeLog'], metavar='REGEXP',
help="Regexp patterns to exclude files. Default: %default")
group.add_option("--upstream_branch", action="store",
help="Specify the upstream branch to diff against in the "
"main checkout")
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Access the try server by HTTP")
group.add_option("--use_http",
action="store_const",
const=_SendChangeHTTP,
dest="send_patch",
help="Use HTTP to talk to the try server [default]")
group.add_option("-H", "--host",
help="Host address")
group.add_option("-P", "--port", type="int",
help="HTTP port")
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Access the try server with SVN")
group.add_option("--use_svn",
action="store_const",
const=_SendChangeSVN,
dest="send_patch",
help="Use SVN to talk to the try server")
group.add_option("-S", "--svn_repo",
metavar="SVN_URL",
help="SVN url to use to write the changes in; --use_svn is "
"implied when using --svn_repo")
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Access the try server with Git")
group.add_option("--use_git",
action="store_const",
const=_SendChangeGit,
dest="send_patch",
help="Use GIT to talk to the try server")
group.add_option("-G", "--git_repo",
metavar="GIT_URL",
help="GIT url to use to write the changes in; --use_git is "
"implied when using --git_repo")
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Access the try server with Gerrit")
group.add_option("--use_gerrit",
action="store_const",
const=_SendChangeGerrit,
dest="send_patch",
help="Use Gerrit to talk to the try server")
group.add_option("--gerrit_url",
metavar="GERRIT_URL",
help="Gerrit url to post a tryjob to; --use_gerrit is "
"implied when using --gerrit_url")
parser.add_option_group(group)
return parser
def TryChange(argv,
change,
swallow_exception,
prog=None,
extra_epilog=None):
"""
Args:
argv: Arguments and options.
change: Change instance corresponding to the CL.
swallow_exception: Whether we raise or swallow exceptions.
"""
parser = gen_parser(prog)
epilog = EPILOG % { 'prog': prog }
if extra_epilog:
epilog += extra_epilog
parser.epilog = epilog
options, args = parser.parse_args(argv)
# If they've asked for help, give it to them
if len(args) == 1 and args[0] == 'help':
parser.print_help()
return 0
# If they've said something confusing, don't spawn a try job until you
# understand what they want.
if args:
parser.error('Extra argument(s) "%s" not understood' % ' '.join(args))
if options.dry_run:
options.verbose += 1
LOG_FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
if not swallow_exception:
if options.verbose == 0:
logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT)
elif options.verbose == 1:
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
elif options.verbose > 1:
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
logging.debug(argv)
if (options.patchlevel is not None and
(options.patchlevel < 0 or options.patchlevel > 10)):
parser.error(
'Have you tried --port instead? You probably confused -p and -P.')
# Strip off any @ in the user, otherwise svn gets confused.
options.user = options.user.split('@', 1)[0]
if options.rietveld_url:
# Try to extract the review number if possible and fix the protocol.
if not '://' in options.rietveld_url:
options.rietveld_url = 'http://' + options.rietveld_url
match = re.match(r'^(.*)/(\d+)/?$', options.rietveld_url)
if match:
if options.issue or options.patchset:
parser.error('Cannot use both --issue and use a review number url')
options.issue = int(match.group(2))
options.rietveld_url = match.group(1)
try:
changed_files = None
# Always include os.getcwd() in the checkout settings.
path = os.getcwd()
file_list = []
if options.files:
file_list = options.files
elif change:
file_list = [f.LocalPath() for f in change.AffectedFiles()]
if options.upstream_branch:
path += '@' + options.upstream_branch
# Clear file list so that the correct list will be retrieved from the
# upstream branch.
file_list = []
current_vcs = GuessVCS(options, path, file_list)
current_vcs.AutomagicalSettings()
options = current_vcs.options
vcs_is_git = type(current_vcs) is GIT
# So far, git_repo doesn't work with SVN
if options.git_repo and not vcs_is_git:
parser.error('--git_repo option is supported only for GIT repositories')
# If revision==auto, resolve it
if options.revision and options.revision.lower() == 'auto':
if not vcs_is_git:
parser.error('--revision=auto is supported only for GIT repositories')
options.revision = scm.GIT.Capture(
['rev-parse', current_vcs.diff_against],
cwd=path)
checkouts = [current_vcs]
for item in options.sub_rep:
# Pass file_list=None because we don't know the sub repo's file list.
checkout = GuessVCS(options,
os.path.join(current_vcs.checkout_root, item),
None)
if checkout.checkout_root in [c.checkout_root for c in checkouts]:
parser.error('Specified the root %s two times.' %
checkout.checkout_root)
checkouts.append(checkout)
can_http = options.port and options.host
can_svn = options.svn_repo
can_git = options.git_repo
can_gerrit = options.gerrit_url
can_something = can_http or can_svn or can_git or can_gerrit
# If there was no transport selected yet, now we must have enough data to
# select one.
if not options.send_patch and not can_something:
parser.error('Please specify an access method.')
# Convert options.diff into the content of the diff.
if options.url:
if options.files:
parser.error('You cannot specify files and --url at the same time.')
options.diff = urllib2.urlopen(options.url).read()
elif options.diff:
if options.files:
parser.error('You cannot specify files and --diff at the same time.')
options.diff = gclient_utils.FileRead(options.diff, 'rb')
elif options.issue and options.patchset is None:
# Retrieve the patch from rietveld when the diff is not specified.
# When patchset is specified, it's because it's done by gcl/git-try.
api_url = '%s/api/%d' % (options.rietveld_url, options.issue)
logging.debug(api_url)
contents = json.loads(urllib2.urlopen(api_url).read())
options.patchset = contents['patchsets'][-1]
diff_url = ('%s/download/issue%d_%d.diff' %
(options.rietveld_url, options.issue, options.patchset))
diff = GetMungedDiff('', urllib2.urlopen(diff_url).readlines())
options.diff = ''.join(diff[0])
changed_files = diff[1]
else:
# Use this as the base.
root = checkouts[0].checkout_root
diffs = []
for checkout in checkouts:
raw_diff = checkout.GenerateDiff()
if not raw_diff:
continue
diff = raw_diff.splitlines(True)
path_diff = gclient_utils.PathDifference(root, checkout.checkout_root)
# Munge it.
diffs.extend(GetMungedDiff(path_diff, diff)[0])
if not diffs:
logging.error('Empty or non-existant diff, exiting.')
return 1
options.diff = ''.join(diffs)
if not options.name:
if options.issue:
options.name = 'Issue %s' % options.issue
else:
options.name = 'Unnamed'
print('Note: use --name NAME to change the try job name.')
if not options.email:
parser.error('Using an anonymous checkout. Please use --email or set '
'the TRYBOT_RESULTS_EMAIL_ADDRESS environment variable.')
print('Results will be emailed to: ' + options.email)
if options.bot:
bot_spec = _ApplyTestFilter(
options.testfilter, _ParseBotList(options.bot, options.testfilter))
else:
bot_spec = _GenTSBotSpec(checkouts, change, changed_files, options)
if options.testfilter:
bot_spec = _ApplyTestFilter(options.testfilter, bot_spec)
if any('triggered' in b[0] for b in bot_spec):
print >> sys.stderr, (
'ERROR You are trying to send a job to a triggered bot. This type of'
' bot requires an\ninitial job from a parent (usually a builder). '
'Instead send your job to the parent.\nBot list: %s' % bot_spec)
return 1
if options.print_bots:
print 'Bots which would be used:'
for bot in bot_spec:
if bot[1]:
print ' %s:%s' % (bot[0], ','.join(bot[1]))
else:
print ' %s' % (bot[0])
return 0
# Determine sending protocol
if options.send_patch:
# If forced.
senders = [options.send_patch]
else:
# Try sending patch using avaialble protocols
all_senders = [
(_SendChangeHTTP, can_http),
(_SendChangeSVN, can_svn),
(_SendChangeGerrit, can_gerrit),
(_SendChangeGit, can_git),
]
senders = [sender for sender, can in all_senders if can]
# Send the patch.
for sender in senders:
try:
sender(bot_spec, options)
return 0
except NoTryServerAccess:
is_last = sender == senders[-1]
if is_last:
raise
assert False, "Unreachable code"
except Error, e:
if swallow_exception:
return 1
print >> sys.stderr, e
return 1
except (gclient_utils.Error, subprocess2.CalledProcessError), e:
print >> sys.stderr, e
return 1
return 0
if __name__ == "__main__":
fix_encoding.fix_encoding()
sys.exit(TryChange(None, None, False))
|
[] |
[] |
[
"TRYBOT_RESULTS_EMAIL_ADDRESS",
"EMAIL_ADDRESS"
] |
[]
|
["TRYBOT_RESULTS_EMAIL_ADDRESS", "EMAIL_ADDRESS"]
|
python
| 2 | 0 | |
zesco_football_club/taskapp/celery.py
|
from __future__ import absolute_import
import os
from celery import Celery
from django.apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover
app = Celery('zesco_football_club')
class CeleryConfig(AppConfig):
name = 'zesco_football_club.taskapp'
verbose_name = 'Celery Config'
def ready(self):
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
installed_apps = [app_config.name for app_config in apps.get_app_configs()]
app.autodiscover_tasks(lambda: installed_apps, force=True)
if hasattr(settings, 'RAVEN_CONFIG'):
# Celery signal registration
from raven import Client as RavenClient
from raven.contrib.celery import register_signal as raven_register_signal
from raven.contrib.celery import register_logger_signal as raven_register_logger_signal
raven_client = RavenClient(dsn=settings.RAVEN_CONFIG['DSN'])
raven_register_logger_signal(raven_client)
raven_register_signal(raven_client)
if hasattr(settings, 'OPBEAT'):
from opbeat.contrib.django.models import client as opbeat_client
from opbeat.contrib.django.models import logger as opbeat_logger
from opbeat.contrib.django.models import register_handlers as opbeat_register_handlers
from opbeat.contrib.celery import register_signal as opbeat_register_signal
try:
opbeat_register_signal(opbeat_client)
except Exception as e:
opbeat_logger.exception('Failed installing celery hook: %s' % e)
if 'opbeat.contrib.django' in settings.INSTALLED_APPS:
opbeat_register_handlers()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request)) # pragma: no cover
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
kombu/connection.py
|
"""Client (Connection)."""
from __future__ import annotations
import os
import socket
import sys
from contextlib import contextmanager
from itertools import count, cycle
from operator import itemgetter
from typing import TYPE_CHECKING, Any
try:
from ssl import CERT_NONE
ssl_available = True
except ImportError: # pragma: no cover
CERT_NONE = None
ssl_available = False
# jython breaks on relative import for .exceptions for some reason
# (Issue #112)
from kombu import exceptions
from .log import get_logger
from .resource import Resource
from .transport import get_transport_cls, supports_librabbitmq
from .utils.collections import HashedSeq
from .utils.functional import dictfilter, lazy, retry_over_time, shufflecycle
from .utils.objects import cached_property
from .utils.url import as_url, maybe_sanitize_url, parse_url, quote, urlparse
if TYPE_CHECKING:
from kombu.transport.virtual import Channel
if sys.version_info < (3, 10):
from typing_extensions import TypeGuard
else:
from typing import TypeGuard
from types import TracebackType
__all__ = ('Connection', 'ConnectionPool', 'ChannelPool')
logger = get_logger(__name__)
roundrobin_failover = cycle
resolve_aliases = {
'pyamqp': 'amqp',
'librabbitmq': 'amqp',
}
failover_strategies = {
'round-robin': roundrobin_failover,
'shuffle': shufflecycle,
}
_log_connection = os.environ.get('KOMBU_LOG_CONNECTION', False)
_log_channel = os.environ.get('KOMBU_LOG_CHANNEL', False)
class Connection:
"""A connection to the broker.
Example:
>>> Connection('amqp://guest:guest@localhost:5672//')
>>> Connection('amqp://foo;amqp://bar',
... failover_strategy='round-robin')
>>> Connection('redis://', transport_options={
... 'visibility_timeout': 3000,
... })
>>> import ssl
>>> Connection('amqp://', login_method='EXTERNAL', ssl={
... 'ca_certs': '/etc/pki/tls/certs/something.crt',
... 'keyfile': '/etc/something/system.key',
... 'certfile': '/etc/something/system.cert',
... 'cert_reqs': ssl.CERT_REQUIRED,
... })
Note:
SSL currently only works with the py-amqp, and qpid
transports. For other transports you can use stunnel.
Arguments:
URL (str, Sequence): Broker URL, or a list of URLs.
Keyword Arguments:
ssl (bool/dict): Use SSL to connect to the server.
Default is ``False``.
May not be supported by the specified transport.
transport (Transport): Default transport if not specified in the URL.
connect_timeout (float): Timeout in seconds for connecting to the
server. May not be supported by the specified transport.
transport_options (Dict): A dict of additional connection arguments to
pass to alternate kombu channel implementations. Consult the
transport documentation for available options.
heartbeat (float): Heartbeat interval in int/float seconds.
Note that if heartbeats are enabled then the
:meth:`heartbeat_check` method must be called regularly,
around once per second.
Note:
The connection is established lazily when needed. If you need the
connection to be established, then force it by calling
:meth:`connect`::
>>> conn = Connection('amqp://')
>>> conn.connect()
and always remember to close the connection::
>>> conn.release()
These options have been replaced by the URL argument, but are still
supported for backwards compatibility:
:keyword hostname: Host name/address.
NOTE: You cannot specify both the URL argument and use the hostname
keyword argument at the same time.
:keyword userid: Default user name if not provided in the URL.
:keyword password: Default password if not provided in the URL.
:keyword virtual_host: Default virtual host if not provided in the URL.
:keyword port: Default port if not provided in the URL.
"""
port = None
virtual_host = '/'
connect_timeout = 5
_closed = None
_connection = None
_default_channel = None
_transport = None
_logger = False
uri_prefix = None
#: The cache of declared entities is per connection,
#: in case the server loses data.
declared_entities = None
#: Iterator returning the next broker URL to try in the event
#: of connection failure (initialized by :attr:`failover_strategy`).
cycle = None
#: Additional transport specific options,
#: passed on to the transport instance.
transport_options = None
#: Strategy used to select new hosts when reconnecting after connection
#: failure. One of "round-robin", "shuffle" or any custom iterator
#: constantly yielding new URLs to try.
failover_strategy = 'round-robin'
#: Heartbeat value, currently only supported by the py-amqp transport.
heartbeat = None
resolve_aliases = resolve_aliases
failover_strategies = failover_strategies
hostname = userid = password = ssl = login_method = None
def __init__(self, hostname='localhost', userid=None,
password=None, virtual_host=None, port=None, insist=False,
ssl=False, transport=None, connect_timeout=5,
transport_options=None, login_method=None, uri_prefix=None,
heartbeat=0, failover_strategy='round-robin',
alternates=None, **kwargs):
alt = [] if alternates is None else alternates
# have to spell the args out, just to get nice docstrings :(
params = self._initial_params = {
'hostname': hostname, 'userid': userid,
'password': password, 'virtual_host': virtual_host,
'port': port, 'insist': insist, 'ssl': ssl,
'transport': transport, 'connect_timeout': connect_timeout,
'login_method': login_method, 'heartbeat': heartbeat
}
if hostname and not isinstance(hostname, str):
alt.extend(hostname)
hostname = alt[0]
params.update(hostname=hostname)
if hostname:
if ';' in hostname:
alt = hostname.split(';') + alt
hostname = alt[0]
params.update(hostname=hostname)
if '://' in hostname and '+' in hostname[:hostname.index('://')]:
# e.g. sqla+mysql://root:masterkey@localhost/
params['transport'], params['hostname'] = \
hostname.split('+', 1)
self.uri_prefix = params['transport']
elif '://' in hostname:
transport = transport or urlparse(hostname).scheme
if not get_transport_cls(transport).can_parse_url:
# we must parse the URL
url_params = parse_url(hostname)
params.update(
dictfilter(url_params),
hostname=url_params['hostname'],
)
params['transport'] = transport
self._init_params(**params)
# fallback hosts
self.alt = alt
# keep text representation for .info
# only temporary solution as this won't work when
# passing a custom object (Issue celery/celery#3320).
self._failover_strategy = failover_strategy or 'round-robin'
self.failover_strategy = self.failover_strategies.get(
self._failover_strategy) or self._failover_strategy
if self.alt:
self.cycle = self.failover_strategy(self.alt)
next(self.cycle) # skip first entry
if transport_options is None:
transport_options = {}
self.transport_options = transport_options
if _log_connection: # pragma: no cover
self._logger = True
if uri_prefix:
self.uri_prefix = uri_prefix
self.declared_entities = set()
def switch(self, conn_str):
"""Switch connection parameters to use a new URL or hostname.
Note:
Does not reconnect!
Arguments:
conn_str (str): either a hostname or URL.
"""
self.close()
self.declared_entities.clear()
self._closed = False
conn_params = (
parse_url(conn_str) if "://" in conn_str else {"hostname": conn_str} # noqa
)
self._init_params(**dict(self._initial_params, **conn_params))
def maybe_switch_next(self):
"""Switch to next URL given by the current failover strategy."""
if self.cycle:
self.switch(next(self.cycle))
def _init_params(self, hostname, userid, password, virtual_host, port,
insist, ssl, transport, connect_timeout,
login_method, heartbeat):
transport = transport or 'amqp'
if transport == 'amqp' and supports_librabbitmq():
transport = 'librabbitmq'
if transport == 'rediss' and ssl_available and not ssl:
logger.warning(
'Secure redis scheme specified (rediss) with no ssl '
'options, defaulting to insecure SSL behaviour.'
)
ssl = {'ssl_cert_reqs': CERT_NONE}
self.hostname = hostname
self.userid = userid
self.password = password
self.login_method = login_method
self.virtual_host = virtual_host or self.virtual_host
self.port = port or self.port
self.insist = insist
self.connect_timeout = connect_timeout
self.ssl = ssl
self.transport_cls = transport
self.heartbeat = heartbeat and float(heartbeat)
def register_with_event_loop(self, loop):
self.transport.register_with_event_loop(self.connection, loop)
def _debug(self, msg, *args, **kwargs):
if self._logger: # pragma: no cover
fmt = '[Kombu connection:{id:#x}] {msg}'
logger.debug(fmt.format(id=id(self), msg=str(msg)),
*args, **kwargs)
def connect(self):
"""Establish connection to server immediately."""
return self._ensure_connection(
max_retries=1, reraise_as_library_errors=False
)
def channel(self):
"""Create and return a new channel."""
self._debug('create channel')
chan = self.transport.create_channel(self.connection)
if _log_channel: # pragma: no cover
from .utils.debug import Logwrapped
return Logwrapped(chan, 'kombu.channel',
'[Kombu channel:{0.channel_id}] ')
return chan
def heartbeat_check(self, rate=2):
"""Check heartbeats.
Allow the transport to perform any periodic tasks
required to make heartbeats work. This should be called
approximately every second.
If the current transport does not support heartbeats then
this is a noop operation.
Arguments:
rate (int): Rate is how often the tick is called
compared to the actual heartbeat value. E.g. if
the heartbeat is set to 3 seconds, and the tick
is called every 3 / 2 seconds, then the rate is 2.
This value is currently unused by any transports.
"""
return self.transport.heartbeat_check(self.connection, rate=rate)
def drain_events(self, **kwargs):
"""Wait for a single event from the server.
Arguments:
timeout (float): Timeout in seconds before we give up.
Raises:
socket.timeout: if the timeout is exceeded.
"""
return self.transport.drain_events(self.connection, **kwargs)
def maybe_close_channel(self, channel):
"""Close given channel, but ignore connection and channel errors."""
try:
channel.close()
except (self.connection_errors + self.channel_errors):
pass
def _do_close_self(self):
# Close only connection and channel(s), but not transport.
self.declared_entities.clear()
if self._default_channel:
self.maybe_close_channel(self._default_channel)
if self._connection:
try:
self.transport.close_connection(self._connection)
except self.connection_errors + (AttributeError, socket.error):
pass
self._connection = None
def _close(self):
"""Really close connection, even if part of a connection pool."""
self._do_close_self()
self._do_close_transport()
self._debug('closed')
self._closed = True
def _do_close_transport(self):
if self._transport:
self._transport.client = None
self._transport = None
def collect(self, socket_timeout=None):
# amqp requires communication to close, we don't need that just
# to clear out references, Transport._collect can also be implemented
# by other transports that want fast after fork
try:
gc_transport = self._transport._collect
except AttributeError:
_timeo = socket.getdefaulttimeout()
socket.setdefaulttimeout(socket_timeout)
try:
self._do_close_self()
except socket.timeout:
pass
finally:
socket.setdefaulttimeout(_timeo)
else:
gc_transport(self._connection)
self._do_close_transport()
self.declared_entities.clear()
self._connection = None
def release(self):
"""Close the connection (if open)."""
self._close()
close = release
def ensure_connection(self, *args, **kwargs):
"""Public interface of _ensure_connection for retro-compatibility.
Returns kombu.Connection instance.
"""
self._ensure_connection(*args, **kwargs)
return self
def _ensure_connection(
self, errback=None, max_retries=None,
interval_start=2, interval_step=2, interval_max=30,
callback=None, reraise_as_library_errors=True,
timeout=None
):
"""Ensure we have a connection to the server.
If not retry establishing the connection with the settings
specified.
Arguments:
errback (Callable): Optional callback called each time the
connection can't be established. Arguments provided are
the exception raised and the interval that will be
slept ``(exc, interval)``.
max_retries (int): Maximum number of times to retry.
If this limit is exceeded the connection error
will be re-raised.
interval_start (float): The number of seconds we start
sleeping for.
interval_step (float): How many seconds added to the interval
for each retry.
interval_max (float): Maximum number of seconds to sleep between
each retry.
callback (Callable): Optional callback that is called for every
internal iteration (1 s).
timeout (int): Maximum amount of time in seconds to spend
waiting for connection
"""
if self.connected:
return self._connection
def on_error(exc, intervals, retries, interval=0):
round = self.completes_cycle(retries)
if round:
interval = next(intervals)
if errback:
errback(exc, interval)
self.maybe_switch_next() # select next host
return interval if round else 0
ctx = self._reraise_as_library_errors
if not reraise_as_library_errors:
ctx = self._dummy_context
with ctx():
return retry_over_time(
self._connection_factory, self.recoverable_connection_errors,
(), {}, on_error, max_retries,
interval_start, interval_step, interval_max,
callback, timeout=timeout
)
@contextmanager
def _reraise_as_library_errors(
self,
ConnectionError=exceptions.OperationalError,
ChannelError=exceptions.OperationalError):
try:
yield
except (ConnectionError, ChannelError):
raise
except self.recoverable_connection_errors as exc:
raise ConnectionError(str(exc)) from exc
except self.recoverable_channel_errors as exc:
raise ChannelError(str(exc)) from exc
@contextmanager
def _dummy_context(self):
yield
def completes_cycle(self, retries):
"""Return true if the cycle is complete after number of `retries`."""
return not (retries + 1) % len(self.alt) if self.alt else True
def revive(self, new_channel):
"""Revive connection after connection re-established."""
if self._default_channel and new_channel is not self._default_channel:
self.maybe_close_channel(self._default_channel)
self._default_channel = None
def ensure(self, obj, fun, errback=None, max_retries=None,
interval_start=1, interval_step=1, interval_max=1,
on_revive=None):
"""Ensure operation completes.
Regardless of any channel/connection errors occurring.
Retries by establishing the connection, and reapplying
the function.
Arguments:
obj: The object to ensure an action on.
fun (Callable): Method to apply.
errback (Callable): Optional callback called each time the
connection can't be established. Arguments provided are
the exception raised and the interval that will
be slept ``(exc, interval)``.
max_retries (int): Maximum number of times to retry.
If this limit is exceeded the connection error
will be re-raised.
interval_start (float): The number of seconds we start
sleeping for.
interval_step (float): How many seconds added to the interval
for each retry.
interval_max (float): Maximum number of seconds to sleep between
each retry.
on_revive (Callable): Optional callback called whenever
revival completes successfully
Examples:
>>> from kombu import Connection, Producer
>>> conn = Connection('amqp://')
>>> producer = Producer(conn)
>>> def errback(exc, interval):
... logger.error('Error: %r', exc, exc_info=1)
... logger.info('Retry in %s seconds.', interval)
>>> publish = conn.ensure(producer, producer.publish,
... errback=errback, max_retries=3)
>>> publish({'hello': 'world'}, routing_key='dest')
"""
def _ensured(*args, **kwargs):
got_connection = 0
conn_errors = self.recoverable_connection_errors
chan_errors = self.recoverable_channel_errors
has_modern_errors = hasattr(
self.transport, 'recoverable_connection_errors',
)
with self._reraise_as_library_errors():
for retries in count(0): # for infinity
try:
return fun(*args, **kwargs)
except conn_errors as exc:
if got_connection and not has_modern_errors:
# transport can not distinguish between
# recoverable/irrecoverable errors, so we propagate
# the error if it persists after a new connection
# was successfully established.
raise
if max_retries is not None and retries >= max_retries:
raise
self._debug('ensure connection error: %r',
exc, exc_info=1)
self.collect()
errback and errback(exc, 0)
remaining_retries = None
if max_retries is not None:
remaining_retries = max(max_retries - retries, 1)
self._ensure_connection(
errback,
remaining_retries,
interval_start, interval_step, interval_max,
reraise_as_library_errors=False,
)
channel = self.default_channel
obj.revive(channel)
if on_revive:
on_revive(channel)
got_connection += 1
except chan_errors as exc:
if max_retries is not None and retries > max_retries:
raise
self._debug('ensure channel error: %r',
exc, exc_info=1)
errback and errback(exc, 0)
_ensured.__name__ = f'{fun.__name__}(ensured)'
_ensured.__doc__ = fun.__doc__
_ensured.__module__ = fun.__module__
return _ensured
def autoretry(self, fun, channel=None, **ensure_options):
"""Decorator for functions supporting a ``channel`` keyword argument.
The resulting callable will retry calling the function if
it raises connection or channel related errors.
The return value will be a tuple of ``(retval, last_created_channel)``.
If a ``channel`` is not provided, then one will be automatically
acquired (remember to close it afterwards).
See Also:
:meth:`ensure` for the full list of supported keyword arguments.
Example:
>>> channel = connection.channel()
>>> try:
... ret, channel = connection.autoretry(
... publish_messages, channel)
... finally:
... channel.close()
"""
channels = [channel]
class Revival:
__name__ = getattr(fun, '__name__', None)
__module__ = getattr(fun, '__module__', None)
__doc__ = getattr(fun, '__doc__', None)
def __init__(self, connection):
self.connection = connection
def revive(self, channel):
channels[0] = channel
def __call__(self, *args, **kwargs):
if channels[0] is None:
self.revive(self.connection.default_channel)
return fun(*args, channel=channels[0], **kwargs), channels[0]
revive = Revival(self)
return self.ensure(revive, revive, **ensure_options)
def create_transport(self):
return self.get_transport_cls()(client=self)
def get_transport_cls(self):
"""Get the currently used transport class."""
transport_cls = self.transport_cls
if not transport_cls or isinstance(transport_cls, str):
transport_cls = get_transport_cls(transport_cls)
return transport_cls
def clone(self, **kwargs):
"""Create a copy of the connection with same settings."""
return self.__class__(**dict(self._info(resolve=False), **kwargs))
def get_heartbeat_interval(self):
return self.transport.get_heartbeat_interval(self.connection)
def _info(self, resolve=True):
transport_cls = self.transport_cls
if resolve:
transport_cls = self.resolve_aliases.get(
transport_cls, transport_cls)
D = self.transport.default_connection_params
if not self.hostname and D.get('hostname'):
logger.warning(
"No hostname was supplied. "
f"Reverting to default '{D.get('hostname')}'")
hostname = D.get('hostname')
else:
hostname = self.hostname
if self.uri_prefix:
hostname = f'{self.uri_prefix}+{hostname}'
info = (
('hostname', hostname),
('userid', self.userid or D.get('userid')),
('password', self.password or D.get('password')),
('virtual_host', self.virtual_host or D.get('virtual_host')),
('port', self.port or D.get('port')),
('insist', self.insist),
('ssl', self.ssl),
('transport', transport_cls),
('connect_timeout', self.connect_timeout),
('transport_options', self.transport_options),
('login_method', self.login_method or D.get('login_method')),
('uri_prefix', self.uri_prefix),
('heartbeat', self.heartbeat),
('failover_strategy', self._failover_strategy),
('alternates', self.alt),
)
return info
def info(self):
"""Get connection info."""
return dict(self._info())
def __eqhash__(self):
return HashedSeq(self.transport_cls, self.hostname, self.userid,
self.password, self.virtual_host, self.port,
repr(self.transport_options))
def as_uri(self, include_password=False, mask='**',
getfields=itemgetter('port', 'userid', 'password',
'virtual_host', 'transport')) -> str:
"""Convert connection parameters to URL form."""
hostname = self.hostname or 'localhost'
if self.transport.can_parse_url:
connection_as_uri = self.hostname
try:
return self.transport.as_uri(
connection_as_uri, include_password, mask)
except NotImplementedError:
pass
if self.uri_prefix:
connection_as_uri = f'{self.uri_prefix}+{hostname}'
if not include_password:
connection_as_uri = maybe_sanitize_url(connection_as_uri)
return connection_as_uri
if self.uri_prefix:
connection_as_uri = f'{self.uri_prefix}+{hostname}'
if not include_password:
connection_as_uri = maybe_sanitize_url(connection_as_uri)
return connection_as_uri
fields = self.info()
port, userid, password, vhost, transport = getfields(fields)
return as_url(
transport, hostname, port, userid, password, quote(vhost),
sanitize=not include_password, mask=mask,
)
def Pool(self, limit=None, **kwargs):
"""Pool of connections.
See Also:
:class:`ConnectionPool`.
Arguments:
limit (int): Maximum number of active connections.
Default is no limit.
Example:
>>> connection = Connection('amqp://')
>>> pool = connection.Pool(2)
>>> c1 = pool.acquire()
>>> c2 = pool.acquire()
>>> c3 = pool.acquire()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "kombu/connection.py", line 354, in acquire
raise ConnectionLimitExceeded(self.limit)
kombu.exceptions.ConnectionLimitExceeded: 2
>>> c1.release()
>>> c3 = pool.acquire()
"""
return ConnectionPool(self, limit, **kwargs)
def ChannelPool(self, limit=None, **kwargs):
"""Pool of channels.
See Also:
:class:`ChannelPool`.
Arguments:
limit (int): Maximum number of active channels.
Default is no limit.
Example:
>>> connection = Connection('amqp://')
>>> pool = connection.ChannelPool(2)
>>> c1 = pool.acquire()
>>> c2 = pool.acquire()
>>> c3 = pool.acquire()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "kombu/connection.py", line 354, in acquire
raise ChannelLimitExceeded(self.limit)
kombu.connection.ChannelLimitExceeded: 2
>>> c1.release()
>>> c3 = pool.acquire()
"""
return ChannelPool(self, limit, **kwargs)
def Producer(self, channel=None, *args, **kwargs):
"""Create new :class:`kombu.Producer` instance."""
from .messaging import Producer
return Producer(channel or self, *args, **kwargs)
def Consumer(self, queues=None, channel=None, *args, **kwargs):
"""Create new :class:`kombu.Consumer` instance."""
from .messaging import Consumer
return Consumer(channel or self, queues, *args, **kwargs)
def SimpleQueue(self, name, no_ack=None, queue_opts=None,
queue_args=None,
exchange_opts=None, channel=None, **kwargs):
"""Simple persistent queue API.
Create new :class:`~kombu.simple.SimpleQueue`, using a channel
from this connection.
If ``name`` is a string, a queue and exchange will be automatically
created using that name as the name of the queue and exchange,
also it will be used as the default routing key.
Arguments:
name (str, kombu.Queue): Name of the queue/or a queue.
no_ack (bool): Disable acknowledgments. Default is false.
queue_opts (Dict): Additional keyword arguments passed to the
constructor of the automatically created :class:`~kombu.Queue`.
queue_args (Dict): Additional keyword arguments passed to the
constructor of the automatically created :class:`~kombu.Queue`
for setting implementation extensions (e.g., in RabbitMQ).
exchange_opts (Dict): Additional keyword arguments passed to the
constructor of the automatically created
:class:`~kombu.Exchange`.
channel (ChannelT): Custom channel to use. If not specified the
connection default channel is used.
"""
from .simple import SimpleQueue
return SimpleQueue(channel or self, name, no_ack, queue_opts,
queue_args,
exchange_opts, **kwargs)
def SimpleBuffer(self, name, no_ack=None, queue_opts=None,
queue_args=None,
exchange_opts=None, channel=None, **kwargs):
"""Simple ephemeral queue API.
Create new :class:`~kombu.simple.SimpleQueue` using a channel
from this connection.
See Also:
Same as :meth:`SimpleQueue`, but configured with buffering
semantics. The resulting queue and exchange will not be durable,
also auto delete is enabled. Messages will be transient (not
persistent), and acknowledgments are disabled (``no_ack``).
"""
from .simple import SimpleBuffer
return SimpleBuffer(channel or self, name, no_ack, queue_opts,
queue_args,
exchange_opts, **kwargs)
def _establish_connection(self):
self._debug('establishing connection...')
conn = self.transport.establish_connection()
self._debug('connection established: %r', self)
return conn
def supports_exchange_type(self, exchange_type):
return exchange_type in self.transport.implements.exchange_type
def __repr__(self):
return f'<Connection: {self.as_uri()} at {id(self):#x}>'
def __copy__(self):
return self.clone()
def __reduce__(self):
return self.__class__, tuple(self.info().values()), None
def __enter__(self):
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None
) -> None:
self.release()
@property
def qos_semantics_matches_spec(self):
return self.transport.qos_semantics_matches_spec(self.connection)
def _extract_failover_opts(self):
conn_opts = {'timeout': self.connect_timeout}
transport_opts = self.transport_options
if transport_opts:
if 'max_retries' in transport_opts:
conn_opts['max_retries'] = transport_opts['max_retries']
if 'interval_start' in transport_opts:
conn_opts['interval_start'] = transport_opts['interval_start']
if 'interval_step' in transport_opts:
conn_opts['interval_step'] = transport_opts['interval_step']
if 'interval_max' in transport_opts:
conn_opts['interval_max'] = transport_opts['interval_max']
return conn_opts
@property
def connected(self):
"""Return true if the connection has been established."""
return (not self._closed and
self._connection is not None and
self.transport.verify_connection(self._connection))
@property
def connection(self):
"""The underlying connection object.
Warning:
This instance is transport specific, so do not
depend on the interface of this object.
"""
if not self._closed:
if not self.connected:
return self._ensure_connection(
max_retries=1, reraise_as_library_errors=False
)
return self._connection
def _connection_factory(self):
self.declared_entities.clear()
self._default_channel = None
self._connection = self._establish_connection()
self._closed = False
return self._connection
@property
def default_channel(self) -> Channel:
"""Default channel.
Created upon access and closed when the connection is closed.
Note:
Can be used for automatic channel handling when you only need one
channel, and also it is the channel implicitly used if
a connection is passed instead of a channel, to functions that
require a channel.
"""
# make sure we're still connected, and if not refresh.
conn_opts = self._extract_failover_opts()
self._ensure_connection(**conn_opts)
if self._default_channel is None:
self._default_channel = self.channel()
return self._default_channel
@property
def host(self):
"""The host as a host name/port pair separated by colon."""
return ':'.join([self.hostname, str(self.port)])
@property
def transport(self):
if self._transport is None:
self._transport = self.create_transport()
return self._transport
@cached_property
def manager(self):
"""AMQP Management API.
Experimental manager that can be used to manage/monitor the broker
instance.
Not available for all transports.
"""
return self.transport.manager
def get_manager(self, *args, **kwargs):
return self.transport.get_manager(*args, **kwargs)
@cached_property
def recoverable_connection_errors(self):
"""Recoverable connection errors.
List of connection related exceptions that can be recovered from,
but where the connection must be closed and re-established first.
"""
try:
return self.get_transport_cls().recoverable_connection_errors
except AttributeError:
# There were no such classification before,
# and all errors were assumed to be recoverable,
# so this is a fallback for transports that do
# not support the new recoverable/irrecoverable classes.
return self.connection_errors + self.channel_errors
@cached_property
def recoverable_channel_errors(self):
"""Recoverable channel errors.
List of channel related exceptions that can be automatically
recovered from without re-establishing the connection.
"""
try:
return self.get_transport_cls().recoverable_channel_errors
except AttributeError:
return ()
@cached_property
def connection_errors(self):
"""List of exceptions that may be raised by the connection."""
return self.get_transport_cls().connection_errors
@cached_property
def channel_errors(self):
"""List of exceptions that may be raised by the channel."""
return self.get_transport_cls().channel_errors
@property
def supports_heartbeats(self):
return self.transport.implements.heartbeats
@property
def is_evented(self):
return self.transport.implements.asynchronous
BrokerConnection = Connection
class ConnectionPool(Resource):
"""Pool of connections."""
LimitExceeded = exceptions.ConnectionLimitExceeded
close_after_fork = True
def __init__(self, connection, limit=None, **kwargs):
self.connection = connection
super().__init__(limit=limit)
def new(self):
return self.connection.clone()
def release_resource(self, resource):
try:
resource._debug('released')
except AttributeError:
pass
def close_resource(self, resource):
resource._close()
def collect_resource(self, resource, socket_timeout=0.1):
if not isinstance(resource, lazy):
return resource.collect(socket_timeout)
@contextmanager
def acquire_channel(self, block=False):
with self.acquire(block=block) as connection:
yield connection, connection.default_channel
def setup(self):
if self.limit:
q = self._resource.queue
while len(q) < self.limit:
self._resource.put_nowait(lazy(self.new))
def prepare(self, resource):
if callable(resource):
resource = resource()
resource._debug('acquired')
return resource
class ChannelPool(Resource):
"""Pool of channels."""
LimitExceeded = exceptions.ChannelLimitExceeded
def __init__(self, connection, limit=None, **kwargs):
self.connection = connection
super().__init__(limit=limit)
def new(self):
return lazy(self.connection.channel)
def setup(self):
channel = self.new()
if self.limit:
q = self._resource.queue
while len(q) < self.limit:
self._resource.put_nowait(lazy(channel))
def prepare(self, channel):
if callable(channel):
channel = channel()
return channel
def maybe_channel(channel: Channel | Connection) -> Channel:
"""Get channel from object.
Return the default channel if argument is a connection instance,
otherwise just return the channel given.
"""
if is_connection(channel):
return channel.default_channel
return channel
def is_connection(obj: Any) -> TypeGuard[Connection]:
return isinstance(obj, Connection)
|
[] |
[] |
[
"KOMBU_LOG_CONNECTION",
"KOMBU_LOG_CHANNEL"
] |
[]
|
["KOMBU_LOG_CONNECTION", "KOMBU_LOG_CHANNEL"]
|
python
| 2 | 0 | |
letsencrypt/client.go
|
package letsencrypt
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"regexp"
"strings"
"time"
"github.com/Sirupsen/logrus"
lego "github.com/xenolf/lego/acme"
loge "github.com/xenolf/lego/log"
)
const (
StorageDir = "/etc/letsencrypt"
ProductionApiUri = "https://acme-v02.api.letsencrypt.org/directory"
StagingApiUri = "https://acme-staging-v02.api.letsencrypt.org/directory"
)
type KeyType string
const (
RSA2048 KeyType = "RSA-2048"
RSA4096 KeyType = "RSA-4096"
RSA8192 KeyType = "RSA-8192"
EC256 KeyType = "ECDSA-256"
EC384 KeyType = "ECDSA-384"
)
type ApiVersion string
const (
Production ApiVersion = "Production"
Sandbox ApiVersion = "Sandbox"
)
// AcmeCertificate represents a CA issued certificate,
// PrivateKey and Certificate are both PEM encoded.
//
// Anonymous fields:
// PrivateKey []byte
// Certificate []byte
// Domain string
type AcmeCertificate struct {
lego.CertificateResource
DnsNames string `json:"dnsNames"`
ExpiryDate time.Time `json:"expiryDate"`
SerialNumber string `json:"serialNumber"`
}
// Client represents a Lets Encrypt client
type Client struct {
client *lego.Client
apiVersion ApiVersion
provider Provider
}
// NewClient returns a new Lets Encrypt client
func NewClient(email string, kt KeyType, apiVer ApiVersion, dnsResolvers []string, provider ProviderOpts) (*Client, error) {
var keyType lego.KeyType
switch kt {
case RSA2048:
keyType = lego.RSA2048
case RSA4096:
keyType = lego.RSA4096
case RSA8192:
keyType = lego.RSA8192
case EC256:
keyType = lego.EC256
case EC384:
keyType = lego.EC384
default:
return nil, fmt.Errorf("Invalid private key type: %s", string(kt))
}
var serverUri string
switch apiVer {
case Production:
serverUri = ProductionApiUri
case Sandbox:
serverUri = StagingApiUri
default:
return nil, fmt.Errorf("Invalid API version: %s", string(apiVer))
}
acc, err := NewAccount(email, apiVer, keyType)
if err != nil {
return nil, fmt.Errorf("Could not initialize account store for %s: %v", email, err)
}
client, err := lego.NewClient(serverUri, acc, keyType)
if err != nil {
return nil, fmt.Errorf("Could not create client: %v", err)
}
loge.Logger = log.New(ioutil.Discard, "", 0)
if acc.Registration == nil {
logrus.Infof("Creating Let's Encrypt account for %s", email)
reg, err := client.Register(true)
if err != nil {
return nil, fmt.Errorf("Failed to register account: %v", err)
}
acc.Registration = reg
err = acc.Save()
if err != nil {
logrus.Errorf("Could not save account data: %v", err)
}
} else {
logrus.Infof("Using locally stored Let's Encrypt account for %s", email)
}
prov, challenge, err := getProvider(provider)
if err != nil {
return nil, fmt.Errorf("Could not get provider: %v", err)
}
err = client.SetChallengeProvider(challenge, prov)
if err != nil {
return nil, fmt.Errorf("Could not set provider: %v", err)
}
if challenge == lego.DNS01 {
client.ExcludeChallenges([]lego.Challenge{lego.HTTP01})
} else if challenge == lego.HTTP01 {
client.ExcludeChallenges([]lego.Challenge{lego.DNS01})
}
if len(dnsResolvers) > 0 {
lego.RecursiveNameservers = dnsResolvers
}
return &Client{
client: client,
apiVersion: apiVer,
provider: provider.Provider,
}, nil
}
// EnableLogs prints logs from the upstream lego library
func (c *Client) EnableLogs() {
logger := logrus.New()
logger.Out = os.Stdout
loge.Logger = log.New(logger.Writer(), "", 0)
}
// Issue obtains a new SAN certificate from the Lets Encrypt CA
func (c *Client) Issue(certName string, domains []string) (*AcmeCertificate, error) {
certRes, err := c.client.ObtainCertificate(domains, true, nil, false)
if err != nil {
return nil, err
}
dnsNames := dnsNamesIdentifier(domains)
acmeCert, err := c.saveCertificate(certName, dnsNames, certRes)
if err != nil {
logrus.Fatalf("Error saving certificate '%s': %v", certName, err)
return nil, err
}
return acmeCert, nil
}
// Renew renewes the given stored certificate
func (c *Client) Renew(certName string) (*AcmeCertificate, error) {
acmeCert, err := c.loadCertificateByName(certName)
if err != nil {
return nil, fmt.Errorf("Error loading certificate '%s': %v", certName, err)
}
certRes := acmeCert.CertificateResource
newCertRes, err := c.client.RenewCertificate(certRes, true, false)
if err != nil {
return nil, err
}
newAcmeCert, err := c.saveCertificate(certName, acmeCert.DnsNames, newCertRes)
if err != nil {
logrus.Fatalf("Error saving certificate '%s': %v", certName, err)
}
return newAcmeCert, nil
}
// GetStoredCertificate returns the locally stored certificate for the given domains
func (c *Client) GetStoredCertificate(certName string, domains []string) (bool, *AcmeCertificate) {
logrus.Debugf("Looking up stored certificate by name '%s'", certName)
if !c.haveCertificateByName(certName) {
return false, nil
}
acmeCert, err := c.loadCertificateByName(certName)
if err != nil {
// Don't quit. Try to issue a new certificate instead.
logrus.Errorf("Error loading certificate '%s': %v", certName, err)
return false, nil
}
// check if the DNS names are a match
if dnsNames := dnsNamesIdentifier(domains); acmeCert.DnsNames != dnsNames {
logrus.Infof("Stored certificate does not have matching domain names: '%s' ", acmeCert.DnsNames)
return false, nil
}
return true, &acmeCert
}
func (c *Client) haveCertificateByName(certName string) bool {
certPath := c.CertPath(certName)
if _, err := os.Stat(path.Join(certPath, "metadata.json")); err != nil {
logrus.Debugf("No certificate in path '%s'", certPath)
return false
}
return true
}
func (c *Client) loadCertificateByName(certName string) (AcmeCertificate, error) {
var acmeCert AcmeCertificate
certPath := c.CertPath(certName)
logrus.Debugf("Loading certificate '%s' from '%s'", certName, certPath)
certIn := path.Join(certPath, "fullchain.pem")
privIn := path.Join(certPath, "privkey.pem")
metaIn := path.Join(certPath, "metadata.json")
certBytes, err := ioutil.ReadFile(certIn)
if err != nil {
return acmeCert, fmt.Errorf("Failed to load certificate from '%s': %v", certIn, err)
}
metaBytes, err := ioutil.ReadFile(metaIn)
if err != nil {
return acmeCert, fmt.Errorf("Failed to load meta data from '%s': %v", metaIn, err)
}
keyBytes, err := ioutil.ReadFile(privIn)
if err != nil {
return acmeCert, fmt.Errorf("Failed to load private key from '%s': %v", privIn, err)
}
err = json.Unmarshal(metaBytes, &acmeCert)
if err != nil {
return acmeCert, fmt.Errorf("Failed to unmarshal json meta data from '%s': %v", metaIn, err)
}
acmeCert.PrivateKey = keyBytes
acmeCert.Certificate = certBytes
return acmeCert, nil
}
func (c *Client) saveCertificate(certName, dnsNames string, certRes *lego.CertificateResource) (*AcmeCertificate, error) {
expiryDate, err := lego.GetPEMCertExpiration(certRes.Certificate)
if err != nil {
return nil, fmt.Errorf("Failed to read certificate expiry date: %v", err)
}
serialNumber, err := getPEMCertSerialNumber(certRes.Certificate)
if err != nil {
return nil, fmt.Errorf("Failed to read certificate serial number: %v", err)
}
acmeCert := AcmeCertificate{
CertificateResource: *certRes,
ExpiryDate: expiryDate,
SerialNumber: serialNumber,
DnsNames: dnsNames,
}
certPath := c.CertPath(certName)
maybeCreatePath(certPath)
logrus.Debugf("Saving certificate '%s' to path '%s'", certName, certPath)
certOut := path.Join(certPath, "fullchain.pem")
privOut := path.Join(certPath, "privkey.pem")
metaOut := path.Join(certPath, "metadata.json")
err = ioutil.WriteFile(certOut, acmeCert.Certificate, 0600)
if err != nil {
return nil, fmt.Errorf("Failed to save certificate to '%s': %v", certOut, err)
}
logrus.Infof("Certificate saved to '%s'", certOut)
err = ioutil.WriteFile(privOut, acmeCert.PrivateKey, 0600)
if err != nil {
return nil, fmt.Errorf("Failed to save private key to '%s': %v", privOut, err)
}
logrus.Infof("Private key saved to '%s'", privOut)
jsonBytes, err := json.MarshalIndent(acmeCert, "", "\t")
if err != nil {
return nil, fmt.Errorf("Failed to marshal meta data for certificate '%s': %v", certName, err)
}
err = ioutil.WriteFile(metaOut, jsonBytes, 0600)
if err != nil {
return nil, fmt.Errorf("Failed to save meta data to '%s': %v", metaOut, err)
}
return &acmeCert, nil
}
func (c *Client) ConfigPath() string {
path := path.Join(StorageDir, strings.ToLower(string(c.apiVersion)))
maybeCreatePath(path)
return path
}
func (c *Client) ProviderName() string {
return string(c.provider)
}
func (c *Client) ApiVersion() string {
return string(c.apiVersion)
}
func (c *Client) CertPath(certName string) string {
return path.Join(c.ConfigPath(), "certs", safeFileName(certName))
}
func dnsNamesIdentifier(domains []string) string {
return strings.Join(domains, "|")
}
func maybeCreatePath(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
err = os.MkdirAll(path, 0700)
if err != nil {
logrus.Fatalf("Failed to create path: %v", err)
}
}
}
// safeFileName replaces separators with dashes and removes all
// characters other than alphanumerics, dashes, underscores and dots.
func safeFileName(str string) string {
separators := regexp.MustCompile(`[ /&=+:]`)
illegals := regexp.MustCompile(`[^[:alnum:]-_.]`)
dashes := regexp.MustCompile(`[\-]+`)
str = separators.ReplaceAllString(str, "-")
str = illegals.ReplaceAllString(str, "")
str = dashes.ReplaceAllString(str, "-")
return str
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
credscontroller/vendor/github.com/hashicorp/vault/vault/mount.go
|
package vault
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"sync"
"time"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/builtin/plugin"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/mitchellh/copystructure"
)
const (
// coreMountConfigPath is used to store the mount configuration.
// Mounts are protected within the Vault itself, which means they
// can only be viewed or modified after an unseal.
coreMountConfigPath = "core/mounts"
// coreLocalMountConfigPath is used to store mount configuration for local
// (non-replicated) mounts
coreLocalMountConfigPath = "core/local-mounts"
// backendBarrierPrefix is the prefix to the UUID used in the
// barrier view for the backends.
backendBarrierPrefix = "logical/"
// systemBarrierPrefix is the prefix used for the
// system logical backend.
systemBarrierPrefix = "sys/"
// mountTableType is the value we expect to find for the mount table and
// corresponding entries
mountTableType = "mounts"
)
// ListingVisibilityType represents the types for listing visibility
type ListingVisibilityType string
const (
// ListingVisibilityDefault is the default value for listing visibility
ListingVisibilityDefault ListingVisibilityType = ""
// ListingVisibilityHidden is the hidden type for listing visibility
ListingVisibilityHidden ListingVisibilityType = "hidden"
// ListingVisibilityUnauth is the unauth type for listing visibility
ListingVisibilityUnauth ListingVisibilityType = "unauth"
systemMountPath = "sys/"
identityMountPath = "identity/"
cubbyholeMountPath = "cubbyhole/"
systemMountType = "system"
identityMountType = "identity"
cubbyholeMountType = "cubbyhole"
pluginMountType = "plugin"
MountTableUpdateStorage = true
MountTableNoUpdateStorage = false
)
var (
// loadMountsFailed if loadMounts encounters an error
errLoadMountsFailed = errors.New("failed to setup mount table")
// protectedMounts cannot be remounted
protectedMounts = []string{
"audit/",
"auth/",
systemMountPath,
cubbyholeMountPath,
identityMountPath,
}
untunableMounts = []string{
cubbyholeMountPath,
systemMountPath,
"audit/",
identityMountPath,
}
// singletonMounts can only exist in one location and are
// loaded by default. These are types, not paths.
singletonMounts = []string{
cubbyholeMountType,
systemMountType,
"token",
identityMountType,
}
// mountAliases maps old backend names to new backend names, allowing us
// to move/rename backends but maintain backwards compatibility
mountAliases = map[string]string{"generic": "kv"}
)
func (c *Core) generateMountAccessor(entryType string) (string, error) {
var accessor string
for {
randBytes, err := uuid.GenerateRandomBytes(4)
if err != nil {
return "", err
}
accessor = fmt.Sprintf("%s_%s", entryType, fmt.Sprintf("%08x", randBytes[0:4]))
if entry := c.router.MatchingMountByAccessor(accessor); entry == nil {
break
}
}
return accessor, nil
}
// MountTable is used to represent the internal mount table
type MountTable struct {
Type string `json:"type"`
Entries []*MountEntry `json:"entries"`
}
// shallowClone returns a copy of the mount table that
// keeps the MountEntry locations, so as not to invalidate
// other locations holding pointers. Care needs to be taken
// if modifying entries rather than modifying the table itself
func (t *MountTable) shallowClone() *MountTable {
mt := &MountTable{
Type: t.Type,
Entries: make([]*MountEntry, len(t.Entries)),
}
for i, e := range t.Entries {
mt.Entries[i] = e
}
return mt
}
// setTaint is used to set the taint on given entry Accepts either the mount
// entry's path or namespace + path, i.e. <ns-path>/secret/ or <ns-path>/token/
func (t *MountTable) setTaint(ctx context.Context, path string, value bool) (*MountEntry, error) {
n := len(t.Entries)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
for i := 0; i < n; i++ {
if entry := t.Entries[i]; entry.Path == path && entry.Namespace().ID == ns.ID {
t.Entries[i].Tainted = value
return t.Entries[i], nil
}
}
return nil, nil
}
// remove is used to remove a given path entry; returns the entry that was
// removed
func (t *MountTable) remove(ctx context.Context, path string) (*MountEntry, error) {
n := len(t.Entries)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
for i := 0; i < n; i++ {
if entry := t.Entries[i]; entry.Path == path && entry.Namespace().ID == ns.ID {
t.Entries[i], t.Entries[n-1] = t.Entries[n-1], nil
t.Entries = t.Entries[:n-1]
return entry, nil
}
}
return nil, nil
}
func (t *MountTable) find(ctx context.Context, path string) (*MountEntry, error) {
n := len(t.Entries)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
for i := 0; i < n; i++ {
if entry := t.Entries[i]; entry.Path == path && entry.Namespace().ID == ns.ID {
return entry, nil
}
}
return nil, nil
}
// sortEntriesByPath sorts the entries in the table by path and returns the
// table; this is useful for tests
func (t *MountTable) sortEntriesByPath() *MountTable {
sort.Slice(t.Entries, func(i, j int) bool {
return t.Entries[i].Path < t.Entries[j].Path
})
return t
}
// sortEntriesByPath sorts the entries in the table by path and returns the
// table; this is useful for tests
func (t *MountTable) sortEntriesByPathDepth() *MountTable {
sort.Slice(t.Entries, func(i, j int) bool {
return len(strings.Split(t.Entries[i].Namespace().Path+t.Entries[i].Path, "/")) < len(strings.Split(t.Entries[j].Namespace().Path+t.Entries[j].Path, "/"))
})
return t
}
// MountEntry is used to represent a mount table entry
type MountEntry struct {
Table string `json:"table"` // The table it belongs to
Path string `json:"path"` // Mount Path
Type string `json:"type"` // Logical backend Type
Description string `json:"description"` // User-provided description
UUID string `json:"uuid"` // Barrier view UUID
BackendAwareUUID string `json:"backend_aware_uuid"` // UUID that can be used by the backend as a helper when a consistent value is needed outside of storage.
Accessor string `json:"accessor"` // Unique but more human-friendly ID. Does not change, not used for any sensitive things (like as a salt, which the UUID sometimes is).
Config MountConfig `json:"config"` // Configuration related to this mount (but not backend-derived)
Options map[string]string `json:"options"` // Backend options
Local bool `json:"local"` // Local mounts are not replicated or affected by replication
SealWrap bool `json:"seal_wrap"` // Whether to wrap CSPs
ExternalEntropyAccess bool `json:"external_entropy_access"` // Whether to allow external entropy source access
Tainted bool `json:"tainted,omitempty"` // Set as a Write-Ahead flag for unmount/remount
NamespaceID string `json:"namespace_id"`
// namespace contains the populated namespace
namespace *namespace.Namespace
// synthesizedConfigCache is used to cache configuration values. These
// particular values are cached since we want to get them at a point-in-time
// without separately managing their locks individually. See SyncCache() for
// the specific values that are being cached.
synthesizedConfigCache sync.Map
}
// MountConfig is used to hold settable options
type MountConfig struct {
DefaultLeaseTTL time.Duration `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` // Override for global default
MaxLeaseTTL time.Duration `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` // Override for global default
ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` // Override for global default
AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"`
AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"`
ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"`
PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"`
AllowedResponseHeaders []string `json:"allowed_response_headers,omitempty" structs:"allowed_response_headers" mapstructure:"allowed_response_headers"`
TokenType logical.TokenType `json:"token_type" structs:"token_type" mapstructure:"token_type"`
// PluginName is the name of the plugin registered in the catalog.
//
// Deprecated: MountEntry.Type should be used instead for Vault 1.0.0 and beyond.
PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"`
}
// APIMountConfig is an embedded struct of api.MountConfigInput
type APIMountConfig struct {
DefaultLeaseTTL string `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"`
MaxLeaseTTL string `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"`
ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"`
AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"`
AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"`
ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"`
PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"`
AllowedResponseHeaders []string `json:"allowed_response_headers,omitempty" structs:"allowed_response_headers" mapstructure:"allowed_response_headers"`
TokenType string `json:"token_type" structs:"token_type" mapstructure:"token_type"`
// PluginName is the name of the plugin registered in the catalog.
//
// Deprecated: MountEntry.Type should be used instead for Vault 1.0.0 and beyond.
PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"`
}
// Clone returns a deep copy of the mount entry
func (e *MountEntry) Clone() (*MountEntry, error) {
cp, err := copystructure.Copy(e)
if err != nil {
return nil, err
}
return cp.(*MountEntry), nil
}
// Namespace returns the namespace for the mount entry
func (e *MountEntry) Namespace() *namespace.Namespace {
return e.namespace
}
// APIPath returns the full API Path for the given mount entry
func (e *MountEntry) APIPath() string {
path := e.Path
if e.Table == credentialTableType {
path = credentialRoutePrefix + path
}
return e.namespace.Path + path
}
// SyncCache syncs tunable configuration values to the cache. In the case of
// cached values, they should be retrieved via synthesizedConfigCache.Load()
// instead of accessing them directly through MountConfig.
func (e *MountEntry) SyncCache() {
if len(e.Config.AuditNonHMACRequestKeys) == 0 {
e.synthesizedConfigCache.Delete("audit_non_hmac_request_keys")
} else {
e.synthesizedConfigCache.Store("audit_non_hmac_request_keys", e.Config.AuditNonHMACRequestKeys)
}
if len(e.Config.AuditNonHMACResponseKeys) == 0 {
e.synthesizedConfigCache.Delete("audit_non_hmac_response_keys")
} else {
e.synthesizedConfigCache.Store("audit_non_hmac_response_keys", e.Config.AuditNonHMACResponseKeys)
}
if len(e.Config.PassthroughRequestHeaders) == 0 {
e.synthesizedConfigCache.Delete("passthrough_request_headers")
} else {
e.synthesizedConfigCache.Store("passthrough_request_headers", e.Config.PassthroughRequestHeaders)
}
if len(e.Config.AllowedResponseHeaders) == 0 {
e.synthesizedConfigCache.Delete("allowed_response_headers")
} else {
e.synthesizedConfigCache.Store("allowed_response_headers", e.Config.AllowedResponseHeaders)
}
}
func (c *Core) decodeMountTable(ctx context.Context, raw []byte) (*MountTable, error) {
// Decode into mount table
mountTable := new(MountTable)
if err := jsonutil.DecodeJSON(raw, mountTable); err != nil {
return nil, err
}
// Populate the namespace in memory
var mountEntries []*MountEntry
for _, entry := range mountTable.Entries {
if entry.NamespaceID == "" {
entry.NamespaceID = namespace.RootNamespaceID
}
ns, err := NamespaceByID(ctx, entry.NamespaceID, c)
if err != nil {
return nil, err
}
if ns == nil {
c.logger.Error("namespace on mount entry not found", "namespace_id", entry.NamespaceID, "mount_path", entry.Path, "mount_description", entry.Description)
continue
}
entry.namespace = ns
mountEntries = append(mountEntries, entry)
}
return &MountTable{
Type: mountTable.Type,
Entries: mountEntries,
}, nil
}
// Mount is used to mount a new backend to the mount table.
func (c *Core) mount(ctx context.Context, entry *MountEntry) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(entry.Path, "/") {
entry.Path += "/"
}
// Prevent protected paths from being mounted
for _, p := range protectedMounts {
if strings.HasPrefix(entry.Path, p) && entry.namespace == nil {
return logical.CodedError(403, fmt.Sprintf("cannot mount %q", entry.Path))
}
}
// Do not allow more than one instance of a singleton mount
for _, p := range singletonMounts {
if entry.Type == p {
return logical.CodedError(403, fmt.Sprintf("mount type of %q is not mountable", entry.Type))
}
}
// Mount internally
if err := c.mountInternal(ctx, entry, MountTableUpdateStorage); err != nil {
return err
}
// Re-evaluate filtered paths
if err := runFilteredPathsEvaluation(ctx, c); err != nil {
c.logger.Error("failed to evaluate filtered paths", "error", err)
// We failed to evaluate filtered paths so we are undoing the mount operation
if unmountInternalErr := c.unmountInternal(ctx, entry.Path, MountTableUpdateStorage); unmountInternalErr != nil {
c.logger.Error("failed to unmount", "error", unmountInternalErr)
}
return err
}
return nil
}
func (c *Core) mountInternal(ctx context.Context, entry *MountEntry, updateStorage bool) error {
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
ns, err := namespace.FromContext(ctx)
if err != nil {
return err
}
if err := verifyNamespace(c, ns, entry); err != nil {
return err
}
entry.NamespaceID = ns.ID
entry.namespace = ns
// Ensure the cache is populated, don't need the result
NamespaceByID(ctx, ns.ID, c)
// Basic check for matching names
for _, ent := range c.mounts.Entries {
if ns.ID == ent.NamespaceID {
switch {
// Existing is oauth/github/ new is oauth/ or
// existing is oauth/ and new is oauth/github/
case strings.HasPrefix(ent.Path, entry.Path):
fallthrough
case strings.HasPrefix(entry.Path, ent.Path):
return logical.CodedError(409, fmt.Sprintf("path is already in use at %s", ent.Path))
}
}
}
// Verify there are no conflicting mounts in the router
if match := c.router.MountConflict(ctx, entry.Path); match != "" {
return logical.CodedError(409, fmt.Sprintf("existing mount at %s", match))
}
// Generate a new UUID and view
if entry.UUID == "" {
entryUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.UUID = entryUUID
}
if entry.BackendAwareUUID == "" {
bUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.BackendAwareUUID = bUUID
}
if entry.Accessor == "" {
accessor, err := c.generateMountAccessor(entry.Type)
if err != nil {
return err
}
entry.Accessor = accessor
}
// Sync values to the cache
entry.SyncCache()
viewPath := entry.ViewPath()
view := NewBarrierView(c.barrier, viewPath)
// Singleton mounts cannot be filtered manually on a per-secondary basis
// from replication.
if strutil.StrListContains(singletonMounts, entry.Type) {
addFilterablePath(c, viewPath)
}
nilMount, err := preprocessMount(c, entry, view)
if err != nil {
return err
}
origReadOnlyErr := view.getReadOnlyErr()
// Mark the view as read-only until the mounting is complete and
// ensure that it is reset after. This ensures that there will be no
// writes during the construction of the backend.
view.setReadOnlyErr(logical.ErrSetupReadOnly)
// We defer this because we're already up and running so we don't need to
// time it for after postUnseal
defer view.setReadOnlyErr(origReadOnlyErr)
var backend logical.Backend
sysView := c.mountEntrySysView(entry)
backend, err = c.newLogicalBackend(ctx, entry, sysView, view)
if err != nil {
return err
}
if backend == nil {
return fmt.Errorf("nil backend of type %q returned from creation function", entry.Type)
}
// Check for the correct backend type
backendType := backend.Type()
if backendType != logical.TypeLogical {
if entry.Type != "kv" && entry.Type != "system" && entry.Type != "cubbyhole" {
return fmt.Errorf(`unknown backend type: "%s"`, entry.Type)
}
}
addPathCheckers(c, entry, backend, viewPath)
c.setCoreBackend(entry, backend, view)
// If the mount is filtered or we are on a DR secondary we don't want to
// keep the actual backend running, so we clean it up and set it to nil
// so the router does not have a pointer to the object.
if nilMount {
backend.Cleanup(ctx)
backend = nil
}
newTable := c.mounts.shallowClone()
newTable.Entries = append(newTable.Entries, entry)
if updateStorage {
if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil {
c.logger.Error("failed to update mount table", "error", err)
if err == logical.ErrReadOnly && c.perfStandby {
return err
}
return logical.CodedError(500, "failed to update mount table")
}
}
c.mounts = newTable
if err := c.router.Mount(backend, entry.Path, entry, view); err != nil {
return err
}
if !nilMount {
// restore the original readOnlyErr, so we can write to the view in
// Initialize() if necessary
view.setReadOnlyErr(origReadOnlyErr)
// initialize, using the core's active context.
err := backend.Initialize(c.activeContext, &logical.InitializationRequest{Storage: view})
if err != nil {
return err
}
}
if c.logger.IsInfo() {
c.logger.Info("successful mount", "namespace", entry.Namespace().Path, "path", entry.Path, "type", entry.Type)
}
return nil
}
// Unmount is used to unmount a path. The boolean indicates whether the mount
// was found.
func (c *Core) unmount(ctx context.Context, path string) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(path, "/") {
path += "/"
}
// Prevent protected paths from being unmounted
for _, p := range protectedMounts {
if strings.HasPrefix(path, p) {
return fmt.Errorf("cannot unmount %q", path)
}
}
// Unmount mount internally
if err := c.unmountInternal(ctx, path, MountTableUpdateStorage); err != nil {
return err
}
// Re-evaluate filtered paths
if err := runFilteredPathsEvaluation(ctx, c); err != nil {
// Even we failed to evaluate filtered paths, the unmount operation was still successful
c.logger.Error("failed to evaluate filtered paths", "error", err)
}
return nil
}
func (c *Core) unmountInternal(ctx context.Context, path string, updateStorage bool) error {
ns, err := namespace.FromContext(ctx)
if err != nil {
return err
}
// Verify exact match of the route
match := c.router.MatchingMount(ctx, path)
if match == "" || ns.Path+path != match {
return fmt.Errorf("no matching mount")
}
// Get the view for this backend
view := c.router.MatchingStorageByAPIPath(ctx, path)
// Get the backend/mount entry for this path, used to remove ignored
// replication prefixes
backend := c.router.MatchingBackend(ctx, path)
entry := c.router.MatchingMountEntry(ctx, path)
// Mark the entry as tainted
if err := c.taintMountEntry(ctx, path, updateStorage); err != nil {
c.logger.Error("failed to taint mount entry for path being unmounted", "error", err, "path", path)
return err
}
// Taint the router path to prevent routing. Note that in-flight requests
// are uncertain, right now.
if err := c.router.Taint(ctx, path); err != nil {
return err
}
rCtx := namespace.ContextWithNamespace(c.activeContext, ns)
if backend != nil && c.rollback != nil {
// Invoke the rollback manager a final time
if err := c.rollback.Rollback(rCtx, path); err != nil {
return err
}
}
if backend != nil && c.expiration != nil && updateStorage {
// Revoke all the dynamic keys
if err := c.expiration.RevokePrefix(rCtx, path, true); err != nil {
return err
}
}
if backend != nil {
// Call cleanup function if it exists
backend.Cleanup(ctx)
}
viewPath := entry.ViewPath()
switch {
case !updateStorage:
// Don't attempt to clear data, replication will handle this
case c.IsDRSecondary():
// If we are a dr secondary we want to clear the view, but the provided
// view is marked as read only. We use the barrier here to get around
// it.
if err := logical.ClearViewWithLogging(ctx, NewBarrierView(c.barrier, viewPath), c.logger.Named("secrets.deletion").With("namespace", ns.ID, "path", path)); err != nil {
c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path)
return err
}
case entry.Local, !c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary):
// Have writable storage, remove the whole thing
if err := logical.ClearViewWithLogging(ctx, view, c.logger.Named("secrets.deletion").With("namespace", ns.ID, "path", path)); err != nil {
c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path)
return err
}
case !entry.Local && c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary):
if err := clearIgnoredPaths(ctx, c, backend, viewPath); err != nil {
return err
}
}
// Remove the mount table entry
if err := c.removeMountEntry(ctx, path, updateStorage); err != nil {
c.logger.Error("failed to remove mount entry for path being unmounted", "error", err, "path", path)
return err
}
// Unmount the backend entirely
if err := c.router.Unmount(ctx, path); err != nil {
return err
}
removePathCheckers(c, entry, viewPath)
if c.logger.IsInfo() {
c.logger.Info("successfully unmounted", "path", path, "namespace", ns.Path)
}
return nil
}
// removeMountEntry is used to remove an entry from the mount table
func (c *Core) removeMountEntry(ctx context.Context, path string, updateStorage bool) error {
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
// Remove the entry from the mount table
newTable := c.mounts.shallowClone()
entry, err := newTable.remove(ctx, path)
if err != nil {
return err
}
if entry == nil {
c.logger.Error("nil entry found removing entry in mounts table", "path", path)
return logical.CodedError(500, "failed to remove entry in mounts table")
}
// When unmounting all entries the JSON code will load back up from storage
// as a nil slice, which kills tests...just set it nil explicitly
if len(newTable.Entries) == 0 {
newTable.Entries = nil
}
if updateStorage {
// Update the mount table
if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil {
c.logger.Error("failed to remove entry from mounts table", "error", err)
return logical.CodedError(500, "failed to remove entry from mounts table")
}
}
c.mounts = newTable
return nil
}
// taintMountEntry is used to mark an entry in the mount table as tainted
func (c *Core) taintMountEntry(ctx context.Context, path string, updateStorage bool) error {
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
// As modifying the taint of an entry affects shallow clones,
// we simply use the original
entry, err := c.mounts.setTaint(ctx, path, true)
if err != nil {
return err
}
if entry == nil {
c.logger.Error("nil entry found tainting entry in mounts table", "path", path)
return logical.CodedError(500, "failed to taint entry in mounts table")
}
if updateStorage {
// Update the mount table
if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil {
if err == logical.ErrReadOnly && c.perfStandby {
return err
}
c.logger.Error("failed to taint entry in mounts table", "error", err)
return logical.CodedError(500, "failed to taint entry in mounts table")
}
}
return nil
}
// remountForceInternal takes a copy of the mount entry for the path and fully unmounts
// and remounts the backend to pick up any changes, such as filtered paths.
// Should be only used for internal usage.
func (c *Core) remountForceInternal(ctx context.Context, path string, updateStorage bool) error {
me := c.router.MatchingMountEntry(ctx, path)
if me == nil {
return fmt.Errorf("cannot find mount for path %q", path)
}
me, err := me.Clone()
if err != nil {
return err
}
if err := c.unmountInternal(ctx, path, updateStorage); err != nil {
return err
}
// Mount internally
if err := c.mountInternal(ctx, me, updateStorage); err != nil {
return err
}
// Re-evaluate filtered paths
if err := runFilteredPathsEvaluation(ctx, c); err != nil {
c.logger.Error("failed to evaluate filtered paths", "error", err)
return err
}
return nil
}
// Remount is used to remount a path at a new mount point.
func (c *Core) remount(ctx context.Context, src, dst string, updateStorage bool) error {
ns, err := namespace.FromContext(ctx)
if err != nil {
return err
}
// Ensure we end the path in a slash
if !strings.HasSuffix(src, "/") {
src += "/"
}
if !strings.HasSuffix(dst, "/") {
dst += "/"
}
// Prevent protected paths from being remounted
for _, p := range protectedMounts {
if strings.HasPrefix(src, p) {
return fmt.Errorf("cannot remount %q", src)
}
}
// Verify exact match of the route
srcMatch := c.router.MatchingMountEntry(ctx, src)
if srcMatch == nil {
return fmt.Errorf("no matching mount at %q", src)
}
if srcMatch.NamespaceID != ns.ID {
return fmt.Errorf("source mount in a different namespace than request")
}
if err := verifyNamespace(c, ns, &MountEntry{Path: dst}); err != nil {
return err
}
if match := c.router.MatchingMount(ctx, dst); match != "" {
return fmt.Errorf("existing mount at %q", match)
}
// Mark the entry as tainted
if err := c.taintMountEntry(ctx, src, updateStorage); err != nil {
return err
}
// Taint the router path to prevent routing
if err := c.router.Taint(ctx, src); err != nil {
return err
}
if !c.IsDRSecondary() {
// Invoke the rollback manager a final time
rCtx := namespace.ContextWithNamespace(c.activeContext, ns)
if c.rollback != nil {
if err := c.rollback.Rollback(rCtx, src); err != nil {
return err
}
}
if entry := c.router.MatchingMountEntry(ctx, src); entry == nil {
return fmt.Errorf("no matching mount at %q", src)
}
// Revoke all the dynamic keys
if err := c.expiration.RevokePrefix(rCtx, src, true); err != nil {
return err
}
}
c.mountsLock.Lock()
var entry *MountEntry
for _, mountEntry := range c.mounts.Entries {
if mountEntry.Path == src && mountEntry.NamespaceID == ns.ID {
entry = mountEntry
entry.Path = dst
entry.Tainted = false
break
}
}
if entry == nil {
c.mountsLock.Unlock()
c.logger.Error("failed to find entry in mounts table")
return logical.CodedError(500, "failed to find entry in mounts table")
}
// Update the mount table
if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil {
entry.Path = src
entry.Tainted = true
c.mountsLock.Unlock()
if err == logical.ErrReadOnly && c.perfStandby {
return err
}
c.logger.Error("failed to update mounts table", "error", err)
return logical.CodedError(500, "failed to update mounts table")
}
c.mountsLock.Unlock()
// Remount the backend
if err := c.router.Remount(ctx, src, dst); err != nil {
return err
}
// Un-taint the path
if err := c.router.Untaint(ctx, dst); err != nil {
return err
}
if c.logger.IsInfo() {
c.logger.Info("successful remount", "old_path", src, "new_path", dst)
}
return nil
}
// loadMounts is invoked as part of postUnseal to load the mount table
func (c *Core) loadMounts(ctx context.Context) error {
// Load the existing mount table
raw, err := c.barrier.Get(ctx, coreMountConfigPath)
if err != nil {
c.logger.Error("failed to read mount table", "error", err)
return errLoadMountsFailed
}
rawLocal, err := c.barrier.Get(ctx, coreLocalMountConfigPath)
if err != nil {
c.logger.Error("failed to read local mount table", "error", err)
return errLoadMountsFailed
}
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
if raw != nil {
// Check if the persisted value has canary in the beginning. If
// yes, decompress the table and then JSON decode it. If not,
// simply JSON decode it.
mountTable, err := c.decodeMountTable(ctx, raw.Value)
if err != nil {
c.logger.Error("failed to decompress and/or decode the mount table", "error", err)
return err
}
c.mounts = mountTable
}
var needPersist bool
if c.mounts == nil {
c.logger.Info("no mounts; adding default mount table")
c.mounts = c.defaultMountTable()
needPersist = true
}
if rawLocal != nil {
localMountTable, err := c.decodeMountTable(ctx, rawLocal.Value)
if err != nil {
c.logger.Error("failed to decompress and/or decode the local mount table", "error", err)
return err
}
if localMountTable != nil && len(localMountTable.Entries) > 0 {
c.mounts.Entries = append(c.mounts.Entries, localMountTable.Entries...)
}
}
// Note that this is only designed to work with singletons, as it checks by
// type only.
// Upgrade to typed mount table
if c.mounts.Type == "" {
c.mounts.Type = mountTableType
needPersist = true
}
for _, requiredMount := range c.requiredMountTable().Entries {
foundRequired := false
for _, coreMount := range c.mounts.Entries {
if coreMount.Type == requiredMount.Type {
foundRequired = true
coreMount.Config = requiredMount.Config
break
}
}
// In a replication scenario we will let sync invalidation take
// care of creating a new required mount that doesn't exist yet.
// This should only happen in the upgrade case where a new one is
// introduced on the primary; otherwise initial bootstrapping will
// ensure this comes over. If we upgrade first, we simply don't
// create the mount, so we won't conflict when we sync. If this is
// local (e.g. cubbyhole) we do still add it.
if !foundRequired && (!c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) || requiredMount.Local) {
c.mounts.Entries = append(c.mounts.Entries, requiredMount)
needPersist = true
}
}
// Upgrade to table-scoped entries
for _, entry := range c.mounts.Entries {
if entry.Type == cubbyholeMountType && !entry.Local {
entry.Local = true
needPersist = true
}
if entry.Table == "" {
entry.Table = c.mounts.Type
needPersist = true
}
if entry.Accessor == "" {
accessor, err := c.generateMountAccessor(entry.Type)
if err != nil {
return err
}
entry.Accessor = accessor
needPersist = true
}
if entry.BackendAwareUUID == "" {
bUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.BackendAwareUUID = bUUID
needPersist = true
}
if entry.NamespaceID == "" {
entry.NamespaceID = namespace.RootNamespaceID
needPersist = true
}
ns, err := NamespaceByID(ctx, entry.NamespaceID, c)
if err != nil {
return err
}
if ns == nil {
return namespace.ErrNoNamespace
}
entry.namespace = ns
// Sync values to the cache
entry.SyncCache()
}
// Done if we have restored the mount table and we don't need
// to persist
if !needPersist {
return nil
}
// Persist both mount tables
if err := c.persistMounts(ctx, c.mounts, nil); err != nil {
c.logger.Error("failed to persist mount table", "error", err)
return errLoadMountsFailed
}
return nil
}
// persistMounts is used to persist the mount table after modification
func (c *Core) persistMounts(ctx context.Context, table *MountTable, local *bool) error {
if table.Type != mountTableType {
c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", mountTableType)
return fmt.Errorf("invalid table type given, not persisting")
}
for _, entry := range table.Entries {
if entry.Table != table.Type {
c.logger.Error("given entry to persist in mount table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type)
return fmt.Errorf("invalid mount entry found, not persisting")
}
}
nonLocalMounts := &MountTable{
Type: mountTableType,
}
localMounts := &MountTable{
Type: mountTableType,
}
for _, entry := range table.Entries {
if entry.Local {
localMounts.Entries = append(localMounts.Entries, entry)
} else {
nonLocalMounts.Entries = append(nonLocalMounts.Entries, entry)
}
}
writeTable := func(mt *MountTable, path string) error {
// Encode the mount table into JSON and compress it (lzw).
compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil)
if err != nil {
c.logger.Error("failed to encode or compress mount table", "error", err)
return err
}
// Create an entry
entry := &logical.StorageEntry{
Key: path,
Value: compressedBytes,
}
// Write to the physical backend
if err := c.barrier.Put(ctx, entry); err != nil {
c.logger.Error("failed to persist mount table", "error", err)
return err
}
return nil
}
var err error
switch {
case local == nil:
// Write non-local mounts
err := writeTable(nonLocalMounts, coreMountConfigPath)
if err != nil {
return err
}
// Write local mounts
err = writeTable(localMounts, coreLocalMountConfigPath)
if err != nil {
return err
}
case *local:
// Write local mounts
err = writeTable(localMounts, coreLocalMountConfigPath)
default:
// Write non-local mounts
err = writeTable(nonLocalMounts, coreMountConfigPath)
}
return err
}
// setupMounts is invoked after we've loaded the mount table to
// initialize the logical backends and setup the router
func (c *Core) setupMounts(ctx context.Context) error {
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
for _, entry := range c.mounts.sortEntriesByPathDepth().Entries {
// Initialize the backend, special casing for system
barrierPath := entry.ViewPath()
// Create a barrier view using the UUID
view := NewBarrierView(c.barrier, barrierPath)
// Singleton mounts cannot be filtered manually on a per-secondary basis
// from replication
if strutil.StrListContains(singletonMounts, entry.Type) {
addFilterablePath(c, barrierPath)
}
// Determining the replicated state of the mount
nilMount, err := preprocessMount(c, entry, view)
if err != nil {
return err
}
origReadOnlyErr := view.getReadOnlyErr()
// Mark the view as read-only until the mounting is complete and
// ensure that it is reset after. This ensures that there will be no
// writes during the construction of the backend.
view.setReadOnlyErr(logical.ErrSetupReadOnly)
if strutil.StrListContains(singletonMounts, entry.Type) {
defer view.setReadOnlyErr(origReadOnlyErr)
} else {
c.postUnsealFuncs = append(c.postUnsealFuncs, func() {
view.setReadOnlyErr(origReadOnlyErr)
})
}
var backend logical.Backend
// Create the new backend
sysView := c.mountEntrySysView(entry)
backend, err = c.newLogicalBackend(ctx, entry, sysView, view)
if err != nil {
c.logger.Error("failed to create mount entry", "path", entry.Path, "error", err)
if !c.builtinRegistry.Contains(entry.Type, consts.PluginTypeSecrets) {
// If we encounter an error instantiating the backend due to an error,
// skip backend initialization but register the entry to the mount table
// to preserve storage and path.
c.logger.Warn("skipping plugin-based mount entry", "path", entry.Path)
goto ROUTER_MOUNT
}
return errLoadMountsFailed
}
if backend == nil {
return fmt.Errorf("created mount entry of type %q is nil", entry.Type)
}
{
// Check for the correct backend type
backendType := backend.Type()
if backendType != logical.TypeLogical {
if entry.Type != "kv" && entry.Type != "system" && entry.Type != "cubbyhole" {
return fmt.Errorf(`unknown backend type: "%s"`, entry.Type)
}
}
addPathCheckers(c, entry, backend, barrierPath)
c.setCoreBackend(entry, backend, view)
}
// If the mount is filtered or we are on a DR secondary we don't want to
// keep the actual backend running, so we clean it up and set it to nil
// so the router does not have a pointer to the object.
if nilMount {
backend.Cleanup(ctx)
backend = nil
}
ROUTER_MOUNT:
// Mount the backend
err = c.router.Mount(backend, entry.Path, entry, view)
if err != nil {
c.logger.Error("failed to mount entry", "path", entry.Path, "error", err)
return errLoadMountsFailed
}
// Initialize
if !nilMount {
// Bind locally
localEntry := entry
c.postUnsealFuncs = append(c.postUnsealFuncs, func() {
if backend == nil {
c.logger.Error("skipping initialization on nil backend", "path", localEntry.Path)
return
}
err := backend.Initialize(ctx, &logical.InitializationRequest{Storage: view})
if err != nil {
c.logger.Error("failed to initialize mount entry", "path", localEntry.Path, "error", err)
}
})
}
if c.logger.IsInfo() {
c.logger.Info("successfully mounted backend", "type", entry.Type, "path", entry.Path)
}
// Ensure the path is tainted if set in the mount table
if entry.Tainted {
c.router.Taint(ctx, entry.Path)
}
// Ensure the cache is populated, don't need the result
NamespaceByID(ctx, entry.NamespaceID, c)
}
return nil
}
// unloadMounts is used before we seal the vault to reset the mounts to
// their unloaded state, calling Cleanup if defined. This is reversed by load and setup mounts.
func (c *Core) unloadMounts(ctx context.Context) error {
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
if c.mounts != nil {
mountTable := c.mounts.shallowClone()
for _, e := range mountTable.Entries {
backend := c.router.MatchingBackend(namespace.ContextWithNamespace(ctx, e.namespace), e.Path)
if backend != nil {
backend.Cleanup(ctx)
}
viewPath := e.ViewPath()
removePathCheckers(c, e, viewPath)
}
}
c.mounts = nil
c.router.reset()
c.systemBarrierView = nil
return nil
}
// newLogicalBackend is used to create and configure a new logical backend by name
func (c *Core) newLogicalBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) {
t := entry.Type
if alias, ok := mountAliases[t]; ok {
t = alias
}
f, ok := c.logicalBackends[t]
if !ok {
f = plugin.Factory
}
// Set up conf to pass in plugin_name
conf := make(map[string]string, len(entry.Options)+1)
for k, v := range entry.Options {
conf[k] = v
}
switch {
case entry.Type == "plugin":
conf["plugin_name"] = entry.Config.PluginName
default:
conf["plugin_name"] = t
}
conf["plugin_type"] = consts.PluginTypeSecrets.String()
backendLogger := c.baseLogger.Named(fmt.Sprintf("secrets.%s.%s", t, entry.Accessor))
c.AddLogger(backendLogger)
config := &logical.BackendConfig{
StorageView: view,
Logger: backendLogger,
Config: conf,
System: sysView,
BackendUUID: entry.BackendAwareUUID,
}
ctx = context.WithValue(ctx, "core_number", c.coreNumber)
b, err := f(ctx, config)
if err != nil {
return nil, err
}
if b == nil {
return nil, fmt.Errorf("nil backend of type %q returned from factory", t)
}
addLicenseCallback(c, b)
return b, nil
}
// defaultMountTable creates a default mount table
func (c *Core) defaultMountTable() *MountTable {
table := &MountTable{
Type: mountTableType,
}
table.Entries = append(table.Entries, c.requiredMountTable().Entries...)
if os.Getenv("VAULT_INTERACTIVE_DEMO_SERVER") != "" {
mountUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create default secret mount UUID: %v", err))
}
mountAccessor, err := c.generateMountAccessor("kv")
if err != nil {
panic(fmt.Sprintf("could not generate default secret mount accessor: %v", err))
}
bUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create default secret mount backend UUID: %v", err))
}
kvMount := &MountEntry{
Table: mountTableType,
Path: "secret/",
Type: "kv",
Description: "key/value secret storage",
UUID: mountUUID,
Accessor: mountAccessor,
BackendAwareUUID: bUUID,
Options: map[string]string{
"version": "2",
},
}
table.Entries = append(table.Entries, kvMount)
}
return table
}
// requiredMountTable() creates a mount table with entries required
// to be available
func (c *Core) requiredMountTable() *MountTable {
table := &MountTable{
Type: mountTableType,
}
cubbyholeUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create cubbyhole UUID: %v", err))
}
cubbyholeAccessor, err := c.generateMountAccessor("cubbyhole")
if err != nil {
panic(fmt.Sprintf("could not generate cubbyhole accessor: %v", err))
}
cubbyholeBackendUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create cubbyhole backend UUID: %v", err))
}
cubbyholeMount := &MountEntry{
Table: mountTableType,
Path: cubbyholeMountPath,
Type: cubbyholeMountType,
Description: "per-token private secret storage",
UUID: cubbyholeUUID,
Accessor: cubbyholeAccessor,
Local: true,
BackendAwareUUID: cubbyholeBackendUUID,
}
sysUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create sys UUID: %v", err))
}
sysAccessor, err := c.generateMountAccessor("system")
if err != nil {
panic(fmt.Sprintf("could not generate sys accessor: %v", err))
}
sysBackendUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create sys backend UUID: %v", err))
}
sysMount := &MountEntry{
Table: mountTableType,
Path: "sys/",
Type: systemMountType,
Description: "system endpoints used for control, policy and debugging",
UUID: sysUUID,
Accessor: sysAccessor,
BackendAwareUUID: sysBackendUUID,
Config: MountConfig{
PassthroughRequestHeaders: []string{"Accept"},
},
}
identityUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create identity mount entry UUID: %v", err))
}
identityAccessor, err := c.generateMountAccessor("identity")
if err != nil {
panic(fmt.Sprintf("could not generate identity accessor: %v", err))
}
identityBackendUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not create identity backend UUID: %v", err))
}
identityMount := &MountEntry{
Table: mountTableType,
Path: "identity/",
Type: "identity",
Description: "identity store",
UUID: identityUUID,
Accessor: identityAccessor,
BackendAwareUUID: identityBackendUUID,
}
table.Entries = append(table.Entries, cubbyholeMount)
table.Entries = append(table.Entries, sysMount)
table.Entries = append(table.Entries, identityMount)
return table
}
// This function returns tables that are singletons. The main usage of this is
// for replication, so we can send over mount info (especially, UUIDs of
// mounts, which are used for salts) for mounts that may not be able to be
// handled normally. After saving these values on the secondary, we let normal
// sync invalidation do its thing. Because of its use for replication, we
// exclude local mounts.
func (c *Core) singletonMountTables() (mounts, auth *MountTable) {
mounts = &MountTable{}
auth = &MountTable{}
c.mountsLock.RLock()
for _, entry := range c.mounts.Entries {
if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local && entry.Namespace().ID == namespace.RootNamespaceID {
mounts.Entries = append(mounts.Entries, entry)
}
}
c.mountsLock.RUnlock()
c.authLock.RLock()
for _, entry := range c.auth.Entries {
if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local && entry.Namespace().ID == namespace.RootNamespaceID {
auth.Entries = append(auth.Entries, entry)
}
}
c.authLock.RUnlock()
return
}
func (c *Core) setCoreBackend(entry *MountEntry, backend logical.Backend, view *BarrierView) {
switch entry.Type {
case systemMountType:
c.systemBackend = backend.(*SystemBackend)
c.systemBarrierView = view
case cubbyholeMountType:
ch := backend.(*CubbyholeBackend)
ch.saltUUID = entry.UUID
ch.storageView = view
c.cubbyholeBackend = ch
case identityMountType:
c.identityStore = backend.(*IdentityStore)
}
}
|
[
"\"VAULT_INTERACTIVE_DEMO_SERVER\""
] |
[] |
[
"VAULT_INTERACTIVE_DEMO_SERVER"
] |
[]
|
["VAULT_INTERACTIVE_DEMO_SERVER"]
|
go
| 1 | 0 | |
go/test/endtoend/cluster/topo_process.go
|
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cluster
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"strings"
"syscall"
"time"
"vitess.io/vitess/go/vt/log"
)
// TopoProcess is a generic handle for a running Topo service .
// It can be spawned manually
type TopoProcess struct {
Name string
Binary string
DataDirectory string
LogDirectory string
ListenClientURL string
AdvertiseClientURL string
Port int
Host string
VerifyURL string
PeerURL string
ZKPorts string
proc *exec.Cmd
exit chan error
}
// Setup starts a new topo service
func (topo *TopoProcess) Setup(topoFlavor string, cluster *LocalProcessCluster) (err error) {
switch topoFlavor {
case "zk2":
return topo.SetupZookeeper(cluster)
case "consul":
return topo.SetupConsul(cluster)
default:
return topo.SetupEtcd()
}
}
// SetupEtcd spawns a new etcd service and initializes it with the defaults.
// The service is kept running in the background until TearDown() is called.
func (topo *TopoProcess) SetupEtcd() (err error) {
topo.proc = exec.Command(
topo.Binary,
"--name", topo.Name,
"--data-dir", topo.DataDirectory,
"--listen-client-urls", topo.ListenClientURL,
"--advertise-client-urls", topo.AdvertiseClientURL,
"--initial-advertise-peer-urls", topo.PeerURL,
"--listen-peer-urls", topo.PeerURL,
"--initial-cluster", fmt.Sprintf("%s=%s", topo.Name, topo.PeerURL),
"--enable-v2=true",
)
err = createDirectory(topo.DataDirectory, 0700)
if err != nil && !os.IsExist(err) {
return err
}
errFile, err := os.Create(path.Join(topo.DataDirectory, "topo-stderr.txt"))
if err != nil {
return err
}
topo.proc.Stderr = errFile
topo.proc.Env = append(topo.proc.Env, os.Environ()...)
log.Infof("Starting etcd with command: %v", strings.Join(topo.proc.Args, " "))
err = topo.proc.Start()
if err != nil {
return
}
topo.exit = make(chan error)
go func() {
topo.exit <- topo.proc.Wait()
}()
timeout := time.Now().Add(60 * time.Second)
for time.Now().Before(timeout) {
if topo.IsHealthy() {
return
}
select {
case err := <-topo.exit:
return fmt.Errorf("process '%s' exited prematurely (err: %s)", topo.Binary, err)
default:
time.Sleep(300 * time.Millisecond)
}
}
return fmt.Errorf("process '%s' timed out after 60s (err: %s)", topo.Binary, <-topo.exit)
}
// SetupZookeeper spawns a new zookeeper topo service and initializes it with the defaults.
// The service is kept running in the background until TearDown() is called.
func (topo *TopoProcess) SetupZookeeper(cluster *LocalProcessCluster) (err error) {
host, err := os.Hostname()
if err != nil {
return
}
topo.ZKPorts = fmt.Sprintf("%d:%d:%d", cluster.GetAndReservePort(), cluster.GetAndReservePort(), topo.Port)
topo.proc = exec.Command(
topo.Binary,
"-log_dir", topo.LogDirectory,
"-zk.cfg", fmt.Sprintf("1@%v:%s", host, topo.ZKPorts),
"init",
)
errFile, _ := os.Create(path.Join(topo.DataDirectory, "topo-stderr.txt"))
topo.proc.Stderr = errFile
topo.proc.Env = append(topo.proc.Env, os.Environ()...)
log.Infof("Starting zookeeper with args %v", strings.Join(topo.proc.Args, " "))
err = topo.proc.Run()
if err != nil {
return
}
return
}
// ConsulConfigs are the configurations that are added the config files which are used by consul
type ConsulConfigs struct {
Ports PortsInfo `json:"ports"`
DataDir string `json:"data_dir"`
LogFile string `json:"log_file"`
}
// PortsInfo is the different ports used by consul
type PortsInfo struct {
DNS int `json:"dns"`
HTTP int `json:"http"`
SerfLan int `json:"serf_lan"`
SerfWan int `json:"serf_wan"`
Server int `json:"server"`
}
// SetupConsul spawns a new consul service and initializes it with the defaults.
// The service is kept running in the background until TearDown() is called.
func (topo *TopoProcess) SetupConsul(cluster *LocalProcessCluster) (err error) {
topo.VerifyURL = fmt.Sprintf("http://%s:%d/v1/kv/?keys", topo.Host, topo.Port)
_ = os.MkdirAll(topo.LogDirectory, os.ModePerm)
_ = os.MkdirAll(topo.DataDirectory, os.ModePerm)
configFile := path.Join(os.Getenv("VTDATAROOT"), "consul.json")
logFile := path.Join(topo.LogDirectory, "/consul.log")
_, _ = os.Create(logFile)
var config []byte
configs := ConsulConfigs{
Ports: PortsInfo{
DNS: cluster.GetAndReservePort(),
HTTP: topo.Port,
SerfLan: cluster.GetAndReservePort(),
SerfWan: cluster.GetAndReservePort(),
Server: cluster.GetAndReservePort(),
},
DataDir: topo.DataDirectory,
LogFile: logFile,
}
config, err = json.Marshal(configs)
if err != nil {
log.Error(err.Error())
return
}
err = ioutil.WriteFile(configFile, config, 0666)
if err != nil {
return
}
topo.proc = exec.Command(
topo.Binary, "agent",
"-server",
"-ui",
"-bootstrap-expect", "1",
"-bind", "127.0.0.1",
"-config-file", configFile,
)
errFile, _ := os.Create(path.Join(topo.DataDirectory, "topo-stderr.txt"))
topo.proc.Stderr = errFile
topo.proc.Env = append(topo.proc.Env, os.Environ()...)
log.Errorf("Starting consul with args %v", strings.Join(topo.proc.Args, " "))
err = topo.proc.Start()
if err != nil {
return
}
topo.exit = make(chan error)
go func() {
topo.exit <- topo.proc.Wait()
}()
timeout := time.Now().Add(60 * time.Second)
for time.Now().Before(timeout) {
if topo.IsHealthy() {
return
}
select {
case err := <-topo.exit:
return fmt.Errorf("process '%s' exited prematurely (err: %s)", topo.Binary, err)
default:
time.Sleep(300 * time.Millisecond)
}
}
return fmt.Errorf("process '%s' timed out after 60s (err: %s)", topo.Binary, <-topo.exit)
}
// TearDown shutdowns the running topo service
func (topo *TopoProcess) TearDown(Cell string, originalVtRoot string, currentRoot string, keepdata bool, topoFlavor string) error {
if topoFlavor == "zk2" {
cmd := "shutdown"
if keepdata {
cmd = "teardown"
}
topo.proc = exec.Command(
topo.Binary,
"-log_dir", topo.LogDirectory,
"-zk.cfg", fmt.Sprintf("1@%v:%s", topo.Host, topo.ZKPorts),
cmd,
)
err := topo.proc.Run()
if err != nil {
return err
}
} else {
if topo.proc == nil || topo.exit == nil {
return nil
}
if !(*keepData || keepdata) {
topo.removeTopoDirectories(Cell)
}
// Attempt graceful shutdown with SIGTERM first
_ = topo.proc.Process.Signal(syscall.SIGTERM)
if !(*keepData || keepdata) {
_ = os.RemoveAll(topo.DataDirectory)
_ = os.RemoveAll(currentRoot)
_ = os.Setenv("VTDATAROOT", originalVtRoot)
}
select {
case <-topo.exit:
topo.proc = nil
return nil
case <-time.After(10 * time.Second):
topo.proc.Process.Kill()
topo.proc = nil
return <-topo.exit
}
}
return nil
}
// IsHealthy function checks if topo server is up and running
func (topo *TopoProcess) IsHealthy() bool {
resp, err := http.Get(topo.VerifyURL)
if err != nil {
return false
}
if resp.StatusCode == 200 {
return true
}
return false
}
func (topo *TopoProcess) removeTopoDirectories(Cell string) {
_ = topo.ManageTopoDir("rmdir", "/vitess/global")
_ = topo.ManageTopoDir("rmdir", "/vitess/"+Cell)
}
// ManageTopoDir creates global and zone in etcd2
func (topo *TopoProcess) ManageTopoDir(command string, directory string) (err error) {
url := topo.VerifyURL + directory
payload := strings.NewReader(`{"dir":"true"}`)
if command == "mkdir" {
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("content-type", "application/json")
_, err = http.DefaultClient.Do(req)
return err
} else if command == "rmdir" {
req, _ := http.NewRequest("DELETE", url+"?dir=true", payload)
_, err = http.DefaultClient.Do(req)
return err
} else {
return nil
}
}
// TopoProcessInstance returns a TopoProcess handle for a etcd sevice,
// configured with the given Config.
// The process must be manually started by calling setup()
func TopoProcessInstance(port int, peerPort int, hostname string, flavor string, name string) *TopoProcess {
binary := "etcd"
if flavor == "zk2" {
binary = "zkctl"
}
if flavor == "consul" {
binary = "consul"
}
topo := &TopoProcess{
Name: name,
Binary: binary,
Port: port,
Host: hostname,
}
topo.AdvertiseClientURL = fmt.Sprintf("http://%s:%d", topo.Host, topo.Port)
topo.ListenClientURL = fmt.Sprintf("http://%s:%d", topo.Host, topo.Port)
topo.DataDirectory = path.Join(os.Getenv("VTDATAROOT"), fmt.Sprintf("%s_%d", "topo", port))
topo.LogDirectory = path.Join(os.Getenv("VTDATAROOT"), fmt.Sprintf("%s_%d", "topo", port), "logs")
topo.VerifyURL = fmt.Sprintf("http://%s:%d/v2/keys", topo.Host, topo.Port)
topo.PeerURL = fmt.Sprintf("http://%s:%d", hostname, peerPort)
return topo
}
|
[
"\"VTDATAROOT\"",
"\"VTDATAROOT\"",
"\"VTDATAROOT\""
] |
[] |
[
"VTDATAROOT"
] |
[]
|
["VTDATAROOT"]
|
go
| 1 | 0 | |
config.py
|
import os
import argparse
import time
import torch
import random
import numpy as np
import json
from prepare_MIND_dataset import prepare_MIND_200k, prepare_MIND_small, prepare_MIND_large
class Config:
def parse_argument(self):
parser = argparse.ArgumentParser(description='Neural news recommendation')
# General config
parser.add_argument('--mode', type=str, default='train', choices=['train', 'dev', 'test'], help='Mode')
parser.add_argument('--news_encoder', type=str, default='CNE', choices=['CNE', 'CNN', 'MHSA', 'KCNN', 'PCNN', 'HDC', 'NAML', 'PNE', 'DAE', 'Inception', 'NAML_Title', 'NAML_Content', 'CNE_Title', 'CNE_Content', 'CNE_wo_CS', 'CNE_wo_CA'], help='News encoder')
parser.add_argument('--user_encoder', type=str, default='SUE', choices=['SUE', 'LSTUR', 'MHSA', 'ATT', 'CATT', 'FIM', 'ARNN', 'PUE', 'GRU', 'OMAP', 'SUE_wo_GCN', 'SUE_wo_HCA'], help='User encoder')
parser.add_argument('--dev_model_path', type=str, default='', help='Dev model path')
parser.add_argument('--test_model_path', type=str, default='', help='Test model path')
parser.add_argument('--test_output_file', type=str, default='', help='Specific test output file')
parser.add_argument('--device_id', type=int, default=0, help='Device ID of GPU')
parser.add_argument('--seed', type=int, default=0, help='Seed for random number generator')
parser.add_argument('--config_file', type=str, default='', help='Config file path')
# Dataset config
parser.add_argument('--dataset', type=str, default='200k', choices=['200k', 'small', 'large'], help='Dataset type')
parser.add_argument('--tokenizer', type=str, default='MIND', choices=['MIND', 'NLTK'], help='Sentence tokenizer')
parser.add_argument('--word_threshold', type=int, default=3, help='Word threshold')
parser.add_argument('--max_title_length', type=int, default=32, help='Sentence truncate length for title')
parser.add_argument('--max_abstract_length', type=int, default=128, help='Sentence truncate length for abstract')
# Training config
parser.add_argument('--negative_sample_num', type=int, default=4, help='Negative sample number of each positive sample')
parser.add_argument('--max_history_num', type=int, default=50, help='Maximum number of history news for each user')
parser.add_argument('--epoch', type=int, default=100, help='Training epoch')
parser.add_argument('--batch_size', type=int, default=64, help='Batch size')
parser.add_argument('--lr', type=float, default=1e-4, help='Learning rate')
parser.add_argument('--weight_decay', type=float, default=0, help='Optimizer weight decay')
parser.add_argument('--gradient_clip_norm', type=float, default=4, help='Gradient clip norm (non-positive value for no clipping)')
parser.add_argument('--world_size', type=int, default=1, help='World size of multi-process GPU training')
# Dev config
parser.add_argument('--dev_criterion', type=str, default='auc', choices=['auc', 'mrr', 'ndcg5', 'ndcg10'], help='Validation criterion to select model')
parser.add_argument('--early_stopping_epoch', type=int, default=5, help='Epoch number of stop training after dev result does not improve')
# Model config
parser.add_argument('--word_embedding_dim', type=int, default=300, choices=[50, 100, 200, 300], help='Word embedding dimension')
parser.add_argument('--entity_embedding_dim', type=int, default=100, choices=[100], help='Entity embedding dimension')
parser.add_argument('--context_embedding_dim', type=int, default=100, choices=[100], help='Context embedding dimension')
parser.add_argument('--cnn_method', type=str, default='naive', choices=['naive', 'group3', 'group4', 'group5'], help='CNN group')
parser.add_argument('--cnn_kernel_num', type=int, default=400, help='Number of CNN kernel')
parser.add_argument('--cnn_window_size', type=int, default=3, help='Window size of CNN kernel')
parser.add_argument('--attention_dim', type=int, default=200, help="Attention dimension")
parser.add_argument('--head_num', type=int, default=20, help='Head number of multi-head self-attention')
parser.add_argument('--head_dim', type=int, default=20, help='Head dimension of multi-head self-attention')
parser.add_argument('--user_embedding_dim', type=int, default=50, help='User embedding dimension')
parser.add_argument('--category_embedding_dim', type=int, default=50, help='Category embedding dimension')
parser.add_argument('--subCategory_embedding_dim', type=int, default=50, help='SubCategory embedding dimension')
parser.add_argument('--dropout_rate', type=float, default=0.2, help='Dropout rate')
parser.add_argument('--no_self_connection', default=False, action='store_true', help='Whether the graph contains self-connection')
parser.add_argument('--no_adjacent_normalization', default=False, action='store_true', help='Whether normalize the adjacent matrix')
parser.add_argument('--gcn_normalization_type', type=str, default='symmetric', choices=['symmetric', 'asymmetric'], help='GCN normalization for adjacent matrix A (\"symmetric\" for D^{-\\frac{1}{2}}AD^{-\\frac{1}{2}}; \"asymmetric\" for D^{-\\frac{1}{2}}A)')
parser.add_argument('--gcn_layer_num', type=int, default=4, help='Number of GCN layer')
parser.add_argument('--no_gcn_residual', default=False, action='store_true', help='Whether apply residual connection to GCN')
parser.add_argument('--gcn_layer_norm', default=False, action='store_true', help='Whether apply layer normalization to GCN')
parser.add_argument('--hidden_dim', type=int, default=200, help='Encoder hidden dimension')
parser.add_argument('--Alpha', type=float, default=0.1, help='Reconstruction loss weight for DAE')
parser.add_argument('--long_term_masking_probability', type=float, default=0.1, help='Probability of masking long-term representation for LSTUR')
parser.add_argument('--personalized_embedding_dim', type=int, default=200, help='Personalized embedding dimension for NPA')
parser.add_argument('--HDC_window_size', type=int, default=3, help='Convolution window size of HDC for FIM')
parser.add_argument('--HDC_filter_num', type=int, default=150, help='Convolution filter num of HDC for FIM')
parser.add_argument('--conv3D_filter_num_first', type=int, default=32, help='3D matching convolution filter num of the first layer for FIM ')
parser.add_argument('--conv3D_kernel_size_first', type=int, default=3, help='3D matching convolution kernel size of the first layer for FIM')
parser.add_argument('--conv3D_filter_num_second', type=int, default=16, help='3D matching convolution filter num of the second layer for FIM ')
parser.add_argument('--conv3D_kernel_size_second', type=int, default=3, help='3D matching convolution kernel size of the second layer for FIM')
parser.add_argument('--maxpooling3D_size', type=int, default=3, help='3D matching pooling size for FIM ')
parser.add_argument('--maxpooling3D_stride', type=int, default=3, help='3D matching pooling stride for FIM')
parser.add_argument('--OMAP_head_num', type=int, default=3, help='Head num of OMAP for Hi-Fi Ark')
parser.add_argument('--HiFi_Ark_regularizer_coefficient', type=float, default=0.1, help='Coefficient of regularization loss for Hi-Fi Ark')
parser.add_argument('--click_predictor', type=str, default='dot_product', choices=['dot_product', 'mlp', 'sigmoid', 'FIM'], help='Click predictor')
self.attribute_dict = dict(vars(parser.parse_args()))
for attribute in self.attribute_dict:
setattr(self, attribute, self.attribute_dict[attribute])
self.train_root = '../MIND-%s/train' % self.dataset
self.dev_root = '../MIND-%s/dev' % self.dataset
self.test_root = '../MIND-%s/test' % self.dataset
if self.dataset == 'small': # suggested configuration for MIND small
self.dropout_rate = 0.3
self.gcn_layer_num = 3
elif self.dataset == '200k': # suggested configuration for MIND 200k
self.dropout_rate = 0.2
self.gcn_layer_num = 4
self.epoch = 10
else: # suggested configuration for MIND large
self.dropout_rate = 0.1
self.gcn_layer_num = 4
self.epoch = 10
self.seed = self.seed if self.seed >= 0 else (int)(time.time())
if self.config_file != '':
if os.path.exists(self.config_file):
print('Get experiment settings from the config file: ' + self.config_file)
with open(self.config_file, 'r', encoding='utf-8') as f:
configs = json.load(f)
for attribute in self.attribute_dict:
if attribute in configs:
setattr(self, attribute, configs[attribute])
else:
raise Exception('Config file does not exist: ' + self.config_file)
assert not (self.no_self_connection and not self.no_adjacent_normalization), 'Adjacent normalization of graph only can be set in case of self-connection'
print('*' * 32 + ' Experiment setting ' + '*' * 32)
for attribute in self.attribute_dict:
print(attribute + ' : ' + str(getattr(self, attribute)))
print('*' * 32 + ' Experiment setting ' + '*' * 32)
assert self.batch_size % self.world_size == 0, 'For multi-gpu training, batch size must be divisible by world size'
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '1024'
def set_cuda(self):
gpu_available = torch.cuda.is_available()
assert gpu_available, 'GPU is not available'
torch.cuda.set_device(self.device_id)
torch.manual_seed(self.seed)
torch.cuda.manual_seed(self.seed)
random.seed(self.seed)
np.random.seed(self.seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True # For reproducibility
def preliminary_setup(self):
dataset_files = [
self.train_root + '/news.tsv', self.train_root + '/behaviors.tsv', self.train_root + '/entity_embedding.vec', self.train_root + '/context_embedding.vec',
self.dev_root + '/news.tsv', self.dev_root + '/behaviors.tsv', self.dev_root + '/entity_embedding.vec', self.dev_root + '/context_embedding.vec',
self.test_root + '/news.tsv', self.test_root + '/behaviors.tsv', self.test_root + '/entity_embedding.vec', self.test_root + '/context_embedding.vec'
]
if not all(list(map(os.path.exists, dataset_files))):
exec('prepare_MIND_%s()' % self.dataset)
model_name = self.news_encoder + '-' + self.user_encoder
mkdirs = lambda x: os.makedirs(x) if not os.path.exists(x) else None
self.config_dir = 'configs/' + self.dataset + '/' + model_name
self.model_dir = 'models/' + self.dataset + '/' + model_name
self.best_model_dir = 'best_model/' + self.dataset + '/' + model_name
self.dev_res_dir = 'dev/res/' + self.dataset + '/' + model_name
self.test_res_dir = 'test/res/' + self.dataset + '/' + model_name
self.result_dir = 'results/' + self.dataset + '/' + model_name
mkdirs(self.config_dir)
mkdirs(self.model_dir)
mkdirs(self.best_model_dir)
mkdirs('dev/ref')
mkdirs(self.dev_res_dir)
mkdirs('test/ref')
mkdirs(self.test_res_dir)
mkdirs(self.result_dir)
if not os.path.exists('dev/ref/truth-%s.txt' % self.dataset):
with open(os.path.join(self.dev_root, 'behaviors.tsv'), 'r', encoding='utf-8') as dev_f:
with open('dev/ref/truth-%s.txt' % self.dataset, 'w', encoding='utf-8') as truth_f:
for dev_ID, line in enumerate(dev_f):
impression_ID, user_ID, time, history, impressions = line.split('\t')
labels = [int(impression[-1]) for impression in impressions.strip().split(' ')]
truth_f.write(('' if dev_ID == 0 else '\n') + str(dev_ID + 1) + ' ' + str(labels).replace(' ', ''))
if self.dataset != 'large':
if not os.path.exists('test/ref/truth-%s.txt' % self.dataset):
with open(os.path.join(self.test_root, 'behaviors.tsv'), 'r', encoding='utf-8') as test_f:
with open('test/ref/truth-%s.txt' % self.dataset, 'w', encoding='utf-8') as truth_f:
for test_ID, line in enumerate(test_f):
impression_ID, user_ID, time, history, impressions = line.split('\t')
labels = [int(impression[-1]) for impression in impressions.strip().split(' ')]
truth_f.write(('' if test_ID == 0 else '\n') + str(test_ID + 1) + ' ' + str(labels).replace(' ', ''))
def __init__(self):
self.parse_argument()
self.preliminary_setup()
self.set_cuda()
if __name__ == '__main__':
config = Config()
|
[] |
[] |
[
"MASTER_ADDR",
"MASTER_PORT"
] |
[]
|
["MASTER_ADDR", "MASTER_PORT"]
|
python
| 2 | 0 | |
tests/models/test_taskinstance.py
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import datetime
import os
import signal
import urllib
from tempfile import NamedTemporaryFile
from typing import List, Optional, Union, cast
from unittest import mock
from unittest.mock import call, mock_open, patch
import pendulum
import pytest
from freezegun import freeze_time
from airflow import models, settings
from airflow.example_dags.plugins.workday import AfterWorkdayTimetable
from airflow.exceptions import (
AirflowException,
AirflowFailException,
AirflowRescheduleException,
AirflowSensorTimeout,
AirflowSkipException,
UnmappableXComLengthPushed,
UnmappableXComTypePushed,
)
from airflow.models import (
DAG,
Connection,
DagRun,
Pool,
RenderedTaskInstanceFields,
TaskInstance as TI,
TaskReschedule,
Variable,
XCom,
)
from airflow.models.taskinstance import load_error_file, set_error_file
from airflow.models.taskmap import TaskMap
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator
from airflow.sensors.base import BaseSensorOperator
from airflow.sensors.python import PythonSensor
from airflow.serialization.serialized_objects import SerializedBaseOperator
from airflow.stats import Stats
from airflow.ti_deps.dependencies_deps import REQUEUEABLE_DEPS, RUNNING_DEPS
from airflow.ti_deps.dependencies_states import RUNNABLE_STATES
from airflow.ti_deps.deps.base_ti_dep import TIDepStatus
from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep
from airflow.utils import timezone
from airflow.utils.db import merge_conn
from airflow.utils.session import create_session, provide_session
from airflow.utils.state import State, TaskInstanceState
from airflow.utils.types import DagRunType
from airflow.version import version
from tests.models import DEFAULT_DATE, TEST_DAGS_FOLDER
from tests.test_utils import db
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_connections, clear_db_runs
@pytest.fixture
def test_pool():
with create_session() as session:
test_pool = Pool(pool='test_pool', slots=1)
session.add(test_pool)
session.flush()
yield test_pool
session.rollback()
class CallbackWrapper:
task_id: Optional[str] = None
dag_id: Optional[str] = None
execution_date: Optional[datetime.datetime] = None
task_state_in_callback: Optional[str] = None
callback_ran = False
def wrap_task_instance(self, ti):
self.task_id = ti.task_id
self.dag_id = ti.dag_id
self.execution_date = ti.execution_date
self.task_state_in_callback = ""
self.callback_ran = False
def success_handler(self, context):
self.callback_ran = True
session = settings.Session()
temp_instance = (
session.query(TI)
.filter(TI.task_id == self.task_id)
.filter(TI.dag_id == self.dag_id)
.filter(TI.execution_date == self.execution_date)
.one()
)
self.task_state_in_callback = temp_instance.state
class TestTaskInstance:
@staticmethod
def clean_db():
db.clear_db_dags()
db.clear_db_pools()
db.clear_db_runs()
db.clear_db_task_fail()
db.clear_rendered_ti_fields()
db.clear_db_task_reschedule()
def setup_method(self):
self.clean_db()
# We don't want to store any code for (test) dags created in this file
with patch.object(settings, "STORE_DAG_CODE", False):
yield
def teardown_method(self):
self.clean_db()
def test_load_error_file_returns_None_for_closed_file(self):
error_fd = NamedTemporaryFile()
error_fd.close()
assert load_error_file(error_fd) is None
def test_load_error_file_loads_correctly(self):
error_message = "some random error message"
with NamedTemporaryFile() as error_fd:
set_error_file(error_fd.name, error=error_message)
assert load_error_file(error_fd) == error_message
def test_set_task_dates(self, dag_maker):
"""
Test that tasks properly take start/end dates from DAGs
"""
with dag_maker('dag', end_date=DEFAULT_DATE + datetime.timedelta(days=10)) as dag:
pass
op1 = DummyOperator(task_id='op_1')
assert op1.start_date is None and op1.end_date is None
# dag should assign its dates to op1 because op1 has no dates
dag.add_task(op1)
dag_maker.create_dagrun()
assert op1.start_date == dag.start_date and op1.end_date == dag.end_date
op2 = DummyOperator(
task_id='op_2',
start_date=DEFAULT_DATE - datetime.timedelta(days=1),
end_date=DEFAULT_DATE + datetime.timedelta(days=11),
)
# dag should assign its dates to op2 because they are more restrictive
dag.add_task(op2)
assert op2.start_date == dag.start_date and op2.end_date == dag.end_date
op3 = DummyOperator(
task_id='op_3',
start_date=DEFAULT_DATE + datetime.timedelta(days=1),
end_date=DEFAULT_DATE + datetime.timedelta(days=9),
)
# op3 should keep its dates because they are more restrictive
dag.add_task(op3)
assert op3.start_date == DEFAULT_DATE + datetime.timedelta(days=1)
assert op3.end_date == DEFAULT_DATE + datetime.timedelta(days=9)
def test_set_dag(self, dag_maker):
"""
Test assigning Operators to Dags, including deferred assignment
"""
with dag_maker('dag') as dag:
pass
with dag_maker('dag2') as dag2:
pass
op = DummyOperator(task_id='op_1')
# no dag assigned
assert not op.has_dag()
with pytest.raises(AirflowException):
getattr(op, 'dag')
# no improper assignment
with pytest.raises(TypeError):
op.dag = 1
op.dag = dag
# no reassignment
with pytest.raises(AirflowException):
op.dag = dag2
# but assigning the same dag is ok
op.dag = dag
assert op.dag is dag
assert op in dag.tasks
def test_infer_dag(self, create_dummy_dag):
op1 = DummyOperator(task_id='test_op_1')
op2 = DummyOperator(task_id='test_op_2')
dag, op3 = create_dummy_dag(task_id='test_op_3')
_, op4 = create_dummy_dag('dag2', task_id='test_op_4')
# double check dags
assert [i.has_dag() for i in [op1, op2, op3, op4]] == [False, False, True, True]
# can't combine operators with no dags
with pytest.raises(AirflowException):
op1.set_downstream(op2)
# op2 should infer dag from op1
op1.dag = dag
op1.set_downstream(op2)
assert op2.dag is dag
# can't assign across multiple DAGs
with pytest.raises(AirflowException):
op1.set_downstream(op4)
with pytest.raises(AirflowException):
op1.set_downstream([op3, op4])
def test_bitshift_compose_operators(self, dag_maker):
with dag_maker('dag'):
op1 = DummyOperator(task_id='test_op_1')
op2 = DummyOperator(task_id='test_op_2')
op3 = DummyOperator(task_id='test_op_3')
op1 >> op2 << op3
dag_maker.create_dagrun()
# op2 should be downstream of both
assert op2 in op1.downstream_list
assert op2 in op3.downstream_list
@patch.object(DAG, 'get_concurrency_reached')
def test_requeue_over_dag_concurrency(self, mock_concurrency_reached, create_task_instance):
mock_concurrency_reached.return_value = True
ti = create_task_instance(
dag_id='test_requeue_over_dag_concurrency',
task_id='test_requeue_over_dag_concurrency_op',
max_active_runs=1,
max_active_tasks=2,
dagrun_state=State.QUEUED,
)
ti.run()
assert ti.state == State.NONE
def test_requeue_over_max_active_tis_per_dag(self, create_task_instance):
ti = create_task_instance(
dag_id='test_requeue_over_max_active_tis_per_dag',
task_id='test_requeue_over_max_active_tis_per_dag_op',
max_active_tis_per_dag=0,
max_active_runs=1,
max_active_tasks=2,
dagrun_state=State.QUEUED,
)
ti.run()
assert ti.state == State.NONE
def test_requeue_over_pool_concurrency(self, create_task_instance, test_pool):
ti = create_task_instance(
dag_id='test_requeue_over_pool_concurrency',
task_id='test_requeue_over_pool_concurrency_op',
max_active_tis_per_dag=0,
max_active_runs=1,
max_active_tasks=2,
)
with create_session() as session:
test_pool.slots = 0
session.flush()
ti.run()
assert ti.state == State.NONE
@pytest.mark.usefixtures('test_pool')
def test_not_requeue_non_requeueable_task_instance(self, dag_maker):
# Use BaseSensorOperator because sensor got
# one additional DEP in BaseSensorOperator().deps
with dag_maker(dag_id='test_not_requeue_non_requeueable_task_instance'):
task = BaseSensorOperator(
task_id='test_not_requeue_non_requeueable_task_instance_op',
pool='test_pool',
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
ti.state = State.QUEUED
with create_session() as session:
session.add(ti)
session.commit()
all_deps = RUNNING_DEPS | task.deps
all_non_requeueable_deps = all_deps - REQUEUEABLE_DEPS
patch_dict = {}
for dep in all_non_requeueable_deps:
class_name = dep.__class__.__name__
dep_patch = patch(f'{dep.__module__}.{class_name}.{dep._get_dep_statuses.__name__}')
method_patch = dep_patch.start()
method_patch.return_value = iter([TIDepStatus('mock_' + class_name, True, 'mock')])
patch_dict[class_name] = (dep_patch, method_patch)
for class_name, (dep_patch, method_patch) in patch_dict.items():
method_patch.return_value = iter([TIDepStatus('mock_' + class_name, False, 'mock')])
ti.run()
assert ti.state == State.QUEUED
dep_patch.return_value = TIDepStatus('mock_' + class_name, True, 'mock')
for (dep_patch, method_patch) in patch_dict.values():
dep_patch.stop()
def test_mark_non_runnable_task_as_success(self, create_task_instance):
"""
test that running task with mark_success param update task state
as SUCCESS without running task despite it fails dependency checks.
"""
non_runnable_state = (set(State.task_states) - RUNNABLE_STATES - set(State.SUCCESS)).pop()
ti = create_task_instance(
dag_id='test_mark_non_runnable_task_as_success',
task_id='test_mark_non_runnable_task_as_success_op',
state=non_runnable_state,
)
ti.run(mark_success=True)
assert ti.state == State.SUCCESS
@pytest.mark.usefixtures('test_pool')
def test_run_pooling_task(self, create_task_instance):
"""
test that running a task in an existing pool update task state as SUCCESS.
"""
ti = create_task_instance(
dag_id='test_run_pooling_task',
task_id='test_run_pooling_task_op',
pool='test_pool',
)
ti.run()
assert ti.state == State.SUCCESS
@pytest.mark.usefixtures('test_pool')
def test_pool_slots_property(self):
"""
test that try to create a task with pool_slots less than 1
"""
with pytest.raises(ValueError, match="pool slots .* cannot be less than 1"):
dag = models.DAG(dag_id='test_run_pooling_task')
DummyOperator(
task_id='test_run_pooling_task_op',
dag=dag,
pool='test_pool',
pool_slots=0,
)
@provide_session
def test_ti_updates_with_task(self, create_task_instance, session=None):
"""
test that updating the executor_config propagates to the TaskInstance DB
"""
ti = create_task_instance(
dag_id='test_run_pooling_task',
task_id='test_run_pooling_task_op',
executor_config={'foo': 'bar'},
)
dag = ti.task.dag
ti.run(session=session)
tis = dag.get_task_instances()
assert {'foo': 'bar'} == tis[0].executor_config
task2 = DummyOperator(
task_id='test_run_pooling_task_op2',
executor_config={'bar': 'baz'},
start_date=timezone.datetime(2016, 2, 1, 0, 0, 0),
dag=dag,
)
ti2 = TI(task=task2, run_id=ti.run_id)
session.add(ti2)
session.flush()
ti2.run(session=session)
# Ensure it's reloaded
ti2.executor_config = None
ti2.refresh_from_db(session)
assert {'bar': 'baz'} == ti2.executor_config
session.rollback()
def test_run_pooling_task_with_mark_success(self, create_task_instance):
"""
test that running task in an existing pool with mark_success param
update task state as SUCCESS without running task
despite it fails dependency checks.
"""
ti = create_task_instance(
dag_id='test_run_pooling_task_with_mark_success',
task_id='test_run_pooling_task_with_mark_success_op',
)
ti.run(mark_success=True)
assert ti.state == State.SUCCESS
def test_run_pooling_task_with_skip(self, dag_maker):
"""
test that running task which returns AirflowSkipOperator will end
up in a SKIPPED state.
"""
def raise_skip_exception():
raise AirflowSkipException
with dag_maker(dag_id='test_run_pooling_task_with_skip'):
task = PythonOperator(
task_id='test_run_pooling_task_with_skip',
python_callable=raise_skip_exception,
)
dr = dag_maker.create_dagrun(execution_date=timezone.utcnow())
ti = dr.task_instances[0]
ti.task = task
ti.run()
assert State.SKIPPED == ti.state
def test_task_sigterm_works_with_retries(self, dag_maker):
"""
Test that ensures that tasks are retried when they receive sigterm
"""
def task_function(ti):
os.kill(ti.pid, signal.SIGTERM)
with dag_maker('test_mark_failure_2'):
task = PythonOperator(
task_id='test_on_failure',
python_callable=task_function,
retries=1,
retry_delay=datetime.timedelta(seconds=2),
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.task = task
with pytest.raises(AirflowException):
ti.run()
ti.refresh_from_db()
assert ti.state == State.UP_FOR_RETRY
@pytest.mark.parametrize("state", [State.SUCCESS, State.FAILED, State.SKIPPED])
def test_task_sigterm_doesnt_change_state_of_finished_tasks(self, state, dag_maker):
session = settings.Session()
def task_function(ti):
ti.state = state
session.merge(ti)
session.commit()
raise AirflowException()
with dag_maker('test_mark_failure_2'):
task = PythonOperator(
task_id='test_on_failure',
python_callable=task_function,
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.task = task
ti.run()
ti.refresh_from_db()
ti.state == state
@pytest.mark.parametrize(
"state, exception, retries",
[
(State.FAILED, AirflowException, 0),
(State.SKIPPED, AirflowSkipException, 0),
(State.SUCCESS, None, 0),
(State.UP_FOR_RESCHEDULE, AirflowRescheduleException(timezone.utcnow()), 0),
(State.UP_FOR_RETRY, AirflowException, 1),
],
)
def test_task_wipes_next_fields(self, session, dag_maker, state, exception, retries):
"""
Test that ensures that tasks wipe their next_method and next_kwargs
when the TI enters one of the configured states.
"""
def _raise_if_exception():
if exception:
raise exception
with dag_maker("test_deferred_method_clear"):
task = PythonOperator(
task_id="test_deferred_method_clear_task",
python_callable=_raise_if_exception,
retries=retries,
retry_delay=datetime.timedelta(seconds=2),
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.next_method = "execute"
ti.next_kwargs = {}
session.merge(ti)
session.commit()
ti.task = task
if state in [State.FAILED, State.UP_FOR_RETRY]:
with pytest.raises(exception):
ti.run()
else:
ti.run()
ti.refresh_from_db()
assert ti.next_method is None
assert ti.next_kwargs is None
assert ti.state == state
@freeze_time('2021-09-19 04:56:35', as_kwarg='frozen_time')
def test_retry_delay(self, dag_maker, frozen_time=None):
"""
Test that retry delays are respected
"""
with dag_maker(dag_id='test_retry_handling'):
task = BashOperator(
task_id='test_retry_handling_op',
bash_command='exit 1',
retries=1,
retry_delay=datetime.timedelta(seconds=3),
)
def run_with_error(ti):
try:
ti.run()
except AirflowException:
pass
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti.try_number == 1
# first run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti.try_number == 2
# second run -- still up for retry because retry_delay hasn't expired
frozen_time.tick(delta=datetime.timedelta(seconds=3))
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
# third run -- failed
frozen_time.tick(delta=datetime.datetime.resolution)
run_with_error(ti)
assert ti.state == State.FAILED
def test_retry_handling(self, dag_maker):
"""
Test that task retries are handled properly
"""
expected_rendered_ti_fields = {'env': None, 'bash_command': 'echo test_retry_handling; exit 1'}
with dag_maker(dag_id='test_retry_handling') as dag:
task = BashOperator(
task_id='test_retry_handling_op',
bash_command='echo {{dag.dag_id}}; exit 1',
retries=1,
retry_delay=datetime.timedelta(seconds=0),
)
def run_with_error(ti):
try:
ti.run()
except AirflowException:
pass
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti.try_number == 1
# first run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti._try_number == 1
assert ti.try_number == 2
# second run -- fail
run_with_error(ti)
assert ti.state == State.FAILED
assert ti._try_number == 2
assert ti.try_number == 3
# Clear the TI state since you can't run a task with a FAILED state without
# clearing it first
dag.clear()
# third run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti._try_number == 3
assert ti.try_number == 4
# fourth run -- fail
run_with_error(ti)
ti.refresh_from_db()
assert ti.state == State.FAILED
assert ti._try_number == 4
assert ti.try_number == 5
assert RenderedTaskInstanceFields.get_templated_fields(ti) == expected_rendered_ti_fields
def test_next_retry_datetime(self, dag_maker):
delay = datetime.timedelta(seconds=30)
max_delay = datetime.timedelta(minutes=60)
with dag_maker(dag_id='fail_dag'):
task = BashOperator(
task_id='task_with_exp_backoff_and_max_delay',
bash_command='exit 1',
retries=3,
retry_delay=delay,
retry_exponential_backoff=True,
max_retry_delay=max_delay,
)
ti = dag_maker.create_dagrun().task_instances[0]
ti.task = task
ti.end_date = pendulum.instance(timezone.utcnow())
date = ti.next_retry_datetime()
# between 30 * 2^0.5 and 30 * 2^1 (15 and 30)
period = ti.end_date.add(seconds=30) - ti.end_date.add(seconds=15)
assert date in period
ti.try_number = 3
date = ti.next_retry_datetime()
# between 30 * 2^2 and 30 * 2^3 (120 and 240)
period = ti.end_date.add(seconds=240) - ti.end_date.add(seconds=120)
assert date in period
ti.try_number = 5
date = ti.next_retry_datetime()
# between 30 * 2^4 and 30 * 2^5 (480 and 960)
period = ti.end_date.add(seconds=960) - ti.end_date.add(seconds=480)
assert date in period
ti.try_number = 9
date = ti.next_retry_datetime()
assert date == ti.end_date + max_delay
ti.try_number = 50
date = ti.next_retry_datetime()
assert date == ti.end_date + max_delay
@pytest.mark.parametrize("seconds", [0, 0.5, 1])
def test_next_retry_datetime_short_or_zero_intervals(self, dag_maker, seconds):
delay = datetime.timedelta(seconds=seconds)
max_delay = datetime.timedelta(minutes=60)
with dag_maker(dag_id='fail_dag'):
task = BashOperator(
task_id='task_with_exp_backoff_and_short_or_zero_time_interval',
bash_command='exit 1',
retries=3,
retry_delay=delay,
retry_exponential_backoff=True,
max_retry_delay=max_delay,
)
ti = dag_maker.create_dagrun().task_instances[0]
ti.task = task
ti.end_date = pendulum.instance(timezone.utcnow())
date = ti.next_retry_datetime()
assert date == ti.end_date + datetime.timedelta(seconds=1)
def test_reschedule_handling(self, dag_maker):
"""
Test that task reschedules are handled properly
"""
# Return values of the python sensor callable, modified during tests
done = False
fail = False
def func():
if fail:
raise AirflowException()
return done
with dag_maker(dag_id='test_reschedule_handling') as dag:
task = PythonSensor(
task_id='test_reschedule_handling_sensor',
poke_interval=0,
mode='reschedule',
python_callable=func,
retries=1,
retry_delay=datetime.timedelta(seconds=0),
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti._try_number == 0
assert ti.try_number == 1
def run_ti_and_assert(
run_date,
expected_start_date,
expected_end_date,
expected_duration,
expected_state,
expected_try_number,
expected_task_reschedule_count,
):
with freeze_time(run_date):
try:
ti.run()
except AirflowException:
if not fail:
raise
ti.refresh_from_db()
assert ti.state == expected_state
assert ti._try_number == expected_try_number
assert ti.try_number == expected_try_number + 1
assert ti.start_date == expected_start_date
assert ti.end_date == expected_end_date
assert ti.duration == expected_duration
trs = TaskReschedule.find_for_task_instance(ti)
assert len(trs) == expected_task_reschedule_count
date1 = timezone.utcnow()
date2 = date1 + datetime.timedelta(minutes=1)
date3 = date2 + datetime.timedelta(minutes=1)
date4 = date3 + datetime.timedelta(minutes=1)
# Run with multiple reschedules.
# During reschedule the try number remains the same, but each reschedule is recorded.
# The start date is expected to remain the initial date, hence the duration increases.
# When finished the try number is incremented and there is no reschedule expected
# for this try.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 0, 1)
done, fail = False, False
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RESCHEDULE, 0, 2)
done, fail = False, False
run_ti_and_assert(date3, date1, date3, 120, State.UP_FOR_RESCHEDULE, 0, 3)
done, fail = True, False
run_ti_and_assert(date4, date1, date4, 180, State.SUCCESS, 1, 0)
# Clear the task instance.
dag.clear()
ti.refresh_from_db()
assert ti.state == State.NONE
assert ti._try_number == 1
# Run again after clearing with reschedules and a retry.
# The retry increments the try number, and for that try no reschedule is expected.
# After the retry the start date is reset, hence the duration is also reset.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 1, 1)
done, fail = False, True
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RETRY, 2, 0)
done, fail = False, False
run_ti_and_assert(date3, date3, date3, 0, State.UP_FOR_RESCHEDULE, 2, 1)
done, fail = True, False
run_ti_and_assert(date4, date3, date4, 60, State.SUCCESS, 3, 0)
@pytest.mark.usefixtures('test_pool')
def test_reschedule_handling_clear_reschedules(self, dag_maker):
"""
Test that task reschedules clearing are handled properly
"""
# Return values of the python sensor callable, modified during tests
done = False
fail = False
def func():
if fail:
raise AirflowException()
return done
with dag_maker(dag_id='test_reschedule_handling') as dag:
task = PythonSensor(
task_id='test_reschedule_handling_sensor',
poke_interval=0,
mode='reschedule',
python_callable=func,
retries=1,
retry_delay=datetime.timedelta(seconds=0),
pool='test_pool',
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti._try_number == 0
assert ti.try_number == 1
def run_ti_and_assert(
run_date,
expected_start_date,
expected_end_date,
expected_duration,
expected_state,
expected_try_number,
expected_task_reschedule_count,
):
with freeze_time(run_date):
try:
ti.run()
except AirflowException:
if not fail:
raise
ti.refresh_from_db()
assert ti.state == expected_state
assert ti._try_number == expected_try_number
assert ti.try_number == expected_try_number + 1
assert ti.start_date == expected_start_date
assert ti.end_date == expected_end_date
assert ti.duration == expected_duration
trs = TaskReschedule.find_for_task_instance(ti)
assert len(trs) == expected_task_reschedule_count
date1 = timezone.utcnow()
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 0, 1)
# Clear the task instance.
dag.clear()
ti.refresh_from_db()
assert ti.state == State.NONE
assert ti._try_number == 0
# Check that reschedules for ti have also been cleared.
trs = TaskReschedule.find_for_task_instance(ti)
assert not trs
def test_depends_on_past(self, dag_maker):
with dag_maker(dag_id='test_depends_on_past'):
task = DummyOperator(
task_id='test_dop_task',
depends_on_past=True,
)
dag_maker.create_dagrun(
state=State.FAILED,
run_type=DagRunType.SCHEDULED,
)
run_date = task.start_date + datetime.timedelta(days=5)
dr = dag_maker.create_dagrun(
execution_date=run_date,
run_type=DagRunType.SCHEDULED,
)
ti = dr.task_instances[0]
ti.task = task
# depends_on_past prevents the run
task.run(start_date=run_date, end_date=run_date, ignore_first_depends_on_past=False)
ti.refresh_from_db()
assert ti.state is None
# ignore first depends_on_past to allow the run
task.run(start_date=run_date, end_date=run_date, ignore_first_depends_on_past=True)
ti.refresh_from_db()
assert ti.state == State.SUCCESS
# Parameterized tests to check for the correct firing
# of the trigger_rule under various circumstances
# Numeric fields are in order:
# successes, skipped, failed, upstream_failed, done
@pytest.mark.parametrize(
"trigger_rule,successes,skipped,failed,upstream_failed,done,"
"flag_upstream_failed,expect_state,expect_completed",
[
#
# Tests for all_success
#
['all_success', 5, 0, 0, 0, 0, True, None, True],
['all_success', 2, 0, 0, 0, 0, True, None, False],
['all_success', 2, 0, 1, 0, 0, True, State.UPSTREAM_FAILED, False],
['all_success', 2, 1, 0, 0, 0, True, State.SKIPPED, False],
#
# Tests for one_success
#
['one_success', 5, 0, 0, 0, 5, True, None, True],
['one_success', 2, 0, 0, 0, 2, True, None, True],
['one_success', 2, 0, 1, 0, 3, True, None, True],
['one_success', 2, 1, 0, 0, 3, True, None, True],
['one_success', 0, 5, 0, 0, 5, True, State.SKIPPED, False],
['one_success', 0, 4, 1, 0, 5, True, State.UPSTREAM_FAILED, False],
['one_success', 0, 3, 1, 1, 5, True, State.UPSTREAM_FAILED, False],
['one_success', 0, 4, 0, 1, 5, True, State.UPSTREAM_FAILED, False],
['one_success', 0, 0, 5, 0, 5, True, State.UPSTREAM_FAILED, False],
['one_success', 0, 0, 4, 1, 5, True, State.UPSTREAM_FAILED, False],
['one_success', 0, 0, 0, 5, 5, True, State.UPSTREAM_FAILED, False],
#
# Tests for all_failed
#
['all_failed', 5, 0, 0, 0, 5, True, State.SKIPPED, False],
['all_failed', 0, 0, 5, 0, 5, True, None, True],
['all_failed', 2, 0, 0, 0, 2, True, State.SKIPPED, False],
['all_failed', 2, 0, 1, 0, 3, True, State.SKIPPED, False],
['all_failed', 2, 1, 0, 0, 3, True, State.SKIPPED, False],
#
# Tests for one_failed
#
['one_failed', 5, 0, 0, 0, 0, True, None, False],
['one_failed', 2, 0, 0, 0, 0, True, None, False],
['one_failed', 2, 0, 1, 0, 0, True, None, True],
['one_failed', 2, 1, 0, 0, 3, True, None, False],
['one_failed', 2, 3, 0, 0, 5, True, State.SKIPPED, False],
#
# Tests for done
#
['all_done', 5, 0, 0, 0, 5, True, None, True],
['all_done', 2, 0, 0, 0, 2, True, None, False],
['all_done', 2, 0, 1, 0, 3, True, None, False],
['all_done', 2, 1, 0, 0, 3, True, None, False],
],
)
def test_check_task_dependencies(
self,
trigger_rule: str,
successes: int,
skipped: int,
failed: int,
upstream_failed: int,
done: int,
flag_upstream_failed: bool,
expect_state: State,
expect_completed: bool,
dag_maker,
):
with dag_maker() as dag:
downstream = DummyOperator(task_id="downstream", trigger_rule=trigger_rule)
for i in range(5):
task = DummyOperator(task_id=f'runme_{i}', dag=dag)
task.set_downstream(downstream)
assert task.start_date is not None
run_date = task.start_date + datetime.timedelta(days=5)
ti = dag_maker.create_dagrun(execution_date=run_date).get_task_instance(downstream.task_id)
ti.task = downstream
dep_results = TriggerRuleDep()._evaluate_trigger_rule(
ti=ti,
successes=successes,
skipped=skipped,
failed=failed,
upstream_failed=upstream_failed,
done=done,
flag_upstream_failed=flag_upstream_failed,
)
completed = all(dep.passed for dep in dep_results)
assert completed == expect_completed
assert ti.state == expect_state
def test_respects_prev_dagrun_dep(self, create_task_instance):
ti = create_task_instance()
failing_status = [TIDepStatus('test fail status name', False, 'test fail reason')]
passing_status = [TIDepStatus('test pass status name', True, 'test passing reason')]
with patch(
'airflow.ti_deps.deps.prev_dagrun_dep.PrevDagrunDep.get_dep_statuses', return_value=failing_status
):
assert not ti.are_dependencies_met()
with patch(
'airflow.ti_deps.deps.prev_dagrun_dep.PrevDagrunDep.get_dep_statuses', return_value=passing_status
):
assert ti.are_dependencies_met()
@pytest.mark.parametrize(
"downstream_ti_state, expected_are_dependents_done",
[
(State.SUCCESS, True),
(State.SKIPPED, True),
(State.RUNNING, False),
(State.FAILED, False),
(State.NONE, False),
],
)
@provide_session
def test_are_dependents_done(
self, downstream_ti_state, expected_are_dependents_done, create_task_instance, session=None
):
ti = create_task_instance(session=session)
dag = ti.task.dag
downstream_task = DummyOperator(task_id='downstream_task', dag=dag)
ti.task >> downstream_task
downstream_ti = TI(downstream_task, run_id=ti.run_id)
downstream_ti.set_state(downstream_ti_state, session)
session.flush()
assert ti.are_dependents_done(session) == expected_are_dependents_done
def test_xcom_pull(self, create_task_instance):
"""
Test xcom_pull, using different filtering methods.
"""
ti1 = create_task_instance(
dag_id='test_xcom',
task_id='test_xcom_1',
start_date=timezone.datetime(2016, 6, 1, 0, 0, 0),
)
# Push a value
ti1.xcom_push(key='foo', value='bar')
# Push another value with the same key (but by a different task)
XCom.set(
key='foo',
value='baz',
task_id='test_xcom_2',
dag_id=ti1.dag_id,
execution_date=ti1.execution_date,
)
# Pull with no arguments
result = ti1.xcom_pull()
assert result is None
# Pull the value pushed most recently by any task.
result = ti1.xcom_pull(key='foo')
assert result in 'baz'
# Pull the value pushed by the first task
result = ti1.xcom_pull(task_ids='test_xcom_1', key='foo')
assert result == 'bar'
# Pull the value pushed by the second task
result = ti1.xcom_pull(task_ids='test_xcom_2', key='foo')
assert result == 'baz'
# Pull the values pushed by both tasks & Verify Order of task_ids pass & values returned
result = ti1.xcom_pull(task_ids=['test_xcom_1', 'test_xcom_2'], key='foo')
assert result == ['bar', 'baz']
def test_xcom_pull_after_success(self, create_task_instance):
"""
tests xcom set/clear relative to a task in a 'success' rerun scenario
"""
key = 'xcom_key'
value = 'xcom_value'
ti = create_task_instance(
dag_id='test_xcom',
schedule_interval='@monthly',
task_id='test_xcom',
pool='test_xcom',
)
ti.run(mark_success=True)
ti.xcom_push(key=key, value=value)
assert ti.xcom_pull(task_ids='test_xcom', key=key) == value
ti.run()
# The second run and assert is to handle AIRFLOW-131 (don't clear on
# prior success)
assert ti.xcom_pull(task_ids='test_xcom', key=key) == value
# Test AIRFLOW-703: Xcom shouldn't be cleared if the task doesn't
# execute, even if dependencies are ignored
ti.run(ignore_all_deps=True, mark_success=True)
assert ti.xcom_pull(task_ids='test_xcom', key=key) == value
# Xcom IS finally cleared once task has executed
ti.run(ignore_all_deps=True)
assert ti.xcom_pull(task_ids='test_xcom', key=key) is None
def test_xcom_pull_different_execution_date(self, create_task_instance):
"""
tests xcom fetch behavior with different execution dates, using
both xcom_pull with "include_prior_dates" and without
"""
key = 'xcom_key'
value = 'xcom_value'
ti = create_task_instance(
dag_id='test_xcom',
schedule_interval='@monthly',
task_id='test_xcom',
pool='test_xcom',
)
exec_date = ti.dag_run.execution_date
ti.run(mark_success=True)
ti.xcom_push(key=key, value=value)
assert ti.xcom_pull(task_ids='test_xcom', key=key) == value
ti.run()
exec_date += datetime.timedelta(days=1)
dr = ti.task.dag.create_dagrun(run_id="test2", execution_date=exec_date, state=None)
ti = TI(task=ti.task, run_id=dr.run_id)
ti.run()
# We have set a new execution date (and did not pass in
# 'include_prior_dates'which means this task should now have a cleared
# xcom value
assert ti.xcom_pull(task_ids='test_xcom', key=key) is None
# We *should* get a value using 'include_prior_dates'
assert ti.xcom_pull(task_ids='test_xcom', key=key, include_prior_dates=True) == value
def test_xcom_push_flag(self, dag_maker):
"""
Tests the option for Operators to push XComs
"""
value = 'hello'
task_id = 'test_no_xcom_push'
with dag_maker(dag_id='test_xcom'):
# nothing saved to XCom
task = PythonOperator(
task_id=task_id,
python_callable=lambda: value,
do_xcom_push=False,
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
ti.run()
assert ti.xcom_pull(task_ids=task_id, key=models.XCOM_RETURN_KEY) is None
def test_post_execute_hook(self, dag_maker):
"""
Test that post_execute hook is called with the Operator's result.
The result ('error') will cause an error to be raised and trapped.
"""
class TestError(Exception):
pass
class TestOperator(PythonOperator):
def post_execute(self, context, result=None):
if result == 'error':
raise TestError('expected error.')
with dag_maker(dag_id='test_post_execute_dag'):
task = TestOperator(
task_id='test_operator',
python_callable=lambda: 'error',
)
ti = dag_maker.create_dagrun(execution_date=DEFAULT_DATE).task_instances[0]
ti.task = task
with pytest.raises(TestError):
ti.run()
def test_check_and_change_state_before_execution(self, create_task_instance):
ti = create_task_instance(dag_id='test_check_and_change_state_before_execution')
assert ti._try_number == 0
assert ti.check_and_change_state_before_execution()
# State should be running, and try_number column should be incremented
assert ti.state == State.RUNNING
assert ti._try_number == 1
def test_check_and_change_state_before_execution_dep_not_met(self, create_task_instance):
ti = create_task_instance(dag_id='test_check_and_change_state_before_execution')
task2 = DummyOperator(task_id='task2', dag=ti.task.dag, start_date=DEFAULT_DATE)
ti.task >> task2
ti = TI(task=task2, run_id=ti.run_id)
assert not ti.check_and_change_state_before_execution()
def test_try_number(self, create_task_instance):
"""
Test the try_number accessor behaves in various running states
"""
ti = create_task_instance(dag_id='test_check_and_change_state_before_execution')
assert 1 == ti.try_number
ti.try_number = 2
ti.state = State.RUNNING
assert 2 == ti.try_number
ti.state = State.SUCCESS
assert 3 == ti.try_number
def test_get_num_running_task_instances(self, create_task_instance):
session = settings.Session()
ti1 = create_task_instance(
dag_id='test_get_num_running_task_instances', task_id='task1', session=session
)
dr = ti1.task.dag.create_dagrun(
execution_date=DEFAULT_DATE + datetime.timedelta(days=1),
state=None,
run_id='2',
session=session,
)
assert ti1 in session
ti2 = dr.task_instances[0]
ti2.task = ti1.task
ti3 = create_task_instance(
dag_id='test_get_num_running_task_instances_dummy', task_id='task2', session=session
)
assert ti3 in session
assert ti1 in session
ti1.state = State.RUNNING
ti2.state = State.QUEUED
ti3.state = State.RUNNING
assert ti3 in session
session.commit()
assert 1 == ti1.get_num_running_task_instances(session=session)
assert 1 == ti2.get_num_running_task_instances(session=session)
assert 1 == ti3.get_num_running_task_instances(session=session)
# def test_log_url(self):
# now = pendulum.now('Europe/Brussels')
# dag = DAG('dag', start_date=DEFAULT_DATE)
# task = DummyOperator(task_id='op', dag=dag)
# ti = TI(task=task, execution_date=now)
# d = urllib.parse.parse_qs(
# urllib.parse.urlparse(ti.log_url).query,
# keep_blank_values=True, strict_parsing=True)
# self.assertEqual(d['dag_id'][0], 'dag')
# self.assertEqual(d['task_id'][0], 'op')
# self.assertEqual(pendulum.parse(d['execution_date'][0]), now)
def test_log_url(self, create_task_instance):
ti = create_task_instance(dag_id='dag', task_id='op', execution_date=timezone.datetime(2018, 1, 1))
expected_url = (
'http://localhost:8080/log?'
'execution_date=2018-01-01T00%3A00%3A00%2B00%3A00'
'&task_id=op'
'&dag_id=dag'
)
assert ti.log_url == expected_url
def test_mark_success_url(self, create_task_instance):
now = pendulum.now('Europe/Brussels')
ti = create_task_instance(dag_id='dag', task_id='op', execution_date=now)
query = urllib.parse.parse_qs(
urllib.parse.urlparse(ti.mark_success_url).query, keep_blank_values=True, strict_parsing=True
)
assert query['dag_id'][0] == 'dag'
assert query['task_id'][0] == 'op'
assert pendulum.parse(query['execution_date'][0]) == now
def test_overwrite_params_with_dag_run_conf(self, create_task_instance):
ti = create_task_instance()
dag_run = ti.dag_run
dag_run.conf = {"override": True}
params = {"override": False}
ti.overwrite_params_with_dag_run_conf(params, dag_run)
assert params["override"] is True
def test_overwrite_params_with_dag_run_none(self, create_task_instance):
ti = create_task_instance()
params = {"override": False}
ti.overwrite_params_with_dag_run_conf(params, None)
assert params["override"] is False
def test_overwrite_params_with_dag_run_conf_none(self, create_task_instance):
ti = create_task_instance()
params = {"override": False}
dag_run = ti.dag_run
ti.overwrite_params_with_dag_run_conf(params, dag_run)
assert params["override"] is False
@patch('airflow.models.taskinstance.send_email')
def test_email_alert(self, mock_send_email, dag_maker):
with dag_maker(dag_id='test_failure_email'):
task = BashOperator(task_id='test_email_alert', bash_command='exit 1', email='to')
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
try:
ti.run()
except AirflowException:
pass
(email, title, body), _ = mock_send_email.call_args
assert email == 'to'
assert 'test_email_alert' in title
assert 'test_email_alert' in body
assert 'Try 1' in body
@conf_vars(
{
('email', 'subject_template'): '/subject/path',
('email', 'html_content_template'): '/html_content/path',
}
)
@patch('airflow.models.taskinstance.send_email')
def test_email_alert_with_config(self, mock_send_email, dag_maker):
with dag_maker(dag_id='test_failure_email'):
task = BashOperator(
task_id='test_email_alert_with_config',
bash_command='exit 1',
email='to',
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
opener = mock_open(read_data='template: {{ti.task_id}}')
with patch('airflow.models.taskinstance.open', opener, create=True):
try:
ti.run()
except AirflowException:
pass
(email, title, body), _ = mock_send_email.call_args
assert email == 'to'
assert 'template: test_email_alert_with_config' == title
assert 'template: test_email_alert_with_config' == body
def test_set_duration(self):
task = DummyOperator(task_id='op', email='[email protected]')
ti = TI(task=task)
ti.start_date = datetime.datetime(2018, 10, 1, 1)
ti.end_date = datetime.datetime(2018, 10, 1, 2)
ti.set_duration()
assert ti.duration == 3600
def test_set_duration_empty_dates(self):
task = DummyOperator(task_id='op', email='[email protected]')
ti = TI(task=task)
ti.set_duration()
assert ti.duration is None
def test_success_callback_no_race_condition(self, create_task_instance):
callback_wrapper = CallbackWrapper()
ti = create_task_instance(
on_success_callback=callback_wrapper.success_handler,
end_date=DEFAULT_DATE + datetime.timedelta(days=10),
execution_date=timezone.utcnow(),
state=State.RUNNING,
)
session = settings.Session()
session.merge(ti)
session.commit()
callback_wrapper.wrap_task_instance(ti)
ti._run_raw_task()
ti._run_finished_callback()
assert callback_wrapper.callback_ran
assert callback_wrapper.task_state_in_callback == State.SUCCESS
ti.refresh_from_db()
assert ti.state == State.SUCCESS
@staticmethod
def _test_previous_dates_setup(
schedule_interval: Union[str, datetime.timedelta, None],
catchup: bool,
scenario: List[TaskInstanceState],
dag_maker,
) -> list:
dag_id = 'test_previous_dates'
with dag_maker(dag_id=dag_id, schedule_interval=schedule_interval, catchup=catchup):
task = DummyOperator(task_id='task')
def get_test_ti(execution_date: pendulum.DateTime, state: str) -> TI:
dr = dag_maker.create_dagrun(
run_id=f'test__{execution_date.isoformat()}',
run_type=DagRunType.SCHEDULED,
state=state,
execution_date=execution_date,
start_date=pendulum.now('UTC'),
)
ti = dr.task_instances[0]
ti.task = task
ti.set_state(state=State.SUCCESS, session=dag_maker.session)
return ti
date = cast(pendulum.DateTime, pendulum.parse('2019-01-01T00:00:00+00:00'))
ret = []
for idx, state in enumerate(scenario):
new_date = date.add(days=idx)
ti = get_test_ti(new_date, state)
ret.append(ti)
return ret
_prev_dates_param_list = [
pytest.param('0 0 * * * ', True, id='cron/catchup'),
pytest.param('0 0 * * *', False, id='cron/no-catchup'),
pytest.param(None, True, id='no-sched/catchup'),
pytest.param(None, False, id='no-sched/no-catchup'),
pytest.param(datetime.timedelta(days=1), True, id='timedelta/catchup'),
pytest.param(datetime.timedelta(days=1), False, id='timedelta/no-catchup'),
]
@pytest.mark.parametrize("schedule_interval, catchup", _prev_dates_param_list)
def test_previous_ti(self, schedule_interval, catchup, dag_maker) -> None:
scenario = [State.SUCCESS, State.FAILED, State.SUCCESS]
ti_list = self._test_previous_dates_setup(schedule_interval, catchup, scenario, dag_maker)
assert ti_list[0].get_previous_ti() is None
assert ti_list[2].get_previous_ti().run_id == ti_list[1].run_id
assert ti_list[2].get_previous_ti().run_id != ti_list[0].run_id
@pytest.mark.parametrize("schedule_interval, catchup", _prev_dates_param_list)
def test_previous_ti_success(self, schedule_interval, catchup, dag_maker) -> None:
scenario = [State.FAILED, State.SUCCESS, State.FAILED, State.SUCCESS]
ti_list = self._test_previous_dates_setup(schedule_interval, catchup, scenario, dag_maker)
assert ti_list[0].get_previous_ti(state=State.SUCCESS) is None
assert ti_list[1].get_previous_ti(state=State.SUCCESS) is None
assert ti_list[3].get_previous_ti(state=State.SUCCESS).run_id == ti_list[1].run_id
assert ti_list[3].get_previous_ti(state=State.SUCCESS).run_id != ti_list[2].run_id
@pytest.mark.parametrize("schedule_interval, catchup", _prev_dates_param_list)
def test_previous_execution_date_success(self, schedule_interval, catchup, dag_maker) -> None:
scenario = [State.FAILED, State.SUCCESS, State.FAILED, State.SUCCESS]
ti_list = self._test_previous_dates_setup(schedule_interval, catchup, scenario, dag_maker)
# vivify
for ti in ti_list:
ti.execution_date
assert ti_list[0].get_previous_execution_date(state=State.SUCCESS) is None
assert ti_list[1].get_previous_execution_date(state=State.SUCCESS) is None
assert ti_list[3].get_previous_execution_date(state=State.SUCCESS) == ti_list[1].execution_date
assert ti_list[3].get_previous_execution_date(state=State.SUCCESS) != ti_list[2].execution_date
@pytest.mark.parametrize("schedule_interval, catchup", _prev_dates_param_list)
def test_previous_start_date_success(self, schedule_interval, catchup, dag_maker) -> None:
scenario = [State.FAILED, State.SUCCESS, State.FAILED, State.SUCCESS]
ti_list = self._test_previous_dates_setup(schedule_interval, catchup, scenario, dag_maker)
assert ti_list[0].get_previous_start_date(state=State.SUCCESS) is None
assert ti_list[1].get_previous_start_date(state=State.SUCCESS) is None
assert ti_list[3].get_previous_start_date(state=State.SUCCESS) == ti_list[1].start_date
assert ti_list[3].get_previous_start_date(state=State.SUCCESS) != ti_list[2].start_date
def test_get_previous_start_date_none(self, dag_maker):
"""
Test that get_previous_start_date() can handle TaskInstance with no start_date.
"""
with dag_maker("test_get_previous_start_date_none", schedule_interval=None) as dag:
task = DummyOperator(task_id="op")
day_1 = DEFAULT_DATE
day_2 = DEFAULT_DATE + datetime.timedelta(days=1)
# Create a DagRun for day_1 and day_2. Calling ti_2.get_previous_start_date()
# should return the start_date of ti_1 (which is None because ti_1 was not run).
# It should not raise an error.
dagrun_1 = dag_maker.create_dagrun(
execution_date=day_1,
state=State.RUNNING,
run_type=DagRunType.MANUAL,
)
dagrun_2 = dag.create_dagrun(
execution_date=day_2,
state=State.RUNNING,
run_type=DagRunType.MANUAL,
)
ti_1 = dagrun_1.get_task_instance(task.task_id)
ti_2 = dagrun_2.get_task_instance(task.task_id)
ti_1.task = task
ti_2.task = task
assert ti_2.get_previous_start_date() == ti_1.start_date
assert ti_1.start_date is None
def test_pendulum_template_dates(self, create_task_instance):
ti = create_task_instance(
dag_id='test_pendulum_template_dates',
task_id='test_pendulum_template_dates_task',
schedule_interval='0 12 * * *',
)
template_context = ti.get_template_context()
assert isinstance(template_context["data_interval_start"], pendulum.DateTime)
assert isinstance(template_context["data_interval_end"], pendulum.DateTime)
def test_template_render(self, create_task_instance):
ti = create_task_instance(
dag_id="test_template_render",
task_id="test_template_render_task",
schedule_interval="0 12 * * *",
)
template_context = ti.get_template_context()
result = ti.task.render_template("Task: {{ dag.dag_id }} -> {{ task.task_id }}", template_context)
assert result == "Task: test_template_render -> test_template_render_task"
def test_template_render_deprecated(self, create_task_instance):
ti = create_task_instance(
dag_id="test_template_render",
task_id="test_template_render_task",
schedule_interval="0 12 * * *",
)
template_context = ti.get_template_context()
with pytest.deprecated_call():
result = ti.task.render_template("Execution date: {{ execution_date }}", template_context)
assert result.startswith("Execution date: ")
@pytest.mark.parametrize(
"content, expected_output",
[
('{{ conn.get("a_connection").host }}', 'hostvalue'),
('{{ conn.get("a_connection", "unused_fallback").host }}', 'hostvalue'),
('{{ conn.get("missing_connection", {"host": "fallback_host"}).host }}', 'fallback_host'),
('{{ conn.a_connection.host }}', 'hostvalue'),
('{{ conn.a_connection.login }}', 'loginvalue'),
('{{ conn.a_connection.password }}', 'passwordvalue'),
('{{ conn.a_connection.extra_dejson["extra__asana__workspace"] }}', 'extra1'),
('{{ conn.a_connection.extra_dejson.extra__asana__workspace }}', 'extra1'),
],
)
def test_template_with_connection(self, content, expected_output, create_task_instance):
"""
Test the availability of variables in templates
"""
with create_session() as session:
clear_db_connections(add_default_connections_back=False)
merge_conn(
Connection(
conn_id="a_connection",
conn_type="a_type",
description="a_conn_description",
host="hostvalue",
login="loginvalue",
password="passwordvalue",
schema="schemavalues",
extra={
"extra__asana__workspace": "extra1",
},
),
session,
)
ti = create_task_instance()
context = ti.get_template_context()
result = ti.task.render_template(content, context)
assert result == expected_output
@pytest.mark.parametrize(
"content, expected_output",
[
('{{ var.value.a_variable }}', 'a test value'),
('{{ var.value.get("a_variable") }}', 'a test value'),
('{{ var.value.get("a_variable", "unused_fallback") }}', 'a test value'),
('{{ var.value.get("missing_variable", "fallback") }}', 'fallback'),
],
)
def test_template_with_variable(self, content, expected_output, create_task_instance):
"""
Test the availability of variables in templates
"""
Variable.set('a_variable', 'a test value')
ti = create_task_instance()
context = ti.get_template_context()
result = ti.task.render_template(content, context)
assert result == expected_output
def test_template_with_variable_missing(self, create_task_instance):
"""
Test the availability of variables in templates
"""
ti = create_task_instance()
context = ti.get_template_context()
with pytest.raises(KeyError):
ti.task.render_template('{{ var.value.get("missing_variable") }}', context)
@pytest.mark.parametrize(
"content, expected_output",
[
('{{ var.value.a_variable }}', '{\n "a": {\n "test": "value"\n }\n}'),
('{{ var.json.a_variable["a"]["test"] }}', 'value'),
('{{ var.json.get("a_variable")["a"]["test"] }}', 'value'),
('{{ var.json.get("a_variable", {"a": {"test": "unused_fallback"}})["a"]["test"] }}', 'value'),
('{{ var.json.get("missing_variable", {"a": {"test": "fallback"}})["a"]["test"] }}', 'fallback'),
],
)
def test_template_with_json_variable(self, content, expected_output, create_task_instance):
"""
Test the availability of variables in templates
"""
Variable.set('a_variable', {'a': {'test': 'value'}}, serialize_json=True)
ti = create_task_instance()
context = ti.get_template_context()
result = ti.task.render_template(content, context)
assert result == expected_output
def test_template_with_json_variable_missing(self, create_task_instance):
ti = create_task_instance()
context = ti.get_template_context()
with pytest.raises(KeyError):
ti.task.render_template('{{ var.json.get("missing_variable") }}', context)
@pytest.mark.parametrize(
("field", "expected"),
[
("next_ds", "2016-01-01"),
("next_ds_nodash", "20160101"),
("prev_ds", "2015-12-31"),
("prev_ds_nodash", "20151231"),
("yesterday_ds", "2015-12-31"),
("yesterday_ds_nodash", "20151231"),
("tomorrow_ds", "2016-01-02"),
("tomorrow_ds_nodash", "20160102"),
],
)
def test_deprecated_context(self, field, expected, create_task_instance):
ti = create_task_instance(execution_date=DEFAULT_DATE)
context = ti.get_template_context()
with pytest.deprecated_call() as recorder:
assert context[field] == expected
message_beginning = (
f"Accessing {field!r} from the template is deprecated and "
f"will be removed in a future version."
)
recorded_message = [str(m.message) for m in recorder]
assert len(recorded_message) == 1
assert recorded_message[0].startswith(message_beginning)
def test_template_with_custom_timetable_deprecated_context(self, create_task_instance):
ti = create_task_instance(
start_date=DEFAULT_DATE,
timetable=AfterWorkdayTimetable(),
run_type=DagRunType.SCHEDULED,
execution_date=timezone.datetime(2021, 9, 6),
data_interval=(timezone.datetime(2021, 9, 6), timezone.datetime(2021, 9, 7)),
)
context = ti.get_template_context()
with pytest.deprecated_call():
assert context["execution_date"] == pendulum.DateTime(2021, 9, 6, tzinfo=timezone.TIMEZONE)
with pytest.deprecated_call():
assert context["next_ds"] == "2021-09-07"
with pytest.deprecated_call():
assert context["next_ds_nodash"] == "20210907"
with pytest.deprecated_call():
assert context["next_execution_date"] == pendulum.DateTime(2021, 9, 7, tzinfo=timezone.TIMEZONE)
with pytest.deprecated_call():
assert context["prev_ds"] is None, "Does not make sense for custom timetable"
with pytest.deprecated_call():
assert context["prev_ds_nodash"] is None, "Does not make sense for custom timetable"
with pytest.deprecated_call():
assert context["prev_execution_date"] is None, "Does not make sense for custom timetable"
def test_execute_callback(self, create_task_instance):
called = False
def on_execute_callable(context):
nonlocal called
called = True
assert context['dag_run'].dag_id == 'test_dagrun_execute_callback'
ti = create_task_instance(
dag_id='test_execute_callback',
on_execute_callback=on_execute_callable,
state=State.RUNNING,
)
session = settings.Session()
session.merge(ti)
session.commit()
ti._run_raw_task()
assert called
ti.refresh_from_db()
assert ti.state == State.SUCCESS
@pytest.mark.parametrize(
"finished_state, expected_message",
[
(State.SUCCESS, "Error when executing on_success_callback"),
(State.UP_FOR_RETRY, "Error when executing on_retry_callback"),
(State.FAILED, "Error when executing on_failure_callback"),
],
)
def test_finished_callbacks_handle_and_log_exception(
self, finished_state, expected_message, create_task_instance
):
called = completed = False
def on_finish_callable(context):
nonlocal called, completed
called = True
raise KeyError
completed = True
ti = create_task_instance(
end_date=DEFAULT_DATE + datetime.timedelta(days=10),
on_success_callback=on_finish_callable,
on_retry_callback=on_finish_callable,
on_failure_callback=on_finish_callable,
state=finished_state,
)
ti._log = mock.Mock()
ti._run_finished_callback()
assert called
assert not completed
ti.log.exception.assert_called_once_with(expected_message)
@provide_session
def test_handle_failure(self, create_dummy_dag, session=None):
start_date = timezone.datetime(2016, 6, 1)
clear_db_runs()
mock_on_failure_1 = mock.MagicMock()
mock_on_retry_1 = mock.MagicMock()
dag, task1 = create_dummy_dag(
dag_id="test_handle_failure",
schedule_interval=None,
start_date=start_date,
task_id="test_handle_failure_on_failure",
with_dagrun_type=DagRunType.MANUAL,
on_failure_callback=mock_on_failure_1,
on_retry_callback=mock_on_retry_1,
session=session,
)
dr = dag.create_dagrun(
run_id="test2",
run_type=DagRunType.MANUAL,
execution_date=timezone.utcnow(),
state=None,
session=session,
)
ti1 = dr.get_task_instance(task1.task_id, session=session)
ti1.task = task1
ti1.state = State.FAILED
ti1.handle_failure("test failure handling")
ti1._run_finished_callback()
context_arg_1 = mock_on_failure_1.call_args[0][0]
assert context_arg_1 and "task_instance" in context_arg_1
mock_on_retry_1.assert_not_called()
mock_on_failure_2 = mock.MagicMock()
mock_on_retry_2 = mock.MagicMock()
task2 = DummyOperator(
task_id="test_handle_failure_on_retry",
on_failure_callback=mock_on_failure_2,
on_retry_callback=mock_on_retry_2,
retries=1,
dag=dag,
)
ti2 = TI(task=task2, run_id=dr.run_id)
ti2.state = State.FAILED
session.add(ti2)
session.flush()
ti2.handle_failure("test retry handling")
ti2._run_finished_callback()
mock_on_failure_2.assert_not_called()
context_arg_2 = mock_on_retry_2.call_args[0][0]
assert context_arg_2 and "task_instance" in context_arg_2
# test the scenario where normally we would retry but have been asked to fail
mock_on_failure_3 = mock.MagicMock()
mock_on_retry_3 = mock.MagicMock()
task3 = DummyOperator(
task_id="test_handle_failure_on_force_fail",
on_failure_callback=mock_on_failure_3,
on_retry_callback=mock_on_retry_3,
retries=1,
dag=dag,
)
ti3 = TI(task=task3, run_id=dr.run_id)
session.add(ti3)
session.flush()
ti3.state = State.FAILED
ti3.handle_failure("test force_fail handling", force_fail=True)
ti3._run_finished_callback()
context_arg_3 = mock_on_failure_3.call_args[0][0]
assert context_arg_3 and "task_instance" in context_arg_3
mock_on_retry_3.assert_not_called()
def test_handle_failure_updates_queued_task_try_number(self, dag_maker):
session = settings.Session()
with dag_maker():
task = DummyOperator(task_id="mytask", retries=1)
dr = dag_maker.create_dagrun()
ti = TI(task=task, run_id=dr.run_id)
ti.state = State.QUEUED
session.merge(ti)
session.commit()
assert ti.state == State.QUEUED
assert ti.try_number == 1
ti.handle_failure("test queued ti", test_mode=True)
assert ti.state == State.UP_FOR_RETRY
# Assert that 'ti._try_number' is bumped from 0 to 1. This is the last/current try
assert ti._try_number == 1
# Check 'ti.try_number' is bumped to 2. This is try_number for next run
assert ti.try_number == 2
def test_does_not_retry_on_airflow_fail_exception(self, dag_maker):
def fail():
raise AirflowFailException("hopeless")
with dag_maker(dag_id='test_does_not_retry_on_airflow_fail_exception'):
task = PythonOperator(
task_id='test_raise_airflow_fail_exception',
python_callable=fail,
retries=1,
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
try:
ti.run()
except AirflowFailException:
pass # expected
assert State.FAILED == ti.state
def test_retries_on_other_exceptions(self, dag_maker):
def fail():
raise AirflowException("maybe this will pass?")
with dag_maker(dag_id='test_retries_on_other_exceptions'):
task = PythonOperator(
task_id='test_raise_other_exception',
python_callable=fail,
retries=1,
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
try:
ti.run()
except AirflowException:
pass # expected
assert State.UP_FOR_RETRY == ti.state
def _env_var_check_callback(self):
assert 'test_echo_env_variables' == os.environ['AIRFLOW_CTX_DAG_ID']
assert 'hive_in_python_op' == os.environ['AIRFLOW_CTX_TASK_ID']
assert DEFAULT_DATE.isoformat() == os.environ['AIRFLOW_CTX_EXECUTION_DATE']
assert DagRun.generate_run_id(DagRunType.MANUAL, DEFAULT_DATE) == os.environ['AIRFLOW_CTX_DAG_RUN_ID']
def test_echo_env_variables(self, dag_maker):
with dag_maker(
'test_echo_env_variables',
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE + datetime.timedelta(days=10),
):
op = PythonOperator(task_id='hive_in_python_op', python_callable=self._env_var_check_callback)
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
external_trigger=False,
)
ti = TI(task=op, run_id=dr.run_id)
ti.state = State.RUNNING
session = settings.Session()
session.merge(ti)
session.commit()
ti._run_raw_task()
ti.refresh_from_db()
assert ti.state == State.SUCCESS
@patch.object(Stats, 'incr')
def test_task_stats(self, stats_mock, create_task_instance):
ti = create_task_instance(
dag_id='test_task_start_end_stats',
end_date=DEFAULT_DATE + datetime.timedelta(days=10),
state=State.RUNNING,
)
stats_mock.reset_mock()
session = settings.Session()
session.merge(ti)
session.commit()
ti._run_raw_task()
ti.refresh_from_db()
stats_mock.assert_called_with(f'ti.finish.{ti.dag_id}.{ti.task_id}.{ti.state}')
assert call(f'ti.start.{ti.dag_id}.{ti.task_id}') in stats_mock.mock_calls
assert stats_mock.call_count == 4
def test_command_as_list(self, create_task_instance):
ti = create_task_instance()
ti.task.dag.fileloc = os.path.join(TEST_DAGS_FOLDER, 'x.py')
assert ti.command_as_list() == [
'airflow',
'tasks',
'run',
ti.dag_id,
ti.task_id,
ti.run_id,
'--subdir',
'DAGS_FOLDER/x.py',
]
def test_generate_command_default_param(self):
dag_id = 'test_generate_command_default_param'
task_id = 'task'
assert_command = ['airflow', 'tasks', 'run', dag_id, task_id, 'run_1']
generate_command = TI.generate_command(dag_id=dag_id, task_id=task_id, run_id='run_1')
assert assert_command == generate_command
def test_generate_command_specific_param(self):
dag_id = 'test_generate_command_specific_param'
task_id = 'task'
assert_command = [
'airflow',
'tasks',
'run',
dag_id,
task_id,
'run_1',
'--mark-success',
'--map-index',
'0',
]
generate_command = TI.generate_command(
dag_id=dag_id, task_id=task_id, run_id='run_1', mark_success=True, map_index=0
)
assert assert_command == generate_command
@provide_session
def test_get_rendered_template_fields(self, dag_maker, session=None):
with dag_maker('test-dag', session=session) as dag:
task = BashOperator(task_id='op1', bash_command="{{ task.task_id }}")
dag.fileloc = TEST_DAGS_FOLDER + '/test_get_k8s_pod_yaml.py'
ti = dag_maker.create_dagrun().task_instances[0]
ti.task = task
session.add(RenderedTaskInstanceFields(ti))
session.flush()
# Create new TI for the same Task
new_task = BashOperator(task_id='op12', bash_command="{{ task.task_id }}", dag=dag)
new_ti = TI(task=new_task, run_id=ti.run_id)
new_ti.get_rendered_template_fields(session=session)
assert "op1" == ti.task.bash_command
# CleanUp
with create_session() as session:
session.query(RenderedTaskInstanceFields).delete()
@mock.patch.dict(os.environ, {"AIRFLOW_IS_K8S_EXECUTOR_POD": "True"})
@mock.patch("airflow.settings.pod_mutation_hook")
def test_render_k8s_pod_yaml(self, pod_mutation_hook, create_task_instance):
ti = create_task_instance(
dag_id='test_render_k8s_pod_yaml',
run_id='test_run_id',
task_id='op1',
execution_date=DEFAULT_DATE,
)
expected_pod_spec = {
'metadata': {
'annotations': {
'dag_id': 'test_render_k8s_pod_yaml',
'execution_date': '2016-01-01T00:00:00+00:00',
'task_id': 'op1',
'try_number': '1',
},
'labels': {
'airflow-worker': '0',
'airflow_version': version,
'dag_id': 'test_render_k8s_pod_yaml',
'execution_date': '2016-01-01T00_00_00_plus_00_00',
'kubernetes_executor': 'True',
'task_id': 'op1',
'try_number': '1',
},
'name': mock.ANY,
'namespace': 'default',
},
'spec': {
'containers': [
{
'args': [
'airflow',
'tasks',
'run',
'test_render_k8s_pod_yaml',
'op1',
'test_run_id',
'--subdir',
__file__,
],
'name': 'base',
'env': [{'name': 'AIRFLOW_IS_K8S_EXECUTOR_POD', 'value': 'True'}],
}
]
},
}
assert ti.render_k8s_pod_yaml() == expected_pod_spec
pod_mutation_hook.assert_called_once_with(mock.ANY)
@mock.patch.dict(os.environ, {"AIRFLOW_IS_K8S_EXECUTOR_POD": "True"})
@mock.patch.object(RenderedTaskInstanceFields, 'get_k8s_pod_yaml')
def test_get_rendered_k8s_spec(self, rtif_get_k8s_pod_yaml, create_task_instance):
# Create new TI for the same Task
ti = create_task_instance()
patcher = mock.patch.object(ti, 'render_k8s_pod_yaml', autospec=True)
fake_spec = {"ermagawds": "pods"}
session = mock.Mock()
with patcher as render_k8s_pod_yaml:
rtif_get_k8s_pod_yaml.return_value = fake_spec
assert ti.get_rendered_k8s_spec(session) == fake_spec
rtif_get_k8s_pod_yaml.assert_called_once_with(ti, session=session)
render_k8s_pod_yaml.assert_not_called()
# Now test that when we _dont_ find it in the DB, it calls render_k8s_pod_yaml
rtif_get_k8s_pod_yaml.return_value = None
render_k8s_pod_yaml.return_value = fake_spec
assert ti.get_rendered_k8s_spec(session) == fake_spec
render_k8s_pod_yaml.assert_called_once()
def test_set_state_up_for_retry(self, create_task_instance):
ti = create_task_instance(state=State.RUNNING)
start_date = timezone.utcnow()
ti.start_date = start_date
ti.set_state(State.UP_FOR_RETRY)
assert ti.state == State.UP_FOR_RETRY
assert ti.start_date == start_date, "Start date should have been left alone"
assert ti.start_date < ti.end_date
assert ti.duration > 0
def test_refresh_from_db(self, create_task_instance):
run_date = timezone.utcnow()
expected_values = {
"task_id": "test_refresh_from_db_task",
"dag_id": "test_refresh_from_db_dag",
"run_id": "test",
"map_index": -1,
"start_date": run_date + datetime.timedelta(days=1),
"end_date": run_date + datetime.timedelta(days=1, seconds=1, milliseconds=234),
"duration": 1.234,
"state": State.SUCCESS,
"_try_number": 1,
"max_tries": 1,
"hostname": "some_unique_hostname",
"unixname": "some_unique_unixname",
"job_id": 1234,
"pool": "some_fake_pool_id",
"pool_slots": 25,
"queue": "some_queue_id",
"priority_weight": 123,
"operator": "some_custom_operator",
"queued_dttm": run_date + datetime.timedelta(hours=1),
"queued_by_job_id": 321,
"pid": 123,
"executor_config": {"Some": {"extra": "information"}},
"external_executor_id": "some_executor_id",
"trigger_timeout": None,
"trigger_id": None,
"next_kwargs": None,
"next_method": None,
}
# Make sure we aren't missing any new value in our expected_values list.
expected_keys = {f"task_instance.{key.lstrip('_')}" for key in expected_values}
assert {str(c) for c in TI.__table__.columns} == expected_keys, (
"Please add all non-foreign values of TaskInstance to this list. "
"This prevents refresh_from_db() from missing a field."
)
ti = create_task_instance(task_id=expected_values['task_id'], dag_id=expected_values['dag_id'])
for key, expected_value in expected_values.items():
setattr(ti, key, expected_value)
with create_session() as session:
session.merge(ti)
session.commit()
mock_task = mock.MagicMock()
mock_task.task_id = expected_values["task_id"]
mock_task.dag_id = expected_values["dag_id"]
ti = TI(task=mock_task, run_id="test")
ti.refresh_from_db()
for key, expected_value in expected_values.items():
assert hasattr(ti, key), f"Key {key} is missing in the TaskInstance."
assert (
getattr(ti, key) == expected_value
), f"Key: {key} had different values. Make sure it loads it in the refresh refresh_from_db()"
def test_operator_field_with_serialization(self, create_task_instance):
ti = create_task_instance()
assert ti.task.task_type == 'DummyOperator'
# Verify that ti.operator field renders correctly "without" Serialization
assert ti.operator == "DummyOperator"
serialized_op = SerializedBaseOperator.serialize_operator(ti.task)
deserialized_op = SerializedBaseOperator.deserialize_operator(serialized_op)
assert deserialized_op.task_type == 'DummyOperator'
# Verify that ti.operator field renders correctly "with" Serialization
ser_ti = TI(task=deserialized_op, run_id=None)
assert ser_ti.operator == "DummyOperator"
@pytest.mark.parametrize("pool_override", [None, "test_pool2"])
def test_refresh_from_task(pool_override):
task = DummyOperator(
task_id="dummy",
queue="test_queue",
pool="test_pool1",
pool_slots=3,
priority_weight=10,
run_as_user="test",
retries=30,
executor_config={"KubernetesExecutor": {"image": "myCustomDockerImage"}},
)
ti = TI(task, run_id=None)
ti.refresh_from_task(task, pool_override=pool_override)
assert ti.queue == task.queue
if pool_override:
assert ti.pool == pool_override
else:
assert ti.pool == task.pool
assert ti.pool_slots == task.pool_slots
assert ti.priority_weight == task.priority_weight_total
assert ti.run_as_user == task.run_as_user
assert ti.max_tries == task.retries
assert ti.executor_config == task.executor_config
assert ti.operator == DummyOperator.__name__
# Test that refresh_from_task does not reset ti.max_tries
expected_max_tries = task.retries + 10
ti.max_tries = expected_max_tries
ti.refresh_from_task(task)
assert ti.max_tries == expected_max_tries
class TestRunRawTaskQueriesCount:
"""
These tests are designed to detect changes in the number of queries executed
when calling _run_raw_task
"""
@staticmethod
def _clean():
db.clear_db_runs()
db.clear_db_pools()
db.clear_db_dags()
db.clear_db_sla_miss()
db.clear_db_import_errors()
def setup_method(self) -> None:
self._clean()
def teardown_method(self) -> None:
self._clean()
@pytest.mark.parametrize("expected_query_count, mark_success", [(12, False), (5, True)])
@provide_session
def test_execute_queries_count(
self, expected_query_count, mark_success, create_task_instance, session=None
):
ti = create_task_instance(session=session, state=State.RUNNING)
assert ti.dag_run
# an extra query is fired in RenderedTaskInstanceFields.delete_old_records
# for other DBs. delete_old_records is called only when mark_success is False
expected_query_count_based_on_db = (
expected_query_count + 1
if session.bind.dialect.name == "mssql" and expected_query_count > 0 and not mark_success
else expected_query_count
)
session.flush()
with assert_queries_count(expected_query_count_based_on_db):
ti._run_raw_task(mark_success=mark_success, session=session)
@provide_session
def test_execute_queries_count_store_serialized(self, create_task_instance, session=None):
ti = create_task_instance(session=session, state=State.RUNNING)
assert ti.dag_run
# an extra query is fired in RenderedTaskInstanceFields.delete_old_records
# for other DBs
expected_query_count_based_on_db = 5
session.flush()
with assert_queries_count(expected_query_count_based_on_db):
ti._run_raw_task(session)
@pytest.mark.parametrize("mode", ["poke", "reschedule"])
@pytest.mark.parametrize("retries", [0, 1])
def test_sensor_timeout(mode, retries, dag_maker):
"""
Test that AirflowSensorTimeout does not cause sensor to retry.
"""
def timeout():
raise AirflowSensorTimeout
mock_on_failure = mock.MagicMock()
with dag_maker(dag_id=f'test_sensor_timeout_{mode}_{retries}'):
PythonSensor(
task_id='test_raise_sensor_timeout',
python_callable=timeout,
on_failure_callback=mock_on_failure,
retries=retries,
mode=mode,
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
with pytest.raises(AirflowSensorTimeout):
ti.run()
assert mock_on_failure.called
assert ti.state == State.FAILED
class TestTaskInstanceRecordTaskMapXComPush:
"""Test TI.xcom_push() correctly records return values for task-mapping."""
def setup_class(self):
"""Ensure we start fresh."""
with create_session() as session:
session.query(TaskMap).delete()
@pytest.mark.parametrize("xcom_value", [[1, 2, 3], {"a": 1, "b": 2}, "abc"])
def test_not_recorded_for_unused(self, dag_maker, xcom_value):
"""A value not used for task-mapping should not be recorded."""
with dag_maker(dag_id="test_not_recorded_for_unused") as dag:
@dag.task()
def push_something():
return xcom_value
push_something()
ti = next(ti for ti in dag_maker.create_dagrun().task_instances if ti.task_id == "push_something")
ti.run()
assert dag_maker.session.query(TaskMap).count() == 0
def test_error_if_unmappable_type(self, dag_maker):
"""If an unmappable return value is used to map, fail the task that pushed the XCom."""
with dag_maker(dag_id="test_not_recorded_for_unused") as dag:
@dag.task()
def push_something():
return "abc"
@dag.task()
def pull_something(value):
print(value)
pull_something.map(value=push_something())
ti = next(ti for ti in dag_maker.create_dagrun().task_instances if ti.task_id == "push_something")
with pytest.raises(UnmappableXComTypePushed) as ctx:
ti.run()
assert dag_maker.session.query(TaskMap).count() == 0
assert ti.state == TaskInstanceState.FAILED
assert str(ctx.value) == "unmappable return type 'str'"
@conf_vars({("core", "max_map_length"): "1"})
def test_error_if_unmappable_length(self, dag_maker):
"""If an unmappable return value is used to map, fail the task that pushed the XCom."""
with dag_maker(dag_id="test_not_recorded_for_unused") as dag:
@dag.task()
def push_something():
return [1, 2]
@dag.task()
def pull_something(value):
print(value)
pull_something.map(value=push_something())
ti = next(ti for ti in dag_maker.create_dagrun().task_instances if ti.task_id == "push_something")
with pytest.raises(UnmappableXComLengthPushed) as ctx:
ti.run()
assert dag_maker.session.query(TaskMap).count() == 0
assert ti.state == TaskInstanceState.FAILED
assert str(ctx.value) == "unmappable return value length: 2 > 1"
@pytest.mark.parametrize(
"xcom_value, expected_length, expected_keys",
[
([1, 2, 3], 3, None),
({"a": 1, "b": 2}, 2, ["a", "b"]),
],
)
def test_written_task_map(self, dag_maker, xcom_value, expected_length, expected_keys):
"""Return value should be recorded in TaskMap if it's used by a downstream to map."""
with dag_maker(dag_id="test_written_task_map") as dag:
@dag.task()
def push_something():
return xcom_value
@dag.task()
def pull_something(value):
print(value)
pull_something.map(value=push_something())
dag_run = dag_maker.create_dagrun()
ti = next(ti for ti in dag_run.task_instances if ti.task_id == "push_something")
ti.run()
task_map = dag_maker.session.query(TaskMap).one()
assert task_map.dag_id == "test_written_task_map"
assert task_map.task_id == "push_something"
assert task_map.run_id == dag_run.run_id
assert task_map.map_index == -1
assert task_map.length == expected_length
assert task_map.keys == expected_keys
|
[] |
[] |
[
"AIRFLOW_CTX_DAG_RUN_ID",
"AIRFLOW_CTX_TASK_ID",
"AIRFLOW_CTX_EXECUTION_DATE",
"AIRFLOW_CTX_DAG_ID"
] |
[]
|
["AIRFLOW_CTX_DAG_RUN_ID", "AIRFLOW_CTX_TASK_ID", "AIRFLOW_CTX_EXECUTION_DATE", "AIRFLOW_CTX_DAG_ID"]
|
python
| 4 | 0 | |
mne/report.py
|
"""Generate self-contained HTML reports from MNE objects."""
# Authors: Alex Gramfort <[email protected]>
# Mainak Jas <[email protected]>
# Teon Brooks <[email protected]>
#
# License: BSD (3-clause)
import base64
from io import BytesIO
import os
import os.path as op
import fnmatch
import re
import codecs
from shutil import copyfile
import time
from glob import glob
import warnings
import webbrowser
import numpy as np
from . import read_evokeds, read_events, pick_types, read_cov
from .fixes import _get_img_fdata
from .io import read_raw_fif, read_info
from .io.pick import _DATA_CH_TYPES_SPLIT
from .utils import (logger, verbose, get_subjects_dir, warn,
fill_doc, _check_option)
from .viz import plot_events, plot_alignment, plot_cov
from .viz._3d import _plot_mri_contours
from .forward import read_forward_solution
from .epochs import read_epochs
from .minimum_norm import read_inverse_operator
from .parallel import parallel_func, check_n_jobs
from .externals.tempita import HTMLTemplate, Template
from .externals.h5io import read_hdf5, write_hdf5
VALID_EXTENSIONS = ['raw.fif', 'raw.fif.gz', 'sss.fif', 'sss.fif.gz',
'-eve.fif', '-eve.fif.gz', '-cov.fif', '-cov.fif.gz',
'-trans.fif', '-trans.fif.gz', '-fwd.fif', '-fwd.fif.gz',
'-epo.fif', '-epo.fif.gz', '-inv.fif', '-inv.fif.gz',
'-ave.fif', '-ave.fif.gz', 'T1.mgz']
SECTION_ORDER = ['raw', 'events', 'epochs', 'evoked', 'covariance', 'trans',
'mri', 'forward', 'inverse']
###############################################################################
# PLOTTING FUNCTIONS
def _ndarray_to_fig(img):
"""Convert to MPL figure, adapted from matplotlib.image.imsave."""
figsize = np.array(img.shape[:2][::-1]) / 100.
fig = _figure_agg(dpi=100, figsize=figsize, frameon=False)
fig.figimage(img)
return fig
def _fig_to_img(fig, image_format='png', scale=None, **kwargs):
"""Plot figure and create a binary image."""
# fig can be ndarray, mpl Figure, Mayavi Figure, or callable that produces
# a mpl Figure
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
if isinstance(fig, np.ndarray):
fig = _ndarray_to_fig(fig)
elif callable(fig):
plt.close('all')
fig = fig(**kwargs)
elif not isinstance(fig, Figure):
from .viz.backends.renderer import (
_check_3d_figure, _take_3d_screenshot,
_close_3d_figure, MNE_3D_BACKEND_TESTING
)
_check_3d_figure(figure=fig)
if not MNE_3D_BACKEND_TESTING:
img = _take_3d_screenshot(figure=fig)
else: # Testing mode
img = np.zeros((2, 2, 3))
_close_3d_figure(figure=fig)
fig = _ndarray_to_fig(img)
output = BytesIO()
if scale is not None:
_scale_mpl_figure(fig, scale)
logger.debug('Saving figure %s with dpi %s'
% (fig.get_size_inches(), fig.get_dpi()))
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore') # incompatible axes
fig.savefig(output, format=image_format, dpi=fig.get_dpi(),
bbox_to_inches='tight')
plt.close(fig)
output = output.getvalue()
return (output.decode('utf-8') if image_format == 'svg' else
base64.b64encode(output).decode('ascii'))
def _scale_mpl_figure(fig, scale):
"""Magic scaling helper.
Keeps font-size and artist sizes constant
0.5 : current font - 4pt
2.0 : current font + 4pt
XXX it's unclear why this works, but good to go for most cases
"""
scale = float(scale)
fig.set_size_inches(fig.get_size_inches() * scale)
fig.set_dpi(fig.get_dpi() * scale)
import matplotlib as mpl
if scale >= 1:
sfactor = scale ** 2
else:
sfactor = -((1. / scale) ** 2)
for text in fig.findobj(mpl.text.Text):
fs = text.get_fontsize()
new_size = fs + sfactor
if new_size <= 0:
raise ValueError('could not rescale matplotlib fonts, consider '
'increasing "scale"')
text.set_fontsize(new_size)
fig.canvas.draw()
def _figs_to_mrislices(sl, n_jobs, **kwargs):
import matplotlib.pyplot as plt
plt.close('all')
use_jobs = min(n_jobs, max(1, len(sl)))
parallel, p_fun, _ = parallel_func(_plot_mri_contours, use_jobs)
outs = parallel(p_fun(slices=s, **kwargs)
for s in np.array_split(sl, use_jobs))
for o in outs[1:]:
outs[0] += o
return outs[0]
def _iterate_trans_views(function, **kwargs):
"""Auxiliary function to iterate over views in trans fig."""
import matplotlib.pyplot as plt
from .viz.backends.renderer import (
_check_3d_figure, _take_3d_screenshot, _close_all,
_set_3d_view, MNE_3D_BACKEND_TESTING
)
fig = function(**kwargs)
_check_3d_figure(fig)
views = [(90, 90), (0, 90), (0, -90)]
fig2, axes = plt.subplots(1, len(views))
for view, ax in zip(views, axes):
_set_3d_view(fig, azimuth=view[0], elevation=view[1],
focalpoint=None, distance=None)
if not MNE_3D_BACKEND_TESTING:
im = _take_3d_screenshot(figure=fig)
else: # Testing mode
im = np.zeros((2, 2, 3))
ax.imshow(im)
ax.axis('off')
_close_all()
img = _fig_to_img(fig2, image_format='png')
return img
###############################################################################
# TOC FUNCTIONS
def _is_bad_fname(fname):
"""Identify bad file naming patterns and highlight them in the TOC."""
if fname.endswith('(whitened)'):
fname = fname[:-11]
if not fname.endswith(tuple(VALID_EXTENSIONS + ['bem', 'custom'])):
return 'red'
else:
return ''
def _get_fname(fname):
"""Get fname without -#-."""
if '-#-' in fname:
fname = fname.split('-#-')[0]
else:
fname = op.basename(fname)
fname = ' ... %s' % fname
return fname
def _get_toc_property(fname):
"""Assign class names to TOC elements to allow toggling with buttons."""
if fname.endswith(('-eve.fif', '-eve.fif.gz')):
div_klass = 'events'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-ave.fif', '-ave.fif.gz')):
div_klass = 'evoked'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-cov.fif', '-cov.fif.gz')):
div_klass = 'covariance'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('raw.fif', 'raw.fif.gz',
'sss.fif', 'sss.fif.gz')):
div_klass = 'raw'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-trans.fif', '-trans.fif.gz')):
div_klass = 'trans'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-fwd.fif', '-fwd.fif.gz')):
div_klass = 'forward'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-inv.fif', '-inv.fif.gz')):
div_klass = 'inverse'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('-epo.fif', '-epo.fif.gz')):
div_klass = 'epochs'
tooltip = fname
text = op.basename(fname)
elif fname.endswith(('.nii', '.nii.gz', '.mgh', '.mgz')):
div_klass = 'mri'
tooltip = 'MRI'
text = 'MRI'
elif fname.endswith(('bem')):
div_klass = 'mri'
tooltip = 'MRI'
text = 'MRI'
elif fname.endswith('(whitened)'):
div_klass = 'evoked'
tooltip = fname
text = op.basename(fname[:-11]) + '(whitened)'
else:
div_klass = fname.split('-#-')[1]
tooltip = fname.split('-#-')[0]
text = fname.split('-#-')[0]
return div_klass, tooltip, text
def _iterate_files(report, fnames, info, cov, baseline, sfreq, on_error,
image_format):
"""Parallel process in batch mode."""
htmls, report_fnames, report_sectionlabels = [], [], []
def _update_html(html, report_fname, report_sectionlabel):
"""Update the lists above."""
htmls.append(html)
report_fnames.append(report_fname)
report_sectionlabels.append(report_sectionlabel)
for fname in fnames:
logger.info("Rendering : %s"
% op.join('...' + report.data_path[-20:],
fname))
try:
if fname.endswith(('raw.fif', 'raw.fif.gz',
'sss.fif', 'sss.fif.gz')):
html = report._render_raw(fname)
report_fname = fname
report_sectionlabel = 'raw'
elif fname.endswith(('-fwd.fif', '-fwd.fif.gz')):
html = report._render_forward(fname)
report_fname = fname
report_sectionlabel = 'forward'
elif fname.endswith(('-inv.fif', '-inv.fif.gz')):
html = report._render_inverse(fname)
report_fname = fname
report_sectionlabel = 'inverse'
elif fname.endswith(('-ave.fif', '-ave.fif.gz')):
if cov is not None:
html = report._render_whitened_evoked(fname, cov, baseline,
image_format)
report_fname = fname + ' (whitened)'
report_sectionlabel = 'evoked'
_update_html(html, report_fname, report_sectionlabel)
html = report._render_evoked(fname, baseline, image_format)
report_fname = fname
report_sectionlabel = 'evoked'
elif fname.endswith(('-eve.fif', '-eve.fif.gz')):
html = report._render_eve(fname, sfreq, image_format)
report_fname = fname
report_sectionlabel = 'events'
elif fname.endswith(('-epo.fif', '-epo.fif.gz')):
html = report._render_epochs(fname, image_format)
report_fname = fname
report_sectionlabel = 'epochs'
elif (fname.endswith(('-cov.fif', '-cov.fif.gz')) and
report.info_fname is not None):
html = report._render_cov(fname, info, image_format)
report_fname = fname
report_sectionlabel = 'covariance'
elif (fname.endswith(('-trans.fif', '-trans.fif.gz')) and
report.info_fname is not None and report.subjects_dir
is not None and report.subject is not None):
html = report._render_trans(fname, report.data_path, info,
report.subject,
report.subjects_dir)
report_fname = fname
report_sectionlabel = 'trans'
else:
html = None
report_fname = None
report_sectionlabel = None
except Exception as e:
if on_error == 'warn':
warn('Failed to process file %s:\n"%s"' % (fname, e))
elif on_error == 'raise':
raise
html = None
report_fname = None
report_sectionlabel = None
_update_html(html, report_fname, report_sectionlabel)
return htmls, report_fnames, report_sectionlabels
def open_report(fname, **params):
"""Read a saved report or, if it doesn't exist yet, create a new one.
The returned report can be used as a context manager, in which case any
changes to the report are saved when exiting the context block.
Parameters
----------
fname : str
The file containing the report, stored in the HDF5 format. If the file
does not exist yet, a new report is created that will be saved to the
specified file.
**params : kwargs
When creating a new report, any named parameters other than ``fname``
are passed to the ``__init__`` function of the `Report` object. When
reading an existing report, the parameters are checked with the
loaded report and an exception is raised when they don't match.
Returns
-------
report : instance of Report
The report.
"""
if op.exists(fname):
# Check **params with the loaded report
state = read_hdf5(fname, title='mnepython')
for param in params.keys():
if param not in state:
raise ValueError('The loaded report has no attribute %s' %
param)
if params[param] != state[param]:
raise ValueError("Attribute '%s' of loaded report does not "
"match the given parameter." % param)
report = Report()
report.__setstate__(state)
else:
report = Report(**params)
# Keep track of the filename in case the Report object is used as a context
# manager.
report._fname = fname
return report
###############################################################################
# IMAGE FUNCTIONS
def _figure_agg(**kwargs):
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
fig = Figure(**kwargs)
FigureCanvas(fig)
return fig
def _build_image_png(data, cmap='gray'):
"""Build an image encoded in base64."""
import matplotlib.pyplot as plt
figsize = data.shape[::-1]
if figsize[0] == 1:
figsize = tuple(figsize[1:])
data = data[:, :, 0]
fig = _figure_agg(figsize=figsize, dpi=1.0, frameon=False)
cmap = getattr(plt.cm, cmap, plt.cm.gray)
fig.figimage(data, cmap=cmap)
output = BytesIO()
fig.savefig(output, dpi=fig.get_dpi(), format='png')
return base64.b64encode(output.getvalue()).decode('ascii')
def _iterate_sagittal_slices(array, limits=None):
"""Iterate sagittal slices."""
shape = array.shape[0]
for ind in range(shape):
if limits and ind not in limits:
continue
yield ind, array[ind, :, :]
def _iterate_axial_slices(array, limits=None):
"""Iterate axial slices."""
shape = array.shape[1]
for ind in range(shape):
if limits and ind not in limits:
continue
yield ind, array[:, ind, :]
def _iterate_coronal_slices(array, limits=None):
"""Iterate coronal slices."""
shape = array.shape[2]
for ind in range(shape):
if limits and ind not in limits:
continue
yield ind, np.flipud(np.rot90(array[:, :, ind]))
def _iterate_mri_slices(name, ind, global_id, slides_klass, data, cmap):
"""Auxiliary function for parallel processing of mri slices."""
img_klass = 'slideimg-%s' % name
caption = u'Slice %s %s' % (name, ind)
slice_id = '%s-%s-%s' % (name, global_id, ind)
div_klass = 'span12 %s' % slides_klass
img = _build_image_png(data, cmap=cmap)
first = True if ind == 0 else False
html = _build_html_image(img, slice_id, div_klass, img_klass, caption,
first, image_format='png')
return ind, html
###############################################################################
# HTML functions
def _build_html_image(img, id, div_klass, img_klass, caption=None,
show=True, image_format='png'):
"""Build a html image from a slice array."""
html = []
add_style = u'' if show else u'style="display: none"'
html.append(u'<li class="%s" id="%s" %s>' % (div_klass, id, add_style))
html.append(u'<div class="thumbnail">')
if image_format == 'png':
html.append(u'<img class="%s" alt="" style="width:90%%;" '
'src="data:image/png;base64,%s">'
% (img_klass, img))
else:
html.append(u'<div style="text-align:center;" class="%s">%s</div>'
% (img_klass, img))
html.append(u'</div>')
if caption:
html.append(u'<h4>%s</h4>' % caption)
html.append(u'</li>')
return u'\n'.join(html)
slider_template = HTMLTemplate(u"""
<script>$("#{{slider_id}}").slider({
range: "min",
/*orientation: "vertical",*/
min: {{minvalue}},
max: {{maxvalue}},
step: {{step}},
value: {{startvalue}},
create: function(event, ui) {
$(".{{klass}}").hide();
$("#{{klass}}-{{startvalue}}").show();},
stop: function(event, ui) {
var list_value = $("#{{slider_id}}").slider("value");
$(".{{klass}}").hide();
$("#{{klass}}-"+list_value).show();}
})</script>
""")
slider_full_template = Template(u"""
<li class="{{div_klass}}" id="{{id}}">
<h4>{{title}}</h4>
<div class="thumbnail">
<ul><li class="slider">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div id="{{slider_id}}"></div>
<ul class="thumbnail">
{{image_html}}
</ul>
{{html}}
</div>
</div>
</li></ul>
</div>
</li>
""")
def _build_html_slider(slices_range, slides_klass, slider_id,
start_value=None):
"""Build an html slider for a given slices range and a slices klass."""
if start_value is None:
start_value = slices_range[len(slices_range) // 2]
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore')
out = slider_template.substitute(
slider_id=slider_id, klass=slides_klass,
step=slices_range[1] - slices_range[0],
minvalue=slices_range[0], maxvalue=slices_range[-1],
startvalue=start_value)
return out
###############################################################################
# HTML scan renderer
header_template = Template(u"""
<!DOCTYPE html>
<html lang="{{lang}}">
<head>
{{include}}
<script type="text/javascript">
var toggle_state = false;
$(document).on('keydown', function (event) {
if (event.which == 84){
if (!toggle_state)
$('.has_toggle').trigger('click');
else if (toggle_state)
$('.has_toggle').trigger('click');
toggle_state = !toggle_state;
}
});
function togglebutton(class_name){
$(class_name).toggle();
if ($(class_name + '-btn').hasClass('active'))
$(class_name + '-btn').removeClass('active');
else
$(class_name + '-btn').addClass('active');
}
/* Scroll down on click to #id so that caption is not hidden
by navbar */
var shiftWindow = function() { scrollBy(0, -60) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
</script>
<style type="text/css">
body {
line-height: 1.5em;
font-family: arial, sans-serif;
}
h1 {
font-size: 30px;
text-align: center;
}
h4 {
text-align: center;
}
@link-color: @brand-primary;
@link-hover-color: darken(@link-color, 15%);
a{
color: @link-color;
&:hover {
color: @link-hover-color;
text-decoration: underline;
}
}
li{
list-style-type:none;
}
#wrapper {
text-align: left;
margin: 5em auto;
width: 700px;
}
#container{
position: relative;
}
#content{
margin-left: 22%;
margin-top: 60px;
width: 75%;
}
#toc {
margin-top: navbar-height;
position: fixed;
width: 20%;
height: 90%;
overflow: auto;
}
#toc li {
overflow: hidden;
padding-bottom: 2px;
margin-left: 20px;
}
#toc span {
float: left;
padding: 0 2px 3px 0;
}
div.footer {
background-color: #C0C0C0;
color: #000000;
padding: 3px 8px 3px 0;
clear: both;
font-size: 0.8em;
text-align: right;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header navbar-left">
<ul class="nav nav-pills"><li class="active">
<a class="navbar-btn" data-toggle="collapse"
data-target="#viewnavbar" href="javascript:void(0)">
></a></li></ul>
</div>
<h3 class="navbar-text" style="color:white">{{title}}</h3>
<ul class="nav nav-pills navbar-right" style="margin-top: 7px;"
id="viewnavbar">
{{for section in sections}}
<li class="active {{sectionvars[section]}}-btn">
<a href="javascript:void(0)"
onclick="togglebutton('.{{sectionvars[section]}}')"
class="has_toggle">
{{section if section != 'mri' else 'MRI'}}
</a>
</li>
{{endfor}}
</ul>
</div>
</nav>
""")
footer_template = HTMLTemplate(u"""
</div></body>
<div class="footer">
© Copyright 2012-{{current_year}}, MNE Developers.
Created on {{date}}.
Powered by <a href="http://mne.tools/">MNE.
</div>
</html>
""")
html_template = Template(u"""
<li class="{{div_klass}}" id="{{id}}">
<h4>{{caption}}</h4>
<div class="thumbnail">{{html}}</div>
</li>
""")
image_template = Template(u"""
{{default interactive = False}}
{{default width = 50}}
{{default id = False}}
{{default image_format = 'png'}}
{{default scale = None}}
{{default comment = None}}
<li class="{{div_klass}}" {{if id}}id="{{id}}"{{endif}}
{{if not show}}style="display: none"{{endif}}>
{{if caption}}
<h4>{{caption}}</h4>
{{endif}}
<div class="thumbnail">
{{if not interactive}}
{{if image_format == 'png'}}
{{if scale is not None}}
<img alt="" style="width:{{width}}%;"
src="data:image/png;base64,{{img}}">
{{else}}
<img alt=""
src="data:image/png;base64,{{img}}">
{{endif}}
{{elif image_format == 'gif'}}
{{if scale is not None}}
<img alt="" style="width:{{width}}%;"
src="data:image/gif;base64,{{img}}">
{{else}}
<img alt=""
src="data:image/gif;base64,{{img}}">
{{endif}}
{{elif image_format == 'svg'}}
<div style="text-align:center;">
{{img}}
</div>
{{endif}}
{{if comment is not None}}
<br><br>
<div style="text-align:center;">
<style>
p.test {word-wrap: break-word;}
</style>
<p class="test">
{{comment}}
</p>
</div>
{{endif}}
{{else}}
<center>{{interactive}}</center>
{{endif}}
</div>
</li>
""")
repr_template = Template(u"""
<li class="{{div_klass}}" id="{{id}}">
<h4>{{caption}}</h4><hr>
{{repr}}
<hr></li>
""")
raw_template = Template(u"""
<li class="{{div_klass}}" id="{{id}}">
<h4>{{caption}}</h4>
<table class="table table-hover">
<tr>
<th>Measurement date</th>
{{if meas_date is not None}}
<td>{{meas_date}}</td>
{{else}}<td>Unknown</td>{{endif}}
</tr>
<tr>
<th>Experimenter</th>
{{if info['experimenter'] is not None}}
<td>{{info['experimenter']}}</td>
{{else}}<td>Unknown</td>{{endif}}
</tr>
<tr>
<th>Digitized points</th>
{{if info['dig'] is not None}}
<td>{{len(info['dig'])}} points</td>
{{else}}
<td>Not available</td>
{{endif}}
</tr>
<tr>
<th>Good channels</th>
<td>{{n_mag}} magnetometer, {{n_grad}} gradiometer,
and {{n_eeg}} EEG channels</td>
</tr>
<tr>
<th>Bad channels</th>
{{if info['bads'] is not None}}
<td>{{', '.join(info['bads'])}}</td>
{{else}}<td>None</td>{{endif}}
</tr>
<tr>
<th>EOG channels</th>
<td>{{eog}}</td>
</tr>
<tr>
<th>ECG channels</th>
<td>{{ecg}}</td>
<tr>
<th>Measurement time range</th>
<td>{{u'%0.2f' % tmin}} to {{u'%0.2f' % tmax}} sec.</td>
</tr>
<tr>
<th>Sampling frequency</th>
<td>{{u'%0.2f' % info['sfreq']}} Hz</td>
</tr>
<tr>
<th>Highpass</th>
<td>{{u'%0.2f' % info['highpass']}} Hz</td>
</tr>
<tr>
<th>Lowpass</th>
<td>{{u'%0.2f' % info['lowpass']}} Hz</td>
</tr>
</table>
</li>
""")
toc_list = Template(u"""
<li class="{{div_klass}}">
{{if id}}
<a href="javascript:void(0)" onclick="window.location.hash={{id}};">
{{endif}}
<span title="{{tooltip}}" style="color:{{color}}"> {{text}}</span>
{{if id}}</a>{{endif}}
</li>
""")
def _check_scale(scale):
"""Ensure valid scale value is passed."""
if np.isscalar(scale) and scale <= 0:
raise ValueError('scale must be positive, not %s' % scale)
def _check_image_format(rep, image_format):
"""Ensure fmt is valid."""
if rep is None:
_check_option('image_format', image_format, ['png', 'svg'])
elif image_format is not None:
_check_option('image_format', image_format, ['png', 'svg', None])
else: # rep is not None and image_format is None
image_format = rep.image_format
return image_format
@fill_doc
class Report(object):
r"""Object for rendering HTML.
Parameters
----------
info_fname : str
Name of the file containing the info dictionary.
%(subjects_dir)s
subject : str | None
Subject name.
title : str
Title of the report.
cov_fname : str
Name of the file containing the noise covariance.
baseline : None or tuple of length 2 (default (None, 0))
The time interval to apply baseline correction for evokeds.
If None do not apply it. If baseline is (a, b)
the interval is between "a (s)" and "b (s)".
If a is None the beginning of the data is used
and if b is None then b is set to the end of the interval.
If baseline is equal to (None, None) all the time
interval is used.
The baseline (a, b) includes both endpoints, i.e. all
timepoints t such that a <= t <= b.
image_format : str
Default image format to use (default is 'png').
SVG uses vector graphics, so fidelity is higher but can increase
file size and browser image rendering time as well.
.. versionadded:: 0.15
raw_psd : bool | dict
If True, include PSD plots for raw files. Can be False (default) to
omit, True to plot, or a dict to pass as ``kwargs`` to
:meth:`mne.io.Raw.plot_psd`.
.. versionadded:: 0.17
%(verbose)s
Notes
-----
See :ref:`tut-report` for an introduction to using ``mne.Report``, and
:ref:`this example <ex-report>` for an example of customizing the report
with a slider.
.. versionadded:: 0.8.0
"""
def __init__(self, info_fname=None, subjects_dir=None,
subject=None, title=None, cov_fname=None, baseline=None,
image_format='png', raw_psd=False, verbose=None):
self.info_fname = info_fname
self.cov_fname = cov_fname
self.baseline = baseline
self.subjects_dir = get_subjects_dir(subjects_dir, raise_error=False)
self.subject = subject
self.title = title
self.image_format = _check_image_format(None, image_format)
self.verbose = verbose
self.initial_id = 0
self.html = []
self.fnames = [] # List of file names rendered
self.sections = [] # List of sections
self.lang = 'en-us' # language setting for the HTML file
self._sectionlabels = [] # Section labels
self._sectionvars = {} # Section variable names in js
# boolean to specify if sections should be ordered in natural
# order of processing (raw -> events ... -> inverse)
self._sort_sections = False
if not isinstance(raw_psd, bool) and not isinstance(raw_psd, dict):
raise TypeError('raw_psd must be bool or dict, got %s'
% (type(raw_psd),))
self.raw_psd = raw_psd
self._init_render() # Initialize the renderer
def __repr__(self):
"""Print useful info about report."""
s = '<Report | %d items' % len(self.fnames)
if self.title is not None:
s += ' | %s' % self.title
fnames = [_get_fname(f) for f in self.fnames]
if len(self.fnames) > 4:
s += '\n%s' % '\n'.join(fnames[:2])
s += '\n ...\n'
s += '\n'.join(fnames[-2:])
elif len(self.fnames) > 0:
s += '\n%s' % '\n'.join(fnames)
s += '\n>'
return s
def __len__(self):
"""Return the number of items in report."""
return len(self.fnames)
def _get_id(self):
"""Get id of plot."""
self.initial_id += 1
return self.initial_id
def _validate_input(self, items, captions, section, comments=None):
"""Validate input."""
if not isinstance(items, (list, tuple)):
items = [items]
if not isinstance(captions, (list, tuple)):
captions = [captions]
if not isinstance(comments, (list, tuple)):
if comments is None:
comments = [comments] * len(captions)
else:
comments = [comments]
if len(comments) != len(items):
raise ValueError('Comments and report items must have the same '
'length or comments should be None, got %d and %d'
% (len(comments), len(items)))
elif len(captions) != len(items):
raise ValueError('Captions and report items must have the same '
'length, got %d and %d'
% (len(captions), len(items)))
# Book-keeping of section names
if section not in self.sections:
self.sections.append(section)
self._sectionvars[section] = _clean_varnames(section)
return items, captions, comments
def remove(self, caption, section=None):
"""Remove a figure from the report.
The figure to remove is searched for by its caption. When searching by
caption, the section label can be specified as well to narrow down the
search. If multiple figures match the search criteria, the last one
will be removed.
Any empty sections will be removed as well.
Parameters
----------
caption : str
If set, search for the figure by caption.
section : str | None
If set, limit the search to the section with the given label.
Returns
-------
removed_index : int | None
The integer index of the figure that was removed, or ``None`` if no
figure matched the search criteria.
"""
# Construct the search pattern
pattern = r'^%s-#-.*-#-custom$' % caption
# Search for figures matching the search pattern, regardless of
# section
matches = [i for i, fname_ in enumerate(self.fnames)
if re.match(pattern, fname_)]
if section is not None:
# Narrow down the search to the given section
svar = self._sectionvars[section]
matches = [i for i in matches
if self._sectionlabels[i] == svar]
if len(matches) == 0:
return None
# Remove last occurrence
index = max(matches)
# Remove the figure
del self.fnames[index]
del self._sectionlabels[index]
del self.html[index]
# Remove any (now) empty sections.
# We use a list() to copy the _sectionvars dictionary, since we are
# removing elements during the loop.
for section_, sectionlabel_ in list(self._sectionvars.items()):
if sectionlabel_ not in self._sectionlabels:
self.sections.remove(section_)
del self._sectionvars[section_]
return index
def _add_or_replace(self, fname, sectionlabel, html, replace=False):
"""Append a figure to the report, or replace it if it already exists.
Parameters
----------
fname : str
A unique identifier for the figure. If a figure with this
identifier has already been added, it will be replaced.
sectionlabel : str
The section to place the figure in.
html : str
The HTML that contains the figure.
replace : bool
Existing figures are only replaced if this is set to ``True``.
Defaults to ``False``.
"""
assert isinstance(html, str) # otherwise later will break
if replace and fname in self.fnames:
# Find last occurrence of the figure
ind = max([i for i, existing in enumerate(self.fnames)
if existing == fname])
self.fnames[ind] = fname
self._sectionlabels[ind] = sectionlabel
self.html[ind] = html
else:
# Append new record
self.fnames.append(fname)
self._sectionlabels.append(sectionlabel)
self.html.append(html)
def add_figs_to_section(self, figs, captions, section='custom',
scale=None, image_format=None, comments=None,
replace=False):
"""Append custom user-defined figures.
Parameters
----------
figs : matplotlib.figure.Figure | mlab.Figure | array | list
A figure or a list of figures to add to the report. Each figure in
the list can be an instance of :class:`matplotlib.figure.Figure`,
:class:`mayavi.core.api.Scene`, or :class:`numpy.ndarray`.
captions : str | list of str
A caption or a list of captions to the figures.
section : str
Name of the section to place the figure in. If section already
exists, the figures will be appended to the end of the section.
scale : float | None | callable
Scale the images maintaining the aspect ratio.
If None, no scaling is applied. If float, scale will determine
the relative scaling (might not work for scale <= 1 depending on
font sizes). If function, should take a figure object as input
parameter. Defaults to None.
image_format : str | None
The image format to be used for the report, can be 'png' or 'svd'.
None (default) will use the default specified during Report
class construction.
comments : None | str | list of str
A string of text or a list of strings of text to be appended after
the figure.
replace : bool
If ``True``, figures already present that have the same caption
will be replaced. Defaults to ``False``.
"""
figs, captions, comments = self._validate_input(figs, captions,
section, comments)
image_format = _check_image_format(self, image_format)
_check_scale(scale)
for fig, caption, comment in zip(figs, captions, comments):
caption = 'custom plot' if caption == '' else caption
sectionvar = self._sectionvars[section]
global_id = self._get_id()
div_klass = self._sectionvars[section]
img_klass = self._sectionvars[section]
img = _fig_to_img(fig, image_format, scale)
html = image_template.substitute(img=img, id=global_id,
div_klass=div_klass,
img_klass=img_klass,
caption=caption,
show=True,
image_format=image_format,
comment=comment)
self._add_or_replace('%s-#-%s-#-custom' % (caption, sectionvar),
sectionvar, html, replace)
def add_images_to_section(self, fnames, captions, scale=None,
section='custom', comments=None, replace=False):
"""Append custom user-defined images.
Parameters
----------
fnames : str | list of str
A filename or a list of filenames from which images are read.
Images can be PNG, GIF or SVG.
captions : str | list of str
A caption or a list of captions to the images.
scale : float | None
Scale the images maintaining the aspect ratio.
Defaults to None. If None, no scaling will be applied.
section : str
Name of the section. If section already exists, the images
will be appended to the end of the section.
comments : None | str | list of str
A string of text or a list of strings of text to be appended after
the image.
replace : bool
If ``True``, figures already present that have the same caption
will be replaced. Defaults to ``False``.
"""
# Note: using scipy.misc is equivalent because scipy internally
# imports PIL anyway. It's not possible to redirect image output
# to binary string using scipy.misc.
fnames, captions, comments = self._validate_input(fnames, captions,
section, comments)
_check_scale(scale)
for fname, caption, comment in zip(fnames, captions, comments):
caption = 'custom plot' if caption == '' else caption
sectionvar = self._sectionvars[section]
global_id = self._get_id()
div_klass = self._sectionvars[section]
img_klass = self._sectionvars[section]
image_format = os.path.splitext(fname)[1][1:]
image_format = image_format.lower()
_check_option('image_format', image_format, ['png', 'gif', 'svg'])
# Convert image to binary string.
with open(fname, 'rb') as f:
img = base64.b64encode(f.read()).decode('ascii')
html = image_template.substitute(img=img, id=global_id,
image_format=image_format,
div_klass=div_klass,
img_klass=img_klass,
caption=caption,
width=scale,
comment=comment,
show=True)
self._add_or_replace('%s-#-%s-#-custom' % (caption, sectionvar),
sectionvar, html, replace)
def add_htmls_to_section(self, htmls, captions, section='custom',
replace=False):
"""Append htmls to the report.
Parameters
----------
htmls : str | list of str
An html str or a list of html str.
captions : str | list of str
A caption or a list of captions to the htmls.
section : str
Name of the section. If section already exists, the images
will be appended to the end of the section.
replace : bool
If ``True``, figures already present that have the same caption
will be replaced. Defaults to ``False``.
Notes
-----
.. versionadded:: 0.9.0
"""
htmls, captions, _ = self._validate_input(htmls, captions, section)
for html, caption in zip(htmls, captions):
caption = 'custom plot' if caption == '' else caption
sectionvar = self._sectionvars[section]
global_id = self._get_id()
div_klass = self._sectionvars[section]
self._add_or_replace(
'%s-#-%s-#-custom' % (caption, sectionvar), sectionvar,
html_template.substitute(div_klass=div_klass, id=global_id,
caption=caption, html=html), replace)
@fill_doc
def add_bem_to_section(self, subject, caption='BEM', section='bem',
decim=2, n_jobs=1, subjects_dir=None,
replace=False):
"""Render a bem slider html str.
Parameters
----------
subject : str
Subject name.
caption : str
A caption for the bem.
section : str
Name of the section. If section already exists, the bem
will be appended to the end of the section.
decim : int
Use this decimation factor for generating MRI/BEM images
(since it can be time consuming).
%(n_jobs)s
%(subjects_dir)s
replace : bool
If ``True``, figures already present that have the same caption
will be replaced. Defaults to ``False``.
Notes
-----
.. versionadded:: 0.9.0
"""
caption = 'custom plot' if caption == '' else caption
html = self._render_bem(subject=subject, subjects_dir=subjects_dir,
decim=decim, n_jobs=n_jobs, section=section,
caption=caption)
html, caption, _ = self._validate_input(html, caption, section)
sectionvar = self._sectionvars[section]
# convert list->str
assert isinstance(html, list)
html = u''.join(html)
self._add_or_replace('%s-#-%s-#-custom' % (caption[0], sectionvar),
sectionvar, html)
def add_slider_to_section(self, figs, captions=None, section='custom',
title='Slider', scale=None, image_format=None,
replace=False):
"""Render a slider of figs to the report.
Parameters
----------
figs : list of Figure
Each figure in the list can be an instance of
:class:`matplotlib.figure.Figure`,
:class:`mayavi.core.api.Scene`, or :class:`numpy.ndarray`.
Must have at least 2 elements.
captions : list of str | list of float | None
A list of captions to the figures. If float, a str will be
constructed as `%f s`. If None, it will default to
`Data slice %d`.
section : str
Name of the section. If section already exists, the figures
will be appended to the end of the section.
title : str
The title of the slider.
scale : float | None | callable
Scale the images maintaining the aspect ratio.
If None, no scaling is applied. If float, scale will determine
the relative scaling (might not work for scale <= 1 depending on
font sizes). If function, should take a figure object as input
parameter. Defaults to None.
image_format : str | None
The image format to be used for the report, can be 'png' or 'svd'.
None (default) will use the default specified during Report
class construction.
replace : bool
If ``True``, figures already present that have the same caption
will be replaced. Defaults to ``False``.
Notes
-----
.. versionadded:: 0.10.0
"""
_check_scale(scale)
image_format = _check_image_format(self, image_format)
if isinstance(figs[0], list):
raise NotImplementedError('`add_slider_to_section` '
'can only add one slider at a time.')
if len(figs) < 2:
raise ValueError('figs must be at least length 2, got %s'
% (len(figs),))
figs = [figs]
figs, _, _ = self._validate_input(figs, section, section)
figs = figs[0]
sectionvar = self._sectionvars[section]
global_id = self._get_id()
name = 'slider'
html = []
slides_klass = '%s-%s' % (name, global_id)
div_klass = 'span12 %s' % slides_klass
sl = np.arange(0, len(figs))
slices = []
img_klass = 'slideimg-%s' % name
if captions is None:
captions = ['Data slice %d' % ii for ii in sl]
elif isinstance(captions, (list, tuple, np.ndarray)):
if len(figs) != len(captions):
raise ValueError('Captions must be the same length as the '
'number of slides.')
if isinstance(captions[0], (float, int)):
captions = ['%0.3f s' % caption for caption in captions]
else:
raise TypeError('Captions must be None or an iterable of '
'float, int, str, Got %s' % type(captions))
for ii, (fig, caption) in enumerate(zip(figs, captions)):
img = _fig_to_img(fig, image_format, scale)
slice_id = '%s-%s-%s' % (name, global_id, sl[ii])
first = True if ii == 0 else False
slices.append(_build_html_image(img, slice_id, div_klass,
img_klass, caption, first,
image_format=image_format))
# Render the slider
slider_id = 'select-%s-%s' % (name, global_id)
# Render the slices
image_html = u'\n'.join(slices)
html.append(_build_html_slider(sl, slides_klass, slider_id,
start_value=0))
html = '\n'.join(html)
slider_klass = sectionvar
self._add_or_replace(
'%s-#-%s-#-custom' % (title, sectionvar), sectionvar,
slider_full_template.substitute(id=global_id, title=title,
div_klass=slider_klass,
slider_id=slider_id, html=html,
image_html=image_html))
###########################################################################
# HTML rendering
def _render_one_axis(self, slices_iter, name, global_id, cmap,
n_elements, n_jobs):
"""Render one axis of the array."""
global_id = global_id or name
html = []
html.append(u'<div class="col-xs-6 col-md-4">')
slides_klass = '%s-%s' % (name, global_id)
use_jobs = min(n_jobs, max(1, n_elements))
parallel, p_fun, _ = parallel_func(_iterate_mri_slices, use_jobs)
r = parallel(p_fun(name, ind, global_id, slides_klass, data, cmap)
for ind, data in slices_iter)
slices_range, slices = zip(*r)
# Render the slider
slider_id = 'select-%s-%s' % (name, global_id)
html.append(u'<div id="%s"></div>' % slider_id)
html.append(u'<ul class="thumbnail">')
# Render the slices
html.append(u'\n'.join(slices))
html.append(u'</ul>')
html.append(_build_html_slider(slices_range, slides_klass, slider_id))
html.append(u'</div>')
return '\n'.join(html)
###########################################################################
# global rendering functions
@verbose
def _init_render(self, verbose=None):
"""Initialize the renderer."""
inc_fnames = ['jquery.js', 'jquery-ui.min.js',
'bootstrap.min.js', 'jquery-ui.min.css',
'bootstrap.min.css']
include = list()
for inc_fname in inc_fnames:
logger.info('Embedding : %s' % inc_fname)
fname = op.join(op.dirname(__file__), 'html', inc_fname)
with open(fname, 'rb') as fid:
file_content = fid.read().decode('utf-8')
if inc_fname.endswith('.js'):
include.append(u'<script type="text/javascript">' +
file_content + u'</script>')
elif inc_fname.endswith('.css'):
include.append(u'<style type="text/css">' +
file_content + u'</style>')
self.include = ''.join(include)
@verbose
def parse_folder(self, data_path, pattern='*.fif', n_jobs=1, mri_decim=2,
sort_sections=True, on_error='warn', image_format=None,
render_bem=True, verbose=None):
r"""Render all the files in the folder.
Parameters
----------
data_path : str
Path to the folder containing data whose HTML report will be
created.
pattern : str | list of str
Filename pattern(s) to include in the report.
Example: [\*raw.fif, \*ave.fif] will include Raw as well as Evoked
files.
%(n_jobs)s
mri_decim : int
Use this decimation factor for generating MRI/BEM images
(since it can be time consuming).
sort_sections : bool
If True, sort sections in the order: raw -> events -> epochs
-> evoked -> covariance -> trans -> mri -> forward -> inverse.
on_error : str
What to do if a file cannot be rendered. Can be 'ignore',
'warn' (default), or 'raise'.
image_format : str | None
The image format to be used for the report, can be 'png' or 'svd'.
None (default) will use the default specified during Report
class construction.
.. versionadded:: 0.15
render_bem : bool
If True (default), try to render the BEM.
.. versionadded:: 0.16
%(verbose_meth)s
"""
image_format = _check_image_format(self, image_format)
_check_option('on_error', on_error, ['ignore', 'warn', 'raise'])
self._sort = sort_sections
n_jobs = check_n_jobs(n_jobs)
self.data_path = data_path
if self.title is None:
self.title = 'MNE Report for ...%s' % self.data_path[-20:]
if not isinstance(pattern, (list, tuple)):
pattern = [pattern]
# iterate through the possible patterns
fnames = list()
for p in pattern:
fnames.extend(sorted(_recursive_search(self.data_path, p)))
if self.info_fname is not None:
info = read_info(self.info_fname, verbose=False)
sfreq = info['sfreq']
else:
# only warn if relevant
if any(fname.endswith(('-cov.fif', '-cov.fif.gz'))
for fname in fnames):
warn('`info_fname` not provided. Cannot render '
'-cov.fif(.gz) files.')
if any(fname.endswith(('-trans.fif', '-trans.fif.gz'))
for fname in fnames):
warn('`info_fname` not provided. Cannot render '
'-trans.fif(.gz) files.')
info, sfreq = None, None
cov = None
if self.cov_fname is not None:
cov = read_cov(self.cov_fname)
baseline = self.baseline
# render plots in parallel; check that n_jobs <= # of files
logger.info('Iterating over %s potential files (this may take some '
'time)' % len(fnames))
use_jobs = min(n_jobs, max(1, len(fnames)))
parallel, p_fun, _ = parallel_func(_iterate_files, use_jobs)
r = parallel(p_fun(self, fname, info, cov, baseline, sfreq, on_error,
image_format)
for fname in np.array_split(fnames, use_jobs))
htmls, report_fnames, report_sectionlabels = zip(*r)
# combine results from n_jobs discarding plots not rendered
self.html = [html for html in sum(htmls, []) if html is not None]
self.fnames = [fname for fname in sum(report_fnames, []) if
fname is not None]
self._sectionlabels = [slabel for slabel in
sum(report_sectionlabels, [])
if slabel is not None]
# find unique section labels
self.sections = sorted(set(self._sectionlabels))
self._sectionvars = dict(zip(self.sections, self.sections))
# render mri
if render_bem:
if self.subjects_dir is not None and self.subject is not None:
logger.info('Rendering BEM')
self.html.append(self._render_bem(
self.subject, self.subjects_dir, mri_decim, n_jobs))
self.fnames.append('bem')
self._sectionlabels.append('mri')
else:
warn('`subjects_dir` and `subject` not provided. Cannot '
'render MRI and -trans.fif(.gz) files.')
def _get_state_params(self):
"""Obtain all fields that are in the state dictionary of this object.
Returns
-------
non_opt_params : list of str
All parameters that must be present in the state dictionary.
opt_params : list of str
All parameters that are optionally present in the state dictionary.
"""
# Note: self._fname is not part of the state
return (['baseline', 'cov_fname', 'fnames', 'html', 'include',
'image_format', 'info_fname', 'initial_id', 'raw_psd',
'_sectionlabels', 'sections', '_sectionvars',
'_sort_sections', 'subjects_dir', 'subject', 'title',
'verbose'],
['data_path', 'lang', '_sort'])
def __getstate__(self):
"""Get the state of the report as a dictionary."""
state = dict()
non_opt_params, opt_params = self._get_state_params()
for param in non_opt_params:
state[param] = getattr(self, param)
for param in opt_params:
if hasattr(self, param):
state[param] = getattr(self, param)
return state
def __setstate__(self, state):
"""Set the state of the report."""
non_opt_params, opt_params = self._get_state_params()
for param in non_opt_params:
setattr(self, param, state[param])
for param in opt_params:
if param in state:
setattr(self, param, state[param])
return state
def save(self, fname=None, open_browser=True, overwrite=False):
"""Save the report and optionally open it in browser.
Parameters
----------
fname : str | None
File name of the report. If the file name ends in '.h5' or '.hdf5',
the report is saved in HDF5 format, so it can later be loaded again
with :func:`open_report`. If the file name ends in anything else,
the report is rendered to HTML. If ``None``, the report is saved to
'report.html' in the current working directory.
Defaults to ``None``.
open_browser : bool
When saving to HTML, open the rendered HTML file browser after
saving if True. Defaults to True.
overwrite : bool
If True, overwrite report if it already exists. Defaults to False.
Returns
-------
fname : str
The file name to which the report was saved.
"""
if fname is None:
if not hasattr(self, 'data_path'):
self.data_path = os.getcwd()
warn('`data_path` not provided. Using %s instead'
% self.data_path)
fname = op.realpath(op.join(self.data_path, 'report.html'))
else:
fname = op.realpath(fname)
if not overwrite and op.isfile(fname):
msg = ('Report already exists at location %s. '
'Overwrite it (y/[n])? '
% fname)
answer = input(msg)
if answer.lower() == 'y':
overwrite = True
_, ext = op.splitext(fname)
is_hdf5 = ext.lower() in ['.h5', '.hdf5']
if overwrite or not op.isfile(fname):
logger.info('Saving report to location %s' % fname)
if is_hdf5:
write_hdf5(fname, self.__getstate__(), overwrite=overwrite,
title='mnepython')
else:
self._render_toc()
# Annotate the HTML with a TOC and footer.
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore')
html = footer_template.substitute(
date=time.strftime("%B %d, %Y"),
current_year=time.strftime("%Y"))
self.html.append(html)
# Writing to disk may fail. However, we need to make sure that
# the TOC and footer are removed regardless, otherwise they
# will be duplicated when the user attempts to save again.
try:
# Write HTML
with codecs.open(fname, 'w', 'utf-8') as fobj:
fobj.write(_fix_global_ids(u''.join(self.html)))
finally:
self.html.pop(0)
self.html.pop(0)
self.html.pop()
building_doc = os.getenv('_MNE_BUILDING_DOC', '').lower() == 'true'
if open_browser and not is_hdf5 and not building_doc:
webbrowser.open_new_tab('file://' + fname)
self.fname = fname
return fname
def __enter__(self):
"""Do nothing when entering the context block."""
return self
def __exit__(self, type, value, traceback):
"""Save the report when leaving the context block."""
if self._fname is not None:
self.save(self._fname, open_browser=False, overwrite=True)
@verbose
def _render_toc(self, verbose=None):
"""Render the Table of Contents."""
logger.info('Rendering : Table of Contents')
html_toc = u'<div id="container">'
html_toc += u'<div id="toc"><center><h4>CONTENTS</h4></center>'
global_id = 1
# Reorder self.sections to reflect natural ordering
if self._sort_sections:
sections = list(set(self.sections) & set(SECTION_ORDER))
custom = [section for section in self.sections if section
not in SECTION_ORDER]
order = [sections.index(section) for section in SECTION_ORDER if
section in sections]
self.sections = np.array(sections)[order].tolist() + custom
# Sort by section
html, fnames, sectionlabels = [], [], []
for section in self.sections:
logger.info('%s' % section)
for sectionlabel, this_html, fname in (zip(self._sectionlabels,
self.html, self.fnames)):
if self._sectionvars[section] == sectionlabel:
html.append(this_html)
fnames.append(fname)
sectionlabels.append(sectionlabel)
logger.info(_get_fname(fname))
color = _is_bad_fname(fname)
div_klass, tooltip, text = _get_toc_property(fname)
# loop through conditions for evoked
if fname.endswith(('-ave.fif', '-ave.fif.gz',
'(whitened)')):
text = os.path.basename(fname)
if fname.endswith('(whitened)'):
fname = fname[:-11]
# XXX: remove redundant read_evokeds
evokeds = read_evokeds(fname, verbose=False)
html_toc += toc_list.substitute(
div_klass=div_klass, id=None, tooltip=fname,
color='#428bca', text=text)
html_toc += u'<li class="evoked"><ul>'
for ev in evokeds:
html_toc += toc_list.substitute(
div_klass=div_klass, id=global_id,
tooltip=fname, color=color, text=ev.comment)
global_id += 1
html_toc += u'</ul></li>'
elif fname.endswith(tuple(VALID_EXTENSIONS +
['bem', 'custom'])):
html_toc += toc_list.substitute(div_klass=div_klass,
id=global_id,
tooltip=tooltip,
color=color,
text=text)
global_id += 1
html_toc += u'\n</ul></div>'
html_toc += u'<div id="content">'
# The sorted html (according to section)
self.html = html
self.fnames = fnames
self._sectionlabels = sectionlabels
lang = getattr(self, 'lang', 'en-us')
html_header = header_template.substitute(
title=self.title, include=self.include, lang=lang,
sections=self.sections, sectionvars=self._sectionvars)
self.html.insert(0, html_header) # Insert header at position 0
self.html.insert(1, html_toc) # insert TOC
def _render_array(self, array, global_id=None, cmap='gray',
limits=None, n_jobs=1):
"""Render mri without bem contours (only PNG)."""
html = []
html.append(u'<div class="thumbnail">')
# Axial
limits = limits or {}
axial_limit = limits.get('axial')
axial_slices_gen = _iterate_axial_slices(array, axial_limit)
html.append(
self._render_one_axis(axial_slices_gen, 'axial',
global_id, cmap, array.shape[1], n_jobs))
# Sagittal
sagittal_limit = limits.get('sagittal')
sagittal_slices_gen = _iterate_sagittal_slices(array, sagittal_limit)
html.append(
self._render_one_axis(sagittal_slices_gen, 'sagittal',
global_id, cmap, array.shape[1], n_jobs))
# Coronal
coronal_limit = limits.get('coronal')
coronal_slices_gen = _iterate_coronal_slices(array, coronal_limit)
html.append(
self._render_one_axis(coronal_slices_gen, 'coronal',
global_id, cmap, array.shape[1], n_jobs))
# Close section
html.append(u'</div>')
return '\n'.join(html)
def _render_one_bem_axis(self, mri_fname, surf_fnames, global_id,
shape, orientation='coronal', decim=2, n_jobs=1):
"""Render one axis of bem contours (only PNG)."""
orientation_name2axis = dict(sagittal=0, axial=1, coronal=2)
orientation_axis = orientation_name2axis[orientation]
n_slices = shape[orientation_axis]
orig_size = np.roll(shape, orientation_axis)[[1, 2]]
name = orientation
html = []
html.append(u'<div class="col-xs-6 col-md-4">')
slides_klass = '%s-%s' % (name, global_id)
sl = np.arange(0, n_slices, decim)
kwargs = dict(mri_fname=mri_fname, surf_fnames=surf_fnames, show=False,
orientation=orientation, img_output=orig_size)
imgs = _figs_to_mrislices(sl, n_jobs, **kwargs)
slices = []
img_klass = 'slideimg-%s' % name
div_klass = 'span12 %s' % slides_klass
for ii, img in enumerate(imgs):
slice_id = '%s-%s-%s' % (name, global_id, sl[ii])
caption = u'Slice %s %s' % (name, sl[ii])
first = True if ii == 0 else False
slices.append(_build_html_image(img, slice_id, div_klass,
img_klass, caption, first,
image_format='png'))
# Render the slider
slider_id = 'select-%s-%s' % (name, global_id)
html.append(u'<div id="%s"></div>' % slider_id)
html.append(u'<ul class="thumbnail">')
# Render the slices
html.append(u'\n'.join(slices))
html.append(u'</ul>')
html.append(_build_html_slider(sl, slides_klass, slider_id))
html.append(u'</div>')
return '\n'.join(html)
def _render_image_png(self, image, cmap='gray', n_jobs=1):
"""Render one slice of mri without bem as a PNG."""
import nibabel as nib
global_id = self._get_id()
if 'mri' not in self.sections:
self.sections.append('mri')
self._sectionvars['mri'] = 'mri'
nim = nib.load(image)
data = _get_img_fdata(nim)
shape = data.shape
limits = {'sagittal': range(0, shape[0], 2),
'axial': range(0, shape[1], 2),
'coronal': range(0, shape[2], 2)}
name = op.basename(image)
html = u'<li class="mri" id="%d">\n' % global_id
html += u'<h4>%s</h4>\n' % name
html += self._render_array(data, global_id=global_id,
cmap=cmap, limits=limits, n_jobs=n_jobs)
html += u'</li>\n'
return html
def _render_raw(self, raw_fname):
"""Render raw (only text)."""
import matplotlib.pyplot as plt
global_id = self._get_id()
raw = read_raw_fif(raw_fname, allow_maxshield='yes')
extra = ' (MaxShield on)' if raw.info.get('maxshield', False) else ''
caption = u'Raw : %s%s' % (raw_fname, extra)
n_eeg = len(pick_types(raw.info, meg=False, eeg=True))
n_grad = len(pick_types(raw.info, meg='grad'))
n_mag = len(pick_types(raw.info, meg='mag'))
pick_eog = pick_types(raw.info, meg=False, eog=True)
if len(pick_eog) > 0:
eog = ', '.join(np.array(raw.info['ch_names'])[pick_eog])
else:
eog = 'Not available'
pick_ecg = pick_types(raw.info, meg=False, ecg=True)
if len(pick_ecg) > 0:
ecg = ', '.join(np.array(raw.info['ch_names'])[pick_ecg])
else:
ecg = 'Not available'
meas_date = raw.info['meas_date']
if meas_date is not None:
meas_date = meas_date.strftime("%B %d, %Y") + ' GMT'
html = raw_template.substitute(
div_klass='raw', id=global_id, caption=caption, info=raw.info,
meas_date=meas_date, n_eeg=n_eeg, n_grad=n_grad, n_mag=n_mag,
eog=eog, ecg=ecg, tmin=raw._first_time, tmax=raw._last_time)
raw_psd = {} if self.raw_psd is True else self.raw_psd
if isinstance(raw_psd, dict):
from matplotlib.backends.backend_agg import FigureCanvasAgg
n_ax = sum(kind in raw for kind in _DATA_CH_TYPES_SPLIT)
fig, axes = plt.subplots(n_ax, 1, figsize=(6, 1 + 1.5 * n_ax),
dpi=92)
FigureCanvasAgg(fig)
img = _fig_to_img(raw.plot_psd, self.image_format,
ax=axes, **raw_psd)
new_html = image_template.substitute(
img=img, div_klass='raw', img_klass='raw',
caption='PSD', show=True, image_format=self.image_format)
html += '\n\n' + new_html
return html
def _render_forward(self, fwd_fname):
"""Render forward."""
div_klass = 'forward'
caption = u'Forward: %s' % fwd_fname
fwd = read_forward_solution(fwd_fname)
repr_fwd = re.sub('>', '', re.sub('<', '', repr(fwd)))
global_id = self._get_id()
html = repr_template.substitute(div_klass=div_klass,
id=global_id,
caption=caption,
repr=repr_fwd)
return html
def _render_inverse(self, inv_fname):
"""Render inverse."""
div_klass = 'inverse'
caption = u'Inverse: %s' % inv_fname
inv = read_inverse_operator(inv_fname)
repr_inv = re.sub('>', '', re.sub('<', '', repr(inv)))
global_id = self._get_id()
html = repr_template.substitute(div_klass=div_klass,
id=global_id,
caption=caption,
repr=repr_inv)
return html
def _render_evoked(self, evoked_fname, baseline, image_format):
"""Render evoked."""
logger.debug('Evoked: Reading %s' % evoked_fname)
evokeds = read_evokeds(evoked_fname, baseline=baseline, verbose=False)
html = []
for ei, ev in enumerate(evokeds):
global_id = self._get_id()
kwargs = dict(show=False)
logger.debug('Evoked: Plotting instance %s/%s'
% (ei + 1, len(evokeds)))
img = _fig_to_img(ev.plot, image_format, **kwargs)
caption = u'Evoked : %s (%s)' % (evoked_fname, ev.comment)
html.append(image_template.substitute(
img=img, id=global_id, div_klass='evoked',
img_klass='evoked', caption=caption, show=True,
image_format=image_format))
has_types = []
if len(pick_types(ev.info, meg=False, eeg=True)) > 0:
has_types.append('eeg')
if len(pick_types(ev.info, meg='grad', eeg=False)) > 0:
has_types.append('grad')
if len(pick_types(ev.info, meg='mag', eeg=False)) > 0:
has_types.append('mag')
for ch_type in has_types:
logger.debug(' Topomap type %s' % ch_type)
img = _fig_to_img(ev.plot_topomap, image_format,
ch_type=ch_type, **kwargs)
caption = u'Topomap (ch_type = %s)' % ch_type
html.append(image_template.substitute(
img=img, div_klass='evoked', img_klass='evoked',
caption=caption, show=True, image_format=image_format))
logger.debug('Evoked: done')
return '\n'.join(html)
def _render_eve(self, eve_fname, sfreq, image_format):
"""Render events."""
global_id = self._get_id()
events = read_events(eve_fname)
kwargs = dict(events=events, sfreq=sfreq, show=False)
img = _fig_to_img(plot_events, image_format, **kwargs)
caption = 'Events : ' + eve_fname
html = image_template.substitute(
img=img, id=global_id, div_klass='events', img_klass='events',
caption=caption, show=True, image_format=image_format)
return html
def _render_epochs(self, epo_fname, image_format):
"""Render epochs."""
global_id = self._get_id()
epochs = read_epochs(epo_fname)
kwargs = dict(subject=self.subject, show=False)
img = _fig_to_img(epochs.plot_drop_log, image_format, **kwargs)
caption = 'Epochs : ' + epo_fname
show = True
html = image_template.substitute(
img=img, id=global_id, div_klass='epochs', img_klass='epochs',
caption=caption, show=show, image_format=image_format)
return html
def _render_cov(self, cov_fname, info_fname, image_format, show_svd=True):
"""Render cov."""
global_id = self._get_id()
cov = read_cov(cov_fname)
fig, svd = plot_cov(cov, info_fname, show=False, show_svd=show_svd)
html = []
figs = [fig]
captions = ['Covariance : %s (n_samples: %s)' % (cov_fname, cov.nfree)]
if svd is not None:
figs.append(svd)
captions.append('Singular values of the noise covariance')
for fig, caption in zip(figs, captions):
img = _fig_to_img(fig, image_format)
show = True
html.append(image_template.substitute(
img=img, id=global_id, div_klass='covariance',
img_klass='covariance', caption=caption, show=show,
image_format=image_format))
return '\n'.join(html)
def _render_whitened_evoked(self, evoked_fname, noise_cov, baseline,
image_format):
"""Render whitened evoked."""
evokeds = read_evokeds(evoked_fname, verbose=False)
html = []
for ev in evokeds:
ev = read_evokeds(evoked_fname, ev.comment, baseline=baseline,
verbose=False)
global_id = self._get_id()
kwargs = dict(noise_cov=noise_cov, show=False)
img = _fig_to_img(ev.plot_white, image_format, **kwargs)
caption = u'Whitened evoked : %s (%s)' % (evoked_fname, ev.comment)
show = True
html.append(image_template.substitute(
img=img, id=global_id, div_klass='evoked',
img_klass='evoked', caption=caption, show=show,
image_format=image_format))
return '\n'.join(html)
def _render_trans(self, trans, path, info, subject, subjects_dir):
"""Render trans (only PNG)."""
kwargs = dict(info=info, trans=trans, subject=subject,
subjects_dir=subjects_dir)
try:
img = _iterate_trans_views(function=plot_alignment, **kwargs)
except IOError:
img = _iterate_trans_views(function=plot_alignment,
surfaces=['head'], **kwargs)
if img is not None:
global_id = self._get_id()
html = image_template.substitute(
img=img, id=global_id, div_klass='trans',
img_klass='trans', caption='Trans : ' + trans, width=75,
show=True, image_format='png')
return html
def _render_bem(self, subject, subjects_dir, decim, n_jobs,
section='mri', caption='BEM'):
"""Render mri+bem (only PNG)."""
import nibabel as nib
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
# Get the MRI filename
mri_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
if not op.isfile(mri_fname):
warn('MRI file "%s" does not exist' % mri_fname)
# Get the BEM surface filenames
bem_path = op.join(subjects_dir, subject, 'bem')
if not op.isdir(bem_path):
warn('Subject bem directory "%s" does not exist' % bem_path)
return self._render_image_png(mri_fname, cmap='gray',
n_jobs=n_jobs)
surf_fnames = []
for surf_name in ['*inner_skull', '*outer_skull', '*outer_skin']:
surf_fname = glob(op.join(bem_path, surf_name + '.surf'))
if len(surf_fname) > 0:
surf_fnames.append(surf_fname[0])
else:
warn('No surface found for %s.' % surf_name)
continue
if len(surf_fnames) == 0:
warn('No surfaces found at all, rendering empty MRI')
return self._render_image_png(mri_fname, cmap='gray',
n_jobs=n_jobs)
# XXX : find a better way to get max range of slices
nim = nib.load(mri_fname)
data = _get_img_fdata(nim)
shape = data.shape
del data # free up memory
html = []
global_id = self._get_id()
if section == 'mri' and 'mri' not in self.sections:
self.sections.append('mri')
self._sectionvars['mri'] = 'mri'
name = caption
html += u'<li class="mri" id="%d">\n' % global_id
html += u'<h4>%s</h4>\n' % name # all other captions are h4
html += self._render_one_bem_axis(mri_fname, surf_fnames, global_id,
shape, 'axial', decim, n_jobs)
html += self._render_one_bem_axis(mri_fname, surf_fnames, global_id,
shape, 'sagittal', decim, n_jobs)
html += self._render_one_bem_axis(mri_fname, surf_fnames, global_id,
shape, 'coronal', decim, n_jobs)
html += u'</li>\n'
return ''.join(html)
def _clean_varnames(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# add report_ at the beginning so that the javascript class names
# are valid ones
return 'report_' + s
def _recursive_search(path, pattern):
"""Auxiliary function for recursive_search of the directory."""
filtered_files = list()
for dirpath, dirnames, files in os.walk(path):
for f in fnmatch.filter(files, pattern):
# only the following file types are supported
# this ensures equitable distribution of jobs
if f.endswith(tuple(VALID_EXTENSIONS)):
filtered_files.append(op.realpath(op.join(dirpath, f)))
return filtered_files
def _fix_global_ids(html):
"""Fix the global_ids after reordering in _render_toc()."""
html = re.sub(r'id="\d+"', 'id="###"', html)
global_id = 1
while len(re.findall('id="###"', html)) > 0:
html = re.sub('id="###"', 'id="%s"' % global_id, html, count=1)
global_id += 1
return html
###############################################################################
# Scraper for sphinx-gallery
_SCRAPER_TEXT = '''
.. only:: builder_html
.. container:: row
.. rubric:: The `HTML document <{0}>`__ written by :meth:`mne.Report.save`:
.. raw:: html
<iframe class="sg_report" sandbox="allow-scripts" src="{0}"></iframe>
''' # noqa: E501
# Adapted from fa-file-code
_FA_FILE_CODE = '<svg class="sg_report" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="#dec" d="M149.9 349.1l-.2-.2-32.8-28.9 32.8-28.9c3.6-3.2 4-8.8.8-12.4l-.2-.2-17.4-18.6c-3.4-3.6-9-3.7-12.4-.4l-57.7 54.1c-3.7 3.5-3.7 9.4 0 12.8l57.7 54.1c1.6 1.5 3.8 2.4 6 2.4 2.4 0 4.8-1 6.4-2.8l17.4-18.6c3.3-3.5 3.1-9.1-.4-12.4zm220-251.2L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM256 51.9l76.1 76.1H256zM336 464H48V48h160v104c0 13.3 10.7 24 24 24h104zM209.6 214c-4.7-1.4-9.5 1.3-10.9 6L144 408.1c-1.4 4.7 1.3 9.6 6 10.9l24.4 7.1c4.7 1.4 9.6-1.4 10.9-6L240 231.9c1.4-4.7-1.3-9.6-6-10.9zm24.5 76.9l.2.2 32.8 28.9-32.8 28.9c-3.6 3.2-4 8.8-.8 12.4l.2.2 17.4 18.6c3.3 3.5 8.9 3.7 12.4.4l57.7-54.1c3.7-3.5 3.7-9.4 0-12.8l-57.7-54.1c-3.5-3.3-9.1-3.2-12.4.4l-17.4 18.6c-3.3 3.5-3.1 9.1.4 12.4z" class=""></path></svg>' # noqa: E501
class _ReportScraper(object):
"""Scrape Report outputs.
Only works properly if conf.py is configured properly and the file
is written to the same directory as the example script.
"""
def __init__(self):
self.app = None
self.files = dict()
def __repr__(self):
return '<ReportScraper>'
def __call__(self, block, block_vars, gallery_conf):
for report in block_vars['example_globals'].values():
if (isinstance(report, Report) and hasattr(report, 'fname') and
report.fname.endswith('.html') and
gallery_conf['builder_name'] == 'html'):
# Thumbnail
image_path_iterator = block_vars['image_path_iterator']
img_fname = next(image_path_iterator)
img_fname = img_fname.replace('.png', '.svg')
with open(img_fname, 'w') as fid:
fid.write(_FA_FILE_CODE)
# copy HTML file
html_fname = op.basename(report.fname)
out_fname = op.join(
self.app.builder.outdir,
op.relpath(op.dirname(block_vars['target_file']),
self.app.builder.srcdir), html_fname)
self.files[report.fname] = out_fname
# embed links/iframe
data = _SCRAPER_TEXT.format(html_fname)
return data
return ''
def copyfiles(self, *args, **kwargs):
for key, value in self.files.items():
copyfile(key, value)
|
[] |
[] |
[
"_MNE_BUILDING_DOC"
] |
[]
|
["_MNE_BUILDING_DOC"]
|
python
| 1 | 0 | |
upup/pkg/fi/cloudup/apply_cluster.go
|
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudup
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"os"
"path"
"strconv"
"strings"
"github.com/blang/semver/v4"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
kopsbase "k8s.io/kops"
"k8s.io/kops/pkg/acls"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/registry"
"k8s.io/kops/pkg/apis/kops/util"
"k8s.io/kops/pkg/apis/kops/validation"
"k8s.io/kops/pkg/apis/nodeup"
"k8s.io/kops/pkg/assets"
"k8s.io/kops/pkg/client/simple"
"k8s.io/kops/pkg/client/simple/vfsclientset"
"k8s.io/kops/pkg/dns"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/model"
"k8s.io/kops/pkg/model/alimodel"
"k8s.io/kops/pkg/model/awsmodel"
"k8s.io/kops/pkg/model/azuremodel"
"k8s.io/kops/pkg/model/components"
"k8s.io/kops/pkg/model/components/etcdmanager"
"k8s.io/kops/pkg/model/components/kubeapiserver"
"k8s.io/kops/pkg/model/domodel"
"k8s.io/kops/pkg/model/gcemodel"
"k8s.io/kops/pkg/model/iam"
"k8s.io/kops/pkg/model/openstackmodel"
"k8s.io/kops/pkg/resources/digitalocean"
"k8s.io/kops/pkg/templates"
"k8s.io/kops/pkg/wellknownports"
"k8s.io/kops/upup/models"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/aliup"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/azure"
"k8s.io/kops/upup/pkg/fi/cloudup/bootstrapchannelbuilder"
"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
"k8s.io/kops/upup/pkg/fi/cloudup/do"
"k8s.io/kops/upup/pkg/fi/cloudup/gce"
"k8s.io/kops/upup/pkg/fi/cloudup/openstack"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
"k8s.io/kops/util/pkg/architectures"
"k8s.io/kops/util/pkg/hashing"
"k8s.io/kops/util/pkg/mirrors"
"k8s.io/kops/util/pkg/vfs"
)
const (
starline = "*********************************************************************************"
)
var (
// AlphaAllowGCE is a feature flag that gates GCE support while it is alpha
AlphaAllowGCE = featureflag.New("AlphaAllowGCE", featureflag.Bool(false))
// AlphaAllowALI is a feature flag that gates aliyun support while it is alpha
AlphaAllowALI = featureflag.New("AlphaAllowALI", featureflag.Bool(false))
// OldestSupportedKubernetesVersion is the oldest kubernetes version that is supported in Kops
OldestSupportedKubernetesVersion = "1.17.0"
// OldestRecommendedKubernetesVersion is the oldest kubernetes version that is not deprecated in Kops
OldestRecommendedKubernetesVersion = "1.19.0"
)
type ApplyClusterCmd struct {
Cloud fi.Cloud
Cluster *kops.Cluster
InstanceGroups []*kops.InstanceGroup
// NodeUpAssets are the assets for downloading nodeup
NodeUpAssets map[architectures.Architecture]*mirrors.MirroredAsset
// TargetName specifies how we are operating e.g. direct to GCE, or AWS, or dry-run, or terraform
TargetName string
// Target is the fi.Target we will operate against
Target fi.Target
// OutDir is a local directory in which we place output, can cache files etc
OutDir string
// Assets is a list of sources for files (primarily when not using everything containerized)
// Formats:
// raw url: http://... or https://...
// url with hash: <hex>@http://... or <hex>@https://...
Assets map[architectures.Architecture][]*mirrors.MirroredAsset
Clientset simple.Clientset
// DryRun is true if this is only a dry run
DryRun bool
// AllowKopsDowngrade permits applying with a kops version older than what was last used to apply to the cluster.
AllowKopsDowngrade bool
// RunTasksOptions defines parameters for task execution, e.g. retry interval
RunTasksOptions *fi.RunTasksOptions
// The channel we are using
channel *kops.Channel
// Phase can be set to a Phase to run the specific subset of tasks, if we don't want to run everything
Phase Phase
// LifecycleOverrides is passed in to override the lifecycle for one of more tasks.
// The key value is the task name such as InternetGateway and the value is the fi.Lifecycle
// that is re-mapped.
LifecycleOverrides map[string]fi.Lifecycle
// TaskMap is the map of tasks that we built (output)
TaskMap map[string]fi.Task
}
func (c *ApplyClusterCmd) Run(ctx context.Context) error {
if c.InstanceGroups == nil {
list, err := c.Clientset.InstanceGroupsFor(c.Cluster).List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
var instanceGroups []*kops.InstanceGroup
for i := range list.Items {
instanceGroups = append(instanceGroups, &list.Items[i])
}
c.InstanceGroups = instanceGroups
}
for _, ig := range c.InstanceGroups {
// Try to guess the path for additional third party volume plugins in Flatcar
image := strings.ToLower(ig.Spec.Image)
if strings.Contains(image, "flatcar") {
if c.Cluster.Spec.Kubelet == nil {
c.Cluster.Spec.Kubelet = &kops.KubeletConfigSpec{}
}
if c.Cluster.Spec.Kubelet.VolumePluginDirectory == "" {
c.Cluster.Spec.Kubelet.VolumePluginDirectory = "/var/lib/kubelet/volumeplugins/"
}
}
}
channel, err := ChannelForCluster(c.Cluster)
if err != nil {
klog.Warningf("%v", err)
}
c.channel = channel
stageAssetsLifecycle := fi.LifecycleSync
securityLifecycle := fi.LifecycleSync
networkLifecycle := fi.LifecycleSync
clusterLifecycle := fi.LifecycleSync
switch c.Phase {
case Phase(""):
// Everything ... the default
// until we implement finding assets we need to Ignore them
stageAssetsLifecycle = fi.LifecycleIgnore
case PhaseStageAssets:
networkLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleIgnore
clusterLifecycle = fi.LifecycleIgnore
case PhaseNetwork:
stageAssetsLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleIgnore
clusterLifecycle = fi.LifecycleIgnore
case PhaseSecurity:
stageAssetsLifecycle = fi.LifecycleIgnore
networkLifecycle = fi.LifecycleExistsAndWarnIfChanges
clusterLifecycle = fi.LifecycleIgnore
case PhaseCluster:
if c.TargetName == TargetDryRun {
stageAssetsLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleExistsAndWarnIfChanges
networkLifecycle = fi.LifecycleExistsAndWarnIfChanges
} else {
stageAssetsLifecycle = fi.LifecycleIgnore
networkLifecycle = fi.LifecycleExistsAndValidates
securityLifecycle = fi.LifecycleExistsAndValidates
}
default:
return fmt.Errorf("unknown phase %q", c.Phase)
}
// This is kinda a hack. Need to move phases out of fi. If we use Phase here we introduce a circular
// go dependency.
phase := string(c.Phase)
assetBuilder := assets.NewAssetBuilder(c.Cluster, phase)
err = c.upgradeSpecs(assetBuilder)
if err != nil {
return err
}
err = c.validateKopsVersion()
if err != nil {
return err
}
err = c.validateKubernetesVersion()
if err != nil {
return err
}
cluster := c.Cluster
configBase, err := vfs.Context.BuildVfsPath(cluster.Spec.ConfigBase)
if err != nil {
return fmt.Errorf("error parsing config base %q: %v", cluster.Spec.ConfigBase, err)
}
if !c.AllowKopsDowngrade {
kopsVersionUpdatedBytes, err := configBase.Join(registry.PathKopsVersionUpdated).ReadFile()
if err == nil {
kopsVersionUpdated := strings.TrimSpace(string(kopsVersionUpdatedBytes))
version, err := semver.Parse(kopsVersionUpdated)
if err != nil {
return fmt.Errorf("error parsing last kops version updated: %v", err)
}
if version.GT(semver.MustParse(kopsbase.Version)) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("The cluster was last updated by kops version %s\n", kopsVersionUpdated)
fmt.Printf("To permit updating by the older version %s, run with the --allow-kops-downgrade flag\n", kopsbase.Version)
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
return fmt.Errorf("kops version older than last used to update the cluster")
}
} else if err != os.ErrNotExist {
return fmt.Errorf("error reading last kops version used to update: %v", err)
}
}
cloud := c.Cloud
err = validation.DeepValidate(c.Cluster, c.InstanceGroups, true, cloud)
if err != nil {
return err
}
if cluster.Spec.KubernetesVersion == "" {
return fmt.Errorf("KubernetesVersion not set")
}
if cluster.Spec.DNSZone == "" && !dns.IsGossipHostname(cluster.ObjectMeta.Name) {
return fmt.Errorf("DNSZone not set")
}
l := &Loader{}
l.Init()
keyStore, err := c.Clientset.KeyStore(cluster)
if err != nil {
return err
}
sshCredentialStore, err := c.Clientset.SSHCredentialStore(cluster)
if err != nil {
return err
}
secretStore, err := c.Clientset.SecretStore(cluster)
if err != nil {
return err
}
addonsClient := c.Clientset.AddonsFor(cluster)
addons, err := addonsClient.List()
if err != nil {
return fmt.Errorf("error fetching addons: %v", err)
}
// Normalize k8s version
versionWithoutV := strings.TrimSpace(cluster.Spec.KubernetesVersion)
versionWithoutV = strings.TrimPrefix(versionWithoutV, "v")
if cluster.Spec.KubernetesVersion != versionWithoutV {
klog.Warningf("Normalizing kubernetes version: %q -> %q", cluster.Spec.KubernetesVersion, versionWithoutV)
cluster.Spec.KubernetesVersion = versionWithoutV
}
// check if we should recommend turning off anonymousAuth
{
// we do a check here because setting modifying the kubelet object messes with the output
warn := false
if cluster.Spec.Kubelet == nil {
warn = true
} else if cluster.Spec.Kubelet.AnonymousAuth == nil {
warn = true
}
if warn {
fmt.Println("")
fmt.Printf("%s\n", starline)
fmt.Println("")
fmt.Println("Kubelet anonymousAuth is currently turned on. This allows RBAC escalation and remote code execution possibilities.")
fmt.Println("It is highly recommended you turn it off by setting 'spec.kubelet.anonymousAuth' to 'false' via 'kops edit cluster'")
fmt.Println("")
fmt.Println("See https://kops.sigs.k8s.io/security/#kubelet-api")
fmt.Println("")
fmt.Printf("%s\n", starline)
fmt.Println("")
}
}
if fi.BoolValue(c.Cluster.Spec.EncryptionConfig) {
secret, err := secretStore.FindSecret("encryptionconfig")
if err != nil {
return fmt.Errorf("could not load encryptionconfig secret: %v", err)
}
if secret == nil {
fmt.Println("")
fmt.Println("You have encryptionConfig enabled, but no encryptionconfig secret has been set.")
fmt.Println("See `kops create secret encryptionconfig -h` and https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/")
return fmt.Errorf("could not find encryptionconfig secret")
}
}
ciliumSpec := c.Cluster.Spec.Networking.Cilium
if ciliumSpec != nil && ciliumSpec.EnableEncryption {
secret, err := secretStore.FindSecret("ciliumpassword")
if err != nil {
return fmt.Errorf("could not load the ciliumpassword secret: %w", err)
}
if secret == nil {
fmt.Println("")
fmt.Println("You have cilium encryption enabled, but no ciliumpassword secret has been set.")
fmt.Println("See `kops create secret ciliumpassword -h`")
return fmt.Errorf("could not find ciliumpassword secret")
}
}
if err := c.addFileAssets(assetBuilder); err != nil {
return err
}
// Only setup transfer of kops assets if using a FileRepository
if c.Cluster.Spec.Assets != nil && c.Cluster.Spec.Assets.FileRepository != nil {
if err := SetKopsAssetsLocations(assetBuilder); err != nil {
return err
}
}
checkExisting := true
project := ""
var sshPublicKeys [][]byte
{
keys, err := sshCredentialStore.FindSSHPublicKeys(fi.SecretNameSSHPrimary)
if err != nil {
return fmt.Errorf("error retrieving SSH public key %q: %v", fi.SecretNameSSHPrimary, err)
}
for _, k := range keys {
sshPublicKeys = append(sshPublicKeys, []byte(k.Spec.PublicKey))
}
}
modelContext := &model.KopsModelContext{
IAMModelContext: iam.IAMModelContext{Cluster: cluster},
InstanceGroups: c.InstanceGroups,
}
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderGCE:
{
gceCloud := cloud.(gce.GCECloud)
project = gceCloud.Project()
if !AlphaAllowGCE.Enabled() {
return fmt.Errorf("GCE support is currently alpha, and is feature-gated. export KOPS_FEATURE_FLAGS=AlphaAllowGCE")
}
}
case kops.CloudProviderDO:
{
if len(sshPublicKeys) == 0 && (c.Cluster.Spec.SSHKeyName == nil || *c.Cluster.Spec.SSHKeyName == "") {
return fmt.Errorf("SSH public key must be specified when running with DigitalOcean (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
}
case kops.CloudProviderAWS:
{
awsCloud := cloud.(awsup.AWSCloud)
accountID, partition, err := awsCloud.AccountInfo()
if err != nil {
return err
}
modelContext.AWSAccountID = accountID
modelContext.AWSPartition = partition
if len(sshPublicKeys) == 0 && c.Cluster.Spec.SSHKeyName == nil {
return fmt.Errorf("SSH public key must be specified when running with AWS (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) > 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AWS; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderALI:
{
fmt.Println("")
fmt.Println("aliyun support has been deprecated due to lack of maintainers. It may be removed in a future version of kOps.")
fmt.Println("")
if !AlphaAllowALI.Enabled() {
return fmt.Errorf("aliyun support is currently alpha, and is feature-gated. export KOPS_FEATURE_FLAGS=AlphaAllowALI")
}
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with ALICloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with ALICloud; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderAzure:
{
if !featureflag.Azure.Enabled() {
return fmt.Errorf("azure support is currently alpha, and is feature-gated. Please export KOPS_FEATURE_FLAGS=Azure")
}
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with AzureCloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AzureCloud; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderOpenstack:
{
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with Openstack (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with Openstack; please delete a key using `kops delete secret`")
}
}
default:
return fmt.Errorf("unknown CloudProvider %q", cluster.Spec.CloudProvider)
}
modelContext.SSHPublicKeys = sshPublicKeys
modelContext.Region = cloud.Region()
if dns.IsGossipHostname(cluster.ObjectMeta.Name) {
klog.Infof("Gossip DNS: skipping DNS validation")
} else {
err = validateDNS(cluster, cloud)
if err != nil {
return err
}
}
tf := &TemplateFunctions{
KopsModelContext: *modelContext,
cloud: cloud,
}
configBuilder, err := newNodeUpConfigBuilder(cluster, assetBuilder, c.Assets)
if err != nil {
return err
}
bootstrapScriptBuilder := &model.BootstrapScriptBuilder{
NodeUpConfigBuilder: configBuilder,
NodeUpAssets: c.NodeUpAssets,
}
{
templates, err := templates.LoadTemplates(cluster, models.NewAssetPath("cloudup/resources"))
if err != nil {
return fmt.Errorf("error loading templates: %v", err)
}
err = tf.AddTo(templates.TemplateFunctions, secretStore)
if err != nil {
return err
}
bcb := bootstrapchannelbuilder.NewBootstrapChannelBuilder(
modelContext,
&clusterLifecycle,
assetBuilder,
templates,
addons,
)
l.Builders = append(l.Builders,
bcb,
&model.PKIModelBuilder{
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&model.IssuerDiscoveryModelBuilder{
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
Cluster: cluster,
},
&kubeapiserver.KubeApiserverBuilder{
AssetBuilder: assetBuilder,
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&etcdmanager.EtcdManagerBuilder{
AssetBuilder: assetBuilder,
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&model.MasterVolumeBuilder{KopsModelContext: modelContext, Lifecycle: &clusterLifecycle},
)
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderAWS:
awsModelContext := &awsmodel.AWSModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&awsmodel.APILoadBalancerBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle, SecurityLifecycle: &securityLifecycle},
&awsmodel.BastionModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle, SecurityLifecycle: &securityLifecycle},
&awsmodel.DNSModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle},
&awsmodel.ExternalAccessModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.FirewallModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.SSHKeyModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.NetworkModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &networkLifecycle},
&awsmodel.IAMModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle, Cluster: cluster},
&awsmodel.OIDCProviderBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle, KeyStore: keyStore},
)
awsModelBuilder := &awsmodel.AutoscalingGroupModelBuilder{
AWSModelContext: awsModelContext,
BootstrapScriptBuilder: bootstrapScriptBuilder,
Lifecycle: &clusterLifecycle,
SecurityLifecycle: &securityLifecycle,
Cluster: cluster,
}
if featureflag.Spotinst.Enabled() {
l.Builders = append(l.Builders, &awsmodel.SpotInstanceGroupModelBuilder{
AWSModelContext: awsModelContext,
BootstrapScriptBuilder: bootstrapScriptBuilder,
Lifecycle: &clusterLifecycle,
SecurityLifecycle: &securityLifecycle,
})
if featureflag.SpotinstHybrid.Enabled() {
l.Builders = append(l.Builders, awsModelBuilder)
}
} else {
l.Builders = append(l.Builders, awsModelBuilder)
}
nth := c.Cluster.Spec.NodeTerminationHandler
if nth != nil && fi.BoolValue(nth.Enabled) && fi.BoolValue(nth.EnableSQSTerminationDraining) {
l.Builders = append(l.Builders, &awsmodel.NodeTerminationHandlerBuilder{
AWSModelContext: awsModelContext,
Lifecycle: &clusterLifecycle,
})
}
case kops.CloudProviderDO:
doModelContext := &domodel.DOModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&domodel.APILoadBalancerModelBuilder{DOModelContext: doModelContext, Lifecycle: &securityLifecycle},
&domodel.DropletBuilder{DOModelContext: doModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderGCE:
gceModelContext := &gcemodel.GCEModelContext{
KopsModelContext: modelContext,
}
storageACLLifecycle := securityLifecycle
if storageACLLifecycle != fi.LifecycleIgnore {
// This is a best-effort permissions fix
storageACLLifecycle = fi.LifecycleWarnIfInsufficientAccess
}
l.Builders = append(l.Builders,
&gcemodel.APILoadBalancerBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.ExternalAccessModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.FirewallModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.NetworkModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &networkLifecycle},
&gcemodel.StorageAclBuilder{GCEModelContext: gceModelContext, Cloud: cloud.(gce.GCECloud), Lifecycle: &storageACLLifecycle},
&gcemodel.AutoscalingGroupModelBuilder{GCEModelContext: gceModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderALI:
aliModelContext := &alimodel.ALIModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&alimodel.APILoadBalancerModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.NetworkModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.RAMModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.SSHKeyModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.FirewallModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.ExternalAccessModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.ScalingGroupModelBuilder{ALIModelContext: aliModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderAzure:
azureModelContext := &azuremodel.AzureModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&azuremodel.APILoadBalancerModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.NetworkModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.ResourceGroupModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.VMScaleSetModelBuilder{AzureModelContext: azureModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderOpenstack:
openstackModelContext := &openstackmodel.OpenstackModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&openstackmodel.NetworkModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &networkLifecycle},
&openstackmodel.SSHKeyModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &securityLifecycle},
&openstackmodel.FirewallModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &securityLifecycle},
&openstackmodel.ServerGroupModelBuilder{OpenstackModelContext: openstackModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
default:
return fmt.Errorf("unknown cloudprovider %q", cluster.Spec.CloudProvider)
}
}
taskMap, err := l.BuildTasks(assetBuilder, &stageAssetsLifecycle, c.LifecycleOverrides)
if err != nil {
return fmt.Errorf("error building tasks: %v", err)
}
c.TaskMap = taskMap
var target fi.Target
dryRun := false
shouldPrecreateDNS := true
switch c.TargetName {
case TargetDirect:
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderGCE:
target = gce.NewGCEAPITarget(cloud.(gce.GCECloud))
case kops.CloudProviderAWS:
target = awsup.NewAWSAPITarget(cloud.(awsup.AWSCloud))
case kops.CloudProviderDO:
target = do.NewDOAPITarget(cloud.(*digitalocean.Cloud))
case kops.CloudProviderOpenstack:
target = openstack.NewOpenstackAPITarget(cloud.(openstack.OpenstackCloud))
case kops.CloudProviderALI:
target = aliup.NewALIAPITarget(cloud.(aliup.ALICloud))
case kops.CloudProviderAzure:
target = azure.NewAzureAPITarget(cloud.(azure.AzureCloud))
default:
return fmt.Errorf("direct configuration not supported with CloudProvider:%q", cluster.Spec.CloudProvider)
}
case TargetTerraform:
checkExisting = false
outDir := c.OutDir
tf := terraform.NewTerraformTarget(cloud, project, outDir, cluster.Spec.Target)
// We include a few "util" variables in the TF output
if err := tf.AddOutputVariable("region", terraformWriter.LiteralFromStringValue(cloud.Region())); err != nil {
return err
}
if project != "" {
if err := tf.AddOutputVariable("project", terraformWriter.LiteralFromStringValue(project)); err != nil {
return err
}
}
if err := tf.AddOutputVariable("cluster_name", terraformWriter.LiteralFromStringValue(cluster.ObjectMeta.Name)); err != nil {
return err
}
target = tf
// Can cause conflicts with terraform management
shouldPrecreateDNS = false
case TargetCloudformation:
checkExisting = false
outDir := c.OutDir
target = cloudformation.NewCloudformationTarget(cloud, project, outDir)
// Can cause conflicts with cloudformation management
shouldPrecreateDNS = false
case TargetDryRun:
target = fi.NewDryRunTarget(assetBuilder, os.Stdout)
dryRun = true
// Avoid making changes on a dry-run
shouldPrecreateDNS = false
default:
return fmt.Errorf("unsupported target type %q", c.TargetName)
}
c.Target = target
if !dryRun {
acl, err := acls.GetACL(configBase, cluster)
if err != nil {
return err
}
err = configBase.Join(registry.PathKopsVersionUpdated).WriteFile(bytes.NewReader([]byte(kopsbase.Version)), acl)
if err != nil {
return fmt.Errorf("error writing kops version: %v", err)
}
err = registry.WriteConfigDeprecated(cluster, configBase.Join(registry.PathClusterCompleted), c.Cluster)
if err != nil {
return fmt.Errorf("error writing completed cluster spec: %v", err)
}
vfsMirror := vfsclientset.NewInstanceGroupMirror(cluster, configBase)
for _, g := range c.InstanceGroups {
// TODO: We need to update the mirror (below), but do we need to update the primary?
_, err := c.Clientset.InstanceGroupsFor(c.Cluster).Update(ctx, g, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("error writing InstanceGroup %q to registry: %v", g.ObjectMeta.Name, err)
}
// TODO: Don't write if vfsMirror == c.ClientSet
if err := vfsMirror.WriteMirror(g); err != nil {
return fmt.Errorf("error writing instance group spec to mirror: %v", err)
}
}
}
context, err := fi.NewContext(target, cluster, cloud, keyStore, secretStore, configBase, checkExisting, taskMap)
if err != nil {
return fmt.Errorf("error building context: %v", err)
}
defer context.Close()
var options fi.RunTasksOptions
if c.RunTasksOptions != nil {
options = *c.RunTasksOptions
} else {
options.InitDefaults()
}
err = context.RunTasks(options)
if err != nil {
return fmt.Errorf("error running tasks: %v", err)
}
if dns.IsGossipHostname(cluster.Name) {
shouldPrecreateDNS = false
}
if shouldPrecreateDNS {
if err := precreateDNS(ctx, cluster, cloud); err != nil {
klog.Warningf("unable to pre-create DNS records - cluster startup may be slower: %v", err)
}
}
err = target.Finish(taskMap) //This will finish the apply, and print the changes
if err != nil {
return fmt.Errorf("error closing target: %v", err)
}
return nil
}
// upgradeSpecs ensures that fields are fully populated / defaulted
func (c *ApplyClusterCmd) upgradeSpecs(assetBuilder *assets.AssetBuilder) error {
fullCluster, err := PopulateClusterSpec(c.Clientset, c.Cluster, c.Cloud, assetBuilder)
if err != nil {
return err
}
c.Cluster = fullCluster
for i, g := range c.InstanceGroups {
fullGroup, err := PopulateInstanceGroupSpec(fullCluster, g, c.Cloud, c.channel)
if err != nil {
return err
}
c.InstanceGroups[i] = fullGroup
}
return nil
}
// validateKopsVersion ensures that kops meet the version requirements / recommendations in the channel
func (c *ApplyClusterCmd) validateKopsVersion() error {
kopsVersion, err := semver.ParseTolerant(kopsbase.Version)
if err != nil {
klog.Warningf("unable to parse kops version %q", kopsbase.Version)
// Not a hard-error
return nil
}
if c.channel == nil {
klog.Warning("channel unavailable, skipping version validation")
return nil
}
versionInfo := kops.FindKopsVersionSpec(c.channel.Spec.KopsVersions, kopsVersion)
if versionInfo == nil {
klog.Warningf("unable to find version information for kops version %q in channel", kopsVersion)
// Not a hard-error
return nil
}
recommended, err := versionInfo.FindRecommendedUpgrade(kopsVersion)
if err != nil {
klog.Warningf("unable to parse version recommendation for kops version %q in channel", kopsVersion)
}
required, err := versionInfo.IsUpgradeRequired(kopsVersion)
if err != nil {
klog.Warningf("unable to parse version requirement for kops version %q in channel", kopsVersion)
}
if recommended != nil && !required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("A new kops version is available: %s", recommended)
fmt.Printf("\n")
fmt.Printf("Upgrading is recommended\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_kops", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
} else if required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if recommended != nil {
fmt.Printf("a new kops version is available: %s\n", recommended)
}
fmt.Println("")
fmt.Printf("This version of kops (%s) is no longer supported; upgrading is required\n", kopsbase.Version)
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_OBSOLETE_VERSION)\n")
fmt.Println("")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_kops", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
if required {
if os.Getenv("KOPS_RUN_OBSOLETE_VERSION") == "" {
return fmt.Errorf("kops upgrade is required")
}
}
return nil
}
// validateKubernetesVersion ensures that kubernetes meet the version requirements / recommendations in the channel
func (c *ApplyClusterCmd) validateKubernetesVersion() error {
parsed, err := util.ParseKubernetesVersion(c.Cluster.Spec.KubernetesVersion)
if err != nil {
klog.Warningf("unable to parse kubernetes version %q", c.Cluster.Spec.KubernetesVersion)
// Not a hard-error
return nil
}
kopsVersion, err := semver.Parse(kopsbase.KOPS_RELEASE_VERSION)
if err != nil {
klog.Warningf("unable to parse kops version %q", kopsVersion)
} else {
tooNewVersion := kopsVersion
tooNewVersion.Minor++
tooNewVersion.Pre = nil
tooNewVersion.Build = nil
if util.IsKubernetesGTE(tooNewVersion.String(), *parsed) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("This version of kubernetes is not yet supported; upgrading kops is required\n")
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_TOO_NEW_VERSION)\n")
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if os.Getenv("KOPS_RUN_TOO_NEW_VERSION") == "" {
return fmt.Errorf("kops upgrade is required")
}
}
}
if !util.IsKubernetesGTE(OldestSupportedKubernetesVersion, *parsed) {
fmt.Printf("This version of Kubernetes is no longer supported; upgrading Kubernetes is required\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", OldestRecommendedKubernetesVersion))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
return fmt.Errorf("kubernetes upgrade is required")
}
if !util.IsKubernetesGTE(OldestRecommendedKubernetesVersion, *parsed) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("Kops support for this Kubernetes version is deprecated and will be removed in a future release.\n")
fmt.Printf("\n")
fmt.Printf("Upgrading Kubernetes is recommended\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", OldestRecommendedKubernetesVersion))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
// TODO: make util.ParseKubernetesVersion not return a pointer
kubernetesVersion := *parsed
if c.channel == nil {
klog.Warning("unable to load channel, skipping kubernetes version recommendation/requirements checks")
return nil
}
versionInfo := kops.FindKubernetesVersionSpec(c.channel.Spec.KubernetesVersions, kubernetesVersion)
if versionInfo == nil {
klog.Warningf("unable to find version information for kubernetes version %q in channel", kubernetesVersion)
// Not a hard-error
return nil
}
recommended, err := versionInfo.FindRecommendedUpgrade(kubernetesVersion)
if err != nil {
klog.Warningf("unable to parse version recommendation for kubernetes version %q in channel", kubernetesVersion)
}
required, err := versionInfo.IsUpgradeRequired(kubernetesVersion)
if err != nil {
klog.Warningf("unable to parse version requirement for kubernetes version %q in channel", kubernetesVersion)
}
if recommended != nil && !required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("A new kubernetes version is available: %s\n", recommended)
fmt.Printf("Upgrading is recommended (try kops upgrade cluster)\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
} else if required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if recommended != nil {
fmt.Printf("A new kubernetes version is available: %s\n", recommended)
}
fmt.Printf("\n")
fmt.Printf("This version of kubernetes is no longer supported; upgrading is required\n")
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_OBSOLETE_VERSION)\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
if required {
if os.Getenv("KOPS_RUN_OBSOLETE_VERSION") == "" {
return fmt.Errorf("kubernetes upgrade is required")
}
}
return nil
}
// addFileAssets adds the file assets within the assetBuilder
func (c *ApplyClusterCmd) addFileAssets(assetBuilder *assets.AssetBuilder) error {
var baseURL string
if components.IsBaseURL(c.Cluster.Spec.KubernetesVersion) {
baseURL = c.Cluster.Spec.KubernetesVersion
} else {
baseURL = "https://storage.googleapis.com/kubernetes-release/release/v" + c.Cluster.Spec.KubernetesVersion
}
c.Assets = make(map[architectures.Architecture][]*mirrors.MirroredAsset)
c.NodeUpAssets = make(map[architectures.Architecture]*mirrors.MirroredAsset)
for _, arch := range architectures.GetSupported() {
c.Assets[arch] = []*mirrors.MirroredAsset{}
k8sAssetsNames := []string{
fmt.Sprintf("/bin/linux/%s/kubelet", arch),
fmt.Sprintf("/bin/linux/%s/kubectl", arch),
}
if needsMounterAsset(c.Cluster, c.InstanceGroups) {
k8sAssetsNames = append(k8sAssetsNames, fmt.Sprintf("/bin/linux/%s/mounter", arch))
}
for _, an := range k8sAssetsNames {
k, err := url.Parse(baseURL)
if err != nil {
return err
}
k.Path = path.Join(k.Path, an)
u, hash, err := assetBuilder.RemapFileAndSHA(k)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(u, hash))
}
cniAsset, cniAssetHash, err := findCNIAssets(c.Cluster, assetBuilder, arch)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(cniAsset, cniAssetHash))
if c.Cluster.Spec.Networking.LyftVPC != nil {
lyftAsset, lyftAssetHash, err := findLyftVPCAssets(c.Cluster, assetBuilder, arch)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(lyftAsset, lyftAssetHash))
}
var containerRuntimeAssetUrl *url.URL
var containerRuntimeAssetHash *hashing.Hash
switch c.Cluster.Spec.ContainerRuntime {
case "docker":
containerRuntimeAssetUrl, containerRuntimeAssetHash, err = findDockerAsset(c.Cluster, assetBuilder, arch)
case "containerd":
containerRuntimeAssetUrl, containerRuntimeAssetHash, err = findContainerdAsset(c.Cluster, assetBuilder, arch)
default:
err = fmt.Errorf("unknown container runtime: %q", c.Cluster.Spec.ContainerRuntime)
}
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(containerRuntimeAssetUrl, containerRuntimeAssetHash))
asset, err := NodeUpAsset(assetBuilder, arch)
if err != nil {
return err
}
c.NodeUpAssets[arch] = asset
}
return nil
}
// buildPermalink returns a link to our "permalink docs", to further explain an error message
func buildPermalink(key, anchor string) string {
url := "https://github.com/kubernetes/kops/blob/master/permalinks/" + key + ".md"
if anchor != "" {
url += "#" + anchor
}
return url
}
func ChannelForCluster(c *kops.Cluster) (*kops.Channel, error) {
channelLocation := c.Spec.Channel
if channelLocation == "" {
channelLocation = kops.DefaultChannel
}
return kops.LoadChannel(channelLocation)
}
// needsMounterAsset checks if we need the mounter program
// This is only needed currently on ContainerOS i.e. GCE, but we don't have a nice way to detect it yet
func needsMounterAsset(c *kops.Cluster, instanceGroups []*kops.InstanceGroup) bool {
// TODO: Do real detection of ContainerOS (but this has to work with image names, and maybe even forked images)
switch kops.CloudProviderID(c.Spec.CloudProvider) {
case kops.CloudProviderGCE:
return true
default:
return false
}
}
type nodeUpConfigBuilder struct {
// Assets is a list of sources for files (primarily when not using everything containerized)
// Formats:
// raw url: http://... or https://...
// url with hash: <hex>@http://... or <hex>@https://...
assets map[architectures.Architecture][]*mirrors.MirroredAsset
assetBuilder *assets.AssetBuilder
channels []string
configBase vfs.Path
cluster *kops.Cluster
etcdManifests map[kops.InstanceGroupRole][]string
images map[kops.InstanceGroupRole]map[architectures.Architecture][]*nodeup.Image
protokubeAsset map[architectures.Architecture][]*mirrors.MirroredAsset
channelsAsset map[architectures.Architecture][]*mirrors.MirroredAsset
}
func newNodeUpConfigBuilder(cluster *kops.Cluster, assetBuilder *assets.AssetBuilder, assets map[architectures.Architecture][]*mirrors.MirroredAsset) (model.NodeUpConfigBuilder, error) {
configBase, err := vfs.Context.BuildVfsPath(cluster.Spec.ConfigBase)
if err != nil {
return nil, fmt.Errorf("error parsing config base %q: %v", cluster.Spec.ConfigBase, err)
}
channels := []string{
configBase.Join("addons", "bootstrap-channel.yaml").Path(),
}
for i := range cluster.Spec.Addons {
channels = append(channels, cluster.Spec.Addons[i].Manifest)
}
etcdManifests := map[kops.InstanceGroupRole][]string{}
images := map[kops.InstanceGroupRole]map[architectures.Architecture][]*nodeup.Image{}
protokubeAsset := map[architectures.Architecture][]*mirrors.MirroredAsset{}
channelsAsset := map[architectures.Architecture][]*mirrors.MirroredAsset{}
for _, arch := range architectures.GetSupported() {
asset, err := ProtokubeAsset(assetBuilder, arch)
if err != nil {
return nil, err
}
protokubeAsset[arch] = append(protokubeAsset[arch], asset)
}
for _, arch := range architectures.GetSupported() {
asset, err := ChannelsAsset(assetBuilder, arch)
if err != nil {
return nil, err
}
channelsAsset[arch] = append(channelsAsset[arch], asset)
}
for _, role := range kops.AllInstanceGroupRoles {
isMaster := role == kops.InstanceGroupRoleMaster
isAPIServer := role == kops.InstanceGroupRoleAPIServer
images[role] = make(map[architectures.Architecture][]*nodeup.Image)
if components.IsBaseURL(cluster.Spec.KubernetesVersion) {
// When using a custom version, we want to preload the images over http
components := []string{"kube-proxy"}
if isMaster {
components = append(components, "kube-apiserver", "kube-controller-manager", "kube-scheduler")
}
if isAPIServer {
components = append(components, "kube-apiserver")
}
for _, arch := range architectures.GetSupported() {
for _, component := range components {
baseURL, err := url.Parse(cluster.Spec.KubernetesVersion)
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/bin/linux", string(arch), component+".tar")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
// `docker load` our images when using a KOPS_BASE_URL, so we
// don't need to push/pull from a registry
if os.Getenv("KOPS_BASE_URL") != "" && isMaster {
for _, arch := range architectures.GetSupported() {
for _, name := range []string{"kops-controller", "dns-controller", "kube-apiserver-healthcheck"} {
baseURL, err := url.Parse(os.Getenv("KOPS_BASE_URL"))
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/images/"+name+"-"+string(arch)+".tar.gz")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
if os.Getenv("KOPS_BASE_URL") != "" && isAPIServer {
for _, arch := range architectures.GetSupported() {
for _, name := range []string{"kube-apiserver-healthcheck"} {
baseURL, err := url.Parse(os.Getenv("KOPS_BASE_URL"))
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/images/"+name+"-"+string(arch)+".tar.gz")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
if isMaster {
for _, etcdCluster := range cluster.Spec.EtcdClusters {
if etcdCluster.Provider == kops.EtcdProviderTypeManager {
p := configBase.Join("manifests/etcd/" + etcdCluster.Name + ".yaml").Path()
etcdManifests[role] = append(etcdManifests[role], p)
}
}
}
}
configBuilder := nodeUpConfigBuilder{
assetBuilder: assetBuilder,
assets: assets,
channels: channels,
configBase: configBase,
cluster: cluster,
etcdManifests: etcdManifests,
images: images,
protokubeAsset: protokubeAsset,
channelsAsset: channelsAsset,
}
return &configBuilder, nil
}
// BuildNodeUpConfig returns the NodeUp config, in YAML format
func (n *nodeUpConfigBuilder) BuildConfig(ig *kops.InstanceGroup, apiserverAdditionalIPs []string, caResource fi.Resource) (*nodeup.Config, error) {
cluster := n.cluster
if ig == nil {
return nil, fmt.Errorf("instanceGroup cannot be nil")
}
role := ig.Spec.Role
if role == "" {
return nil, fmt.Errorf("cannot determine role for instance group: %v", ig.ObjectMeta.Name)
}
useGossip := dns.IsGossipHostname(cluster.Spec.MasterInternalName)
isMaster := role == kops.InstanceGroupRoleMaster
config := nodeup.NewConfig(cluster, ig)
config.Assets = make(map[architectures.Architecture][]string)
for _, arch := range architectures.GetSupported() {
config.Assets[arch] = []string{}
for _, a := range n.assets[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
config.ClusterName = cluster.ObjectMeta.Name
config.InstanceGroupName = ig.ObjectMeta.Name
if isMaster || useGossip {
for _, arch := range architectures.GetSupported() {
for _, a := range n.protokubeAsset[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
for _, arch := range architectures.GetSupported() {
for _, a := range n.channelsAsset[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
}
useConfigServer := featureflag.KopsControllerStateStore.Enabled() && (role != kops.InstanceGroupRoleMaster)
if useConfigServer {
baseURL := url.URL{
Scheme: "https",
Host: net.JoinHostPort("kops-controller.internal."+cluster.ObjectMeta.Name, strconv.Itoa(wellknownports.KopsControllerPort)),
Path: "/",
}
ca, err := fi.ResourceAsString(caResource)
if err != nil {
// CA task may not have run yet; we'll retry
return nil, fmt.Errorf("failed to read CA certificate: %w", err)
}
configServer := &nodeup.ConfigServerOptions{
Server: baseURL.String(),
CloudProvider: cluster.Spec.CloudProvider,
CA: ca,
}
config.ConfigServer = configServer
} else {
config.ConfigBase = fi.String(n.configBase.Path())
}
if isMaster {
config.ApiserverAdditionalIPs = apiserverAdditionalIPs
}
for _, manifest := range n.assetBuilder.StaticManifests {
match := false
for _, r := range manifest.Roles {
if r == role {
match = true
}
}
if !match {
continue
}
config.StaticManifests = append(config.StaticManifests, &nodeup.StaticManifest{
Key: manifest.Key,
Path: manifest.Path,
})
}
config.Images = n.images[role]
config.Channels = n.channels
config.EtcdManifests = n.etcdManifests[role]
return config, nil
}
|
[
"\"KOPS_RUN_OBSOLETE_VERSION\"",
"\"KOPS_RUN_TOO_NEW_VERSION\"",
"\"KOPS_RUN_OBSOLETE_VERSION\"",
"\"KOPS_BASE_URL\"",
"\"KOPS_BASE_URL\"",
"\"KOPS_BASE_URL\"",
"\"KOPS_BASE_URL\""
] |
[] |
[
"KOPS_BASE_URL",
"KOPS_RUN_TOO_NEW_VERSION",
"KOPS_RUN_OBSOLETE_VERSION"
] |
[]
|
["KOPS_BASE_URL", "KOPS_RUN_TOO_NEW_VERSION", "KOPS_RUN_OBSOLETE_VERSION"]
|
go
| 3 | 0 | |
config_test.go
|
package main
import (
"fmt"
"io"
"os"
"strings"
"testing"
"github.com/matryer/is"
)
func TestParseConfig(t *testing.T) {
is := is.New(t)
configFile := strings.NewReader(`
data_directory:
/tmp/webp-server/
default_image_quality:
80
server_address:
127.0.0.1:9000
token:
abcdefg
valid_image_sizes:
- 200x200
- 500x500
- 600x600
valid_image_qualities:
- 90
- 95
- 100
max_uploaded_image_size:
3
http_cache_ttl:
10
debug:
true
convert_concurrency:
3
`)
defer os.RemoveAll("/tmp/webp-server")
cfg, err := parseConfig(configFile)
if err != nil {
t.Fatal(err)
}
expected := &Config{
DataDir: "/tmp/webp-server/",
DefaultImageQuality: 80,
ServerAddress: "127.0.0.1:9000",
Token: "abcdefg",
ValidImageSizes: []string{"200x200", "500x500", "600x600"},
ValidImageQualities: []int{90, 95, 100},
MaxUploadedImageSize: 3,
HTTPCacheTTL: 10,
Debug: true,
ConvertConcurrency: 3,
}
is.Equal(cfg, expected)
if tok := os.Getenv("WEBP_SERVER_TOKEN"); len(tok) == 0 {
os.Setenv("WEBP_SERVER_TOKEN", "123")
defer os.Unsetenv("WEBP_SERVER_TOKEN")
}
_, err = configFile.Seek(0, 0)
is.NoErr(err)
cfg, err = parseConfig(configFile)
if err != nil {
t.Fatal(err)
}
is.Equal(cfg.Token, os.Getenv("WEBP_SERVER_TOKEN"))
}
func TestParseConfigErrors(t *testing.T) {
tt := []struct {
name string
file io.Reader
err error
}{
{
name: "parse_error",
file: strings.NewReader("----"),
err: fmt.Errorf("Invalid Config File: yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `----` into main.Config"),
},
{
name: "empty_data_dir",
file: strings.NewReader("server_address: 127.0.0.1:8080"),
err: fmt.Errorf("Set data_directory in your config file."),
},
{
name: "non_absolute_data_dir",
file: strings.NewReader("data_directory: ~/data"),
err: fmt.Errorf("Absolute path for data_dir needed but got: ~/data"),
},
{
name: "non_absolute_log_path",
file: strings.NewReader("data_directory: /tmp/\nlog_path: ~/log"),
err: fmt.Errorf("Absolute path for log_path needed but got: ~/log"),
},
{
name: "invalid_image_size",
file: strings.NewReader("data_directory: /tmp/\nvalid_image_sizes:\n - 300x"),
err: fmt.Errorf("Image size 300x is not valid. Try use WIDTHxHEIGHT format."),
},
{
name: "invalid_default_quality",
file: strings.NewReader("data_directory: /tmp/\ndefault_image_quality: 120"),
err: fmt.Errorf("Default image quality should be 10 < q < 100."),
},
{
name: "invalid_convert_concurrency",
file: strings.NewReader("data_directory: /tmp/\nconvert_concurrency: 0"),
err: fmt.Errorf("Convert Concurrency should be greater than zero"),
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
is := is.NewRelaxed(t)
_, err := parseConfig(tc.file)
is.True(err != nil)
is.Equal(err, tc.err)
})
}
}
|
[
"\"WEBP_SERVER_TOKEN\"",
"\"WEBP_SERVER_TOKEN\""
] |
[] |
[
"WEBP_SERVER_TOKEN"
] |
[]
|
["WEBP_SERVER_TOKEN"]
|
go
| 1 | 0 | |
pkg/dockerclient/shell.go
|
/*
Copyright 2017 The Nuclio Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dockerclient
import (
"fmt"
"os"
"path"
"strings"
"time"
"github.com/nuclio/nuclio/pkg/cmdrunner"
"github.com/nuclio/nuclio/pkg/common"
"github.com/nuclio/errors"
"github.com/nuclio/logger"
"k8s.io/apimachinery/pkg/util/json"
)
// ShellClient is a docker client that uses the shell to communicate with docker
type ShellClient struct {
logger logger.Logger
cmdRunner cmdrunner.CmdRunner
redactedValues []string
buildTimeout time.Duration
buildRetryInterval time.Duration
}
// NewShellClient creates a new docker client
func NewShellClient(parentLogger logger.Logger, runner cmdrunner.CmdRunner) (*ShellClient, error) {
var err error
newClient := &ShellClient{
logger: parentLogger.GetChild("docker"),
cmdRunner: runner,
buildTimeout: 1 * time.Hour,
buildRetryInterval: 3 * time.Second,
}
// set cmdrunner
if newClient.cmdRunner == nil {
newClient.cmdRunner, err = cmdrunner.NewShellRunner(newClient.logger)
if err != nil {
return nil, errors.Wrap(err, "Failed to create command runner")
}
}
// verify
_, err = newClient.cmdRunner.Run(nil, "docker version")
if err != nil {
return nil, errors.Wrap(err, "No docker client found")
}
return newClient, nil
}
// Build will build a docker image, given build options
func (c *ShellClient) Build(buildOptions *BuildOptions) error {
c.logger.DebugWith("Building image", "buildOptions", buildOptions)
// if context dir is not passed, use the dir containing the dockerfile
if buildOptions.ContextDir == "" && buildOptions.DockerfilePath != "" {
buildOptions.ContextDir = path.Dir(buildOptions.DockerfilePath)
}
// user can only specify context directory
if buildOptions.DockerfilePath == "" && buildOptions.ContextDir != "" {
buildOptions.DockerfilePath = path.Join(buildOptions.ContextDir, "Dockerfile")
}
buildArgs := ""
for buildArgName, buildArgValue := range buildOptions.BuildArgs {
buildArgs += fmt.Sprintf("--build-arg %s=%s ", buildArgName, buildArgValue)
}
cacheOption := ""
if buildOptions.NoCache {
cacheOption = "--no-cache"
}
return c.build(buildOptions, buildArgs, cacheOption)
}
// CopyObjectsFromImage copies objects (files, directories) from a given image to local storage. it does
// this through an intermediate container which is deleted afterwards
func (c *ShellClient) CopyObjectsFromImage(imageName string,
objectsToCopy map[string]string,
allowCopyErrors bool) error {
// create container from image
containerID, err := c.createContainer(imageName)
if err != nil {
return errors.Wrapf(err, "Failed to create container from %s", imageName)
}
// delete once done copying objects
defer c.runCommand(nil, "docker rm -f %s", containerID) // nolint: errcheck
// copy objects
for objectImagePath, objectLocalPath := range objectsToCopy {
_, err = c.runCommand(nil, "docker cp %s:%s %s", containerID, objectImagePath, objectLocalPath)
if err != nil && !allowCopyErrors {
return errors.Wrapf(err, "Can't copy %s:%s -> %s", containerID, objectImagePath, objectLocalPath)
}
}
return nil
}
// PushImage pushes a local image to a remote docker repository
func (c *ShellClient) PushImage(imageName string, registryURL string) error {
taggedImage := common.CompileImageName(registryURL, imageName)
c.logger.InfoWith("Pushing image", "from", imageName, "to", taggedImage)
_, err := c.runCommand(nil, "docker tag %s %s", imageName, taggedImage)
if err != nil {
return errors.Wrap(err, "Failed to tag image")
}
_, err = c.runCommand(nil, "docker push %s", taggedImage)
if err != nil {
return errors.Wrap(err, "Failed to push image")
}
return nil
}
// PullImage pulls an image from a remote docker repository
func (c *ShellClient) PullImage(imageURL string) error {
c.logger.InfoWith("Pulling image", "imageName", imageURL)
_, err := c.runCommand(nil, "docker pull %s", imageURL)
return err
}
// RemoveImage will remove (delete) a local image
func (c *ShellClient) RemoveImage(imageName string) error {
_, err := c.runCommand(nil, "docker rmi -f %s", imageName)
return err
}
// RunContainer will run a container based on an image and run options
func (c *ShellClient) RunContainer(imageName string, runOptions *RunOptions) (string, error) {
portsArgument := ""
for localPort, dockerPort := range runOptions.Ports {
portsArgument += fmt.Sprintf("-p %d:%d ", localPort, dockerPort)
}
restartPolicy := ""
if runOptions.RestartPolicy != nil && runOptions.RestartPolicy.Name != RestartPolicyNameNo {
// sanity check
// https://docs.docker.com/engine/reference/run/#restart-policies---restart
// combining --restart (restart policy) with the --rm (clean up) flag results in an error.
if runOptions.Remove {
return "", errors.Errorf("Cannot combine restart policy with container removal")
}
restartMaxRetries := runOptions.RestartPolicy.MaximumRetryCount
restartPolicy = fmt.Sprintf("--restart %s", runOptions.RestartPolicy.Name)
if runOptions.RestartPolicy.Name == RestartPolicyNameOnFailure && restartMaxRetries >= 0 {
restartPolicy += fmt.Sprintf(":%d", restartMaxRetries)
}
}
detach := "-d"
if runOptions.Attach {
detach = ""
}
removeContainer := ""
if runOptions.Remove {
removeContainer = "--rm"
}
nameArgument := ""
if runOptions.ContainerName != "" {
nameArgument = fmt.Sprintf("--name %s", runOptions.ContainerName)
}
netArgument := ""
if runOptions.Network != "" {
netArgument = fmt.Sprintf("--net %s", runOptions.Network)
}
labelArgument := ""
if runOptions.Labels != nil {
for labelName, labelValue := range runOptions.Labels {
labelArgument += fmt.Sprintf("--label %s='%s' ", labelName, c.replaceSingleQuotes(labelValue))
}
}
envArgument := ""
if runOptions.Env != nil {
for envName, envValue := range runOptions.Env {
envArgument += fmt.Sprintf("--env %s='%s' ", envName, envValue)
}
}
volumeArgument := ""
if runOptions.Volumes != nil {
for volumeHostPath, volumeContainerPath := range runOptions.Volumes {
volumeArgument += fmt.Sprintf("--volume %s:%s ", volumeHostPath, volumeContainerPath)
}
}
runResult, err := c.cmdRunner.Run(
&cmdrunner.RunOptions{LogRedactions: c.redactedValues},
"docker run %s %s %s %s %s %s %s %s %s %s %s",
restartPolicy,
detach,
removeContainer,
portsArgument,
nameArgument,
netArgument,
labelArgument,
envArgument,
volumeArgument,
imageName,
runOptions.Command)
if err != nil {
c.logger.WarnWith("Failed to run container",
"err", err,
"stdout", runResult.Output,
"stderr", runResult.Stderr)
return "", err
}
// if user requested, set stdout / stderr
if runOptions.Stdout != nil {
*runOptions.Stdout = runResult.Output
}
if runOptions.Stderr != nil {
*runOptions.Stderr = runResult.Stderr
}
stdoutLines := strings.Split(runResult.Output, "\n")
lastStdoutLine := c.getLastNonEmptyLine(stdoutLines, 0)
// make sure there are no spaces in the ID, as normally we expect this command to only produce container ID
if strings.Contains(lastStdoutLine, " ") {
// if the image didn't exist prior to calling RunContainer, it will be pulled implicitly which will
// cause additional information to be outputted. if runOptions.ImageMayNotExist is false,
// this will result in an error.
if !runOptions.ImageMayNotExist {
return "", fmt.Errorf("Output from docker command includes more than just ID: %s", lastStdoutLine)
}
// if the implicit image pull was allowed and actually happened, the container ID will appear in the
// second to last line ¯\_(ツ)_/¯
lastStdoutLine = c.getLastNonEmptyLine(stdoutLines, 1)
}
return lastStdoutLine, err
}
// ExecInContainer will run a command in a container
func (c *ShellClient) ExecInContainer(containerID string, execOptions *ExecOptions) error {
envArgument := ""
if execOptions.Env != nil {
for envName, envValue := range execOptions.Env {
envArgument += fmt.Sprintf("--env %s='%s' ", envName, envValue)
}
}
runResult, err := c.cmdRunner.Run(
&cmdrunner.RunOptions{LogRedactions: c.redactedValues},
"docker exec %s %s %s",
envArgument,
containerID,
execOptions.Command)
if err != nil {
c.logger.DebugWith("Failed to execute command in container",
"err", err,
"stdout", runResult.Output,
"stderr", runResult.Stderr)
return err
}
// if user requested, set stdout / stderr
if execOptions.Stdout != nil {
*execOptions.Stdout = runResult.Output
}
if execOptions.Stderr != nil {
*execOptions.Stderr = runResult.Stderr
}
return nil
}
// RemoveContainer removes a container given a container ID
func (c *ShellClient) RemoveContainer(containerID string) error {
_, err := c.runCommand(nil, "docker rm -f %s", containerID)
return err
}
// StopContainer stops a container given a container ID
func (c *ShellClient) StopContainer(containerID string) error {
_, err := c.runCommand(nil, "docker stop %s", containerID)
return err
}
// StartContainer stops a container given a container ID
func (c *ShellClient) StartContainer(containerID string) error {
_, err := c.runCommand(nil, "docker start %s", containerID)
return err
}
// GetContainerLogs returns raw logs from a given container ID
// Concatenating stdout and stderr since there's no way to re-interlace them
func (c *ShellClient) GetContainerLogs(containerID string) (string, error) {
runOptions := &cmdrunner.RunOptions{
CaptureOutputMode: cmdrunner.CaptureOutputModeCombined,
}
runResult, err := c.runCommand(runOptions, "docker logs %s", containerID)
return runResult.Output, err
}
// AwaitContainerHealth blocks until the given container is healthy or the timeout passes
func (c *ShellClient) AwaitContainerHealth(containerID string, timeout *time.Duration) error {
timedOut := false
containerHealthy := make(chan error, 1)
var timeoutChan <-chan time.Time
// if no timeout is given, create a channel that we'll never send on
if timeout == nil {
timeoutChan = make(<-chan time.Time, 1)
} else {
timeoutChan = time.After(*timeout)
}
go func() {
// start with a small interval between health checks, increasing it gradually
inspectInterval := 100 * time.Millisecond
for !timedOut {
containers, err := c.GetContainers(&GetContainerOptions{
ID: containerID,
Stopped: true,
})
if err == nil && len(containers) > 0 {
container := containers[0]
// container is healthy
if container.State.Health.Status == "healthy" {
containerHealthy <- nil
return
}
// container exited, bail out
if container.State.Status == "exited" {
containerHealthy <- errors.Errorf("Container exited with status: %d", container.State.ExitCode)
return
}
// container is dead, bail out
// https://docs.docker.com/engine/reference/commandline/ps/#filtering
if container.State.Status == "dead" {
containerHealthy <- errors.New("Container seems to be dead")
return
}
// wait a bit before retrying
c.logger.DebugWith("Container not healthy yet, retrying soon",
"timeout", timeout,
"containerID", containerID,
"containerState", container.State,
"nextCheckIn", inspectInterval)
}
time.Sleep(inspectInterval)
// increase the interval up to a cap
if inspectInterval < 800*time.Millisecond {
inspectInterval *= 2
}
}
}()
// wait for either the container to be healthy or the timeout
select {
case err := <-containerHealthy:
if err != nil {
return errors.Wrapf(err, "Container %s is not healthy", containerID)
}
c.logger.DebugWith("Container is healthy", "containerID", containerID)
case <-timeoutChan:
timedOut = true
containerLogs, err := c.GetContainerLogs(containerID)
if err != nil {
c.logger.ErrorWith("Container wasn't healthy within timeout (failed to get logs)",
"containerID", containerID,
"timeout", timeout,
"err", err)
} else {
c.logger.WarnWith("Container wasn't healthy within timeout",
"containerID", containerID,
"timeout", timeout,
"logs", containerLogs)
}
return errors.New("Container wasn't healthy in time")
}
return nil
}
// GetContainers returns a list of container IDs which match a certain criteria
func (c *ShellClient) GetContainers(options *GetContainerOptions) ([]Container, error) {
c.logger.DebugWith("Getting containers", "options", options)
stoppedContainersArgument := ""
if options.Stopped {
stoppedContainersArgument = "--all "
}
nameFilterArgument := ""
if options.Name != "" {
nameFilterArgument = fmt.Sprintf(`--filter "name=^/%s$" `, options.Name)
}
idFilterArgument := ""
if options.ID != "" {
idFilterArgument = fmt.Sprintf(`--filter "id=%s"`, options.ID)
}
labelFilterArgument := ""
for labelName, labelValue := range options.Labels {
labelFilterArgument += fmt.Sprintf(`--filter "label=%s=%s" `,
labelName,
labelValue)
}
runResult, err := c.runCommand(nil,
"docker ps --quiet %s %s %s %s",
stoppedContainersArgument,
idFilterArgument,
nameFilterArgument,
labelFilterArgument)
if err != nil {
return nil, errors.Wrap(err, "Failed to get containers")
}
containerIDsAsString := runResult.Output
if len(containerIDsAsString) == 0 {
return []Container{}, nil
}
runResult, err = c.runCommand(nil,
"docker inspect %s",
strings.Replace(containerIDsAsString, "\n", " ", -1))
if err != nil {
return nil, errors.Wrap(err, "Failed to inspect containers")
}
containersInfoString := runResult.Output
var containersInfo []Container
// parse the result
if err := json.Unmarshal([]byte(containersInfoString), &containersInfo); err != nil {
return nil, errors.Wrap(err, "Failed to parse inspect response")
}
return containersInfo, nil
}
// GetContainerEvents returns a list of container events which occurred within a time range
func (c *ShellClient) GetContainerEvents(containerName string, since string, until string) ([]string, error) {
runResults, err := c.runCommand(nil, "docker events --filter container=%s --since %s --until %s",
containerName,
since,
until)
if err != nil {
return nil, errors.Wrap(err, "Failed to get container events")
}
return strings.Split(strings.TrimSpace(runResults.Output), "\n"), nil
}
// LogIn allows docker client to access secured registries
func (c *ShellClient) LogIn(options *LogInOptions) error {
c.redactedValues = append(c.redactedValues, options.Password)
_, err := c.runCommand(nil, `docker login -u %s -p '%s' %s`,
options.Username,
options.Password,
options.URL)
return err
}
// CreateNetwork creates a docker network
func (c *ShellClient) CreateNetwork(options *CreateNetworkOptions) error {
_, err := c.runCommand(nil, `docker network create %s`, options.Name)
return err
}
// DeleteNetwork deletes a docker network
func (c *ShellClient) DeleteNetwork(networkName string) error {
_, err := c.runCommand(nil, `docker network rm %s`, networkName)
return err
}
func (c *ShellClient) Save(imageName string, outPath string) error {
_, err := c.runCommand(nil, `docker save --output %s %s`, outPath, imageName)
return err
}
func (c *ShellClient) Load(inPath string) error {
_, err := c.runCommand(nil, `docker load --input %s`, inPath)
return err
}
func (c *ShellClient) runCommand(runOptions *cmdrunner.RunOptions, format string, vars ...interface{}) (cmdrunner.RunResult, error) {
// if user
if runOptions == nil {
runOptions = &cmdrunner.RunOptions{
CaptureOutputMode: cmdrunner.CaptureOutputModeStdout,
}
}
runOptions.LogRedactions = append(runOptions.LogRedactions, c.redactedValues...)
runResult, err := c.cmdRunner.Run(runOptions, format, vars...)
if runOptions.CaptureOutputMode == cmdrunner.CaptureOutputModeStdout && runResult.Stderr != "" {
c.logger.WarnWith("Docker command outputted to stderr - this may result in errors",
"workingDir", runOptions.WorkingDir,
"cmd", common.Redact(runOptions.LogRedactions, fmt.Sprintf(format, vars...)),
"stderr", runResult.Stderr)
}
return runResult, err
}
func (c *ShellClient) getLastNonEmptyLine(lines []string, offset int) string {
numLines := len(lines)
// protect ourselves from overflows
if offset >= numLines {
offset = numLines - 1
} else if offset < 0 {
offset = 0
}
// iterate backwards over the lines
for idx := numLines - 1 - offset; idx >= 0; idx-- {
if lines[idx] != "" {
return lines[idx]
}
}
return ""
}
func (c *ShellClient) replaceSingleQuotes(input string) string {
return strings.Replace(input, "'", "’", -1)
}
func (c *ShellClient) resolveDockerBuildNetwork() string {
// may contain none as a value
networkInterface := os.Getenv("NUCLIO_DOCKER_BUILD_NETWORK")
if networkInterface == "" {
networkInterface = common.GetEnvOrDefaultString("NUCLIO_BUILD_USE_HOST_NET", "host")
}
switch networkInterface {
case "host":
fallthrough
case "default":
fallthrough
case "none":
return fmt.Sprintf("--network %s", networkInterface)
default:
return ""
}
}
func (c *ShellClient) build(buildOptions *BuildOptions, buildArgs string, cacheOption string) error {
var lastBuildErr error
retryOnErrorMessages := []string{
// when one of the underlying image is gone (from cache)
"^No such image: sha256:",
// when overlay image is gone (from disk)
"^failed to get digest sha256:",
}
runOptions := &cmdrunner.RunOptions{
CaptureOutputMode: cmdrunner.CaptureOutputModeStdout,
WorkingDir: &buildOptions.ContextDir,
}
// retry build on predefined errors that occur during race condition and collisions between
// shared onbuild layers
common.RetryUntilSuccessfulOnErrorPatterns(c.buildTimeout, // nolint: errcheck
c.buildRetryInterval,
retryOnErrorMessages,
func() string { // nolint: errcheck
runResults, err := c.runCommand(runOptions,
"docker build %s --force-rm -t %s -f %s %s %s .",
c.resolveDockerBuildNetwork(),
buildOptions.Image,
buildOptions.DockerfilePath,
cacheOption,
buildArgs)
// preserve error
lastBuildErr = err
if err != nil {
return runResults.Stderr
}
return ""
})
return lastBuildErr
}
func (c *ShellClient) createContainer(imageName string) (string, error) {
var lastCreateContainerError error
var containerID string
retryOnErrorMessages := []string{
// sometimes, creating the container fails on not finding the image because
// docker was on high load and did not get to update its cache
fmt.Sprintf("^Unable to find image '%s.*' locally", imageName),
}
// retry in case docker daemon is under high load
// e.g.: between build and create, docker would need to update its cached manifest of built images
common.RetryUntilSuccessfulOnErrorPatterns(10*time.Second, // nolint: errcheck
2*time.Second,
retryOnErrorMessages,
func() string {
// create container from image
runResults, err := c.runCommand(nil, "docker create %s /bin/sh", imageName)
// preserve error
lastCreateContainerError = err
if err != nil {
return runResults.Stderr
}
containerID = runResults.Output
containerID = strings.TrimSpace(containerID)
return ""
})
return containerID, lastCreateContainerError
}
|
[
"\"NUCLIO_DOCKER_BUILD_NETWORK\""
] |
[] |
[
"NUCLIO_DOCKER_BUILD_NETWORK"
] |
[]
|
["NUCLIO_DOCKER_BUILD_NETWORK"]
|
go
| 1 | 0 | |
cmd/dev_client/main.go
|
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"os/user"
"time"
"github.com/pinterest/knox"
"github.com/pinterest/knox/client"
)
// certPEMBlock is the certificate signed by the CA to identify the machine using the client
// (Should be pulled from a file or via another process)
const certPEMBlock = `-----BEGIN CERTIFICATE-----
MIIB7TCCAZOgAwIBAgIDEAAEMAoGCCqGSM49BAMCMFExCzAJBgNVBAYTAlVTMQsw
CQYDVQQIEwJDQTEYMBYGA1UEChMPTXkgQ29tcGFueSBOYW1lMRswGQYDVQQDExJ1
c2VPbmx5SW5EZXZPclRlc3QwHhcNMTgwMzAyMDI1NjEyWhcNMTkwMzAyMDI1NjEy
WjBKMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExGDAWBgNVBAoMD015IENvbXBh
bnkgTmFtZTEUMBIGA1UEAwwLZXhhbXBsZS5jb20wWTATBgcqhkjOPQIBBggqhkjO
PQMBBwNCAAQQTbdQNoE5/j6mgh4HAdbgPyGbuzjpHI/x34p6qPojduUK+ifUW6Mb
bS5Zumjh31K5AmWYt4jWfU82Sb6sxPKXo2EwXzAJBgNVHRMEAjAAMAsGA1UdDwQE
AwIF4DBFBgNVHREEPjA8hhxzcGlmZmU6Ly9leGFtcGxlLmNvbS9zZXJ2aWNlggtl
eGFtcGxlLmNvbYIPd3d3LmV4YW1wbGUuY29tMAoGCCqGSM49BAMCA0gAMEUCIQDO
TaI0ltMPlPDt4XSdWJawZ4euAGXJCyoxHFs8HQK8XwIgVokWyTcajFoP0/ZfzrM5
SihfFJr39Ck4V5InJRHPPtY=
-----END CERTIFICATE-----`
// keyPEMBlock is the private key that should only be available on the machine running this client
// (Should be pulled from a file or via another process)
const keyPEMBlock = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDHDjs9Ug8QvsuKRrtC6QUmz4u++oBJF2VtCZe9gYyzOoAoGCCqGSM49
AwEHoUQDQgAEEE23UDaBOf4+poIeBwHW4D8hm7s46RyP8d+Keqj6I3blCvon1Fuj
G20uWbpo4d9SuQJlmLeI1n1PNkm+rMTylw==
-----END EC PRIVATE KEY-----`
// hostname is the host running the knox server
const hostname = "localhost:9000"
// tokenEndpoint and clientID are used by "knox login" if your oauth client supports password flows.
const tokenEndpoint = "https://oauth.token.endpoint.used.for/knox/login"
const clientID = ""
// keyFolder is the directory where keys are cached
const keyFolder = "/var/lib/knox/v0/keys/"
// authTokenResp is the format of the OAuth response generated by "knox login"
type authTokenResp struct {
AccessToken string `json:"access_token"`
Error string `json:"error"`
}
// getCert returns the cert in the tls.Certificate format. This should be a config option in prod.
func getCert() (tls.Certificate, error) {
return tls.X509KeyPair([]byte(certPEMBlock), []byte(keyPEMBlock))
}
// authHandler is used to generate an authentication header.
// The server expects VersionByte + TypeByte + IDToPassToAuthHandler.
func authHandler() string {
if s := os.Getenv("KNOX_USER_AUTH"); s != "" {
return "0u" + s
}
if s := os.Getenv("KNOX_MACHINE_AUTH"); s != "" {
c, _ := getCert()
x509Cert, err := x509.ParseCertificate(c.Certificate[0])
if err != nil {
return "0t" + s
}
if len(x509Cert.Subject.CommonName) > 0 {
return "0t" + x509Cert.Subject.CommonName
} else if len(x509Cert.DNSNames) > 0 {
return "0t" + x509Cert.DNSNames[0]
} else {
return "0t" + s
}
}
if s := os.Getenv("KNOX_SERVICE_AUTH"); s != "" {
return "0s" + s
}
u, err := user.Current()
if err != nil {
return ""
}
d, err := ioutil.ReadFile(u.HomeDir + "/.knox_user_auth")
if err != nil {
return ""
}
var authResp authTokenResp
err = json.Unmarshal(d, &authResp)
if err != nil {
return ""
}
return "0u" + authResp.AccessToken
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
tlsConfig := &tls.Config{
ServerName: "knox",
InsecureSkipVerify: true,
}
cert, err := getCert()
if err == nil {
tlsConfig.Certificates = []tls.Certificate{cert}
}
cli := &knox.HTTPClient{
Host: hostname,
AuthHandler: authHandler,
KeyFolder: keyFolder,
Client: &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}},
}
client.Run(cli, &client.VisibilityParams{log.Printf, log.Printf, func(map[string]uint64) {}}, tokenEndpoint, clientID)
}
|
[
"\"KNOX_USER_AUTH\"",
"\"KNOX_MACHINE_AUTH\"",
"\"KNOX_SERVICE_AUTH\""
] |
[] |
[
"KNOX_MACHINE_AUTH",
"KNOX_USER_AUTH",
"KNOX_SERVICE_AUTH"
] |
[]
|
["KNOX_MACHINE_AUTH", "KNOX_USER_AUTH", "KNOX_SERVICE_AUTH"]
|
go
| 3 | 0 | |
cmd/gateway-main.go
|
/*
* Minio Cloud Storage, (C) 2017, 2018 Minio, 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.
*/
package cmd
import (
"context"
"fmt"
"net"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"github.com/gorilla/mux"
"github.com/minio/cli"
xhttp "github.com/minio/minio/cmd/http"
"github.com/minio/minio/cmd/logger"
"github.com/minio/minio/pkg/certs"
)
func init() {
logger.Init(GOPATH, GOROOT)
logger.RegisterUIError(fmtError)
}
var (
gatewayCmd = cli.Command{
Name: "gateway",
Usage: "start object storage gateway",
Flags: append(serverFlags, globalFlags...),
HideHelpCommand: true,
}
)
// RegisterGatewayCommand registers a new command for gateway.
func RegisterGatewayCommand(cmd cli.Command) error {
cmd.Flags = append(append(cmd.Flags, append(cmd.Flags, serverFlags...)...), globalFlags...)
gatewayCmd.Subcommands = append(gatewayCmd.Subcommands, cmd)
return nil
}
// ParseGatewayEndpoint - Return endpoint.
func ParseGatewayEndpoint(arg string) (endPoint string, secure bool, err error) {
schemeSpecified := len(strings.Split(arg, "://")) > 1
if !schemeSpecified {
// Default connection will be "secure".
arg = "https://" + arg
}
u, err := url.Parse(arg)
if err != nil {
return "", false, err
}
switch u.Scheme {
case "http":
return u.Host, false, nil
case "https":
return u.Host, true, nil
default:
return "", false, fmt.Errorf("Unrecognized scheme %s", u.Scheme)
}
}
// ValidateGatewayArguments - Validate gateway arguments.
func ValidateGatewayArguments(serverAddr, endpointAddr string) error {
if err := CheckLocalServerAddr(serverAddr); err != nil {
return err
}
if endpointAddr != "" {
// Reject the endpoint if it points to the gateway handler itself.
sameTarget, err := sameLocalAddrs(endpointAddr, serverAddr)
if err != nil {
return err
}
if sameTarget {
return fmt.Errorf("endpoint points to the local gateway")
}
}
return nil
}
// StartGateway - handler for 'minio gateway <name>'.
func StartGateway(ctx *cli.Context, gw Gateway) {
if gw == nil {
logger.FatalIf(errUnexpected, "Gateway implementation not initialized")
}
// Disable logging until gateway initialization is complete, any
// error during initialization will be shown as a fatal message
logger.Disable = true
// Validate if we have access, secret set through environment.
gatewayName := gw.Name()
if ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, gatewayName, 1)
}
// Get "json" flag from command line argument and
// enable json and quite modes if jason flag is turned on.
jsonFlag := ctx.IsSet("json") || ctx.GlobalIsSet("json")
if jsonFlag {
logger.EnableJSON()
}
// Get quiet flag from command line argument.
quietFlag := ctx.IsSet("quiet") || ctx.GlobalIsSet("quiet")
if quietFlag {
logger.EnableQuiet()
}
// Fetch address option
gatewayAddr := ctx.GlobalString("address")
if gatewayAddr == ":"+globalMinioPort {
gatewayAddr = ctx.String("address")
}
// Handle common command args.
handleCommonCmdArgs(ctx)
// Get port to listen on from gateway address
var pErr error
_, globalMinioPort, pErr = net.SplitHostPort(gatewayAddr)
if pErr != nil {
logger.FatalIf(pErr, "Unable to start gateway")
}
// On macOS, if a process already listens on LOCALIPADDR:PORT, net.Listen() falls back
// to IPv6 address ie minio will start listening on IPv6 address whereas another
// (non-)minio process is listening on IPv4 of given port.
// To avoid this error situation we check for port availability.
logger.FatalIf(checkPortAvailability(globalMinioPort), "Unable to start the gateway")
// Create certs path.
logger.FatalIf(createConfigDir(), "Unable to create configuration directories")
// Check and load TLS certificates.
var err error
globalPublicCerts, globalTLSCerts, globalIsSSL, err = getTLSConfig()
logger.FatalIf(err, "Invalid TLS certificate file")
// Check and load Root CAs.
globalRootCAs, err = getRootCAs(getCADir())
logger.FatalIf(err, "Failed to read root CAs (%v)", err)
// Handle common env vars.
handleCommonEnvVars()
// Validate if we have access, secret set through environment.
if !globalIsEnvCreds {
logger.Fatal(uiErrEnvCredentialsMissingGateway(nil), "Unable to start gateway")
}
// Set system resources to maximum.
logger.LogIf(context.Background(), setMaxResources())
initNSLock(false) // Enable local namespace lock.
router := mux.NewRouter().SkipClean(true)
if globalEtcdClient != nil {
// Enable STS router if etcd is enabled.
registerSTSRouter(router)
// Enable admin router if etcd is enabled.
registerAdminRouter(router)
}
// Add healthcheck router
registerHealthCheckRouter(router)
// Add server metrics router
registerMetricsRouter(router)
// Register web router when its enabled.
if globalIsBrowserEnabled {
logger.FatalIf(registerWebRouter(router), "Unable to configure web browser")
}
// Add API router.
registerAPIRouter(router)
var getCert certs.GetCertificateFunc
if globalTLSCerts != nil {
getCert = globalTLSCerts.GetCertificate
}
globalHTTPServer = xhttp.NewServer([]string{gatewayAddr}, criticalErrorHandler{registerHandlers(router, globalHandlers...)}, getCert)
globalHTTPServer.UpdateBytesReadFunc = globalConnStats.incInputBytes
globalHTTPServer.UpdateBytesWrittenFunc = globalConnStats.incOutputBytes
go func() {
globalHTTPServerErrorCh <- globalHTTPServer.Start()
}()
signal.Notify(globalOSSignalCh, os.Interrupt, syscall.SIGTERM)
newObject, err := gw.NewGatewayLayer(globalServerConfig.GetCredential())
if err != nil {
// Stop watching for any certificate changes.
globalTLSCerts.Stop()
globalHTTPServer.Shutdown()
logger.FatalIf(err, "Unable to initialize gateway backend")
}
// Create a new config system.
globalConfigSys = NewConfigSys()
// Initialize server config.
srvCfg := newServerConfig()
// Override any values from ENVs.
srvCfg.loadFromEnvs()
// Load values to cached global values.
srvCfg.loadToCachedConfigs()
// hold the mutex lock before a new config is assigned.
globalServerConfigMu.Lock()
globalServerConfig = srvCfg
globalServerConfigMu.Unlock()
// Load logger subsystem
loadLoggers()
// This is only to uniquely identify each gateway deployments.
globalDeploymentID = os.Getenv("MINIO_GATEWAY_DEPLOYMENT_ID")
var cacheConfig = globalServerConfig.GetCacheConfig()
if len(cacheConfig.Drives) > 0 {
var err error
// initialize the new disk cache objects.
globalCacheObjectAPI, err = newServerCacheObjects(cacheConfig)
logger.FatalIf(err, "Unable to initialize disk caching")
}
// Re-enable logging
logger.Disable = false
// Create new IAM system.
globalIAMSys = NewIAMSys()
if globalEtcdClient != nil {
// Initialize IAM sys.
go globalIAMSys.Init(newObject)
}
// Create new policy system.
globalPolicySys = NewPolicySys()
// Initialize policy system.
go globalPolicySys.Init(newObject)
// Create new notification system.
globalNotificationSys = NewNotificationSys(globalServerConfig, globalEndpoints)
// Once endpoints are finalized, initialize the new object api.
globalObjLayerMutex.Lock()
globalObjectAPI = newObject
globalObjLayerMutex.Unlock()
// Prints the formatted startup message once object layer is initialized.
if !quietFlag {
mode := globalMinioModeGatewayPrefix + gatewayName
// Check update mode.
checkUpdate(mode)
// Print a warning message if gateway is not ready for production before the startup banner.
if !gw.Production() {
logger.StartupMessage(colorYellow(" *** Warning: Not Ready for Production ***"))
}
// Print gateway startup message.
printGatewayStartupMessage(getAPIEndpoints(gatewayAddr), gatewayName)
}
handleSignals()
}
|
[
"\"MINIO_GATEWAY_DEPLOYMENT_ID\""
] |
[] |
[
"MINIO_GATEWAY_DEPLOYMENT_ID"
] |
[]
|
["MINIO_GATEWAY_DEPLOYMENT_ID"]
|
go
| 1 | 0 | |
firstCall/service.go
|
package firstCall
import (
"context"
"github.com/pkg/errors"
"os"
)
type Service interface {
GetFirstCall(ctx context.Context, chat uint32) (name string, number string, err error)
}
type defaultFirstCallService struct {
}
func NewDefaultFirstcallService() Service {
return &defaultFirstCallService{}
}
func (*defaultFirstCallService) GetFirstCall(ctx context.Context, chat uint32) (name string, number string, err error) {
return "DEFAULT", os.Getenv("DEFAULT_CALLOUT_NUMBER"), nil
}
func (*defaultFirstCallService) setGroup(ctx context.Context, chat uint32, group string) (name string, number string, err error) {
return "", "", errors.New("Set Group not implimented for default callout")
}
func (*defaultFirstCallService) getGroup(ctx context.Context, chat uint32) (string, error) {
return "", errors.New("get Group not implimented for default callout")
}
|
[
"\"DEFAULT_CALLOUT_NUMBER\""
] |
[] |
[
"DEFAULT_CALLOUT_NUMBER"
] |
[]
|
["DEFAULT_CALLOUT_NUMBER"]
|
go
| 1 | 0 | |
octoprint_discordremote/__init__.py
|
# coding=utf-8
from __future__ import absolute_import
import threading
import time
from base64 import b64decode
from datetime import timedelta, datetime
import humanfriendly
import octoprint.plugin
import octoprint.settings
import os
import requests
import socket
import subprocess
import logging
from PIL import Image
from flask import make_response
from io import BytesIO
from octoprint.server import user_permission
from requests import ConnectionError
from threading import Thread, Event
from octoprint_discordremote.libs import ipgetter
from octoprint_discordremote.command import Command
from octoprint_discordremote.embedbuilder import info_embed
from octoprint_discordremote.presence import Presence
from .discord import Discord
class DiscordRemotePlugin(octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.ProgressPlugin,
octoprint.plugin.SimpleApiPlugin):
#extend Octoprint's allowed file types by .zip, .zip.001, .zip.002, ...)
def get_extension_tree(self, *args, **kwargs):
allowed_list = ['zip']
for i in range(0, 100):
allowed_list.append(str(i).zfill(3))
return dict(machinecode=dict(discordremote=allowed_list))
def __init__(self):
self.discord = None
self.command = None
self.last_progress_message = None
self.last_progress_percent = 0
self.is_muted = False
self.periodic_signal = None
self.periodic_thread = None
self.presence = None
# Events definition here (better for intellisense in IDE)
# referenced in the settings too.
self.events = {
"startup": {
"name": "Octoprint Startup",
"enabled": True,
"with_snapshot": False,
"message": "⏰ I just woke up! What are we gonna print today?\n"
"Local IP: {ipaddr} External IP: {externaddr}"
},
"shutdown": {
"name": "Octoprint Shutdown",
"enabled": True,
"with_snapshot": False,
"message": "💤 Going to bed now!"
},
"printer_state_operational": {
"name": "Printer state : operational",
"enabled": True,
"with_snapshot": False,
"message": "✅ Your printer is operational."
},
"printer_state_error": {
"name": "Printer state : error",
"enabled": True,
"with_snapshot": False,
"message": "⚠️ Your printer is in an erroneous state."
},
"printer_state_unknown": {
"name": "Printer state : unknown",
"enabled": True,
"with_snapshot": False,
"message": "❔ Your printer is in an unknown state."
},
"printing_started": {
"name": "Printing process : started",
"enabled": True,
"with_snapshot": True,
"message": "🖨️ I've started printing {path}"
},
"printing_paused": {
"name": "Printing process : paused",
"enabled": True,
"with_snapshot": True,
"message": "⏸️ The printing was paused."
},
"printing_resumed": {
"name": "Printing process : resumed",
"enabled": True,
"with_snapshot": True,
"message": "▶️ The printing was resumed."
},
"printing_cancelled": {
"name": "Printing process : cancelled",
"enabled": True,
"with_snapshot": True,
"message": "🛑 The printing was stopped."
},
"printing_done": {
"name": "Printing process : done",
"enabled": True,
"with_snapshot": True,
"message": "👍 Printing is done! Took about {time_formatted}"
},
"printing_failed": {
"name": "Printing process : failed",
"enabled": True,
"with_snapshot": True,
"message": "👎 Printing has failed! :("
},
"printing_progress": {
"name": "Printing progress (Percentage)",
"enabled": True,
"with_snapshot": True,
"message": "📢 Printing is at {progress}%",
"step": 10
},
"printing_progress_periodic": {
"name": "Printing progress (Periodic)",
"enabled": False,
"with_snapshot": True,
"message": "📢 Printing is at {progress}%",
"period": 300
},
"test": { # Not a real message, but we will treat it as one
"enabled": True,
"with_snapshot": True,
"message": "Hello hello! If you see this message, it means that the settings are correct!"
},
}
self.permissions = {
'1': {'users': '*', 'commands': ''},
'2': {'users': '', 'commands': ''},
'3': {'users': '', 'commands': ''},
'4': {'users': '', 'commands': ''},
'5': {'users': '', 'commands': ''}
}
def configure_discord(self, send_test=False):
# Configure discord
if self.command is None:
self.command = Command(self)
if self.discord is None:
self.discord = Discord()
self.discord.configure_discord(self._settings.get(['bottoken'], merged=True),
self._settings.get(['channelid'], merged=True),
self._logger,
self.command,
self.update_discord_status)
if send_test:
self.notify_event("test")
def configure_presence(self):
if self.presence is None:
self.presence = Presence()
self.presence.configure_presence(self, self.discord)
def on_after_startup(self):
# Use a different log file for DiscordRemote, as it is very noisy.
self._logger = logging.getLogger("octoprint.plugins.discordremote")
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
hdlr = CleaningTimedRotatingFileHandler(
self._settings.get_plugin_logfile_path(), when="D", backupCount=3)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
self._logger.addHandler(hdlr)
# Initialise DiscordRemote
self._logger.info("DiscordRemote is started !")
self.configure_discord(False)
self.configure_presence()
# Transition settings
allowed_users = self._settings.get(['allowedusers'], merged=True)
if allowed_users:
self._settings.set(["allowedusers"], None, True)
self._settings.set(['permissions'], {'1': {'users': allowed_users, 'commands': ''}}, True)
self.send_message(None, "⚠️⚠️⚠️ Allowed users has been changed to a more granular system. "
"Check the DiscordRemote settings and check that it is suitable⚠️⚠️⚠️")
# ShutdownPlugin mixin
def on_shutdown(self):
self._logger.info("DiscordRemote is shutting down.")
self.discord.shutdown_discord()
self._logger.info("Discord bot has excited cleanly.")
# SettingsPlugin mixin
def get_settings_defaults(self):
return {
'bottoken': "",
'channelid': "",
'baseurl': "",
'presence': True,
'presence_cycle_time': 10,
'prefix': "/",
'show_local_ip': 'auto',
'show_external_ip': 'auto',
'use_hostname': False,
'hostname': "YOUR.HOST.NAME",
'use_hostname_only': False,
'events': self.events,
'permissions': self.permissions,
'allow_scripts': False,
'script_before': '',
'script_after': '',
'allowed_gcode': ''
}
# Restricts some paths to some roles only
def get_settings_restricted_paths(self):
# settings.events.tests is a false message, so we should never see it as configurable.
# settings.bottoken and channelid are admin only.
return dict(never=[["events", "test"]],
admin=[["bottoken"],
["channelid"],
["permissions"],
['baseurl'],
['presence'],
['presence_cycle_time'],
['prefix'],
["show_local_ip"],
["show_external_ip"],
["use_hostname"],
["hostname"],
["use_hostname_only"],
['script_before'],
['script_after'],
['allowed_gcode']])
# AssetPlugin mixin
def get_assets(self):
# Define your plugin's asset files to automatically include in the
# core UI here.
return dict(
js=["js/discordremote.js"],
css=["css/discordremote.css"],
less=["less/discordremote.less"]
)
# TemplatePlugin mixin
def get_template_configs(self):
return [
dict(type="settings", custom_bindings=False)
]
# Softwareupdate hook
def get_update_information(self):
# Define the configuration for your plugin to use with the Software Update
# Plugin here. See https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update
# for details.
return dict(
discordremote=dict(
displayName="DiscordRemote Plugin",
displayVersion=self._plugin_version,
# version check: github repository
type="github_release",
user="cameroncros",
repo="OctoPrint-DiscordRemote",
current=self._plugin_version,
# update method: pip
pip="https://github.com/cameroncros/OctoPrint-DiscordRemote/archive/{target_version}.zip"
)
)
# EventHandlerPlugin hook
def on_event(self, event, payload):
if event == "Startup":
return self.notify_event("startup")
if event == "Shutdown":
return self.notify_event("shutdown")
if event == "PrinterStateChanged":
if payload["state_id"] == "OPERATIONAL":
return self.notify_event("printer_state_operational")
elif payload["state_id"] == "ERROR":
return self.notify_event("printer_state_error")
elif payload["state_id"] == "UNKNOWN":
return self.notify_event("printer_state_unknown")
if event == "PrintStarted":
self.start_periodic_reporting()
return self.notify_event("printing_started", payload)
if event == "PrintPaused":
return self.notify_event("printing_paused", payload)
if event == "PrintResumed":
return self.notify_event("printing_resumed", payload)
if event == "PrintCancelled":
return self.notify_event("printing_cancelled", payload)
if event == "PrintDone":
self.stop_periodic_reporting()
payload['time_formatted'] = timedelta(seconds=int(payload["time"]))
return self.notify_event("printing_done", payload)
return True
def on_print_progress(self, location, path, progress):
# Avoid sending duplicate percentage progress messages
if progress != self.last_progress_percent:
self.last_progress_percent = progress
self.notify_event("printing_progress", {"progress": progress})
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._logger.info("Settings have saved. Send a test message...")
thread = threading.Thread(target=self.configure_discord, args=(True,))
thread.start()
# SimpleApiPlugin mixin
def get_api_commands(self):
return dict(
executeCommand=['args'],
sendMessage=[]
)
def on_api_command(self, comm, data):
if not user_permission.can():
return make_response("Insufficient rights", 403)
if comm == 'executeCommand':
return self.execute_command(data)
if comm == 'sendMessage':
return self.unpack_message(data)
def execute_command(self, data):
args = ""
if 'args' in data:
args = data['args']
snapshots, embeds = self.command.parse_command(args)
if not self.discord.send(snapshots=snapshots, embeds=embeds):
return make_response("Failed to send message", 404)
def unpack_message(self, data):
builder = embedbuilder.EmbedBuilder()
if 'title' in data:
builder.set_title(data['title'])
if 'author' in data:
builder.set_author(data['author'])
if 'color' in data:
builder.set_color(data['color'])
if 'description' in data:
builder.set_description(data['description'])
if 'image' in data:
b64image = data['image']
imagename = data.get('imagename', 'snapshot.png')
bytes = b64decode(b64image)
image = BytesIO(bytes)
builder.set_image((imagename, image))
if not self.discord.send(embeds=builder.get_embeds()):
return make_response("Failed to send message", 404)
def notify_event(self, event_id, data=None):
self._logger.info("Received event: %s" % event_id)
if self.is_muted:
return True
if data is None:
data = {}
if event_id not in self.events:
self._logger.error("Tried to notify on non-existant eventID : ", event_id)
return False
tmp_config = self._settings.get(["events", event_id], merged=True)
if not tmp_config["enabled"]:
self._logger.debug("Event {} is not enabled. Returning gracefully".format(event_id))
return False
# Store IP address for message
data['ipaddr'] = self.get_ip_address()
data['externaddr'] = self.get_external_ip_address()
data['timeremaining'] = self.get_print_time_remaining()
data['timespent'] = self.get_print_time_spent()
# Special case for progress eventID : we check for progress and steps
if event_id == 'printing_progress':
# Skip if just started
if int(data["progress"]) == 0:
return False
# Skip if not a multiple of the given interval
if int(data["progress"]) % int(tmp_config["step"]) != 0:
return False
# Always send last message, and reset timer.
if int(data["progress"]) == 100:
self.last_progress_message = None
done_config = self._settings.get(["events", "printing_done"], merged=True)
# Don't send last message if the "printing_done" event is enabled.
if done_config["enabled"]:
return False
# Otherwise work out if time since last message has passed.
try:
min_progress_time = timedelta(seconds=int(tmp_config["timeout"]))
if self.last_progress_message is not None \
and self.last_progress_message > (datetime.now() - min_progress_time):
return False
except ValueError:
pass
except KeyError:
pass
self.last_progress_message = datetime.now()
return self.send_message(event_id, tmp_config["message"].format(**data), tmp_config["with_snapshot"])
def get_ip_address(self):
if self._settings.get(['show_local_ip'], merged=True) == 'hostname':
return self._settings.get(['hostname'], merged=True)
elif self._settings.get(['show_local_ip'], merged=True) == 'auto':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
return s.getsockname()[0]
except Exception as e:
print(e)
return '127.0.0.1'
finally:
s.close()
else:
return None
def get_external_ip_address(self):
if self._settings.get(['show_local_ip'], merged=True) == 'hostname':
return self._settings.get(['hostname'], merged=True)
elif self._settings.get(['show_local_ip'], merged=True) == 'auto':
return ipgetter.myip()
else:
return None
def get_port(self):
port = self.get_settings().global_get(["plugins", "discovery", "publicPort"])
if port:
return port
port = self.get_settings().global_get(["server", "port"])
if port:
return port
return 5000 # Default to a sane value
def exec_script(self, event_name, which=""):
# I want to be sure that the scripts are allowed by the special configuration flag
scripts_allowed = self._settings.get(["allow_scripts"], merged=True)
if scripts_allowed is None or scripts_allowed is False:
return ""
# Finding which one should be used.
script_to_exec = None
if which == "before":
script_to_exec = self._settings.get(["script_before"], merged=True)
elif which == "after":
script_to_exec = self._settings.get(["script_after"], merged=True)
# Finally exec the script
out = ""
self._logger.info("{}:{} File to start: '{}'".format(event_name, which, script_to_exec))
try:
if script_to_exec is not None and len(script_to_exec) > 0 and os.path.exists(script_to_exec):
out = subprocess.check_output(script_to_exec)
except (OSError, subprocess.CalledProcessError) as err:
out = err
finally:
self._logger.info("{}:{} > Output: '{}'".format(event_name, which, out))
return out
def send_message(self, event_id, message, with_snapshot=False):
# exec "before" script if any
self.exec_script(event_id, "before")
# Get snapshot if asked for
snapshot = None
if with_snapshot:
snapshots = self.get_snapshot()
if snapshots and len(snapshots) == 1:
snapshot = snapshots[0]
# Send to Discord bot (Somehow events can happen before discord bot has been created and initialised)
if self.discord is None:
self.discord = Discord()
out = self.discord.send(embeds=info_embed(author=self.get_printer_name(),
title=message,
snapshot=snapshot))
if not out:
self._logger.error("Failed to send message")
return out
# exec "after" script if any
self.exec_script(event_id, "after")
return out
def get_snapshot(self):
if 'FAKE_SNAPSHOT' in os.environ:
return self.get_snapshot_fake()
else:
return self.get_snapshot_camera()
@staticmethod
def get_snapshot_fake():
fl = open(os.environ['FAKE_SNAPSHOT'], "rb")
return [("snapshot.png", fl)]
def get_snapshot_camera(self):
snapshot = None
snapshot_url = self._settings.global_get(["webcam", "snapshot"])
if snapshot_url is None:
return None
if "http" in snapshot_url:
try:
snapshot_call = requests.get(snapshot_url)
if not snapshot_call:
return None
snapshot = BytesIO(snapshot_call.content)
except ConnectionError:
return None
if snapshot_url.startswith("file://"):
snapshot = open(snapshot_url.partition('file://')[2], "rb")
if snapshot is None:
return None
# Get the settings used for streaming to know if we should transform the snapshot
must_flip_h = self._settings.global_get_boolean(["webcam", "flipH"])
must_flip_v = self._settings.global_get_boolean(["webcam", "flipV"])
must_rotate = self._settings.global_get_boolean(["webcam", "rotate90"])
# Only call Pillow if we need to transpose anything
if must_flip_h or must_flip_v or must_rotate:
img = Image.open(snapshot)
self._logger.info(
"Transformations : FlipH={}, FlipV={} Rotate={}".format(must_flip_h, must_flip_v, must_rotate))
if must_flip_h:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
if must_flip_v:
img = img.transpose(Image.FLIP_TOP_BOTTOM)
if must_rotate:
img = img.transpose(Image.ROTATE_90)
new_image = BytesIO()
img.save(new_image, 'png')
return [("snapshot.png", new_image)]
return [("snapshot.png", snapshot)]
def get_printer_name(self):
printer_name = self._settings.global_get(["appearance", "name"])
if printer_name is None:
printer_name = "OctoPrint"
return printer_name
def update_discord_status(self, connected):
self._plugin_manager.send_plugin_message(self._identifier, dict(isConnected=connected))
def mute(self):
self.is_muted = True
def unmute(self):
self.is_muted = False
def get_file_manager(self):
return self._file_manager
def get_settings(self):
return self._settings
def get_printer(self):
return self._printer
def get_plugin_manager(self):
return self._plugin_manager
def get_print_time_spent(self):
current_data = self._printer.get_current_data()
try:
current_time_val = current_data['progress']['printTime']
return humanfriendly.format_timespan(current_time_val, max_units=2)
except (KeyError, ValueError):
return 'Unknown'
def get_print_time_remaining(self):
current_data = self._printer.get_current_data()
try:
remaining_time_val = current_data['progress']['printTimeLeft']
return humanfriendly.format_timespan(remaining_time_val, max_units=2)
except (KeyError, ValueError):
return 'Unknown'
def start_periodic_reporting(self):
self.stop_periodic_reporting()
self.last_progress_percent = 0
self.periodic_signal = Event()
self.periodic_signal.clear()
self.periodic_thread = Thread(target=self.periodic_reporting)
self.periodic_thread.start()
def stop_periodic_reporting(self):
if self.periodic_signal is None or self.periodic_thread is None:
return
self.periodic_signal.set()
self.periodic_thread.join(timeout=60)
if self.periodic_thread.is_alive():
self._logger.error("Periodic thread has hung, leaking it now.")
else:
self._logger.info("Periodic thread joined.")
self.periodic_thread = None
self.periodic_signal = None
def periodic_reporting(self):
if not self._settings.get(["events", "printing_progress_periodic", "enabled"]):
return
timeout = self._settings.get(["events", "printing_progress_periodic", "period"])
while True:
cur_time = time.time()
next_time = cur_time + int(timeout)
while time.time() < next_time:
time.sleep(1)
if self.periodic_signal.is_set():
return
if not self._printer.is_printing():
return
self.notify_event("printing_progress_periodic", data={"progress": self.last_progress_percent})
# If you want your plugin to be registered within OctoPrint under a different name than what you defined in setup.py
# ("OctoPrint-PluginSkeleton"), you may define that here. Same goes for the other metadata derived from setup.py that
# can be overwritten via __plugin_xyz__ control properties. See the documentation for that.
__plugin_name__ = "DiscordRemote"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = DiscordRemotePlugin()
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information,
"octoprint.filemanager.extension_tree": __plugin_implementation__.get_extension_tree
}
|
[] |
[] |
[
"FAKE_SNAPSHOT"
] |
[]
|
["FAKE_SNAPSHOT"]
|
python
| 1 | 0 | |
messaging/message.go
|
package messaging
import (
"encoding/json"
result "github.com/heaptracetechnology/microservice-nexmo/result"
"github.com/nexmo-community/nexmo-go"
"net/http"
"os"
)
//Send SMS
func Send(responseWriter http.ResponseWriter, request *http.Request) {
var apiKey = os.Getenv("API_KEY")
var apiSecret = os.Getenv("API_SECRET")
decoder := json.NewDecoder(request.Body)
var requestBody nexmo.SendSMSRequest
decodeErr := decoder.Decode(&requestBody)
if decodeErr != nil {
result.WriteErrorResponse(responseWriter, decodeErr)
return
}
auth := nexmo.NewAuthSet()
auth.SetAPISecret(apiKey, apiSecret)
client := nexmo.NewClient(http.DefaultClient, auth)
requestBody.APIKey = apiKey
requestBody.APISecret = apiSecret
smsResponse, httpResponse, smsErr := client.SMS.SendSMS(requestBody)
if smsErr != nil {
result.WriteErrorResponse(responseWriter, smsErr)
return
}
bytes, _ := json.Marshal(smsResponse)
result.WriteJsonResponse(responseWriter, bytes, httpResponse.StatusCode)
}
|
[
"\"API_KEY\"",
"\"API_SECRET\""
] |
[] |
[
"API_KEY",
"API_SECRET"
] |
[]
|
["API_KEY", "API_SECRET"]
|
go
| 2 | 0 | |
kettle/model.py
|
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import sqlite3
import time
import zlib
class Database(object):
"""
Store build and test result information, and support incremental updates to results.
"""
DEFAULT_INCREMENTAL_TABLE = 'build_emitted'
def __init__(self, path=None):
if path is None:
path = os.getenv('KETTLE_DB') or 'build.db'
self.db = sqlite3.connect(path)
self.db.executescript('''
create table if not exists build(gcs_path primary key, started_json, finished_json, finished_time);
create table if not exists file(path string primary key, data);
create table if not exists build_junit_grabbed(build_id integer primary key);
create index if not exists build_finished_time_idx on build(finished_time)
''')
def commit(self):
self.db.commit()
def get_existing_builds(self, jobs_dir):
"""
Return a set of (job, number) tuples indicating already present builds.
A build is already present if it has a finished.json, or if it's older than
five days with no finished.json.
"""
builds_have_paths = self.db.execute(
'select gcs_path from build'
' where gcs_path LIKE ?'
' and finished_json IS NOT NULL'
,
(jobs_dir + '%',)).fetchall()
path_tuple = lambda path: tuple(path[len(jobs_dir):].split('/')[-2:])
builds_have = {path_tuple(path) for (path,) in builds_have_paths}
for path, started_json in self.db.execute(
'select gcs_path, started_json from build'
' where gcs_path LIKE ?'
' and started_json IS NOT NULL and finished_json IS NULL',
(jobs_dir + '%',)):
started = json.loads(started_json)
if int(started['timestamp']) < time.time() - 60*60*24*5:
# over 5 days old, no need to try looking for finished any more.
builds_have.add(path_tuple(path))
return builds_have
### make_db
def insert_build(self, build_dir, started, finished):
"""
Add a build with optional started and finished dictionaries to the database.
"""
started_json = started and json.dumps(started, sort_keys=True)
finished_json = finished and json.dumps(finished, sort_keys=True)
if not self.db.execute(
'select 1 from build where gcs_path=? '
'and started_json=? and finished_json=?',
(build_dir, started_json, finished_json)).fetchone():
self.db.execute(
'replace into build values(?,?,?,?)',
(build_dir, started_json, finished_json,
finished and finished.get('timestamp', None)))
return True
return False
def get_builds_missing_junit(self):
"""
Return (rowid, path) for each build that hasn't enumerated junit files.
"""
return self.db.execute(
'select rowid, gcs_path from build'
' where rowid not in (select build_id from build_junit_grabbed)'
).fetchall()
def insert_build_junits(self, build_id, junits):
"""
Insert a junit dictionary {gcs_path: contents} for a given build's rowid.
"""
for path, data in junits.iteritems():
self.db.execute('replace into file values(?,?)',
(path, buffer(zlib.compress(data, 9))))
self.db.execute('insert into build_junit_grabbed values(?)', (build_id,))
### make_json
def _init_incremental(self, table):
"""
Create tables necessary for storing incremental emission state.
"""
self.db.execute('create table if not exists %s(build_id integer primary key, gen)' % table)
@staticmethod
def _get_builds(results):
for rowid, path, started, finished in results:
started = started and json.loads(started)
finished = finished and json.loads(finished)
yield rowid, path, started, finished
def get_builds(self, path='', min_started=None, incremental_table=DEFAULT_INCREMENTAL_TABLE):
"""
Iterate through (buildid, gcs_path, started, finished) for each build under
the given path that has not already been emitted.
"""
self._init_incremental(incremental_table)
results = self.db.execute(
'select rowid, gcs_path, started_json, finished_json from build '
'where gcs_path like ?'
' and finished_time >= ?' +
' and rowid not in (select build_id from %s)'
' order by finished_time' % incremental_table
, (path + '%', min_started or 0)).fetchall()
return self._get_builds(results)
def get_builds_from_paths(self, paths, incremental_table=DEFAULT_INCREMENTAL_TABLE):
self._init_incremental(incremental_table)
results = self.db.execute(
'select rowid, gcs_path, started_json, finished_json from build '
'where gcs_path in (%s)'
' and rowid not in (select build_id from %s)'
' order by finished_time' % (','.join(['?'] * len(paths)), incremental_table)
, paths).fetchall()
return self._get_builds(results)
def test_results_for_build(self, path):
"""
Return a list of file data under the given path. Intended for JUnit artifacts.
"""
results = []
for dataz, in self.db.execute(
'select data from file where path between ? and ?',
(path, path + '\x7F')):
data = zlib.decompress(dataz)
if data:
results.append(data)
return results
def get_oldest_emitted(self, incremental_table):
return self.db.execute('select min(finished_time) from build '
'where rowid in (select build_id from %s)'
% incremental_table).fetchone()[0]
def reset_emitted(self, incremental_table=DEFAULT_INCREMENTAL_TABLE):
self.db.execute('drop table if exists %s' % incremental_table)
def insert_emitted(self, rows_emitted, incremental_table=DEFAULT_INCREMENTAL_TABLE):
self._init_incremental(incremental_table)
gen, = self.db.execute('select max(gen)+1 from %s' % incremental_table).fetchone()
if not gen:
gen = 0
self.db.executemany(
'insert into %s values(?,?)' % incremental_table,
((row, gen) for row in rows_emitted))
self.db.commit()
return gen
|
[] |
[] |
[
"KETTLE_DB"
] |
[]
|
["KETTLE_DB"]
|
python
| 1 | 0 | |
pkg/ttnpb/ttnpb_encoding_test.go
|
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// 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.
package ttnpb_test
import (
"encoding"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"github.com/gogo/protobuf/jsonpb"
"github.com/smartystreets/assertions"
. "go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
"go.thethings.network/lorawan-stack/v3/pkg/util/test"
"go.thethings.network/lorawan-stack/v3/pkg/util/test/assertions/should"
)
func TestStringers(t *testing.T) {
for _, tc := range []struct {
Stringer fmt.Stringer
String string
}{
{
Stringer: MAC_V1_0,
String: "1.0.0",
},
{
Stringer: MAC_V1_0_1,
String: "1.0.1",
},
{
Stringer: MAC_V1_0_2,
String: "1.0.2",
},
{
Stringer: MAC_V1_1,
String: "1.1.0",
},
{
Stringer: PHY_V1_0,
String: "1.0.0",
},
{
Stringer: PHY_V1_0_1,
String: "1.0.1",
},
{
Stringer: PHY_V1_0_2_REV_A,
String: "1.0.2-a",
},
{
Stringer: PHY_V1_0_2_REV_B,
String: "1.0.2-b",
},
{
Stringer: PHY_V1_1_REV_A,
String: "1.1.0-a",
},
{
Stringer: PHY_V1_1_REV_B,
String: "1.1.0-b",
},
} {
assertions.New(t).So(tc.Stringer.String(), should.Equal, tc.String)
}
}
func TestMarshalers(t *testing.T) {
var vals [][]interface{}
vals = append(vals, []interface{}{
BoolValue{},
BoolValue{Value: true},
})
var mTypes []interface{}
for i := range MType_name {
mTypes = append(mTypes, MType(i))
}
vals = append(vals, mTypes)
var majors []interface{}
for i := range Major_name {
majors = append(majors, Major(i))
}
vals = append(vals, majors)
var macVers []interface{}
for i := range MACVersion_name {
macVers = append(macVers, MACVersion(i))
}
vals = append(vals, macVers)
var phyVers []interface{}
for i := range PHYVersion_name {
phyVers = append(phyVers, PHYVersion(i))
}
vals = append(vals, phyVers)
var drIdxs []interface{}
for i := range DataRateIndex_name {
drIdxs = append(drIdxs, DataRateIndex(i))
}
vals = append(vals, drIdxs)
var drIdxVals []interface{}
for i := range DataRateIndex_name {
drIdxVals = append(drIdxVals, DataRateIndexValue{
Value: DataRateIndex(i),
})
}
vals = append(vals, drIdxVals)
var drOffsets []interface{}
for i := range DataRateOffset_name {
drOffsets = append(drOffsets, DataRateOffset(i))
}
vals = append(vals, drOffsets)
var drOffsetVals []interface{}
for i := range DataRateOffset_name {
drOffsetVals = append(drOffsetVals, DataRateOffsetValue{
Value: DataRateOffset(i),
})
}
vals = append(vals, drOffsetVals)
vals = append(vals, []interface{}{
FrequencyValue{Value: 100000},
FrequencyValue{Value: 2000000},
FrequencyValue{Value: 30000000},
})
var joinRequestTypes []interface{}
for i := range JoinRequestType_name {
joinRequestTypes = append(joinRequestTypes, JoinRequestType(i))
}
vals = append(vals, joinRequestTypes)
var rejoinRequestTypes []interface{}
for i := range RejoinRequestType_name {
rejoinRequestTypes = append(rejoinRequestTypes, RejoinRequestType(i))
}
vals = append(vals, rejoinRequestTypes)
var cfLists []interface{}
for i := range CFListType_name {
cfLists = append(cfLists, CFListType(i))
}
vals = append(vals, cfLists)
var classes []interface{}
for i := range Class_name {
classes = append(classes, Class(i))
}
vals = append(vals, classes)
var txSchedulePrios []interface{}
for i := range TxSchedulePriority_name {
txSchedulePrios = append(txSchedulePrios, TxSchedulePriority(i))
}
vals = append(vals, txSchedulePrios)
var cids []interface{}
for i := range MACCommandIdentifier_name {
cids = append(cids, MACCommandIdentifier(i))
}
vals = append(vals, cids)
var dutyCycles []interface{}
for i := range AggregatedDutyCycle_name {
dutyCycles = append(dutyCycles, AggregatedDutyCycle(i))
}
vals = append(vals, dutyCycles)
var dutyCycleVals []interface{}
for i := range AggregatedDutyCycle_name {
dutyCycleVals = append(dutyCycleVals, AggregatedDutyCycleValue{
Value: AggregatedDutyCycle(i),
})
}
vals = append(vals, dutyCycleVals)
var pingSlots []interface{}
for i := range PingSlotPeriod_name {
pingSlots = append(pingSlots, PingSlotPeriod(i))
}
vals = append(vals, pingSlots)
var pingSlotVals []interface{}
for i := range PingSlotPeriod_name {
pingSlotVals = append(pingSlotVals, PingSlotPeriodValue{
Value: PingSlotPeriod(i),
})
}
vals = append(vals, pingSlotVals)
var rejoinCounts []interface{}
for i := range RejoinCountExponent_name {
rejoinCounts = append(rejoinCounts, RejoinCountExponent(i))
}
vals = append(vals, rejoinCounts)
var rejoinTimes []interface{}
for i := range RejoinTimeExponent_name {
rejoinTimes = append(rejoinTimes, RejoinTimeExponent(i))
}
vals = append(vals, rejoinTimes)
var rejoinPeriods []interface{}
for i := range RejoinPeriodExponent_name {
rejoinPeriods = append(rejoinPeriods, RejoinPeriodExponent(i))
}
vals = append(vals, rejoinPeriods)
var deviceEIRPs []interface{}
for i := range DeviceEIRP_name {
deviceEIRPs = append(deviceEIRPs, DeviceEIRP(i))
}
vals = append(vals, deviceEIRPs)
var ackLimitExponents []interface{}
for i := range ADRAckLimitExponent_name {
ackLimitExponents = append(ackLimitExponents, ADRAckLimitExponent(i))
}
vals = append(vals, ackLimitExponents)
var ackLimitExponentVals []interface{}
for i := range ADRAckLimitExponent_name {
ackLimitExponentVals = append(ackLimitExponentVals, ADRAckLimitExponentValue{
Value: ADRAckLimitExponent(i),
})
}
vals = append(vals, ackLimitExponentVals)
var ackDelayExponents []interface{}
for i := range ADRAckDelayExponent_name {
ackDelayExponents = append(ackDelayExponents, ADRAckDelayExponent(i))
}
vals = append(vals, ackDelayExponents)
var ackDelayExponentVals []interface{}
for i := range ADRAckDelayExponent_name {
ackDelayExponentVals = append(ackDelayExponentVals, ADRAckDelayExponentValue{
Value: ADRAckDelayExponent(i),
})
}
vals = append(vals, ackDelayExponentVals)
var rxDelays []interface{}
for i := range RxDelay_name {
rxDelays = append(rxDelays, RxDelay(i))
}
vals = append(vals, rxDelays)
var rxDelayVals []interface{}
for i := range RxDelay_name {
rxDelayVals = append(rxDelayVals, RxDelayValue{
Value: RxDelay(i),
})
}
vals = append(vals, rxDelayVals)
var minors []interface{}
for i := range Minor_name {
minors = append(minors, Minor(i))
}
vals = append(vals, minors)
var grants []interface{}
for i := range GrantType_name {
grants = append(grants, GrantType(i))
}
vals = append(vals, grants)
var clusterRoles []interface{}
for i := range ClusterRole_name {
clusterRoles = append(clusterRoles, ClusterRole(i))
}
vals = append(vals, clusterRoles)
var states []interface{}
for i := range State_name {
states = append(states, State(i))
}
vals = append(vals, states)
var locationSources []interface{}
for i := range LocationSource_name {
locationSources = append(locationSources, LocationSource(i))
}
vals = append(vals, locationSources)
var rights []interface{}
for i := range Right_name {
rights = append(rights, Right(i))
}
vals = append(vals, rights)
var outLines []string
for _, vs := range vals {
typ := reflect.TypeOf(vs[0])
newV := func() interface{} { return reflect.New(typ).Interface() }
t.Run(typ.String(), func(t *testing.T) {
for _, v := range vs {
t.Run(fmt.Sprint(v), func(t *testing.T) {
if m, ok := v.(encoding.TextMarshaler); ok {
t.Run("Text", func(t *testing.T) {
a := assertions.New(t)
b, err := m.MarshalText()
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
outLines = append(outLines, fmt.Sprintf(`Text | %s | %v | %s`, typ, v, b))
got, ok := newV().(encoding.TextUnmarshaler)
if !ok {
t.Fatal("Does not implement TextUnmarshaler")
}
err = got.UnmarshalText(b)
a.So(err, should.BeNil)
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
sv, ok := v.(fmt.Stringer)
if !ok {
// Structs (e.g. Value wrappers) implement String() on pointer types and do not
// require compatibility of string and text encoding
return
}
var s string
if !a.So(func() { s = sv.String() }, should.NotPanic) {
t.Fatalf("Failed to call String()")
}
got = newV().(encoding.TextUnmarshaler)
err = got.UnmarshalText([]byte(s))
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
})
}
if m, ok := v.(encoding.BinaryMarshaler); ok {
t.Run("Binary", func(t *testing.T) {
a := assertions.New(t)
b, err := m.MarshalBinary()
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
outLines = append(outLines, fmt.Sprintf(`Binary | %s | %v | %v`, typ, v, b))
got, ok := newV().(encoding.BinaryUnmarshaler)
if !ok {
t.Fatal("Does not implement BinaryUnmarshaler")
}
err = got.UnmarshalBinary(b)
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
})
}
if m, ok := v.(json.Marshaler); ok {
t.Run("JSON", func(t *testing.T) {
a := assertions.New(t)
b, err := m.MarshalJSON()
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
outLines = append(outLines, fmt.Sprintf(`JSON | %s | %v | %s`, typ, v, b))
got, ok := newV().(json.Unmarshaler)
if !ok {
t.Fatal("Does not implement JSONUnmarshaler")
}
err = got.UnmarshalJSON(b)
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
})
}
if m, ok := v.(jsonpb.JSONPBMarshaler); ok {
t.Run("JSONPB", func(t *testing.T) {
a := assertions.New(t)
b, err := m.MarshalJSONPB(&jsonpb.Marshaler{})
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
outLines = append(outLines, fmt.Sprintf(`JSONPB | %s | %v | %s`, typ, v, b))
{
got, ok := newV().(jsonpb.JSONPBUnmarshaler)
if !ok {
t.Fatal("Does not implement JSONPBUnmarshaler")
}
err = got.UnmarshalJSONPB(&jsonpb.Unmarshaler{}, b)
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
}
{
got := newV()
err = json.Unmarshal(b, got)
if !a.So(err, should.BeNil) {
t.Error(test.FormatError(err))
}
a.So(reflect.Indirect(reflect.ValueOf(got)).Interface(), should.Resemble, v)
}
})
}
})
}
})
}
if t.Failed() {
return
}
sort.Strings(outLines)
out := fmt.Sprintf(`Format | Type | Value | Encoding
:---: | :---: | :---: | :---:
%s`+"\n",
strings.Join(outLines, "\n"),
)
goldenPath := filepath.Join("testdata", "ttnpb_encoding_golden.md")
if os.Getenv("TEST_WRITE_GOLDEN") == "1" {
if err := ioutil.WriteFile(goldenPath, []byte(out), 0o644); err != nil {
t.Fatalf("Failed to write golden file: %s", err)
}
} else {
prevOut, err := ioutil.ReadFile(goldenPath)
if err != nil {
t.Fatalf("Failed to read golden file: %s", err)
}
assertions.New(t).So(out, should.Resemble, string(prevOut))
}
}
|
[
"\"TEST_WRITE_GOLDEN\""
] |
[] |
[
"TEST_WRITE_GOLDEN"
] |
[]
|
["TEST_WRITE_GOLDEN"]
|
go
| 1 | 0 | |
myshop/celery.py
|
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')
app = Celery('myshop')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
myproject/wsgi_staging.py
|
"""
WSGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.staging')
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
src/conftest.py
|
import base64
import os
from typing import Dict
from unittest.mock import MagicMock
import pytest
from flask.testing import FlaskClient
from pymongo.database import Database
from dotenv import load_dotenv
load_dotenv()
from src.migrations.v001_load_data import V001LoadData
# TODO: Update to Flask 2+
from app import app as flask_app
from src.dao.mongodb import MongoDb
# TODO: Remove from import time
V001LoadData().run()
@pytest.fixture
def flask_test_client() -> FlaskClient:
# suppress error logging
import app
app.logger = MagicMock()
flask_test_client = flask_app.test_client()
flask_test_client.testing = True
return flask_test_client
@pytest.fixture
def authorized_header_with_json_content_type() -> Dict:
basic_auth_username = os.getenv('BASIC_AUTH_USERNAME')
basic_auth_password = os.getenv('BASIC_AUTH_PASSWORD')
authorization = f'{basic_auth_username}:{basic_auth_password}'
encoded_authorization_bytes = base64.b64encode(authorization.encode('utf-8'))
encoded_authorization_str = str(encoded_authorization_bytes, 'utf-8')
headers = {'Content-Type': 'application/json',
'Authorization': f'Basic {encoded_authorization_str}'}
return headers
@pytest.fixture
def mongo_db() -> Database:
_mongo_db = MongoDb.instance(force=True)
return _mongo_db
|
[] |
[] |
[
"BASIC_AUTH_PASSWORD",
"BASIC_AUTH_USERNAME"
] |
[]
|
["BASIC_AUTH_PASSWORD", "BASIC_AUTH_USERNAME"]
|
python
| 2 | 0 | |
pkg/vmextension/vmextension_test.go
|
package vmextension
import (
"errors"
"github.com/Azure/VMApplication-Extension/VmExtensionHelper/extensionerrors"
"github.com/Azure/VMApplication-Extension/VmExtensionHelper/handlerenv"
"github.com/Azure/VMApplication-Extension/VmExtensionHelper/seqno"
"github.com/Azure/VMApplication-Extension/VmExtensionHelper/settings"
"github.com/Azure/VMApplication-Extension/VmExtensionHelper/status"
"github.com/go-kit/kit/log"
"github.com/stretchr/testify/require"
"os"
"os/exec"
"path"
"testing"
"time"
)
var (
statusTestDirectory = "./statustest"
)
type mockGetVMExtensionEnvironmentManager struct {
seqNo uint
currentSeqNo uint
he *handlerenv.HandlerEnvironment
hs *settings.HandlerSettings
getHandlerEnvironmentError error
findSeqNumError error
getCurrentSequenceNumberError error
getHandlerSettingsError error
setSequenceNumberError error
}
func (mm *mockGetVMExtensionEnvironmentManager) getHandlerEnvironment(name string, version string) (he *handlerenv.HandlerEnvironment, _ error) {
if mm.getHandlerEnvironmentError != nil {
return he, mm.getHandlerEnvironmentError
}
return mm.he, nil
}
func (mm *mockGetVMExtensionEnvironmentManager) findSeqNum(ctx log.Logger, configFolder string) (uint, error) {
if mm.findSeqNumError != nil {
return 0, mm.findSeqNumError
}
return mm.seqNo, nil
}
func (mm *mockGetVMExtensionEnvironmentManager) getCurrentSequenceNumber(ctx log.Logger, retriever seqno.ISequenceNumberRetriever, name, version string) (uint, error) {
if mm.getCurrentSequenceNumberError != nil {
return 0, mm.getCurrentSequenceNumberError
}
return mm.currentSeqNo, nil
}
func (mm *mockGetVMExtensionEnvironmentManager) getHandlerSettings(ctx log.Logger, he *handlerenv.HandlerEnvironment, seqNo uint) (hs *settings.HandlerSettings, _ error) {
if mm.getHandlerSettingsError != nil {
return hs, mm.getHandlerSettingsError
}
return mm.hs, nil
}
func (mm *mockGetVMExtensionEnvironmentManager) setSequenceNumberInternal(ve *VMExtension, seqNo uint) error {
if mm.setSequenceNumberError != nil {
return mm.setSequenceNumberError
}
return nil
}
func Test_reportStatusShouldntReport(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
ext := createTestVMExtension()
c := cmd{nil, "Install", false, 99}
ext.HandlerEnv.StatusFolder = statusTestDirectory
ext.RequestedSequenceNumber = 45
err := reportStatus(ctx, ext, status.StatusSuccess, c, "msg")
require.NoError(t, err, "reportStatus failed")
_, err = os.Stat(path.Join(statusTestDirectory, "45.status"))
require.True(t, os.IsNotExist(err), "File exists when we don't expect it to")
}
func Test_reportStatusCouldntSave(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
ext := createTestVMExtension()
c := cmd{nil, "Install", true, 99}
ext.HandlerEnv.StatusFolder = "./yabamonster"
ext.RequestedSequenceNumber = 45
err := reportStatus(ctx, ext, status.StatusSuccess, c, "msg")
require.Error(t, err)
}
func Test_reportStatusSaved(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
ext := createTestVMExtension()
c := cmd{nil, "Install", true, 99}
ext.HandlerEnv.StatusFolder = statusTestDirectory
ext.RequestedSequenceNumber = 45
createDirsForVMExtension(ext)
defer cleanupDirsForVMExtension(ext)
err := reportStatus(ctx, ext, status.StatusSuccess, c, "msg")
require.NoError(t, err, "reportStatus failed")
_, err = os.Stat(path.Join(statusTestDirectory, "45.status"))
require.NoError(t, err, "File doesn't exist")
}
func Test_getVMExtensionNilValues(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
_, err := GetVMExtension(ctx, nil)
require.Equal(t, extensionerrors.ErrArgCannotBeNull, err)
initInfo := &InitializationInfo{Name: ""}
_, err = GetVMExtension(ctx, initInfo)
require.Equal(t, extensionerrors.ErrArgCannotBeNullOrEmpty, err)
initInfo = &InitializationInfo{Name: "yaba", Version: ""}
_, err = GetVMExtension(ctx, initInfo)
require.Equal(t, extensionerrors.ErrArgCannotBeNullOrEmpty, err)
initInfo = &InitializationInfo{Name: "yaba", Version: "1.0", EnableCallback: nil}
_, err = GetVMExtension(ctx, initInfo)
require.Equal(t, extensionerrors.ErrArgCannotBeNull, err)
}
func Test_getVMExtensionGetHandlerEnvironmentError(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
myerr := errors.New("cannot handle the environment")
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
mm := &mockGetVMExtensionEnvironmentManager{getHandlerEnvironmentError: myerr}
_, err := getVMExtensionInternal(ctx, ii, mm)
require.Equal(t, myerr, err)
}
func Test_getVMExtensionCannotFindSeqNo(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
mm.findSeqNumError = errors.New("the sequence number annoys me")
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
_, err := getVMExtensionInternal(ctx, ii, mm)
require.Error(t, err)
}
func Test_getVMExtensionCannotReadCurrentSeqNo(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
mm.getCurrentSequenceNumberError = errors.New("the current sequence number is beyond our comprehension")
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
_, err := getVMExtensionInternal(ctx, ii, mm)
require.Error(t, err)
}
func Test_getVMExtensionUpdateSupport(t *testing.T) {
// Update disabled
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, err := getVMExtensionInternal(ctx, ii, mm)
require.NoError(t, err, "getVMExtensionInternal failed")
require.NotNil(t, ext)
// Verify this is a noop
updateNormalCallbackCalled = false
cmd := ext.exec.cmds["update"]
require.NotNil(t, cmd)
_, err = cmd.f(ctx, ext)
require.NoError(t, err, "updateCallback failed")
require.False(t, updateNormalCallbackCalled)
// Update enabled
ii.UpdateCallback = testUpdateCallbackNormal
ext, err = getVMExtensionInternal(ctx, ii, mm)
require.NoError(t, err, "getVMExtensionInternal failed")
require.NotNil(t, ext)
// Verify this is not a noop
cmd = ext.exec.cmds["update"]
require.NotNil(t, cmd)
_, err = cmd.f(ctx, ext)
require.NoError(t, err, "updateCallback failed")
require.True(t, updateNormalCallbackCalled)
}
func Test_getVMExtensionDisableSupport(t *testing.T) {
// Disbable disabled
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ii.SupportsDisable = false
ext, err := getVMExtensionInternal(ctx, ii, mm)
require.NoError(t, err, "getVMExtensionInternal failed")
require.NotNil(t, ext)
createDirsForVMExtension(ext)
defer cleanupDirsForVMExtension(ext)
// Verify this is a noop
err = setDisabled(ctx, ext, false)
require.NoError(t, err, "setDisabled failed")
cmd := ext.exec.cmds["disable"]
require.NotNil(t, cmd)
_, err = cmd.f(ctx, ext)
require.NoError(t, err, "disable cmd failed")
require.False(t, isDisabled(ctx, ext))
// Disable enabled
ii.SupportsDisable = true
ext, err = getVMExtensionInternal(ctx, ii, mm)
require.NoError(t, err, "getVMExtensionInternal failed")
require.NotNil(t, ext)
// Verify this is not a noop
cmd = ext.exec.cmds["disable"]
require.NotNil(t, cmd)
_, err = cmd.f(ctx, ext)
defer setDisabled(ctx, ext, false)
require.NoError(t, err, "disable cmd failed")
require.True(t, isDisabled(ctx, ext))
}
func Test_getVMExtensionCannotGetSettings(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
mm.getHandlerSettingsError = errors.New("the settings exist only in a parallel dimension")
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
_, err := getVMExtensionInternal(ctx, ii, mm)
require.Equal(t, mm.getHandlerSettingsError, err)
}
func Test_getVMExtensionNormalOperation(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, err := getVMExtensionInternal(ctx, ii, mm)
require.NoError(t, err, "getVMExtensionInternal failed")
require.NotNil(t, ext)
}
func Test_parseCommandWrongArgsCount(t *testing.T) {
if os.Getenv("DIE_PROCESS_DIE") == "1" {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
args := make([]string, 1)
args[0] = "install"
ext.parseCmd(args)
return
}
// Verify that the process exits
cmd := exec.Command(os.Args[0], "-test.run=Test_parseCommandWrongArgsCount")
cmd.Env = append(os.Environ(), "DIE_PROCESS_DIE=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
func Test_parseCommandUnsupportedOperation(t *testing.T) {
if os.Getenv("DIE_PROCESS_DIE") == "1" {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
args := make([]string, 2)
args[0] = "processname_dont_care"
args[1] = "flipperdoodle"
ext.parseCmd(args)
return
}
// Verify that the process exits
cmd := exec.Command(os.Args[0], "-test.run=Test_parseCommandUnsupportedOperation")
cmd.Env = append(os.Environ(), "DIE_PROCESS_DIE=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
func Test_parseCommandNormalOperation(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
args := make([]string, 2)
args[0] = "processname_dont_care"
args[1] = "install"
cmd := ext.parseCmd(args)
require.NotNil(t, cmd)
}
func Test_enableNoSeqNoChangeButRequired(t *testing.T) {
if os.Getenv("DIE_PROCESS_DIE") == "1" {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
mm.currentSeqNo = mm.seqNo
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ii.RequiresSeqNoChange = true
ext, _ := getVMExtensionInternal(ctx, ii, mm)
enable(ctx, ext)
os.Exit(2) // enable above should exit the process cleanly. If it doesn't, fail.
}
// Verify that the process exits
cmd := exec.Command(os.Args[0], "-test.run=Test_enableNoSeqNoChangeButRequired")
cmd.Env = append(os.Environ(), "DIE_PROCESS_DIE=1")
err := cmd.Run()
if _, ok := err.(*exec.ExitError); !ok {
return
}
t.Fatal("Process didn't shut cleanly as expected")
}
func Test_reenableExtension(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ii.SupportsDisable = true
ext, _ := getVMExtensionInternal(ctx, ii, mm)
createDirsForVMExtension(ext)
defer cleanupDirsForVMExtension(ext)
resetDependencies()
err := setDisabled(ctx, ext, true)
//defer setDisabled(ctx, ext, false)
time.Sleep(1000 * time.Millisecond)
require.NoError(t, err, "setDisabled failed")
_, err = enable(ctx, ext)
time.Sleep(1000 * time.Millisecond)
require.NoError(t, err, "enable failed")
require.False(t, isDisabled(ctx, ext))
}
func Test_reenableExtensionFails(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ii.SupportsDisable = true
ext, _ := getVMExtensionInternal(ctx, ii, mm)
createDirsForVMExtension(ext)
defer cleanupDirsForVMExtension(ext)
err := setDisabled(ctx, ext, true)
defer setDisabled(ctx, ext, false)
require.NoError(t, err, "setDisabled failed")
disableDependency = evilDisableDependencies{}
defer resetDependencies()
msg, err := enable(ctx, ext)
require.NoError(t, err) // We let the extension continue if we fail to reenable it
require.Equal(t, "blah", msg)
}
func Test_enableCallbackFails(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testFailEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
_, err := enable(ctx, ext)
require.Equal(t, extensionerrors.ErrMustRunAsAdmin, err)
}
func Test_enableCallbackSucceeds(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
msg, err := enable(ctx, ext)
require.NoError(t, err, "enable failed")
require.Equal(t, "blah", msg)
}
func Test_doFailToWriteSequenceNumber(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
mm.setSequenceNumberError = extensionerrors.ErrMustRunAsAdmin
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
// We log but continue if we fail to write the sequence number
oldArgs := os.Args
defer putBackArgs(oldArgs)
os.Args = make([]string, 2)
os.Args[0] = "dontcare"
os.Args[1] = "enable"
ext.Do(ctx)
}
func Test_doCommandFails(t *testing.T) {
if os.Getenv("DIE_PROCESS_DIE") == "1" {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testFailEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
oldArgs := os.Args
defer putBackArgs(oldArgs)
os.Args = make([]string, 2)
os.Args[0] = "dontcare"
os.Args[1] = "enable"
ext.Do(ctx)
return
}
// Verify that the process exits
cmd := exec.Command(os.Args[0], "-test.run=Test_doCommandFails")
cmd.Env = append(os.Environ(), "DIE_PROCESS_DIE=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 3", err)
}
func Test_doCommandSucceeds(t *testing.T) {
ctx := log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))
mm := createMockVMExtensionEnvironmentManager()
ii, _ := GetInitializationInfo("yaba", "5.0", true, testEnableCallback)
ext, _ := getVMExtensionInternal(ctx, ii, mm)
oldArgs := os.Args
defer putBackArgs(oldArgs)
os.Args = make([]string, 2)
os.Args[0] = "dontcare"
os.Args[1] = "enable"
ext.Do(ctx)
}
func putBackArgs(args []string) {
os.Args = args
}
func testFailEnableCallback(ctx log.Logger, ext *VMExtension) (string, error) {
return "", extensionerrors.ErrMustRunAsAdmin
}
func getTestHandlerEnvironment() *handlerenv.HandlerEnvironment {
return &handlerenv.HandlerEnvironment{
HeartbeatFile: path.Join(".", "testdir", "heartbeat.txt"),
StatusFolder: path.Join(".", "testdir", "status"),
ConfigFolder: path.Join(".", "testdir", "config"),
LogFolder: path.Join(".", "testdir", "log"),
DataFolder: path.Join(".", "testdir", "data"),
}
}
func createTestVMExtension() *VMExtension {
return &VMExtension{
Name: "yaba",
Version: "5.0",
RequestedSequenceNumber: 2,
CurrentSequenceNumber: 1,
HandlerEnv: getTestHandlerEnvironment(),
Settings: &settings.HandlerSettings{},
exec: &executionInfo{
requiresSeqNoChange: true,
supportsDisable: true,
enableCallback: testEnableCallback,
disableCallback: testDisableCallbackNormal,
updateCallback: nil,
cmds: nil,
},
}
}
func createMockVMExtensionEnvironmentManager() *mockGetVMExtensionEnvironmentManager {
publicSettings := make(map[string]interface{})
publicSettings["Flipper"] = "flip"
publicSettings["Flopper"] = "flop"
hs := &settings.HandlerSettings{PublicSettings: publicSettings, ProtectedSettings: nil}
he := getTestHandlerEnvironment()
return &mockGetVMExtensionEnvironmentManager{
seqNo: 5,
currentSeqNo: 4,
hs: hs,
he: he,
}
}
func createDirsForVMExtension(vmExt *VMExtension) (error) {
if err := os.MkdirAll(vmExt.HandlerEnv.StatusFolder, 0700); err != nil {
return err
}
if err := os.MkdirAll(vmExt.HandlerEnv.ConfigFolder, 0700); err != nil {
return err
}
if err := os.MkdirAll(vmExt.HandlerEnv.LogFolder, 0700); err != nil {
return err
}
return os.MkdirAll(vmExt.HandlerEnv.DataFolder, 0700)
}
func cleanupDirsForVMExtension(vmExt *VMExtension) (combinedError error) {
combinedError = extensionerrors.CombineErrors(combinedError, os.RemoveAll(vmExt.HandlerEnv.StatusFolder))
combinedError = extensionerrors.CombineErrors(combinedError, os.RemoveAll(vmExt.HandlerEnv.ConfigFolder))
combinedError = extensionerrors.CombineErrors(combinedError, os.RemoveAll(vmExt.HandlerEnv.LogFolder))
combinedError = extensionerrors.CombineErrors(combinedError, os.RemoveAll(vmExt.HandlerEnv.DataFolder))
return
}
|
[
"\"DIE_PROCESS_DIE\"",
"\"DIE_PROCESS_DIE\"",
"\"DIE_PROCESS_DIE\"",
"\"DIE_PROCESS_DIE\""
] |
[] |
[
"DIE_PROCESS_DIE"
] |
[]
|
["DIE_PROCESS_DIE"]
|
go
| 1 | 0 | |
dev/devcam/devcam.go
|
/*
Copyright 2013 The Perkeep Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
pathpkg "path"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"perkeep.org/internal/osutil"
"perkeep.org/pkg/cmdmain"
)
var (
noBuild = flag.Bool("nobuild", false, "do not rebuild anything")
race = flag.Bool("race", false, "build with race detector")
quiet, _ = strconv.ParseBool(os.Getenv("CAMLI_QUIET"))
wipeCache = flag.Bool("wipecache", false, "wipe the cache directory. Server cache with devcam server, client cache otherwise.")
// Whether to build the subcommand with sqlite support. This only
// concerns the server subcommand, which sets it to serverCmd.sqlite.
withSqlite bool
)
// The path to the Perkeep source tree. Any devcam command
// should be run from there.
var camliSrcRoot string
// sysExec is set to syscall.Exec on platforms that support it.
var sysExec func(argv0 string, argv []string, envv []string) (err error)
// runExec execs bin. If the platform doesn't support exec, it runs it and waits
// for it to finish.
func runExec(bin string, args []string, env *Env) error {
if sysExec != nil {
sysExec(bin, append([]string{filepath.Base(bin)}, args...), env.Flat())
}
cmd := exec.Command(bin, args...)
cmd.Env = env.Flat()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("Could not run %v: %v", bin, err)
}
go handleSignals(cmd.Process)
return cmd.Wait()
}
// cpDir copies the contents of src dir into dst dir.
// filter is a list of file suffixes to skip. ex: ".go"
func cpDir(src, dst string, filter []string) error {
return filepath.Walk(src, func(fullpath string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
for _, suffix := range filter {
if strings.HasSuffix(fi.Name(), suffix) {
return nil
}
}
suffix, err := filepath.Rel(src, fullpath)
if err != nil {
return fmt.Errorf("Failed to find Rel(%q, %q): %v", src, fullpath, err)
}
if fi.IsDir() {
return nil
}
return cpFile(fullpath, filepath.Join(dst, suffix))
})
}
func cpFile(src, dst string) error {
sfi, err := os.Stat(src)
if err != nil {
return err
}
if !sfi.Mode().IsRegular() {
return fmt.Errorf("cpFile can't deal with non-regular file %s", src)
}
dstDir := filepath.Dir(dst)
if err := os.MkdirAll(dstDir, 0755); err != nil {
return err
}
df, err := os.Create(dst)
if err != nil {
return err
}
sf, err := os.Open(src)
if err != nil {
return err
}
defer sf.Close()
n, err := io.Copy(df, sf)
if err == nil && n != sfi.Size() {
err = fmt.Errorf("copied wrong size for %s -> %s: copied %d; want %d", src, dst, n, sfi.Size())
}
cerr := df.Close()
if err == nil {
err = cerr
}
return err
}
func handleSignals(camliProc *os.Process) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT)
for {
sig := <-c
sysSig, ok := sig.(syscall.Signal)
if !ok {
log.Fatal("Not a unix signal")
}
switch sysSig {
case syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT:
log.Printf("Received %v signal, terminating.", sig)
err := camliProc.Kill()
if err != nil {
log.Fatalf("Failed to kill child: %v ", err)
}
default:
log.Fatal("Received another signal, should not happen.")
}
}
}
func checkCamliSrcRoot() {
args := flag.Args()
// TODO(mpl): we should probably get rid of that limitation someday.
if len(args) > 0 && (args[0] == "review" ||
args[0] == "hook" ||
args[0] == "fixv") {
// exception for devcam review, which does its own check.
return
}
if _, err := os.Stat("make.go"); err != nil {
if !os.IsNotExist(err) {
log.Fatalf("Could not stat make.go: %v", err)
}
log.Fatal("./make.go not found; devcam needs to be run from the Perkeep source tree root.")
}
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
camliSrcRoot = cwd
}
func repoRoot() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("could not get current directory: %v", err)
}
rootlen := 1
if runtime.GOOS == "windows" {
rootlen += len(filepath.VolumeName(dir))
}
for {
if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
return dir, nil
}
if len(dir) == rootlen && dir[rootlen-1] == filepath.Separator {
return "", fmt.Errorf(".git not found. Rerun from within the Perkeep source tree")
}
dir = filepath.Dir(dir)
}
}
func selfModTime() (time.Time, error) {
var modTime time.Time
devcamBin, err := osutil.SelfPath()
if err != nil {
return modTime, err
}
fi, err := os.Stat(devcamBin)
if err != nil {
return modTime, err
}
return fi.ModTime(), nil
}
func checkModtime() error {
binModtime, err := selfModTime()
if err != nil {
return fmt.Errorf("could not get ModTime of current devcam executable: %v", err)
}
devcamDir := filepath.Join(camliSrcRoot, "dev", "devcam")
d, err := os.Open(devcamDir)
if err != nil {
return fmt.Errorf("could not read devcam source dir %v: %v", devcamDir, err)
}
defer d.Close()
fis, err := d.Readdir(-1)
if err != nil {
return fmt.Errorf("could not read devcam source dir %v: %v", devcamDir, err)
}
for _, fi := range fis {
if fi.ModTime().After(binModtime) {
log.Printf("**************************************************************")
log.Printf("WARNING: your devcam binary is outdated, you should rebuild it")
log.Printf("**************************************************************")
return nil
}
}
return nil
}
// Build builds the camlistore command at the given path from the source tree root.
func build(path string) error {
if v, _ := strconv.ParseBool(os.Getenv("CAMLI_FAST_DEV")); v {
// Demo mode. See dev/demo.sh.
return nil
}
_, cmdName := filepath.Split(path)
target := pathpkg.Join("perkeep.org", filepath.ToSlash(path))
binPath := filepath.Join("bin", cmdName)
var modtime int64
fi, err := os.Stat(binPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("Could not stat %v: %v", binPath, err)
}
} else {
modtime = fi.ModTime().Unix()
}
args := []string{
"run", "make.go",
"--quiet",
"--race=" + strconv.FormatBool(*race),
"--embed_static=false",
"--sqlite=" + strconv.FormatBool(withSqlite),
fmt.Sprintf("--if_mods_since=%d", modtime),
"--targets=" + target,
}
cmd := exec.Command("go", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("Error building %v: %v", target, err)
}
return nil
}
func main() {
cmdmain.PostFlag = func() {
checkCamliSrcRoot()
if err := checkModtime(); err != nil {
log.Printf("Skipping freshness check: %v", err)
}
}
// TODO(mpl): usage error is not really correct for devcam.
// See if I can reimplement it while still using cmdmain.Main().
cmdmain.Main()
}
|
[
"\"CAMLI_QUIET\"",
"\"CAMLI_FAST_DEV\""
] |
[] |
[
"CAMLI_QUIET",
"CAMLI_FAST_DEV"
] |
[]
|
["CAMLI_QUIET", "CAMLI_FAST_DEV"]
|
go
| 2 | 0 | |
opentree/ws_wrapper.py
|
#!/usr/bin/env python3
# Implementation file for the calling of HTTP methods and deserializing from JSON.
# This file is intended as a low-level wrapper that most users would never call directly, but which handles
# peforming the calls (and if requested) keeping a log of methods called or a curl representation of the
# calls that were performed.
#
import json
import logging
import sys
import re
import os
from enum import Enum
from .node_reference import SynthNodeReference, OTTaxonRef
import requests
def _escape_dq(s):
"""Lightweight escaping function used in writing curl calls...
"""
if not isinstance(s, str):
if isinstance(s, bool):
return 'true' if s else 'false'
return s
if '"' in s:
ss = s.split('"')
return '"{}"'.format('\\"'.join(ss))
return '"{}"'.format(s)
class OTWebServicesError(Exception):
"""This type of error is raised when a web-service call fails for a reason that is
impossible or difficult to diagnose. The string representation of the error should contain
some helpful information.
"""
def __init__(self, message, call_record=None):
super().__init__(message)
self.call_record = call_record
class OTClientError(OTWebServicesError):
"""This type of error is raised when the calling code does not make a legitimate request
based on the Open Tree of Life API's (see https://opentreeoflife.github.io/develop/api).
"""
def __init__(self, message, call_record=None):
super().__init__(message, call_record=call_record)
class WebServiceCallRecord(object):
"""Wrapper around a web-service call, returned by WebServiceWrapper methods.
The main client methods to call are:
* __bool__ (check if status code was 200)
* __str__ (explanation of the call status
* `write_response` (writes call explanation and response, if there was one).
The most commonly used properties:
* url: string
* response: a requests response object
* status_codeL: None or the HTTP status code as an integer
* response_dict: None, decoding of a JSON response or {'content' : raw_content} (for non-JSON methods)
If the API call returns some encoding of a tree, then the `tree` property of the WebServiceCallRecord
can be used to decode the response.
"""
def __init__(self, service_wrapper, url, http_method, headers, data):
self._request_url = url
self._request_headers = headers
self._request_http_method = http_method
self._request_data = data
self._response_obj = None
self._response_dict = None
self._tree = None
self._node_ref = None
self._taxon_ref = None
self._tree_from_response_extractor = None
try:
self._to_object_converter = service_wrapper.to_object_converter
except:
self._to_object_converter = None
# noinspection PyPep8
@property
def curl_call(self):
"""Returns a string that is a curl representation of the call
"""
# may want to revisit this implementation
v = self._request_http_method
headers = self._request_headers
data = self._request_data
url = self._request_url
varg = '' if v == 'GET' else '-X {} '.format(v)
if headers:
hal = ['-H {}:{}'.format(_escape_dq(k), _escape_dq(v)) for k, v in headers.items()]
hargs = ' '.join(hal)
else:
hargs = ''
dargs = " --data '{}'".format(json.dumps(data)) if data else ''
return 'curl {v} {h} {u}{d}'.format(v=varg, u=url, h=hargs, d=dargs)
def __str__(self):
"""Returns and explanation of the URL and status of the call."""
prefix = "Web-service call to {}".format(self._request_url)
if self:
return '{} succeeded.'.format(prefix)
elif self._response_obj is None:
return '{} has not been completed (in progress or has not been triggered yet).'.format(prefix)
return '{} failed with http_status_code={}'.format(prefix, self.status_code)
def write_response(self, out):
out.write(str(self))
if self._response_obj is None:
out.write('\n')
return
out.write(' Response:\n')
rdict = self.response_dict
sf = json.dumps(rdict, sort_keys=True, indent=2, separators=(',', ': '), ensure_ascii=True)
out.write('{}\n'.format(sf))
@property
def url(self):
return self._request_url
@property
def response(self):
return self._response_obj
@property
def status_code(self):
return None if self._response_obj is None else self._response_obj.status_code
@property
def response_dict(self):
if self._response_dict is None:
if self._response_obj is None:
return None
try:
self._response_dict = self._response_obj.json() # NOTE: if response is not JSON this will fail
except json.decoder.JSONDecodeError:
self._response_dict = {'content': self._response_obj.content}
# TODO make this not fail on Newick/NEXUS responses
return self._response_dict
def __bool__(self):
"""Returns True if call completed with an HTTP status of 200"""
sc = self.status_code
return sc is not None and sc == 200
@property
def taxon(self):
if self._taxon_ref is None:
if not self:
return None
self._taxon_ref = OTTaxonRef(self.response_dict)
return self._taxon_ref
@property
def node_ref(self):
if self._node_ref is None:
if not self:
return None
self._node_ref = SynthNodeReference(self.response_dict)
return self._node_ref
@property
def tree(self):
if self._tree is None:
if not self:
return None
extractor = self._tree_from_response_extractor
if extractor is None:
extractor = default_tree_extractor(self._to_object_converter)
self._tree = extractor(self.response_dict)
return self._tree
def extract_content_from_raw_text_method_dict(response_dict):
return response_dict['content']
def extract_newick(response_dict):
return response_dict['newick']
def extract_newick_then_obj(response_dict, to_obj_conv):
newick = extract_newick(response_dict)
return to_obj_conv.tree_from_newick(newick, suppress_internal_node_taxa=True)
def default_tree_extractor(to_obj_conv):
if to_obj_conv is None:
return extract_newick
return lambda rd: extract_newick_then_obj(rd, to_obj_conv)
class WebServiceRunMode(Enum):
RUN = 1
CURL = 2
CURL_ON_EXIT = 3
class WebServiceWrapper(object):
def __init__(self, api_endpoint, run_mode=WebServiceRunMode.RUN):
self._run_mode = run_mode
self._generate_curl = run_mode in [WebServiceRunMode.CURL, WebServiceRunMode.CURL_ON_EXIT]
self._perform_ws_calls = run_mode != WebServiceRunMode.CURL
if api_endpoint == 'production':
api_endpoint = os.environ.get('OVERRIDE_OT_PRODUCTION_API_ENDPOINT', 'production')
self._api_endpoint = api_endpoint
self._api_version = 'v3'
self._store_responses = False
self._store_api_calls = True
self.curl_strings = []
self.call_history = []
self.to_object_converter = None
def _call_api(self, method_url_fragment, data=None,
http_method='POST', demand_success=True, headers=None):
"""Returns a ws_call_rec"""
url = self.make_url(method_url_fragment)
if headers is None:
headers = {'content-type': 'application/json', 'accept': 'application/json', }
elif isinstance(headers, str) and headers.lower() == 'text':
headers = {'content-type': 'text/plain', 'accept': 'text/plain', }
try:
ws_call_rec = self._http_request(url, http_method, data=data, headers=headers)
if demand_success and not ws_call_rec:
if not self._perform_ws_calls:
return None
m = 'Wrong HTTP status code from server. Expected 200. Got {}.'
m = m.format(ws_call_rec.status_code)
raise OTWebServicesError(m, ws_call_rec)
return ws_call_rec
except:
logging.exception("Error in {} to {}".format(http_method, url))
raise
def make_url(self, frag, front_end=False):
while frag.startswith('/'):
frag = frag[1:]
while frag.startswith('/'):
frag = frag[1:]
while frag.endswith('/'):
frag = frag[:-1]
if self._api_endpoint == 'production':
if front_end:
return 'https://tree.opentreeoflife.org/{}/{}'.format(self._api_version, frag)
return 'https://api.opentreeoflife.org/{}/{}'.format(self._api_version, frag)
if self._api_endpoint == 'files':
return 'https://files.opentreeoflife.org/{}'.format(frag)
if self._api_endpoint == 'dev':
if front_end:
return 'https://devtree.opentreeoflife.org/{}/{}'.format(self._api_version, frag)
return 'https://devapi.opentreeoflife.org/{}/{}'.format(self._api_version, frag)
if self._api_endpoint == 'next':
return 'https://nexttree.opentreeoflife.org/{}/{}'.format(self._api_version, frag)
if self._api_endpoint == 'local':
tax_pat = re.compile(r'^(v[0-9.]+)/([a-z_]+)/(.+)$')
m = tax_pat.match(frag)
if m:
vers, top_level, tail_frag = m.groups()
if top_level in ('taxonomy', 'tnrs'):
t = 'http://localhost:7474/db/data/ext/{}_{}/graphdb/{}'
return t.format(top_level, vers, tail_frag)
elif top_level in ('tree_of_life',):
t = 'http://localhost:6543/{}/{}/{}'
return t.format(vers, top_level, tail_frag)
raise NotImplemented('non-taxonomy local system_to_test')
if self._api_endpoint.startswith('ot'):
return 'https://{}.opentreeoflife.org/{}/{}'.format(self._api_endpoint, self._api_version, frag)
if self._api_endpoint[0].isdigit():
return 'http://{}/{}/{}'.format(self._api_endpoint, self._api_version, frag)
raise OTClientError('api_endpoint = "{}" is not supported'.format(self._api_endpoint))
def _http_request(self, url, http_method="GET", data=None, headers=None):
"""Performs an HTTP call and returns a WebServiceCallRecord instance."""
rec = WebServiceCallRecord(self, url, http_method, headers, data)
if self._store_api_calls:
self.call_history.append(rec)
if self._generate_curl:
self.curl_strings.append(rec.curl_call)
if not self._perform_ws_calls:
if self._run_mode == WebServiceRunMode.CURL:
sys.stderr.write('{}\n'.format(self.curl_strings[-1]))
return rec
if data:
resp = requests.request(http_method, url, headers=headers, data=json.dumps(data), allow_redirects=True)
else:
resp = requests.request(http_method, url, headers=headers, allow_redirects=True)
rec._response_obj = resp
logging.debug('Sent {v} to {s}'.format(v=http_method, s=resp.url))
return rec
|
[] |
[] |
[
"OVERRIDE_OT_PRODUCTION_API_ENDPOINT"
] |
[]
|
["OVERRIDE_OT_PRODUCTION_API_ENDPOINT"]
|
python
| 1 | 0 | |
home.go
|
package main
import (
"embed"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
docopt "github.com/docopt/docopt-go"
"github.com/google/shlex"
"github.com/kataras/golog"
"github.com/logrusorgru/aurora"
"github.com/mattn/go-isatty"
)
const shell = "dash"
//go:embed VERSION
//go:embed install
//go:embed files
//go:embed files/.*
var embedded embed.FS
var tmpdir = "/tmp"
var ansi aurora.Aurora
type CliArgs struct {
// Options
DryRun bool
Upgrade bool
Debug bool
Color string
// Args
Command string
Os string
Arch string
Names []string
}
func main() {
var err error
var name string
if os.Getenv("DEBUG") != "" {
golog.SetLevel("debug")
}
// Get the current executable full path
if name, err = os.Executable(); err != nil {
golog.Fatal("Unable to retrieve executable name")
}
// Get the actual command name
name = filepath.Base(name)
oper := runtime.GOOS
arch := runtime.GOARCH
version := string(embeddedFile("VERSION"))
// Get a safe temp directory to use for downloads, etc.
tmpdir, err = os.MkdirTemp("", name+"-")
if err != nil {
log.Fatal(err)
}
// Ensure we clean it up later
defer os.RemoveAll(tmpdir)
golog.Debug("tmpdir:", tmpdir)
// Create the command help with our executable name
usage := fmt.Sprintf(`Home directory management.
This command is intended to help manage home directory files and
dependencies. It can even be extended to set up a default environment for
development.
Usage:
%v [-h|--help] [-d|--debug] [--version] [--color=<color>] [--os=<os>]
[--arch=<arch>] <command> [--dry-run] [--upgrade] [<names>...]
Options:
--dry-run don't make any changes
--upgrade upgrade installed if they exist
--color=<color> color output auto, always or never [default: auto]
--os=<os> operating system [default: %v]
--arch=<arch> platform [default: %v]
-d --debug show debug output
-h --help show this help
--version show the version
The subcommands are:
setup run install, copy, and status
install install system dependencies
copy copy user files into place
status report status of all installs and user files`, name, oper, arch)
var args CliArgs
// Parse the CLI args and store them
parsed, _ := docopt.ParseArgs(usage, os.Args[1:], version)
// Force color settings
initColor(parsed["--color"].(string))
// Bind to our struct
if err = parsed.Bind(&args); err != nil {
golog.Fatal(err)
}
// Set debug output in our logger
if args.Debug {
golog.SetLevel("debug")
}
golog.Debugf("args = %+v", args)
// Sanity check so scripts can run
if !commandExists("dash") {
golog.Fatal("Error: Missing 'dash' shell")
}
cmd := args.Command
golog.Debug("Running command: ", cmd)
// Try to install all our dependencies (this should be idempotent)
if cmd == "install" || cmd == "setup" {
CliInstall(&args)
}
// Copy all our files in place, this is destructive
if cmd == "copy" || cmd == "setup" {
CliCopyFiles(&args)
}
// Report the status on all the files
if cmd == "status" || cmd == "setup" {
CliStatus(&args)
}
os.Exit(0)
}
// Set the logging and color libs to output color in line with the desired flags
// and/or TTY
func initColor(color string) {
tty := isatty.IsTerminal(os.Stdout.Fd())
if color == "" {
color = "auto"
}
if color == "never" || !tty {
// Disable manual colors
ansi = aurora.NewAurora(false)
// Disable logging colors
for _, level := range golog.Levels {
level.ColorCode = 7
level.Style = nil
}
return
}
if color == "always" || tty {
ansi = aurora.NewAurora(true)
// There's no good way to force golog to output color if it's not a tty
}
}
// Run all the embedded install scripts or exit.
// This will run all the install scripts, or a specified list of script names.
// If there is an error with any script it will exit this process.
func CliInstall(args *CliArgs, names ...string) {
var targets map[string](bool)
targets, names = Targets(args, &names)
log := golog.Child(fmt.Sprint(ansi.Blue("[install]")))
log.Infof("Installing %s...", strings.Join(names, ", "))
// Get our target directory for the platform
target := fmt.Sprintf("install/%v_%v", args.Os, args.Arch)
// Append $HOME/.bin to $PATH
binpath, _ := os.UserHomeDir()
binpath += "/.bin"
if !strings.Contains(os.Getenv("PATH"), binpath) {
os.Setenv("PATH", os.Getenv("PATH")+":"+binpath)
}
// Get all our install scripts
files, err := embedded.ReadDir(target)
if err != nil {
log.Fatal(err)
}
// Iterate through all the install scripts
for _, fd := range files {
// Actual script filename
script_name := fd.Name()
// Just the name portion of 00-name
name := getInstallName(script_name)
// We have targeted a subset to install
if len(names) > 0 {
// Skip anything not in our targets
if _, ok := targets[name]; !ok {
log.Debugf("Skipping '%v'", name)
continue
}
}
// If we're not upgrading or targeting, skip installed commands
if commandExists(name) && (!args.Upgrade && len(names) == 0) {
log.Debugf("Skipping '%v', already installed", name)
continue
}
// Create Script
script := Script{
name: fmt.Sprintf("%v/%v", target, script_name),
env: []string{},
}
// Set the script name to use
script.env = append(script.env, "NAME="+name)
// Set the tmp path name for use in the scripts
tmp := fmt.Sprintf("%v/%v-%v", tmpdir, name, time.Now().UnixNano())
tmp = fmt.Sprintf("TMP=%v", tmp)
script.env = append(script.env, tmp)
verb := "Installing"
// Set the upgrade flag if we need to
if args.Upgrade || len(names) > 0 {
script.env = append(script.env, "UPGRADE=true")
verb = "Upgrading"
}
// Set the dry run flag
if args.DryRun {
script.env = append(script.env, "RUN=echo "+fmt.Sprint(ansi.Black("dry-run:")))
}
// Run our install script
fmt.Println(ansi.Blue(verb), ansi.Blue(name))
log.Debug(script.name)
script.RunOrExit()
if args.DryRun {
fmt.Println(ansi.Yellow("No changes"))
} else {
fmt.Println(ansi.BrightGreen("Success"))
}
}
log.Info("Done.")
}
func CliCopyFiles(args *CliArgs) {
log := golog.Child(fmt.Sprint(ansi.Blue("[copy]")))
log.Info("Copying files...")
// Get the home directory
home, _ := os.UserHomeDir()
// This has to match the embedded path
base := "files"
// Filenames in embedded
names := make([]string, 0, 50) // Just allocate something to save time
// Get our filenames that we embedded
getFileNames(base, &names)
// Loop over our names copying them in
for _, name := range names {
// Strip the leading "files"
target, _ := filepath.Rel(base, name)
// Get just the directory part
dir := path.Join(home, filepath.Dir(target))
// Target to write file to
target = path.Join(home, target)
// Create the directories we need
if _, err := os.Stat(dir); os.IsNotExist(err) {
if args.DryRun {
fmt.Println(ansi.Black("dry-run:"), "mkdir -p", "\""+dir+"\"")
} else {
if err := os.MkdirAll(dir, 0755); err != nil {
log.Fatal(err)
}
}
}
// Write the file
if args.DryRun {
fmt.Println(ansi.Black("dry-run:"), "cp", "\"<embed>/"+name+"\"", "\""+target+"\"")
} else {
func() {
// It's our file, we'll write if we want to
os.Chmod(target, 0600)
// Read the embedded file
data, _ := embedded.ReadFile(name)
// Write it back out
if err := os.WriteFile(target, data, 0600); err != nil {
log.Fatal(err)
}
if strings.Contains(name, ".githooks") {
// TODO: Figure out a better way to not make this a hack
// This is a hack so the githooks are executable
os.Chmod(target, 0500)
} else {
// Make the files generated here read-only as a reminder to not
// edit them directly
os.Chmod(target, 0400)
}
}()
}
}
log.Info("Done.")
}
func CliStatus(args *CliArgs, names ...string) {
// Override args with local names
// Check all the filesystem hashes against our embedded
}
// Return a map and a deduplicated slice of all the names given.
func Targets(args *CliArgs, names *[]string) (map[string]bool, []string) {
targets := map[string](bool){}
// Default to argument provided names
if len(*names) == 0 {
names = &(args.Names)
}
// Populate our map
for _, name := range *names {
targets[name] = true
}
// Get the slice of target names deduplicated
keys := make([]string, len(targets))
i := 0
for key := range targets {
keys[i] = key
i++
}
return targets, keys
}
// Return the name portion of "00-name" scripts.
func getInstallName(name string) string {
re := regexp.MustCompile(`^(?P<order>\d+)-(?P<command>.*)$`)
matches := re.FindStringSubmatch(name)
if len(matches) > 0 {
return matches[re.SubexpIndex("command")]
}
return name
}
// Return true if cmd exists.
func commandExists(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
// Walk the embedded filesystem starting at base and populate paths.
// This is recursive and may sufffer with very large filesystems or very deep
// nested directories.
func getFileNames(base string, paths *[]string) {
files, err := embedded.ReadDir(base)
if err != nil {
log.Fatal(err)
}
// Iterate through all the files
for _, fd := range files {
if fd.IsDir() {
getFileNames(path.Join(base, fd.Name()), paths)
continue
}
*paths = append(*paths, path.Join(base, fd.Name()))
}
}
func Run(command string) int {
argv, err := shlex.Split(command)
if err != nil {
golog.Fatal(err)
}
return RunCommand(argv)
}
func RunCommand(argv []string) int {
exit, err := func() (int, error) {
cmd := exec.Command(argv[0], argv[1:]...)
// Always directly output to our calling tty
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Start the subprocess
if err := cmd.Start(); err != nil {
return -1, err
}
// Get the error code from the subprocess if it exists
if exitError, ok := cmd.Wait().(*exec.ExitError); ok {
return exitError.ExitCode(), exitError
}
return 0, nil
}()
// Handle bad exit codes
if exit != 0 || err != nil {
fmt.Println(err)
if exit == 0 {
exit = -2
}
}
return exit
}
type Script struct {
name string
env []string
}
func (script *Script) RunOrExit(args ...string) int {
// Run the embedded script
exit, err := script.Run(args...)
if err != nil {
golog.Fatal(err)
}
// This seems like an edge case
if exit != 0 {
golog.Fatal("Unknown error, exit code: ", exit)
}
// Exit codes are nice to have
return exit
}
func (script *Script) Run(args ...string) (int, error) {
// Get embedded script
data := embeddedFile(script.name)
// Set the script arguments
argv := []string{"-s", "-"}
argv = append(argv, args...)
// And a shell to run it in
cmd := exec.Command(shell, argv...)
// Always directly output to our calling tty
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Set the runtime environment
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, script.env...)
// Grab the pipe to the subprocess stdin
stdin, err := cmd.StdinPipe()
if err != nil {
return -1, err
}
// Start the subprocess
if err := cmd.Start(); err != nil {
return -1, err
}
// Write the script to stdin and close the pipe when finished
go func() {
defer stdin.Close()
io.WriteString(stdin, string(data))
}()
// Get the error code from the subprocess if it exists
if exitError, ok := cmd.Wait().(*exec.ExitError); ok {
return exitError.ExitCode(), exitError
}
return 0, nil
}
// Shorthand for a slice of bytes.
type file = []byte
// Return the bytes for the named file in our embedded FS.
func embeddedFile(name string) file {
data, err := embedded.ReadFile(name)
if err != nil {
golog.Fatal(err)
}
return data
}
|
[
"\"DEBUG\"",
"\"PATH\"",
"\"PATH\""
] |
[] |
[
"PATH",
"DEBUG"
] |
[]
|
["PATH", "DEBUG"]
|
go
| 2 | 0 | |
vendor/github.com/cloudfoundry/libbuildpack/packager/packager.go
|
package packager
//go:generate go-bindata -pkg $GOPACKAGE -prefix scaffold scaffold/...
import (
"archive/zip"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/cloudfoundry/libbuildpack"
)
var CacheDir = filepath.Join(os.Getenv("HOME"), ".buildpack-packager", "cache")
var Stdout, Stderr io.Writer = os.Stdout, os.Stderr
func CompileExtensionPackage(bpDir, version string, cached bool, stack string) (string, error) {
bpDir, err := filepath.Abs(bpDir)
if err != nil {
return "", fmt.Errorf("Failed to get the absolute path of %s: %v", bpDir, err)
}
dir, err := copyDirectory(bpDir)
if err != nil {
return "", fmt.Errorf("Failed to copy %s: %v", bpDir, err)
}
err = ioutil.WriteFile(filepath.Join(dir, "VERSION"), []byte(version), 0644)
if err != nil {
return "", fmt.Errorf("Failed to write VERSION file: %v", err)
}
isCached := "--uncached"
if cached {
isCached = "--cached"
}
stackArg := "--stack=" + stack
if stack == "any" {
stackArg = "--any-stack"
}
cmd := exec.Command("bundle", "exec", "buildpack-packager", isCached, stackArg)
cmd.Stdout = Stdout
cmd.Stderr = Stderr
cmd.Env = append(os.Environ(), "BUNDLE_GEMFILE=cf.Gemfile")
cmd.Dir = dir
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("Failed to run %s %s: %v", cmd.Path, strings.Join(cmd.Args, " "), err)
}
var manifest struct {
Language string `yaml:"language"`
}
if err := libbuildpack.NewYAML().Load(filepath.Join(bpDir, "manifest.yml"), &manifest); err != nil {
return "", fmt.Errorf("Failed to load manifest.yml: %v", err)
}
stackName := fmt.Sprintf("-%s", stack)
if stackName == "any" {
stackName = ""
}
zipFile := fmt.Sprintf("%s_buildpack%s-v%s.zip", manifest.Language, stackName, version)
if cached {
zipFile = fmt.Sprintf("%s_buildpack-cached%s-v%s.zip", manifest.Language, stackName, version)
}
if err := libbuildpack.CopyFile(filepath.Join(dir, zipFile), filepath.Join(bpDir, zipFile)); err != nil {
return "", fmt.Errorf("Failed to copy %s from %s to %s: %v", zipFile, dir, bpDir, err)
}
return filepath.Join(dir, zipFile), nil
}
func validateStack(stack, bpDir string) error {
manifest, err := readManifest(bpDir)
if err != nil {
return err
}
if manifest.Stack != "" {
return fmt.Errorf("Cannot package from already packaged buildpack manifest")
}
if stack == "" {
return nil
}
if len(manifest.Dependencies) > 0 && !manifest.hasStack(stack) {
return fmt.Errorf("Stack `%s` not found in manifest", stack)
}
for _, d := range manifest.Defaults {
if _, err := libbuildpack.FindMatchingVersion(d.Version, manifest.versionsOfDependencyWithStack(d.Name, stack)); err != nil {
return fmt.Errorf("No matching default dependency `%s` for stack `%s`", d.Name, stack)
}
}
return nil
}
func updateDependencyMap(dependencyMap interface{}, file File) error {
dep, ok := dependencyMap.(map[interface{}]interface{})
if !ok {
return fmt.Errorf("Could not cast deps[idx] to map[interface{}]interface{}")
}
dep["file"] = file.Name
return nil
}
func downloadDependency(dependency Dependency, cacheDir string) (File, error) {
file := filepath.Join("dependencies", fmt.Sprintf("%x", md5.Sum([]byte(dependency.URI))), filepath.Base(dependency.URI))
if err := os.MkdirAll(cacheDir, 0755); err != nil {
log.Fatalf("error: %v", err)
}
if _, err := os.Stat(filepath.Join(cacheDir, file)); err != nil {
if err := downloadFromURI(dependency.URI, filepath.Join(cacheDir, file)); err != nil {
return File{}, err
}
}
if err := checkSha256(filepath.Join(cacheDir, file), dependency.SHA256); err != nil {
return File{}, err
}
return File{file, filepath.Join(cacheDir, file)}, nil
}
func Package(bpDir, cacheDir, version, stack string, cached bool) (string, error) {
bpDir, err := filepath.Abs(bpDir)
if err != nil {
return "", err
}
err = validateStack(stack, bpDir)
if err != nil {
return "", err
}
dir, err := copyDirectory(bpDir)
if err != nil {
return "", err
}
err = ioutil.WriteFile(filepath.Join(dir, "VERSION"), []byte(version), 0644)
if err != nil {
return "", err
}
manifest, err := readManifest(dir)
if err != nil {
return "", err
}
if manifest.PrePackage != "" {
cmd := exec.Command(manifest.PrePackage)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(Stdout, string(out))
return "", err
}
}
files := []File{}
for _, name := range manifest.IncludeFiles {
files = append(files, File{name, filepath.Join(dir, name)})
}
var m map[string]interface{}
if err := libbuildpack.NewYAML().Load(filepath.Join(dir, "manifest.yml"), &m); err != nil {
return "", err
}
if stack != "" {
m["stack"] = stack
}
deps, ok := m["dependencies"].([]interface{})
if !ok {
return "", fmt.Errorf("Could not cast dependencies to []interface{}")
}
dependenciesForStack := []interface{}{}
for idx, d := range manifest.Dependencies {
for _, s := range d.Stacks {
if stack == "" || s == stack {
dependencyMap := deps[idx]
if cached {
if file, err := downloadDependency(d, cacheDir); err != nil {
return "", err
} else {
updateDependencyMap(dependencyMap, file)
files = append(files, file)
}
}
if stack != "" {
delete(dependencyMap.(map[interface{}]interface{}), "cf_stacks")
}
dependenciesForStack = append(dependenciesForStack, dependencyMap)
break
}
}
}
m["dependencies"] = dependenciesForStack
if err := libbuildpack.NewYAML().Write(filepath.Join(dir, "manifest.yml"), m); err != nil {
return "", err
}
stackPart := ""
if stack != "" {
stackPart = "-" + stack
}
cachedPart := ""
if cached {
cachedPart = "-cached"
}
fileName := fmt.Sprintf("%s_buildpack%s%s-v%s.zip", manifest.Language, cachedPart, stackPart, version)
zipFile := filepath.Join(bpDir, fileName)
if err := ZipFiles(zipFile, files); err != nil {
return "", err
}
return zipFile, err
}
func downloadFromURI(uri, fileName string) error {
err := os.MkdirAll(filepath.Dir(fileName), 0755)
if err != nil {
return err
}
output, err := os.Create(fileName)
if err != nil {
return err
}
defer output.Close()
u, err := url.Parse(uri)
if err != nil {
return err
}
var source io.ReadCloser
if u.Scheme == "file" {
source, err = os.Open(u.Path)
if err != nil {
return err
}
defer source.Close()
} else {
response, err := http.Get(uri)
if err != nil {
return err
}
defer response.Body.Close()
source = response.Body
if response.StatusCode < 200 || response.StatusCode > 299 {
return fmt.Errorf("could not download: %d", response.StatusCode)
}
}
_, err = io.Copy(output, source)
return err
}
func checkSha256(filePath, expectedSha256 string) error {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
sum := sha256.Sum256(content)
actualSha256 := hex.EncodeToString(sum[:])
if actualSha256 != expectedSha256 {
return fmt.Errorf("dependency sha256 mismatch: expected sha256 %s, actual sha256 %s", expectedSha256, actualSha256)
}
return nil
}
func ZipFiles(filename string, files []File) error {
newfile, err := os.Create(filename)
if err != nil {
return err
}
defer newfile.Close()
zipWriter := zip.NewWriter(newfile)
defer zipWriter.Close()
// Add files to zip
for _, file := range files {
zipfile, err := os.Open(file.Path)
if err != nil {
returnErr := fmt.Errorf("failed to open included_file: %s, %v", file.Path, err)
err = os.Remove(filename)
if err != nil {
returnErr = fmt.Errorf("%s. Failed to remove broken buildpack file: %s", returnErr.Error(), filename)
}
return returnErr
}
defer zipfile.Close()
// Get the file information
info, err := zipfile.Stat()
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
// Change to deflate to gain better compression
// see http://golang.org/pkg/archive/zip/#pkg-constants
header.Method = zip.Deflate
header.Name = file.Name
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
if _, err = io.Copy(writer, zipfile); err != nil {
return err
}
}
}
return nil
}
func copyDirectory(srcDir string) (string, error) {
destDir, err := ioutil.TempDir("", "buildpack-packager")
if err != nil {
return "", err
}
err = filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
path, err = filepath.Rel(srcDir, path)
if err != nil {
return err
}
if path == ".git" || path == "tests" {
return filepath.SkipDir
}
dest := filepath.Join(destDir, path)
if m := info.Mode(); m&os.ModeSymlink != 0 {
srcPath := filepath.Join(srcDir, path)
target, err := os.Readlink(srcPath)
if err != nil {
return fmt.Errorf("Error while reading symlink '%s': %v", srcPath, err)
}
if err := os.Symlink(target, dest); err != nil {
return fmt.Errorf("Error while creating '%s' as symlink to '%s': %v", dest, target, err)
}
} else if info.IsDir() {
err = os.MkdirAll(dest, info.Mode())
if err != nil {
return err
}
} else {
src, err := os.Open(filepath.Join(srcDir, path))
if err != nil {
return err
}
defer src.Close()
err = os.MkdirAll(filepath.Dir(dest), 0755)
if err != nil {
return err
}
fh, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode())
if err != nil {
return err
}
_, err = io.Copy(fh, src)
fh.Close()
return err
}
return nil
})
return destDir, err
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
compute/hybrid/compute_test.go
|
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package compute
import (
"context"
"flag"
"os"
"testing"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/config"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/util"
hybridnetwork "github.com/Azure-Samples/azure-sdk-for-go-samples/network/hybrid"
hybridresources "github.com/Azure-Samples/azure-sdk-for-go-samples/resources/hybrid"
hybridstorage "github.com/Azure-Samples/azure-sdk-for-go-samples/storage/hybrid"
"github.com/marstr/randname"
)
var (
vmName = randname.GenerateWithPrefix("az-samples-go-", 10)
nicName = "nic1"
username = "az-samples-go-user"
password = "NoSoupForYou1!"
sshPublicKeyPath = os.Getenv("HOME") + "/.ssh/id_rsa.pub"
virtualNetworkName = "vnet1"
subnetName = "subnet1"
nsgName = "nsg1"
ipName = "ip1"
storageAccountName = randname.Prefixed{Prefix: "storageaccount", Acceptable: randname.LowercaseAlphabet, Len: 10}.Generate()
)
func TestMain(m *testing.M) {
config.ParseEnvironment()
config.AddFlags()
flag.Parse()
os.Exit(m.Run())
}
func ExampleCreateVM() {
var groupName = config.GenerateGroupName("HybridVM")
config.SetGroupName(groupName)
ctx := context.Background()
defer hybridresources.Cleanup(ctx)
_, err := hybridresources.CreateGroup(ctx)
if err != nil {
util.PrintAndLog(err.Error())
}
_, err = hybridnetwork.CreateVirtualNetworkAndSubnets(ctx, virtualNetworkName, subnetName)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created vnet and a subnet")
_, err = hybridnetwork.CreateNetworkSecurityGroup(ctx, nsgName)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created network security group")
_, err = hybridnetwork.CreatePublicIP(ctx, ipName)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created public IP")
_, err = hybridnetwork.CreateNetworkInterface(ctx, nicName, nsgName, virtualNetworkName, subnetName, ipName)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created nic")
_, err = hybridstorage.CreateStorageAccount(ctx, storageAccountName)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created storage account")
_, err = CreateVM(ctx, vmName, nicName, username, password, storageAccountName, sshPublicKeyPath)
if err != nil {
util.PrintAndLog(err.Error())
}
util.PrintAndLog("created VM")
// Output:
// created vnet and a subnet
// created network security group
// created public IP
// created nic
// created storage account
// created VM
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
test/perf01.py
|
#!/usr/bin/env python
import difflib, sys
if len(sys.argv) < 3:
sys.exit(1)
file_a = open(sys.argv[1],"r")
a = file_a.read()
file_b = open(sys.argv[2],"r")
b = file_b.read()
r = 0.
nb_match = 0
for i in range(0,1000):
s = difflib.SequenceMatcher(None, a, b)
r = s.ratio()
print(r)
#print(nb_match)
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
molecule/default/tests/test_default.py
|
import os
import testinfra.utils.ansible_runner
import pytest
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize("name", [
("cockpit-system"),
("cockpit-pcp"),
("cockpit-docker"),
("cockpit-machines"),
("cockpit-ws"),
("cockpit-dashboard"),
])
def test_cockpit_pkg(host, name):
pkg = host.package(name)
assert pkg.is_installed
def test_cockpit_web_srv(host):
srv = host.service('cockpit.socket')
assert srv.is_running
assert srv.is_enabled
def test_cockpit_web_conf(host):
file = host.file('/etc/cockpit/cockpit.conf')
assert file.exists
assert file.user == 'root'
assert file.group == 'root'
def test_cockpit_web_socket(host):
sock = host.socket('tcp://9090')
assert sock.is_listening
def test_cockpit_web_clients(host):
file = host.file('/etc/cockpit/machines.d/99-webui.json')
assert file.exists
assert file.user == 'root'
assert file.group == 'root'
assert file.contains('192.168.0.10')
assert file.contains('host2')
assert file.contains('host3.example.com')
|
[] |
[] |
[
"MOLECULE_INVENTORY_FILE"
] |
[]
|
["MOLECULE_INVENTORY_FILE"]
|
python
| 1 | 0 | |
application/video_search_app/wsgi.py
|
"""
WSGI config for video_search_app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "video_search_app.settings")
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
stop/main.go
|
package main
import (
"encoding/json"
"fmt"
"github.com/joho/godotenv"
"log"
"net/http"
"os"
"stop/frame"
"stop/jwt"
"stop/pubsub"
"stop/remote"
"stop/ws"
"strings"
"time"
)
func main() {
_ = godotenv.Load()
serversStr := os.Getenv("SERVERS")
servers := strings.Split(serversStr, ",")
var clients []remote.Client
for _, server := range servers {
client := remote.NewClient(server)
if client == nil {
continue
}
clients = append(clients, *client)
}
ps := pubsub.NewPubSub()
go func() {
for {
time.Sleep(time.Second * 5)
if ps.SubscribersNum() == 0 {
continue
}
for _, client := range clients {
f, err := frame.NewFrame(client)
if err != nil {
continue
}
msg, err := json.Marshal(f)
if err != nil {
continue
}
ps.Publish(string(msg))
}
}
}()
jwtSecret := []byte(os.Getenv("JWT_SECRET"))
token, err := jwt.GenJwt("stop", jwtSecret, 365)
if err != nil {
return
}
fmt.Printf(`
__
___ / /____ ___
(_-</ __/ _ \/ _ \
/___/\__/\___/ .__/
/_/ Simple and extendable server monitor.
Token: %s
`, token)
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
client, err := ws.NewClient(w, r)
if err != nil {
return
}
defer client.Close()
tokenStr, ok := <-client.ReceiveChan()
if !ok {
return
}
_, err = jwt.ParseJwt(tokenStr, jwtSecret)
if err != nil {
return
}
msgChan := make(chan string)
ps.Subscribe(msgChan)
for {
select {
case <-client.DoneChan():
ps.Unsubscribe(msgChan)
return
case msg := <-msgChan:
client.SendChan() <- msg
case <-time.After(1 * time.Second):
}
}
})
err = http.ListenAndServe(":5566", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|
[
"\"SERVERS\"",
"\"JWT_SECRET\""
] |
[] |
[
"JWT_SECRET",
"SERVERS"
] |
[]
|
["JWT_SECRET", "SERVERS"]
|
go
| 2 | 0 | |
diffusion/analytical/diffusion.py
|
"""Routines to calculate 1D solutions to the diffusion problem."""
import math
import numpy as np
def solution_1D(t, x, idx0, *args, **kwargs):
"""Calculate the fundamental 1D solution.
t := (scalar) time
x = (array) position
idx0 = (scalar) index such that x0 = x[idx0]
soltype & kwargs (only for t>0):
'free', D0
'plates', D0, L, N, [sumtype], [clip, thresh]
'arbitrary', lambdas, nus, [sumtype], [clip, thresh]
"""
if t == 0: # initial condition
# By definition, this is G(x, t0; x0). If the numerical approximation is
# desired, one should call this function with t = `realmin`, `eps`, etc.
peak = kwargs.pop('peak', math.inf)
G = diracdelta(x, idx0, peak=peak)
elif t > 0:
soltype = args[0]
if soltype == 'free':
D0 = kwargs.pop('D0')
G = gaussian(x, idx0, D0, t)
elif soltype == 'plates':
D0 = kwargs.pop('D0') # constant diffusivity between plates
L = kwargs.pop('L') # spacing between plates
N = kwargs.pop('N', 100) # number of terms in the series
# set the eigenvalues and eigenmodes from the known solution
n = np.arange(0, N).reshape(N, 1) # column vector of n-terms
a_n = np.sqrt(1/L) * np.ones(n.shape)
a_n[1:] = np.sqrt(2) * a_n[1:]
nu_n = np.cos( n*np.pi/L * x ) * a_n
lambda_n = (n*np.pi/L)**2 * D0
G = series(lambda_n, nu_n, idx0, t, **kwargs)
elif soltype == 'arbitrary':
lambda_n = kwargs.pop('lambdas')
nu_n = kwargs.pop('nus')
G = series(lambda_n, nu_n, idx0, t, **kwargs)
return G
def diracdelta(x, idx0, peak=math.inf):
"""Diract delta function."""
y = np.zeros(x.size) # zero everywhere ...
y[idx0] = peak # ... except at x0
return y
def gaussian(x, idx0, D0, t):
"""Gaussian normal distribution."""
MU = x[idx0]
SIGMA = np.sqrt(2*D0*t)
y = 1/(SIGMA*np.sqrt(2*np.pi)) * np.exp(-1/2*((x-MU)/SIGMA)**2)
return y
def series(lambdas, nus, idx0, t_n, sumtype='default', clip=False, thresh=0, **kwargs):
"""Series solution.
lambdas: (1xN) array
nus: (NxM) matrix
idx0: (scalar) index
t_n: (scalar) time
sumtype: (str) 'default' or 'fejer' summation
clip: (bool) whether to clip all values <=thresh to 0
thresh: (scalar) where to clip
"""
lambdas = np.squeeze(lambdas)
nu_0 = nus[:, idx0]
solution = np.exp(-lambdas[:, np.newaxis] * t_n) * nus * nu_0[:, np.newaxis]
# sum down the columns over all terms
if sumtype == 'default':
y = np.sum(solution, 0) # standard fourier summation
elif sumtype == 'fejer': # fejer summation
Nmodes = solution.shape[0]
ps = np.cumsum(solution, 0)/Nmodes # running average
y = np.sum(ps, 0) # sum the partial sums
else:
raise Exception('Wrong sumtype')
if clip:
y = np.where(y<thresh, 0, y)
return y
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
Python/Tests/TestData/DjangoApplication1/manage.py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoApplication1.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
examples/sediment_meander_2d/meander_hydro.py
|
"""
Meander Test case
=======================
Solves the initial hydrodynamics simulation of flow around a 180 degree bend replicating
lab experiment 4 in Yen & Lee (1995).
Note this is not the main run-file and is just used to create an initial checkpoint for
the morphodynamic simulation.
For more details of the test case set-up see
[1] Clare et al. (2020). Hydro-morphodynamics 2D modelling using a discontinuous Galerkin discretisation.
Computers & Geosciences, 104658. https://doi.org/10.1016/j.cageo.2020.104658
"""
from thetis import *
# import bathymetry and mesh for meander
from meander_setup import *
# define function spaces
P1_2d = FunctionSpace(mesh2d, 'DG', 1)
vectorP1_2d = VectorFunctionSpace(mesh2d, 'DG', 1)
# simulate initial hydrodynamics
# define initial elevation
elev_init = Function(P1_2d).interpolate(0.0544 - bathymetry_2d)
# define initial velocity
uv_init = Function(vectorP1_2d).interpolate(as_vector((0.001, 0.001)))
# choose directory to output results
outputdir = 'outputs'
print_output('Exporting to '+outputdir)
t_end = 200
if os.getenv('THETIS_REGRESSION_TEST') is not None:
# run as tests, not sufficient for proper spin up
# but we simply want a run-through-without-error test
t_end = 25
# export interval in seconds
t_export = numpy.round(t_end/40, 0)
# define parameters
average_size = 10**(-3)
ksp = Constant(3*average_size)
# set up solver
solver_obj = solver2d.FlowSolver2d(mesh2d, bathymetry_2d)
options = solver_obj.options
options.simulation_export_time = t_export
options.simulation_end_time = t_end
options.output_directory = outputdir
options.check_volume_conservation_2d = True
options.fields_to_export = ['uv_2d', 'elev_2d']
options.use_lax_friedrichs_tracer = False
# using nikuradse friction
options.nikuradse_bed_roughness = ksp
# setting viscosity
options.horizontal_viscosity = Constant(5*10**(-2))
# crank-nicholson used to integrate in time system of ODEs resulting from application of galerkin FEM
options.set_timestepper_type('CrankNicolson', implicitness_theta=1.0)
if not hasattr(options.swe_timestepper_options, 'use_automatic_timestep'):
options.timestep = 1
# set boundary conditions
elev_init_const = (-max(bathymetry_2d.dat.data[:]) + 0.05436)
left_bnd_id = 1
right_bnd_id = 2
swe_bnd = {}
swe_bnd[3] = {'un': Constant(0.0)}
swe_bnd[1] = {'flux': Constant(-0.02)}
swe_bnd[2] = {'elev': Constant(elev_init_const), 'flux': Constant(0.02)}
solver_obj.bnd_functions['shallow_water'] = swe_bnd
solver_obj.assign_initial_conditions(uv=uv_init, elev=elev_init)
# run model
solver_obj.iterate()
# store hydrodynamics for next simulation
uv, elev = solver_obj.fields.solution_2d.split()
checkpoint_dir = "hydrodynamics_meander"
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
with DumbCheckpoint(checkpoint_dir + '/velocity', mode=FILE_CREATE) as chk:
chk.store(uv, name="velocity")
chk.close()
with DumbCheckpoint(checkpoint_dir + "/elevation", mode=FILE_CREATE) as chk:
chk.store(elev, name="elevation")
chk.close()
|
[] |
[] |
[
"THETIS_REGRESSION_TEST"
] |
[]
|
["THETIS_REGRESSION_TEST"]
|
python
| 1 | 0 | |
vendor/cloud.google.com/go/bigtable/internal/cbtconfig/cbtconfig.go
|
/*
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.
*/
// Package cbtconfig encapsulates common code for reading configuration from .cbtrc and gcloud.
package cbtconfig
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"golang.org/x/oauth2"
)
// Config represents a configuration.
type Config struct {
Project, Instance string // required
Creds string // optional
AdminEndpoint string // optional
DataEndpoint string // optional
TokenSource oauth2.TokenSource // derived
}
type RequiredFlags uint
const NoneRequired RequiredFlags = 0
const (
ProjectRequired RequiredFlags = 1 << iota
InstanceRequired
)
const ProjectAndInstanceRequired RequiredFlags = ProjectRequired | InstanceRequired
// RegisterFlags registers a set of standard flags for this config.
// It should be called before flag.Parse.
func (c *Config) RegisterFlags() {
flag.StringVar(&c.Project, "project", c.Project, "project ID, if unset uses gcloud configured project")
flag.StringVar(&c.Instance, "instance", c.Instance, "Cloud Bigtable instance")
flag.StringVar(&c.Creds, "creds", c.Creds, "if set, use application credentials in this file")
flag.StringVar(&c.AdminEndpoint, "admin-endpoint", c.AdminEndpoint, "Override the admin api endpoint")
flag.StringVar(&c.DataEndpoint, "data-endpoint", c.DataEndpoint, "Override the data api endpoint")
}
// CheckFlags checks that the required config values are set.
func (c *Config) CheckFlags(required RequiredFlags) error {
var missing []string
if required != NoneRequired {
c.SetFromGcloud()
}
if required&ProjectRequired != 0 && c.Project == "" {
missing = append(missing, "-project")
}
if required&InstanceRequired != 0 && c.Instance == "" {
missing = append(missing, "-instance")
}
if len(missing) > 0 {
return fmt.Errorf("Missing %s", strings.Join(missing, " and "))
}
return nil
}
// Filename returns the filename consulted for standard configuration.
func Filename() string {
// TODO(dsymonds): Might need tweaking for Windows.
return filepath.Join(os.Getenv("HOME"), ".cbtrc")
}
// Load loads a .cbtrc file.
// If the file is not present, an empty config is returned.
func Load() (*Config, error) {
filename := Filename()
data, err := ioutil.ReadFile(filename)
if err != nil {
// silent fail if the file isn't there
if os.IsNotExist(err) {
return &Config{}, nil
}
return nil, fmt.Errorf("Reading %s: %v", filename, err)
}
c := new(Config)
s := bufio.NewScanner(bytes.NewReader(data))
for s.Scan() {
line := s.Text()
i := strings.Index(line, "=")
if i < 0 {
return nil, fmt.Errorf("Bad line in %s: %q", filename, line)
}
key, val := strings.TrimSpace(line[:i]), strings.TrimSpace(line[i+1:])
switch key {
default:
return nil, fmt.Errorf("Unknown key in %s: %q", filename, key)
case "project":
c.Project = val
case "instance":
c.Instance = val
case "creds":
c.Creds = val
case "admin-endpoint":
c.AdminEndpoint = val
case "data-endpoint":
c.DataEndpoint = val
}
}
return c, s.Err()
}
type GcloudCredential struct {
AccessToken string `json:"access_token"`
Expiry time.Time `json:"token_expiry"`
}
func (cred *GcloudCredential) Token() *oauth2.Token {
return &oauth2.Token{AccessToken: cred.AccessToken, TokenType: "Bearer", Expiry: cred.Expiry}
}
type GcloudConfig struct {
Configuration struct {
Properties struct {
Core struct {
Project string `json:"project"`
} `json:"core"`
} `json:"properties"`
} `json:"configuration"`
Credential GcloudCredential `json:"credential"`
}
type GcloudCmdTokenSource struct {
Command string
Args []string
}
// Token implements the oauth2.TokenSource interface
func (g *GcloudCmdTokenSource) Token() (*oauth2.Token, error) {
gcloudConfig, err := LoadGcloudConfig(g.Command, g.Args)
if err != nil {
return nil, err
}
return gcloudConfig.Credential.Token(), nil
}
// LoadGcloudConfig retrieves the gcloud configuration values we need use via the
// 'config-helper' command
func LoadGcloudConfig(gcloudCmd string, gcloudCmdArgs []string) (*GcloudConfig, error) {
out, err := exec.Command(gcloudCmd, gcloudCmdArgs...).Output()
if err != nil {
return nil, fmt.Errorf("Could not retrieve gcloud configuration")
}
var gcloudConfig GcloudConfig
if err := json.Unmarshal(out, &gcloudConfig); err != nil {
return nil, fmt.Errorf("Could not parse gcloud configuration")
}
log.Printf("Retrieved gcloud configuration, active project is \"%s\"",
gcloudConfig.Configuration.Properties.Core.Project)
return &gcloudConfig, nil
}
// SetFromGcloud retrieves and sets any missing config values from the gcloud
// configuration if possible possible
func (c *Config) SetFromGcloud() error {
if c.Creds == "" {
c.Creds = os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
if c.Creds == "" {
log.Printf("-creds flag unset, will use gcloud credential")
}
} else {
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", c.Creds)
}
if c.Project == "" {
log.Printf("-project flag unset, will use gcloud active project")
}
if c.Creds != "" && c.Project != "" {
return nil
}
gcloudCmd := "gcloud"
if runtime.GOOS == "windows" {
gcloudCmd = gcloudCmd + ".cmd"
}
gcloudCmdArgs := []string{"config", "config-helper",
"--format=json(configuration.properties.core.project,credential)"}
gcloudConfig, err := LoadGcloudConfig(gcloudCmd, gcloudCmdArgs)
if err != nil {
return err
}
if c.Project == "" {
c.Project = gcloudConfig.Configuration.Properties.Core.Project
}
if c.Creds == "" {
c.TokenSource = oauth2.ReuseTokenSource(
gcloudConfig.Credential.Token(),
&GcloudCmdTokenSource{Command: gcloudCmd, Args: gcloudCmdArgs})
}
return nil
}
|
[
"\"HOME\"",
"\"GOOGLE_APPLICATION_CREDENTIALS\""
] |
[] |
[
"HOME",
"GOOGLE_APPLICATION_CREDENTIALS"
] |
[]
|
["HOME", "GOOGLE_APPLICATION_CREDENTIALS"]
|
go
| 2 | 0 | |
out_sqs.go
|
package main
import (
"C"
"errors"
"fmt"
"time"
"unsafe"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/fluent/fluent-bit-go/output"
)
import (
"encoding/json"
"net/http"
"net/url"
"strings"
)
// integer representation for this plugin log level
// 0 - debug
// 1 - info
// 2 - error
var sqsOutLogLevel int
// MessageCounter is used for count the current SQS Batch messages
var MessageCounter int = 0
// SqsRecords is the actual aws messages batch
var SqsRecords []*sqs.SendMessageBatchRequestEntry
type sqsConfig struct {
queueURL string
queueMessageGroupID string
mySQS *sqs.SQS
pluginTagAttribute string
proxyURL string
}
//export FLBPluginRegister
func FLBPluginRegister(def unsafe.Pointer) int {
setLogLevel()
return output.FLBPluginRegister(def, "sqs", "aws sqs output plugin")
}
//export FLBPluginInit
func FLBPluginInit(plugin unsafe.Pointer) int {
queueURL := output.FLBPluginConfigKey(plugin, "QueueUrl")
queueRegion := output.FLBPluginConfigKey(plugin, "QueueRegion")
queueMessageGroupID := output.FLBPluginConfigKey(plugin, "QueueMessageGroupId")
pluginTagAttribute := output.FLBPluginConfigKey(plugin, "PluginTagAttribute")
proxyURL := output.FLBPluginConfigKey(plugin, "ProxyUrl")
writeInfoLog(fmt.Sprintf("QueueUrl is: %s", queueURL))
writeInfoLog(fmt.Sprintf("QueueRegion is: %s", queueRegion))
writeInfoLog(fmt.Sprintf("QueueMessageGroupId is: %s", queueMessageGroupID))
writeInfoLog(fmt.Sprintf("pluginTagAttribute is: %s", pluginTagAttribute))
writeInfoLog(fmt.Sprintf("ProxyUrl is: %s", proxyURL))
if queueURL == "" {
writeErrorLog(errors.New("QueueUrl configuration key is mandatory"))
return output.FLB_ERROR
}
if queueRegion == "" {
writeErrorLog(errors.New("QueueRegion configuration key is mandatory"))
return output.FLB_ERROR
}
if strings.HasSuffix(queueURL, ".fifo") {
if queueMessageGroupID == "" {
writeErrorLog(errors.New("QueueMessageGroupId configuration key is mandatory for FIFO queues: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html"))
return output.FLB_ERROR
}
}
writeInfoLog("retrieving aws credentials from environment variables")
awsCredentials := credentials.NewEnvCredentials()
var myAWSSession *session.Session
var sessionError error
var awsConfig *aws.Config
// Retrieve the credentials value
_, credError := awsCredentials.Get()
if credError != nil {
writeInfoLog("unable to find aws credentials from environment variables..using credentials chain")
awsConfig = &aws.Config{
Region: aws.String(queueRegion),
CredentialsChainVerboseErrors: aws.Bool(true),
}
} else {
writeInfoLog("environment variables credentials where found")
awsConfig = &aws.Config{
Region: aws.String(queueRegion),
CredentialsChainVerboseErrors: aws.Bool(true),
Credentials: awsCredentials,
}
}
// if proxy
if proxyURL != "" {
writeInfoLog("set http client struct on aws configuration since proxy url has been found")
awsConfig.HTTPClient = &http.Client{
Transport: &http.Transport{
Proxy: func(*http.Request) (*url.URL, error) {
return url.Parse(proxyURL) // Or your own implementation that decides a proxy based on the URL in the request
},
},
}
}
// create the session
myAWSSession, sessionError = session.NewSession(awsConfig)
if sessionError != nil {
writeErrorLog(sessionError)
return output.FLB_ERROR
}
// Set the context to point to any Go variable
output.FLBPluginSetContext(plugin, &sqsConfig{
queueURL: queueURL,
queueMessageGroupID: queueMessageGroupID,
mySQS: sqs.New(myAWSSession),
pluginTagAttribute: pluginTagAttribute,
})
return output.FLB_OK
}
//export FLBPluginFlushCtx
func FLBPluginFlushCtx(ctx, data unsafe.Pointer, length C.int, tag *C.char) int {
var ret int
var ts interface{}
var record map[interface{}]interface{}
var sqsRecord *sqs.SendMessageBatchRequestEntry
// Type assert context back into the original type for the Go variable
sqsConf, ok := output.FLBPluginGetContext(ctx).(*sqsConfig)
if !ok {
writeErrorLog(errors.New("Unexpected error during get plugin context in flush function"))
return output.FLB_ERROR
}
// Create Fluent Bit decoder
dec := output.NewDecoder(data, int(length))
// Iterate Records
for {
// Extract Record
ret, ts, record = output.GetRecord(dec)
if ret != 0 {
break
}
writeDebugLog(fmt.Sprintf("got new record from input. record length is: %d", len(record)))
if len(record) == 0 {
writeInfoLog("got empty record from input. skipping it")
continue
}
// Print record keys and values
var timeStamp time.Time
switch t := ts.(type) {
case output.FLBTime:
timeStamp = ts.(output.FLBTime).Time
case uint64:
timeStamp = time.Unix(int64(t), 0)
default:
writeInfoLog("given time is not in a known format, defaulting to now")
timeStamp = time.Now()
}
tagStr := C.GoString(tag)
recordString, err := createRecordString(timeStamp, tagStr, record)
if err != nil {
writeErrorLog(err)
// DO NOT RETURN HERE becase one message has an error when json is
// generated, but a retry would fetch ALL messages again. instead an
// error should be printed to console
continue
}
MessageCounter++
writeDebugLog(fmt.Sprintf("record string: %s", recordString))
writeDebugLog(fmt.Sprintf("message counter: %d", MessageCounter))
sqsRecord = &sqs.SendMessageBatchRequestEntry{
Id: aws.String(fmt.Sprintf("MessageNumber-%d", MessageCounter)),
MessageBody: aws.String(recordString),
}
if sqsConf.pluginTagAttribute != "" {
sqsRecord.MessageAttributes = map[string]*sqs.MessageAttributeValue{
sqsConf.pluginTagAttribute: &sqs.MessageAttributeValue{
DataType: aws.String("String"),
StringValue: aws.String(tagStr),
},
}
}
if sqsConf.queueMessageGroupID != "" {
sqsRecord.MessageGroupId = aws.String(sqsConf.queueMessageGroupID)
}
SqsRecords = append(SqsRecords, sqsRecord)
if MessageCounter == 10 {
err := sendBatchToSqs(sqsConf, SqsRecords)
SqsRecords = nil
MessageCounter = 0
if err != nil {
writeErrorLog(err)
return output.FLB_ERROR
}
}
}
return output.FLB_OK
}
//export FLBPluginExit
func FLBPluginExit() int {
return output.FLB_OK
}
func sendBatchToSqs(sqsConf *sqsConfig, sqsRecords []*sqs.SendMessageBatchRequestEntry) error {
sqsBatch := sqs.SendMessageBatchInput{
Entries: sqsRecords,
QueueUrl: aws.String(sqsConf.queueURL),
}
output, err := sqsConf.mySQS.SendMessageBatch(&sqsBatch)
if err != nil {
return err
}
if len(output.Failed) > 0 {
fmt.Println(output.Failed)
}
return nil
}
func createRecordString(timestamp time.Time, tag string, record map[interface{}]interface{}) (string, error) {
m := make(map[string]interface{})
// convert timestamp to RFC3339Nano
m["@timestamp"] = timestamp.UTC().Format(time.RFC3339Nano)
for k, v := range record {
switch t := v.(type) {
case []byte:
// prevent encoding to base64
m[k.(string)] = string(t)
default:
m[k.(string)] = v
}
}
js, err := json.Marshal(m)
if err != nil {
writeErrorLog(fmt.Errorf("error creating message for sqs. tag: %s. error: %v", tag, err))
return "", err
}
return string(js), nil
}
func writeDebugLog(message string) {
if sqsOutLogLevel == 0 {
currentTime := time.Now()
fmt.Printf("[%s] [ debug] [sqs-out] %s\n", currentTime.Format("2006.01.02 15:04:05"), message)
}
}
func writeInfoLog(message string) {
if sqsOutLogLevel <= 1 {
currentTime := time.Now()
fmt.Printf("[%s] [ info] [sqs-out] %s\n", currentTime.Format("2006.01.02 15:04:05"), message)
}
}
func writeErrorLog(err error) {
if sqsOutLogLevel <= 2 {
currentTime := time.Now()
fmt.Printf("[%s] [ error] [sqs-out] %v\n", currentTime.Format("2006.01.02 15:04:05"), err)
}
}
func setLogLevel() {
logEnv := os.Getenv("SQS_OUT_LOG_LEVEL")
switch strings.ToLower(logEnv) {
case "debug":
sqsOutLogLevel = 0
case "info":
sqsOutLogLevel = 1
case "error":
sqsOutLogLevel = 2
default:
sqsOutLogLevel = 1 // info
}
}
func main() {
}
|
[
"\"SQS_OUT_LOG_LEVEL\""
] |
[] |
[
"SQS_OUT_LOG_LEVEL"
] |
[]
|
["SQS_OUT_LOG_LEVEL"]
|
go
| 1 | 0 | |
svc/news_service/service/service.go
|
package service
import (
"fmt"
"github.com/nomoremehere/delinkcious/pb/news_service/pb"
nm "github.com/nomoremehere/delinkcious/pkg/news_manager"
"google.golang.org/grpc"
"log"
"net"
"os"
)
func Run() {
port := os.Getenv("PORT")
if port == "" {
port = "6060"
}
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatal(err)
}
natsHostname := os.Getenv("NATS_CLUSTER_SERVICE_HOST")
natsPort := os.Getenv("NATS_CLUSTER_SERVICE_PORT")
svc, err := nm.NewNewsManager(natsHostname, natsPort)
if err != nil {
log.Fatal(err)
}
gRPCServer := grpc.NewServer()
pb.RegisterNewsServer(gRPCServer, newNewsServer(svc))
fmt.Printf("News service is listening on port %s...\n", port)
err = gRPCServer.Serve(listener)
fmt.Println("Serve() failed", err)
}
|
[
"\"PORT\"",
"\"NATS_CLUSTER_SERVICE_HOST\"",
"\"NATS_CLUSTER_SERVICE_PORT\""
] |
[] |
[
"PORT",
"NATS_CLUSTER_SERVICE_HOST",
"NATS_CLUSTER_SERVICE_PORT"
] |
[]
|
["PORT", "NATS_CLUSTER_SERVICE_HOST", "NATS_CLUSTER_SERVICE_PORT"]
|
go
| 3 | 0 | |
internal/service/middlewares/authentication.go
|
package middlewares
import (
"context"
"errors"
"fmt"
"github.com/Baja-KS/WebshopAPI-ProductService/internal/database"
"github.com/Baja-KS/WebshopAPI-ProductService/internal/service"
"net/http"
"os"
)
func CheckAuth(ctx context.Context, authServiceURL string) bool {
client := &http.Client{}
req, err := http.NewRequest("GET", authServiceURL+"/User", nil)
if err != nil {
return false
}
token := ctx.Value("auth").(string)
authHeader := fmt.Sprintf("Bearer %s", token)
req.Header.Add("Authorization", authHeader)
res, err := client.Do(req)
if err != nil || res.StatusCode != 200 {
return false
}
return true
}
type AuthenticationMiddleware struct {
Next service.Service
}
func (a *AuthenticationMiddleware) GetByID(ctx context.Context, id uint) (database.ProductOut, error) {
return a.Next.GetByID(ctx, id)
}
func (a *AuthenticationMiddleware) Search(ctx context.Context, search string, category uint, minPrice float32, maxPrice float32, discount bool, sortName string, sortPrice string) ([]database.ProductOut, error) {
return a.Next.Search(ctx, search, category, minPrice, maxPrice, discount, sortName, sortPrice)
}
func (a *AuthenticationMiddleware) Create(ctx context.Context, data database.ProductIn) (string, error) {
if !CheckAuth(ctx, os.Getenv("AUTH_SERVICE")) {
return "Unauthorized", errors.New("unauthorized")
}
return a.Next.Create(ctx, data)
}
func (a *AuthenticationMiddleware) Update(ctx context.Context, id uint, data database.ProductIn) (string, error) {
if !CheckAuth(ctx, os.Getenv("AUTH_SERVICE")) {
return "Unauthorized", errors.New("unauthorized")
}
return a.Next.Update(ctx, id, data)
}
func (a *AuthenticationMiddleware) Delete(ctx context.Context, id uint) (string, error) {
if !CheckAuth(ctx, os.Getenv("AUTH_SERVICE")) {
return "Unauthorized", errors.New("unauthorized")
}
return a.Next.Delete(ctx, id)
}
|
[
"\"AUTH_SERVICE\"",
"\"AUTH_SERVICE\"",
"\"AUTH_SERVICE\""
] |
[] |
[
"AUTH_SERVICE"
] |
[]
|
["AUTH_SERVICE"]
|
go
| 1 | 0 | |
event/github/impl.go
|
// Copyright © 2017 Heptio
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright © 2017 The Kubicorn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package github
import (
"context"
"fmt"
"os"
"time"
"github.com/google/go-github/github"
"github.com/heptiolabs/git-events-operator/event"
"github.com/kubicorn/kubicorn/pkg/logger"
)
const (
GithubImplementation event.ImplementationType = "GitHub"
LoopIterationSleepSeconds = 3
)
type EventImplementation struct {
Name string
KindValue event.EventKind
ImplementationType event.ImplementationType
Authors map[string]string
FileName string
}
func (e *EventImplementation) Kind() event.EventKind {
return e.KindValue
}
func (e *EventImplementation) Type() event.ImplementationType {
return e.ImplementationType
}
type EventBrokerImplementation struct {
client *github.Client
queue *event.Queue
// Path Information
// TODO @kris-nova this might be the wrong place to define this if we want more than 1 instance but works for now
Owner string
Repo string
Path string
}
// ConcurrentWatch will watch a directory and send an event for each file in the directory, and when a new file is created.
func (b *EventBrokerImplementation) ConcurrentWatch(queue *event.Queue) chan error {
b.queue = queue
errch := make(chan error)
go func() {
// Concurrent logic for GitHub goes here
// return errors over the channel
var cache []string
for {
time.Sleep(time.Duration(time.Second * LoopIterationSleepSeconds))
logger.Debug("Querying repository")
opt := &github.RepositoryContentGetOptions{}
_, dirContent, _, err := b.client.Repositories.GetContents(context.TODO(), b.Owner, b.Repo, b.Path, opt)
if err != nil {
errch <- fmt.Errorf("unable to download contents from repository: %v", err)
return
}
for _, repoContent := range dirContent {
cached := false
name := *repoContent.Name
//fmt.Printf("(%s) ", name)
for _, cachedFile := range cache {
if name == cachedFile {
cached = true
break
}
}
if cached {
continue
}
// Hooray a new file, let's look up the author information
//opt := &github.ListContributorsOptions{
// ListOptions: github.ListOptions{},
//}
logger.Info("Parsing file: %s", name)
opt := &github.CommitsListOptions{
Path: fmt.Sprintf("%s%s", b.Path, name),
}
commits, _, err := b.client.Repositories.ListCommits(context.TODO(), b.Owner, b.Repo, opt)
if err != nil {
errch <- fmt.Errorf("unable to list commits: %v", err)
return
}
//logger.Info("Number of commits: %d", len(commits))
authors := make(map[string]string)
for _, commit := range commits {
// TODO This is very strange logic and if we are having issues with empty/missing emails
// or email in general it's probably happening here.
author := commit.Commit.Author
if author == nil {
continue
}
// Get the name and email of the committer
name := author.GetName()
email := author.GetEmail()
//fmt.Printf("%+v ", commit)
//fmt.Println(name, email)
// Index on email so we know we don't spam anyones inbox
authors[email] = name
}
// Send the event to the queue
event := &EventImplementation{
Name: name,
KindValue: event.NewFile,
ImplementationType: GithubImplementation,
Authors: authors,
FileName: name,
}
queue.AddEvent(event)
logger.Info("Adding event: %s", name)
// Cache this file
cache = append(cache, name)
}
}
}()
return errch
}
func (b *EventBrokerImplementation) Auth() error {
user := os.Getenv("GITHUB_USER")
if user == "" {
return fmt.Errorf("missing or empty GITHUB_USER environmental variable, unable to authenticate with GitHub")
}
pass := os.Getenv("GITHUB_PASS")
if user == "" {
return fmt.Errorf("missing or empty GITHUB_PASS environmental variable, unable to authenticate with GitHub")
}
authTransport := github.BasicAuthTransport{
Username: user,
Password: pass,
}
client := github.NewClient(authTransport.Client())
logger.Info("Authenticated with GitHub [%s]", user)
b.client = client
return nil
}
|
[
"\"GITHUB_USER\"",
"\"GITHUB_PASS\""
] |
[] |
[
"GITHUB_USER",
"GITHUB_PASS"
] |
[]
|
["GITHUB_USER", "GITHUB_PASS"]
|
go
| 2 | 0 | |
lib/server_test.go
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016,2017 aerth <[email protected]>
*
* 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.
*/
package diamond
import (
"io/ioutil"
"os"
"testing"
)
func TestNewServer(t *testing.T) {
socket, err := ioutil.TempFile("", "testsocket") // unique filename
if err != nil {
t.Log(err)
t.FailNow()
}
os.Remove(socket.Name())
defer os.Remove(socket.Name()) // isnt created yet
_, err = New(socket.Name())
if err != nil {
t.Logf("tried to create socket %q, got error: %v", socket.Name(), err)
t.FailNow()
}
}
func createTestServer(t *testing.T) (*System, string) {
socket, err := ioutil.TempFile("", "testsocket") // unique filename
if err != nil {
t.Log(err)
t.FailNow()
}
os.Remove(socket.Name())
srv, err := New(socket.Name())
if err != nil {
t.Logf("tried to create socket %q, got error: %v", socket.Name(), err)
t.FailNow()
return nil, socket.Name()
}
return srv, socket.Name()
}
func TestRunlevelBasic(t *testing.T) {
srv, socket := createTestServer(t)
defer os.Remove(socket)
// set runlevel
srv.SetRunlevel(1, func() error { println("runlevel works"); return nil })
// enter runlevel
if err := srv.Runlevel(1); err != nil {
t.Logf("error while trying to enter runlevel 1: %v", err)
t.FailNow()
}
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
vault/utils.go
|
package vault
import (
"os"
"regexp"
"runtime"
"strings"
)
// ParsePath splits the given path string into its respective secret path
// and contained key parts
func ParsePath(path string) (secret, key string) {
secret = path
if idx := strings.LastIndex(path, ":"); idx >= 0 {
secret = path[:idx]
key = path[idx+1:]
}
secret = Canonicalize(secret)
return
}
// PathHasKey returns true if the given path has a key specified in its syntax.
// False otherwise.
func PathHasKey(path string) bool {
_, key := ParsePath(path)
return key != ""
}
func Canonicalize(p string) string {
p = strings.TrimSuffix(p, "/")
p = strings.TrimPrefix(p, "/")
re := regexp.MustCompile("//+")
p = re.ReplaceAllString(p, "/")
return p
}
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("USERPROFILE")
if home == "" {
home = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
return home
}
return os.Getenv("HOME")
}
|
[
"\"USERPROFILE\"",
"\"HOMEDRIVE\"",
"\"HOMEPATH\"",
"\"HOME\""
] |
[] |
[
"HOME",
"HOMEPATH",
"HOMEDRIVE",
"USERPROFILE"
] |
[]
|
["HOME", "HOMEPATH", "HOMEDRIVE", "USERPROFILE"]
|
go
| 4 | 0 | |
tests/functional/validators/test_validators_directives_are_in_valid_locations.py
|
import pytest
from tartiflette import create_engine
@pytest.fixture(scope="module", name="ttftt_engine")
async def ttftt_engine_fixture():
SDL = """
directive @queryDirective on QUERY
directive @subscriptionDirective on SUBSCRIPTION
directive @mutationDirective on MUTATION
directive @fieldDirective on FIELD
directive @fragmentDirective on FRAGMENT_DEFINITION
directive @fragmentSpreadDirective on FRAGMENT_SPREAD
directive @inlineFragmentDirective on INLINE_FRAGMENT
type Query {
bob: Int
}
type Mutation {
lol: Int
}
type Subscription {
mdr: Int
}
"""
return await create_engine(
SDL, schema_name="test_validators_directives_are_in_valid_locations"
)
@pytest.mark.parametrize(
"query,expected",
[
(
"""
query a @queryDirective {
bob
}
mutation b @queryDirective {
lol
}
subscription c @queryDirective {
mdr
}
""",
{
"data": None,
"errors": [
{
"message": "Directive < @queryDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 6, "column": 13},
{"line": 6, "column": 24},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @queryDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 10, "column": 13},
{"line": 10, "column": 28},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
],
},
),
(
"""
query a @mutationDirective {
bob
}
mutation b @mutationDirective {
lol
}
subscription c @mutationDirective {
mdr
}
""",
{
"data": None,
"errors": [
{
"message": "Directive < @mutationDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 2, "column": 21},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @mutationDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 10, "column": 13},
{"line": 10, "column": 28},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
],
},
),
(
"""
query a @subscriptionDirective {
bob
}
mutation b @subscriptionDirective {
lol
}
subscription c @subscriptionDirective {
mdr
}
""",
{
"data": None,
"errors": [
{
"message": "Directive < @subscriptionDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 2, "column": 21},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @subscriptionDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 6, "column": 13},
{"line": 6, "column": 24},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
],
},
),
(
"""
query a {
bob @fieldDirective
}
mutation b {
lol @fragmentSpreadDirective
}
subscription c {
mdr @inlineFragmentDirective
}
""",
{
"data": None,
"errors": [
{
"message": "Directive < @fragmentSpreadDirective > is not used in a valid location.",
"path": ["lol"],
"locations": [
{"line": 7, "column": 17},
{"line": 7, "column": 21},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @inlineFragmentDirective > is not used in a valid location.",
"path": ["mdr"],
"locations": [
{"line": 11, "column": 17},
{"line": 11, "column": 21},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
],
},
),
(
"""
fragment John on Query @fragmentDirective @fieldDirective {
bob
}
query a {
...John @fragmentSpreadDirective @inlineFragmentDirective
}
mutation b {
... on Mutation @inlineFragmentDirective @fragmentSpreadDirective {
lol
}
}
subscription c {
mdr
}
""",
{
"data": None,
"errors": [
{
"message": "Directive < @fieldDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 2, "column": 55},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @inlineFragmentDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 7, "column": 17},
{"line": 7, "column": 50},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
{
"message": "Directive < @fragmentSpreadDirective > is not used in a valid location.",
"path": None,
"locations": [
{"line": 11, "column": 17},
{"line": 11, "column": 58},
],
"extensions": {
"rule": "5.7.2",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Directives-Are-In-Valid-Locations",
"tag": "directives-are-in-valid-locations",
},
},
],
},
),
],
)
@pytest.mark.asyncio
async def test_validators_directives_are_in_valid_locations(
query, expected, ttftt_engine
):
assert await ttftt_engine.execute(query) == expected
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
renderer/phantomjs.go
|
// Copyright 2015, Yahoo Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package renderer
import (
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/yahoo/gryffin"
_ "github.com/yahoo/gryffin/renderer/resource"
)
/* all of these are the JSON struct for phantomjs render.js */
type PhantomJSRenderer struct {
BaseRenderer
Timeout int
process *os.Process
}
type input struct {
Method string `json:"method"`
AllowedDomains []string `json:"allowed_domains,omitempty"`
Headers inputHeaders `json:"headers"`
}
type inputHeaders struct {
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Cookie string
UserAgent string `json:"User-Agent"`
}
type details struct {
Links []link
Forms []string
}
type link struct {
Text string
Url string
}
type response struct {
Headers map[string][]string
Body string
ContentType string
Status int
Url string
Details details
}
type responseMessage struct {
Response response
Elapsed int
Ok int
}
type domMessage struct {
Action string
Events []string
KeyChain []string
Links []link
JSError []string
}
type message struct {
*responseMessage
*domMessage
Signature string
MsgType string
}
type noCloseReader struct {
io.Reader
}
func (r noCloseReader) Close() error {
return nil
}
func (m *response) fill(s *gryffin.Scan) {
/*
{"response":{"headers":{"Date":["Thu, 30 Jul 2015 00:13:43 GMT"],"Set-Cookie":["B=82j3nrdarir1n&b=3&s=23; expires=Sun, 30-Jul-2017 00:13:43 GMT; path=/; domain=.yahoo.com"]
*/
resp := &http.Response{
Request: s.Request,
StatusCode: m.Status,
Status: strconv.FormatInt(int64(m.Status), 10),
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: m.Headers,
Body: noCloseReader{strings.NewReader(m.Body)},
}
s.Response = resp
s.ReadResponseBody()
}
func (l *link) toScan(parent *gryffin.Scan) *gryffin.Scan {
if req, err := http.NewRequest("GET", l.Url, nil); err == nil {
s := parent.Spawn()
s.MergeRequest(req)
return s
}
// invalid url
return nil
}
func (r *PhantomJSRenderer) extract(stdout io.ReadCloser, s *gryffin.Scan) {
defer close(r.done)
dec := json.NewDecoder(stdout)
for {
var m message
err := dec.Decode(&m)
if err == io.EOF {
return
} else {
if m.responseMessage != nil {
m.Response.fill(s)
if s.IsDuplicatedPage() {
return
}
r.chanResponse <- s
for _, link := range m.Response.Details.Links {
if newScan := link.toScan(s); newScan != nil && newScan.IsScanAllowed() {
r.chanLinks <- newScan
}
}
} else if m.domMessage != nil {
for _, link := range m.domMessage.Links {
if newScan := link.toScan(s); newScan != nil && newScan.IsScanAllowed() {
r.chanLinks <- newScan
}
}
}
}
}
}
func (r *PhantomJSRenderer) kill(reason string, s *gryffin.Scan) {
if err := r.process.Kill(); err == nil {
s.Logmf("PhantomjsRenderer.Do", "[%s] Terminating the crawl process.", reason)
}
}
func (r *PhantomJSRenderer) wait(s *gryffin.Scan) {
select {
case <-r.done:
r.kill("Cleanup", s)
case <-time.After(time.Duration(r.Timeout) * time.Second):
r.kill("Timeout", s)
}
close(r.chanResponse)
close(r.chanLinks)
}
func (r *PhantomJSRenderer) Do(s *gryffin.Scan) {
r.chanResponse = make(chan *gryffin.Scan, 10)
r.chanLinks = make(chan *gryffin.Scan, 10)
r.done = make(chan string)
// Construct the command.
// render.js http(s)://<host>[:port][/path] [{"method":"post", "data":"a=1&b=2"}]
url := s.Request.URL.String()
cookies := make([]string, 0)
// ua := s.Request.UserAgent()
ua := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"
for _, c := range s.Cookies {
cookies = append(cookies, c.String())
}
arg := input{
Method: s.Request.Method,
Headers: inputHeaders{
UserAgent: ua,
Cookie: strings.Join(cookies, ";"),
},
}
opt, err := json.Marshal(arg)
if err != nil {
s.Error("PhantomjsRenderer.Do", err)
return
}
// s.Logmf("PhantomjsRenderer.Do", "Running: render.js %s '%s'", url, string(opt))
s.Logmf("PhantomjsRenderer.Do", "Running: render.js")
cmd := exec.Command(
os.Getenv("GOPATH")+"/src/github.com/yahoo/gryffin/renderer/resource/render.js",
url,
string(opt))
stdout, err := cmd.StdoutPipe()
if err != nil {
s.Error("PhantomjsRenderer.Do", err)
return
}
if err := cmd.Start(); err != nil {
s.Error("PhantomjsRenderer.Do", err)
return
}
r.process = cmd.Process
// wait until done or timeout.
go r.extract(stdout, s)
go r.wait(s)
cmd.Wait()
}
|
[
"\"GOPATH\""
] |
[] |
[
"GOPATH"
] |
[]
|
["GOPATH"]
|
go
| 1 | 0 | |
internal/segments/time_test.go
|
package segments
// import (
// "os"
// . "github.com/onsi/ginkgo"
// . "github.com/onsi/gomega"
// )
// var _ = Describe("Login{}", func() {
// login := Login{}
// user := os.Getenv("USER")
// Describe("Output()", func() {
// It("is expected to be the logged in user", func() {
// Expect(login.Output()).To(Equal(user))
// })
// })
// Describe("Len()", func() {
// It("is expected to be the length of user", func() {
// Expect(login.Len()).To(Equal(len(user)))
// })
// })
// })
|
[
"\"USER\""
] |
[] |
[
"USER"
] |
[]
|
["USER"]
|
go
| 1 | 0 | |
main.go
|
/*
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.
*/
package main
import (
"flag"
"os"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
policyv1beta1 "k8s.io/kubernetes/pkg/apis/policy/v1beta1"
rbacv1 "k8s.io/kubernetes/pkg/apis/rbac/v1"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metallbv1alpha1 "github.com/metallb/metallb-operator/api/v1alpha1"
"github.com/metallb/metallb-operator/controllers"
// +kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(metallbv1alpha1.AddToScheme(scheme))
utilruntime.Must(corev1.AddToScheme(scheme))
utilruntime.Must(appsv1.AddToScheme(scheme))
utilruntime.Must(policyv1beta1.AddToScheme(scheme))
utilruntime.Must(rbacv1.AddToScheme(scheme))
// +kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var enableLeaderElection bool
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
watchNamepace := os.Getenv("WATCH_NAMESPACE")
if watchNamepace == "" {
setupLog.Error(nil, "WATCH_NAMESPACE env variable must be set")
os.Exit(1)
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
LeaderElection: enableLeaderElection,
LeaderElectionID: "metallb.io.metallboperator",
Namespace: watchNamepace,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
if err = (&controllers.MetallbReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("Metallb"),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Metallb")
os.Exit(1)
}
// +kubebuilder:scaffold:builder
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
|
[
"\"WATCH_NAMESPACE\""
] |
[] |
[
"WATCH_NAMESPACE"
] |
[]
|
["WATCH_NAMESPACE"]
|
go
| 1 | 0 | |
main.py
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import sys
import json
import sqlite3
import subprocess
# SQLite3 aggregate 类
class Concatenate():
def __init__(self):
self.itemList = []
def step(self, value):
# print 'step(%r)' % value
self.itemList.append(value)
def finalize(self):
# print("final: %r" % ",".join(self.itemList))
return "!@#$".join(self.itemList)
# SQLite3 aggregate 类
class IdentifiersConcat():
def __init__(self):
self.itemList = []
def step(self, key, val):
# print 'step(%r)' % value
# 当val中存在冒号时,id2weblink 中 idJsonStr 会出现 {"aa":"bb":"xx", ...} 的情况而出错
# 所以使用 #kvSeparator# 作为 key 与 val 的分隔符
self.itemList.append(u'%s#kvSeparator#%s' % (key, val))
def finalize(self):
# print("final: %r" % ",".join(self.itemList))
return "!@#$".join(self.itemList)
# book's website id to link
def id2weblink(idStrs):
# idStrs amazon:0596005954, douban:1850938, isbn:9780596005955
websiteLinkDict = {"douban": "https://book.douban.com/subject/{}/",
"amazon": "https://www.amazon.com/dp/{}",
"amazon_cn": "https://www.amazon.cn/dp/{}",
"google": "https://books.google.com/books?id={}",
"isbn": "https://www.worldcat.org/isbn/{}"}
websiteOrderedList = ["douban", "amazon_cn", "amazon", "google", "isbn"]
idJsonStr = '{"' + idStrs.replace('#kvSeparator#', '":"').replace(', ', '", "') + '"}'
# {"isbn":"xxxx", "amazon":"xxxxx"}
idJsonObj = json.loads(idJsonStr)
bookWebsite = os.getenv("BookWebsite")
# if the env exists and the book has the website id
if bookWebsite and bookWebsite in idJsonObj:
return websiteLinkDict[bookWebsite].format(idJsonObj[bookWebsite])
# 如果没有指定的网站 或者 这本书没有指定网站的id,则按照一定的优先级顺序处理
for website in websiteOrderedList:
if website in idJsonObj:
return websiteLinkDict[website].format(idJsonObj[website])
# 如果没有以上网站的id,则获取 idJsonObj 中的第一个
return idJsonObj[idJsonObj.keys()[0]]
def main(querySQL):
libraryPath = subprocess.check_output(
'/Applications/calibre.app/Contents/MacOS/calibre-debug -c "from calibre.utils.config import prefs; print(prefs.get(\'library_path\'),end=\'\')"', shell=True)
libraryName = libraryPath.split("/")[-1]
metaDbPath = os.path.join(libraryPath, 'metadata.db')
con = sqlite3.connect(metaDbPath)
con.create_aggregate("concat", 1, Concatenate)
con.create_aggregate("identifiers_concat", 2, IdentifiersConcat)
cur = con.cursor()
cur.execute(querySQL)
queryResult = cur.fetchall()
workflowResult = {"items": []}
for item in queryResult:
bookCalibreID = item[0]
bookTitle = item[1]
# if the book has no author, error will occur: "AttributeError: 'NoneType' object has no attribute 'replace'"
bookAuthors = item[2].replace("!@#$", ", ") if item[2] else ""
# bookSize = item[3]
bookTags = item[4].replace("!@#$", ", ") if item[4] else "No Tags"
bookFormatList = item[5].split("!@#$") if item[5] else ""
bookFilenameList = item[6].split("!@#$") if item[6] else ""
bookRating = (str(item[7]) + " ") if isinstance(item[7], int) else "N/A"
bookIdentifiers = item[8].replace("!@#$", ", ").replace("#kvSeparator#", ": ") if item[8] else "No data"
bookWeblink = id2weblink(item[8].replace("!@#$", ", ")) if item[8] else ""
bookPath = item[9]
bookFormat = bookFormatList[0] if bookFormatList else "No book file"
bookFilename = bookFilenameList[0] if bookFormatList else "No book file"
# 在没有书籍文件时,该值会成为 "/librarypath/author/booktitle/No book file.No book file"
# 不过可能由于 temp["type"] = "file" 因而 Alfred 会检查文件是否存在 因而 Alfred 不会出错
bookFullPath = os.path.join(libraryPath, bookPath, bookFilename + "." + bookFormat.lower())
temp = {}
temp["type"] = "file"
temp["title"] = bookTitle
temp["icon"] = {"path": os.path.join(libraryPath, bookPath, "cover.jpg")}
temp["subtitle"] = u"📙 {:<7} ⭐️ {:<5} ✍️ {}".format(bookFormat, bookRating, bookAuthors)
temp["arg"] = bookFullPath
temp["mods"] = {
"alt": {"valid": True, "arg": bookWeblink, "subtitle": u"🎫 " + bookIdentifiers},
"cmd": {"valid": True, "arg": bookFullPath, "subtitle": u"🏷 " + bookTags},
"shift": {"valid": True, "arg": bookFullPath, "subtitle": "Open with default app"},
"cmd+alt": {"valid": True, "arg": "calibre://show-book/" + libraryName + "/" + str(bookCalibreID), "subtitle": "Reveal in Calibre"}}
workflowResult['items'].append(temp)
# if more than one format
if len(bookFormatList) > 1:
for i in range(1, len(bookFormatList)):
bookFormat = bookFormatList[i]
bookFilename = bookFilenameList[i]
temp = {}
temp["type"] = "file"
temp["title"] = bookTitle
temp["icon"] = {"path": os.path.join(
libraryPath, bookPath, "cover.jpg")}
temp["subtitle"] = u"📙 {:<7} ⭐️ {:<5} ✍️ {}".format(
bookFormat, bookRating, bookAuthors)
temp["arg"] = os.path.join(
libraryPath, bookPath, bookFilename + "." + bookFormat.lower())
temp["mods"] = {
"alt": {"valid": True, "arg": bookWeblink, "subtitle": u"🎫 " + bookIdentifiers},
"cmd": {"valid": True, "arg": bookTags, "subtitle": u"🏷 " + bookTags},
"shift": {"valid": True, "arg": bookFullPath, "subtitle": "Open with default app"},
"cmd+alt": {"valid": True, "arg": "calibre://show-book/" + libraryName + "/" + str(bookCalibreID), "subtitle": "Reveal in Calibre"}}
workflowResult['items'].append(temp)
if workflowResult["items"]:
print(json.dumps(workflowResult, indent=4, sort_keys=True))
else:
print('{"items": [{"title": "None found","subtitle": "(*´・д・)?"}]}')
if __name__ == '__main__':
queryScope = sys.argv[1].strip()
queryStr = sys.argv[2].strip()
if not queryStr:
sys.exit()
if queryScope == "all":
querySQL = """SELECT id, title,
(SELECT concat(name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
(SELECT concat(name) FROM data WHERE data.book=books.id) filename,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
(SELECT identifiers_concat(type,val) FROM identifiers WHERE identifiers.book=books.id) ids,
path
FROM books
WHERE title like '%{qs}%' or tags like '%{qs}%' or authors like '%{qs}%' """.format(qs=queryStr)
elif queryScope == "title":
querySQL = """SELECT id, title,
(SELECT concat(name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
(SELECT concat(name) FROM data WHERE data.book=books.id) filename,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
(SELECT identifiers_concat(type,val) FROM identifiers WHERE identifiers.book=books.id) ids,
path
FROM books
WHERE title like '%{qs}%'""".format(qs=queryStr)
elif queryScope == "tags":
querySQL = """SELECT id, title,
(SELECT concat(name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
(SELECT concat(name) FROM data WHERE data.book=books.id) filename,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
(SELECT identifiers_concat(type,val) FROM identifiers WHERE identifiers.book=books.id) ids,
path
FROM books
WHERE tags like '%{qs}%'""".format(qs=queryStr)
elif queryScope == "authors":
querySQL = """SELECT id, title,
(SELECT concat(name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
(SELECT concat(name) FROM data WHERE data.book=books.id) filename,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
(SELECT identifiers_concat(type,val) FROM identifiers WHERE identifiers.book=books.id) ids,
path
FROM books
WHERE authors like '%{qs}%'""".format(qs=queryStr)
main(querySQL)
|
[] |
[] |
[
"BookWebsite"
] |
[]
|
["BookWebsite"]
|
python
| 1 | 0 | |
molecule/default/tests/test_default.py
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_kibana_running_and_enabled(host):
kibana = host.service("kibana")
assert kibana.is_running
assert kibana.is_enabled
|
[] |
[] |
[
"MOLECULE_INVENTORY_FILE"
] |
[]
|
["MOLECULE_INVENTORY_FILE"]
|
python
| 1 | 0 | |
felix/fv/fv_infra_test.go
|
// Copyright (c) 2020-2022 Tigera, 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.
//go:build fvtests
package fv_test
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/calico/libcalico-go/lib/apiconfig"
"github.com/projectcalico/calico/felix/fv/connectivity"
"github.com/projectcalico/calico/felix/fv/infrastructure"
"github.com/projectcalico/calico/felix/fv/workload"
)
// These tests verify that test-connection and test-workload work properly across all the different protocols.
var _ = describeConnCheckTests("tcp")
var _ = describeConnCheckTests("sctp")
var _ = describeConnCheckTests("udp")
var _ = describeConnCheckTests("ip4:253")
var _ = describeConnCheckTests("udp-recvmsg")
var _ = describeConnCheckTests("udp-noconn")
func describeConnCheckTests(protocol string) bool {
return infrastructure.DatastoreDescribe("Connectivity checker self tests: "+protocol,
[]apiconfig.DatastoreType{apiconfig.EtcdV3}, // Skipping k8s since these tests don't rely on the datastore.
func(getInfra infrastructure.InfraFactory) {
var (
infra infrastructure.DatastoreInfra
felixes []*infrastructure.Felix
hostW [2]*workload.Workload
cc *connectivity.Checker
)
BeforeEach(func() {
infra = getInfra()
felixes, _ = infrastructure.StartNNodeTopology(2, infrastructure.DefaultTopologyOptions(), infra)
// Create host-networked "workloads", one on each "host".
for ii := range felixes {
// Workload doesn't understand the extra connectivity types that test-connection tries.
wlProto := protocol
if strings.Contains(protocol, "-") {
wlProto = strings.Split(protocol, "-")[0]
}
hostW[ii] = workload.Run(felixes[ii], fmt.Sprintf("host%d", ii), "", felixes[ii].IP, "8055", wlProto)
}
cc = &connectivity.Checker{}
cc.Protocol = protocol
})
AfterEach(func() {
for _, wl := range hostW {
wl.Stop()
}
for _, felix := range felixes {
felix.Stop()
}
if CurrentGinkgoTestDescription().Failed {
infra.DumpErrorData()
}
infra.Stop()
})
It("should have host-to-host on right port only", func() {
cc.ExpectSome(felixes[0], hostW[1])
if !strings.HasPrefix(protocol, "ip") {
cc.ExpectNone(felixes[0], hostW[1], 8066)
}
cc.CheckConnectivity()
})
if protocol == "udp" {
Describe("with tc configured to drop 5% of packets", func() {
BeforeEach(func() {
// Make sure we have connectivity before we start packet loss measurements.
cc.ExpectSome(felixes[0], hostW[1])
cc.CheckConnectivity()
cc.ResetExpectations()
felixes[0].Exec("tc", "qdisc", "add", "dev", "eth0", "root", "netem", "loss", "5%")
})
It("and a 1% threshold, should see packet loss", func() {
failed := false
cc.OnFail = func(msg string) {
log.WithField("msg", msg).Info("Connectivity checker failed (as expected)")
failed = true
}
cc.ExpectLoss(felixes[0], hostW[1], 2*time.Second, 1, -1)
cc.CheckConnectivityPacketLoss()
Expect(failed).To(BeTrue(), "Expected the connection checker to detect packet loss")
})
It("and a 20% threshold, should tolerate packet loss", func() {
cc.ExpectLoss(felixes[0], hostW[1], 2*time.Second, 20, -1)
cc.CheckConnectivityPacketLoss()
})
It("with tcpdump", func() {
tcpdF := felixes[0].AttachTCPDump("eth0")
tcpdF.SetLogEnabled(true)
tcpdF.AddMatcher("UDP", regexp.MustCompile(`.*UDP.*`))
tcpdF.Start()
tcpdW := hostW[1].AttachTCPDump()
tcpdW.SetLogEnabled(true)
tcpdW.AddMatcher("UDP", regexp.MustCompile(`.*UDP.*`))
tcpdW.Start()
cc.ExpectLoss(felixes[0], hostW[1], 2*time.Second, 20, -1)
cc.CheckConnectivityPacketLoss()
Eventually(func() int { return tcpdF.MatchCount("UDP") }).Should(BeNumerically(">", 0))
Eventually(func() int { return tcpdW.MatchCount("UDP") }).Should(BeNumerically(">", 0))
})
})
}
},
)
}
var _ = infrastructure.DatastoreDescribe("Container self tests",
[]apiconfig.DatastoreType{apiconfig.EtcdV3}, // Skipping k8s since these tests don't rely on the datastore.
func(getInfra infrastructure.InfraFactory) {
var (
infra infrastructure.DatastoreInfra
felixes []*infrastructure.Felix
options infrastructure.TopologyOptions
)
BeforeEach(func() {
options = infrastructure.DefaultTopologyOptions()
})
JustBeforeEach(func() {
infra = getInfra()
felixes, _ = infrastructure.StartNNodeTopology(1, options, infra)
})
AfterEach(func() {
for _, felix := range felixes {
felix.Stop()
}
if CurrentGinkgoTestDescription().Failed {
infra.DumpErrorData()
}
infra.Stop()
})
It("should only report that existing files actually exist", func() {
Expect(felixes[0].FileExists("/usr/local/bin/calico-felix")).To(BeTrue())
Expect(felixes[0].FileExists("/garbage")).To(BeFalse())
})
Describe("with DebugPanicAfter set to 2s", func() {
BeforeEach(func() {
options.ExtraEnvVars["FELIX_DebugPanicAfter"] = "2"
})
It("should panic and drop a core file", func() {
felixes[0].WaitNotRunning(5 * time.Second)
dir, err := ioutil.ReadDir("/tmp")
Expect(err).NotTo(HaveOccurred())
name := ""
for _, f := range dir {
if strings.Contains(f.Name(), "core_"+felixes[0].Hostname) {
name = f.Name()
}
}
Expect(name).NotTo(Equal(""), "Couldn't find core file")
s, err := os.Stat("/tmp/" + name)
Expect(err).NotTo(HaveOccurred())
Expect(s.Size()).To(BeNumerically(">", 4096))
})
})
Describe("with DebugSimulateDataRace set", func() {
BeforeEach(func() {
options.ExtraEnvVars["FELIX_DebugSimulateDataRace"] = "true"
})
if os.Getenv("FV_RACE_DETECTOR_ENABLED") == "true" {
It("should detect a race", func() {
Eventually(felixes[0].DataRaces).ShouldNot(BeEmpty())
})
} else {
It("should not detect a race because race detector is disabled", func() {
Consistently(felixes[0].DataRaces).Should(BeEmpty())
})
}
})
},
)
|
[
"\"FV_RACE_DETECTOR_ENABLED\""
] |
[] |
[
"FV_RACE_DETECTOR_ENABLED"
] |
[]
|
["FV_RACE_DETECTOR_ENABLED"]
|
go
| 1 | 0 | |
savu/plugins/utils.py
|
# Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. module:: utils
:platform: Unix
:synopsis: Utilities for plugin management
.. moduleauthor:: Mark Basham <[email protected]>
"""
import os
import re
import sys
import ast
import logging
import savu
import importlib
import inspect
import itertools
from collections import OrderedDict
import numpy as np
from savu.plugins.loaders.utils.my_safe_constructor import MySafeConstructor
# can I remove these from here?
load_tools = {}
plugins = {}
plugins_path = {}
dawn_plugins = {}
count = 0
OUTPUT_TYPE_DATA_ONLY = 0
OUTPUT_TYPE_METADATA_ONLY = 1
OUTPUT_TYPE_METADATA_AND_DATA = 2
def register_plugin(clazz):
"""decorator to add plugins to a central register"""
plugins[clazz.__name__] = clazz
if clazz.__module__.split(".")[0] != "savu":
plugins_path[clazz.__name__] = clazz.__module__
return clazz
def dawn_compatible(plugin_output_type=OUTPUT_TYPE_METADATA_AND_DATA):
def _dawn_compatible(clazz):
"""
decorator to add dawn compatible plugins and details to a central
register
"""
dawn_plugins[clazz.__name__] = {}
try:
plugin_path = sys.modules[clazz.__module__].__file__
# looks out for .pyc files
dawn_plugins[clazz.__name__]['path2plugin'] = plugin_path.split('.py')[0] + '.py'
dawn_plugins[clazz.__name__]['plugin_output_type'] = _plugin_output_type
except Exception as e:
print(e)
return clazz
# for backwards compatibility, if decorator is invoked without brackets...
if inspect.isclass(plugin_output_type):
_plugin_output_type = OUTPUT_TYPE_METADATA_AND_DATA
return _dawn_compatible(plugin_output_type)
else:
_plugin_output_type = plugin_output_type
return _dawn_compatible
def get_plugin(plugin_name, params, exp, check=False):
"""Get an instance of the plugin class and populate default parameters.
:param plugin_name: Name of the plugin to import
:type plugin_name: str.
:returns: An instance of the class described by the named plugin.
"""
logging.debug("Importing the module %s", plugin_name)
instance = load_class(plugin_name)()
instance.initialise(params, exp, check=check)
return instance
def _get_cls_name(name):
return "".join(x.capitalize() for x in name.split(".")[-1].split("_"))
def load_class(name, cls_name=None):
"""Returns an instance of the class associated with the module name.
:param name: Module name or path to a module file
:returns: An instance of the class associated with module.
"""
path = name if os.path.dirname(name) else None
name = os.path.basename(os.path.splitext(name)[0]) if path else name
cls_name = _get_cls_name(name) if not cls_name else cls_name
if cls_name in plugins.keys():
return plugins[cls_name]
if path:
mod = importlib.machinery.SourceFileLoader(name, path).load_module()
else:
mod = importlib.import_module(name)
return getattr(mod, cls_name)
def plugin_loader(exp, plugin_dict, check=False):
logging.debug("Running plugin loader")
try:
plugin = get_plugin(plugin_dict['id'],
plugin_dict['data'],
exp,
check=check)
except Exception as e:
logging.error("failed to load the plugin")
logging.error(e)
# re-raise the original error
raise
if check:
exp.meta_data.plugin_list._set_datasets_list(plugin)
logging.debug("finished plugin loader")
return plugin
def get_tools_class(plugin_tools_id, cls=None):
"""Load the plugin tools class
:param plugin_tools_id: plugin tools module name
:param cls: Class to initialise
:return:
"""
if plugin_tools_id == "savu.plugins.plugin_tools":
plugin_tools_id = "savu.plugins.base_tools"
if cls:
return load_class(plugin_tools_id)(cls)
else:
return load_class(plugin_tools_id)
def get_plugins_paths(examples=True):
"""
This gets the plugin paths, but also adds any that are not on the
pythonpath to it.
"""
plugins_paths = OrderedDict()
# Add the savu plugins paths first so it is overridden by user folders
savu_plugins_path = os.path.join(savu.__path__[0], 'plugins')
savu_plugins_subpaths = [d for d in next(os.walk(savu_plugins_path))[1] \
if d != "__pycache__"]
for path in savu_plugins_subpaths:
plugins_paths[os.path.join(savu_plugins_path, path)] = \
''.join(['savu.plugins.', path, '.'])
# get user, environment and example plugin paths
user_path = [os.path.join(os.path.expanduser("~"), "savu_plugins")]
env_paths = os.getenv("SAVU_PLUGINS_PATH", "").replace(" ", "").split(":")
templates = "../plugin_examples/plugin_templates"
eg_path = [os.path.join(savu.__path__[0], templates)] if examples else []
for ppath in env_paths + user_path + eg_path:
if os.path.exists(ppath):
plugins_paths[ppath] = os.path.basename(ppath) + "."
if ppath not in sys.path:
sys.path.append(os.path.dirname(ppath))
return plugins_paths
def is_template_param(param):
"""Identifies if the parameter should be included in an input template
and returns the default value of the parameter if it exists.
"""
start = 0
ptype = "local"
if isinstance(param, str):
param = param.strip()
if not param.split("global")[0]:
ptype = "global"
start = 6
first, last = param[start], param[-1]
if first == "<" and last == ">":
param = param[start + 1 : -1]
param = None if not param else param
try:
param = eval(param)
except:
pass
return [ptype, param]
return False
def blockPrint():
""" Disable printing to stdout """
import tempfile
fname = tempfile.mkdtemp() + "/unwanted_prints.txt"
sys.stdout = open(fname, "w")
def enablePrint():
""" Enable printing to stdout """
sys.stdout = sys.__stdout__
def parse_config_string(string):
regex = r"[\[\]\, ]+"
split_vals = [_f for _f in re.split(regex, string) if _f]
delimitors = re.findall(regex, string)
split_vals = [repr(a.strip()) for a in split_vals]
zipped = itertools.zip_longest(delimitors, split_vals)
string = "".join([i for l in zipped for i in l if i is not None])
try:
return ast.literal_eval(string)
except ValueError:
return ast.literal_eval(parse_array_index_as_string(string))
def parse_array_index_as_string(string):
p = re.compile(r"'\['")
for m in p.finditer(string):
offset = m.start() - count + 3
end = string[offset:].index("']") + offset
string = string[:end] + "]'" + string[end + 2 :]
string = string.replace("'['", "[")
return string
def param_to_str(param_name, keys):
"""Check the parameter is within the provided list and
return the string name.
"""
if param_name.isdigit():
param_name = int(param_name)
if param_name <= len(keys):
param_name = keys[param_name - 1]
else:
raise ValueError(
"This parameter number is not valid for this plugin"
)
elif param_name not in keys:
raise Exception("This parameter is not present in this plug in.")
return param_name
def set_order_by_visibility(parameters, level=False):
"""Return an ordered list of parameters depending on the
visibility level
:param parameters: The dictionary of parameters
:param level: The visibility level
:return: An ordered list of parameters
"""
data_keys = []
basic_keys = []
interm_keys = []
adv_keys = []
for k, v in parameters.items():
if v["display"] == "on":
if v["visibility"] == "datasets":
data_keys.append(k)
if v["visibility"] == "basic":
basic_keys.append(k)
if v["visibility"] == "intermediate":
interm_keys.append(k)
if v["visibility"] == "advanced":
adv_keys.append(k)
if level:
if level == "datasets":
keys = data_keys
elif level == "basic":
keys = basic_keys
elif level == "intermediate":
keys = basic_keys + interm_keys + data_keys
elif level == "advanced":
keys = basic_keys + interm_keys + adv_keys + data_keys
else:
keys = basic_keys + interm_keys + adv_keys + data_keys
else:
keys = basic_keys + interm_keys + adv_keys + data_keys
return keys
def convert_multi_params(param_name, value):
"""Check if value is a multi parameter and check if each item is valid.
Change from the input multi parameter string to a list
:param param_name: Name of the parameter
:param value: Parameter value
:return: List or unchanged value
"""
error_str = ""
multi_parameters = (
isinstance(value, str) and (";" in value) and param_name != "preview"
)
if multi_parameters:
value = value.split(";")
isdict = re.findall(r"[\{\}]+", value[0])
if ":" in value[0] and not isdict:
seq = value[0].split(":")
try:
seq = [ast.literal_eval(s) for s in seq]
if len(value) == 0:
error_str = (
f"No values for tuned parameter "
f"'{param_name}' ensure start:stop:step; values "
f"are valid"
)
elif len(seq) == 2:
value = list(np.arange(seq[0], seq[1]))
elif len(seq) > 2:
value = list(np.arange(seq[0], seq[1], seq[2]))
else:
error_str = "Ensure start:stop:step; values are valid."
if not value:
# Don't allow an empty list
raise ValueError
except:
error_str = "Ensure start:stop:step; values are valid."
val_list = (
parse_config_string(value) if isinstance(value, str) else value
)
# Remove blank list entries
# Change type to int, float or str
val_list = [_dumps(val) for val in value if val]
value = val_list
return value, error_str
def _dumps(val):
"""Replace any missing quotes around variables
Change the string to an integer, float, tuple, list, str, dict
"""
import yaml
# Prevent conversion from on/off to boolean
yaml.SafeLoader.add_constructor(
"tag:yaml.org,2002:bool", MySafeConstructor.add_bool
)
if isinstance(val, str):
try:
# Safely evaluate an expression node or a string containing
# a Python literal or container display
value = ast.literal_eval(val)
return value
except Exception:
pass
try:
isdict = re.findall(r"[\{\}]+", val)
val = _sexagesimal_check(val, isdict, remove=False)
value = yaml.safe_load(val)
return _sexagesimal_check(value, isdict)
except Exception:
val = _sexagesimal_check(val, isdict)
pass
try:
isdict = re.findall(r"[\{\}]+", val)
# Matches { } between one and unlimited number of times
if isdict:
if isinstance(val, dict):
value_dict = {}
for k, v in val.items():
v = v.replace("[", "'[").replace("]", "]'")
value_dict[k] = _dumps(
yaml.safe_load(v)
)
return value_dict
else:
value = val.replace("[", "'[").replace("]", "]'")
return _dumps(yaml.safe_load(value))
else:
value = parse_config_string(val)
return value
except Exception:
if len(val.split(";")) > 1:
value = val
return value
else:
raise Exception("Invalid string %s" % val)
else:
value = val
return value
def _sexagesimal_check(val, isdict, remove=True):
"""To avoid sexagesimal values being evaluated, replace colon
values temporarily
:param val:
:param isdict: True if braces {} found
:return: value
"""
if isinstance(val, str) and not isdict:
if remove:
val = val.replace(":?", ":")
else:
val = val.replace(":", ":?")
return val
def check_valid_dimension(dim, prev_list):
"""Check the dimension is within the correct range"""
if not 0 < dim < 21:
raise Exception("Please use a dimension between 1 and 20.")
if prev_list and (dim > len(prev_list)):
raise Exception(
"You have not specified enough dimensions "
"inside the preview parameter."
)
return True
def is_slice_notation(value):
"""Return True if the value is made up of multiple"""
return isinstance(value, str) and (":" in value)
def create_dir(file_path):
"""Check if directories provided exist at this file path. If they don't
create the directories.
"""
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
def indent_multi_line_str(text, indent_level=1, justify=False):
text = text.split("\n")
# Remove additional spacing on the left side so that text aligns
if justify is False:
text = [(" " * 4 * indent_level) + line for line in text]
else:
text = [(" " * 4 * indent_level) + line.lstrip() for line in text]
text = "\n".join(text)
return text
def indent(text, indent_level=1):
text = (" " * 4 * indent_level) + text
return text
def sort_alphanum(_list):
"""Sort list numerically and alphabetically
*While maintaining original list value types*
:param _list: Input list to be sorted
:return: List sorted by number and letter alphabetically
"""
return sorted(_list, key=_alphanum)
def _str_to_int(_str):
"""Convert the input str to an int if possible
:param _str: input string
:return: integer if text is a digit, else string
"""
return int(_str) if _str.isdigit() else _str
def _alphanum(_str):
"""Split string into numbers and letters
:param _str:
:return: list of numbers and letters
"""
char_list = re.split("([0-9]+)", _str)
return [_str_to_int(c) for c in char_list]
|
[] |
[] |
[
"SAVU_PLUGINS_PATH"
] |
[]
|
["SAVU_PLUGINS_PATH"]
|
python
| 1 | 0 | |
cmd/mavenBuild_generated.go
|
// Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/spf13/cobra"
)
type mavenBuildOptions struct {
PomPath string `json:"pomPath,omitempty"`
Profiles []string `json:"profiles,omitempty"`
Flatten bool `json:"flatten,omitempty"`
Verify bool `json:"verify,omitempty"`
ProjectSettingsFile string `json:"projectSettingsFile,omitempty"`
GlobalSettingsFile string `json:"globalSettingsFile,omitempty"`
M2Path string `json:"m2Path,omitempty"`
LogSuccessfulMavenTransfers bool `json:"logSuccessfulMavenTransfers,omitempty"`
CreateBOM bool `json:"createBOM,omitempty"`
AltDeploymentRepositoryPassword string `json:"altDeploymentRepositoryPassword,omitempty"`
AltDeploymentRepositoryUser string `json:"altDeploymentRepositoryUser,omitempty"`
AltDeploymentRepositoryURL string `json:"altDeploymentRepositoryUrl,omitempty"`
AltDeploymentRepositoryID string `json:"altDeploymentRepositoryID,omitempty"`
CustomTLSCertificateLinks []string `json:"customTlsCertificateLinks,omitempty"`
Publish bool `json:"publish,omitempty"`
}
// MavenBuildCommand This step will install the maven project into the local maven repository.
func MavenBuildCommand() *cobra.Command {
const STEP_NAME = "mavenBuild"
metadata := mavenBuildMetadata()
var stepConfig mavenBuildOptions
var startTime time.Time
var logCollector *log.CollectorHook
var createMavenBuildCmd = &cobra.Command{
Use: STEP_NAME,
Short: "This step will install the maven project into the local maven repository.",
Long: `This step will install the maven project into the local maven repository.
It will also prepare jacoco to record the code coverage and
supports ci friendly versioning by flattening the pom before installing.`,
PreRunE: func(cmd *cobra.Command, _ []string) error {
startTime = time.Now()
log.SetStepName(STEP_NAME)
log.SetVerbose(GeneralConfig.Verbose)
GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
path, _ := os.Getwd()
fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
log.RegisterHook(fatalHook)
err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
if err != nil {
log.SetErrorCategory(log.ErrorConfiguration)
return err
}
log.RegisterSecret(stepConfig.AltDeploymentRepositoryPassword)
if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
log.RegisterHook(&sentryHook)
}
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
log.RegisterHook(logCollector)
}
return nil
},
Run: func(_ *cobra.Command, _ []string) {
telemetryData := telemetry.CustomData{}
telemetryData.ErrorCode = "1"
handler := func() {
config.RemoveVaultSecretFiles()
telemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
telemetryData.ErrorCategory = log.GetErrorCategory().String()
telemetry.Send(&telemetryData)
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
splunk.Send(&telemetryData, logCollector)
}
}
log.DeferExitHandler(handler)
defer handler()
telemetry.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
splunk.Initialize(GeneralConfig.CorrelationID,
GeneralConfig.HookConfig.SplunkConfig.Dsn,
GeneralConfig.HookConfig.SplunkConfig.Token,
GeneralConfig.HookConfig.SplunkConfig.Index,
GeneralConfig.HookConfig.SplunkConfig.SendLogs)
}
mavenBuild(stepConfig, &telemetryData)
telemetryData.ErrorCode = "0"
log.Entry().Info("SUCCESS")
},
}
addMavenBuildFlags(createMavenBuildCmd, &stepConfig)
return createMavenBuildCmd
}
func addMavenBuildFlags(cmd *cobra.Command, stepConfig *mavenBuildOptions) {
cmd.Flags().StringVar(&stepConfig.PomPath, "pomPath", `pom.xml`, "Path to the pom file which should be installed including all children.")
cmd.Flags().StringSliceVar(&stepConfig.Profiles, "profiles", []string{}, "Defines list of maven build profiles to be used.")
cmd.Flags().BoolVar(&stepConfig.Flatten, "flatten", true, "Defines if the pom files should be flattened to support ci friendly maven versioning.")
cmd.Flags().BoolVar(&stepConfig.Verify, "verify", false, "Instead of installing the artifact only the verify lifecycle phase is executed.")
cmd.Flags().StringVar(&stepConfig.ProjectSettingsFile, "projectSettingsFile", os.Getenv("PIPER_projectSettingsFile"), "Path to the mvn settings file that should be used as project settings file.")
cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "Path to the location of the local repository that should be used.")
cmd.Flags().BoolVar(&stepConfig.LogSuccessfulMavenTransfers, "logSuccessfulMavenTransfers", false, "Configures maven to log successful downloads. This is set to `false` by default to reduce the noise in build logs.")
cmd.Flags().BoolVar(&stepConfig.CreateBOM, "createBOM", false, "Creates the bill of materials (BOM) using CycloneDX Maven plugin.")
cmd.Flags().StringVar(&stepConfig.AltDeploymentRepositoryPassword, "altDeploymentRepositoryPassword", os.Getenv("PIPER_altDeploymentRepositoryPassword"), "Password for the alternative deployment repository to which the project artifacts should be deployed ( other than those specified in <distributionManagement> ). This password will be updated in settings.xml . When no settings.xml is provided a new one is created corresponding with <servers> tag")
cmd.Flags().StringVar(&stepConfig.AltDeploymentRepositoryUser, "altDeploymentRepositoryUser", os.Getenv("PIPER_altDeploymentRepositoryUser"), "User for the alternative deployment repository to which the project artifacts should be deployed ( other than those specified in <distributionManagement> ). This user will be updated in settings.xml . When no settings.xml is provided a new one is created corresponding with <servers> tag")
cmd.Flags().StringVar(&stepConfig.AltDeploymentRepositoryURL, "altDeploymentRepositoryUrl", os.Getenv("PIPER_altDeploymentRepositoryUrl"), "Url for the alternative deployment repository to which the project artifacts should be deployed ( other than those specified in <distributionManagement> ). This Url will be updated in settings.xml . When no settings.xml is provided a new one is created corresponding with <servers> tag")
cmd.Flags().StringVar(&stepConfig.AltDeploymentRepositoryID, "altDeploymentRepositoryID", os.Getenv("PIPER_altDeploymentRepositoryID"), "Id for the alternative deployment repository to which the project artifacts should be deployed ( other than those specified in <distributionManagement> ). This id will be updated in settings.xml and will be used as a flag with DaltDeploymentRepository along with mavenAltDeploymentRepositoryUrl during maven deploy . When no settings.xml is provided a new one is created corresponding with <servers> tag")
cmd.Flags().StringSliceVar(&stepConfig.CustomTLSCertificateLinks, "customTlsCertificateLinks", []string{}, "List of download links to custom TLS certificates. This is required to ensure trusted connections to instances with repositories (like nexus) when publish flag is set to true.")
cmd.Flags().BoolVar(&stepConfig.Publish, "publish", false, "Configures maven to run the deploy plugin to publish artifacts to a repository.")
}
// retrieve step metadata
func mavenBuildMetadata() config.StepData {
var theMetaData = config.StepData{
Metadata: config.StepMetadata{
Name: "mavenBuild",
Aliases: []config.Alias{{Name: "mavenExecute", Deprecated: false}},
Description: "This step will install the maven project into the local maven repository.",
},
Spec: config.StepSpec{
Inputs: config.StepInputs{
Secrets: []config.StepSecrets{
{Name: "altDeploymentRepositoryPasswordId", Description: "Jenkins credentials ID containing the artifact deployment repository password.", Type: "jenkins"},
},
Parameters: []config.StepParameters{
{
Name: "pomPath",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: `pom.xml`,
},
{
Name: "profiles",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "GENERAL", "STAGES", "STEPS"},
Type: "[]string",
Mandatory: false,
Aliases: []config.Alias{},
Default: []string{},
},
{
Name: "flatten",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{},
Default: true,
},
{
Name: "verify",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{},
Default: false,
},
{
Name: "projectSettingsFile",
ResourceRef: []config.ResourceReference{},
Scope: []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/projectSettingsFile"}},
Default: os.Getenv("PIPER_projectSettingsFile"),
},
{
Name: "globalSettingsFile",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "custom/mavenGlobalSettingsFile",
},
},
Scope: []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/globalSettingsFile"}},
Default: os.Getenv("PIPER_globalSettingsFile"),
},
{
Name: "m2Path",
ResourceRef: []config.ResourceReference{},
Scope: []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/m2Path"}},
Default: os.Getenv("PIPER_m2Path"),
},
{
Name: "logSuccessfulMavenTransfers",
ResourceRef: []config.ResourceReference{},
Scope: []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/logSuccessfulMavenTransfers"}},
Default: false,
},
{
Name: "createBOM",
ResourceRef: []config.ResourceReference{},
Scope: []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/createBOM"}},
Default: false,
},
{
Name: "altDeploymentRepositoryPassword",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "custom/repositoryPassword",
},
{
Name: "altDeploymentRepositoryPasswordId",
Type: "secret",
},
{
Name: "",
Paths: []string{"$(vaultPath)/alt-deployment-repository-passowrd", "$(vaultBasePath)/$(vaultPipelineName)/alt-deployment-repository-passowrd", "$(vaultBasePath)/GROUP-SECRETS/alt-deployment-repository-passowrd"},
Type: "vaultSecretFile",
},
},
Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_altDeploymentRepositoryPassword"),
},
{
Name: "altDeploymentRepositoryUser",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "custom/repositoryUsername",
},
},
Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_altDeploymentRepositoryUser"),
},
{
Name: "altDeploymentRepositoryUrl",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "custom/repositoryUrl",
},
},
Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_altDeploymentRepositoryUrl"),
},
{
Name: "altDeploymentRepositoryID",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "custom/repositoryId",
},
},
Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_altDeploymentRepositoryID"),
},
{
Name: "customTlsCertificateLinks",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "[]string",
Mandatory: false,
Aliases: []config.Alias{},
Default: []string{},
},
{
Name: "publish",
ResourceRef: []config.ResourceReference{},
Scope: []string{"STEPS", "STAGES", "PARAMETERS"},
Type: "bool",
Mandatory: false,
Aliases: []config.Alias{{Name: "maven/publish"}},
Default: false,
},
},
},
Containers: []config.Container{
{Name: "mvn", Image: "maven:3.6-jdk-8"},
},
},
}
return theMetaData
}
|
[
"\"PIPER_projectSettingsFile\"",
"\"PIPER_globalSettingsFile\"",
"\"PIPER_m2Path\"",
"\"PIPER_altDeploymentRepositoryPassword\"",
"\"PIPER_altDeploymentRepositoryUser\"",
"\"PIPER_altDeploymentRepositoryUrl\"",
"\"PIPER_altDeploymentRepositoryID\"",
"\"PIPER_projectSettingsFile\"",
"\"PIPER_globalSettingsFile\"",
"\"PIPER_m2Path\"",
"\"PIPER_altDeploymentRepositoryPassword\"",
"\"PIPER_altDeploymentRepositoryUser\"",
"\"PIPER_altDeploymentRepositoryUrl\"",
"\"PIPER_altDeploymentRepositoryID\""
] |
[] |
[
"PIPER_altDeploymentRepositoryID",
"PIPER_globalSettingsFile",
"PIPER_altDeploymentRepositoryUser",
"PIPER_altDeploymentRepositoryPassword",
"PIPER_m2Path",
"PIPER_altDeploymentRepositoryUrl",
"PIPER_projectSettingsFile"
] |
[]
|
["PIPER_altDeploymentRepositoryID", "PIPER_globalSettingsFile", "PIPER_altDeploymentRepositoryUser", "PIPER_altDeploymentRepositoryPassword", "PIPER_m2Path", "PIPER_altDeploymentRepositoryUrl", "PIPER_projectSettingsFile"]
|
go
| 7 | 0 | |
cmd/run_test.go
|
package cmd
import (
"io/ioutil"
"os"
"testing"
"github.com/jarcoal/httpmock"
"github.com/urfave/cli"
)
func TestCheckEnvVars(t *testing.T) {
result, err := checkEnvVars([]string{"ABC=def", "GHI=jkl"})
if err != nil {
t.Errorf("Expected there to be no error but got: %s", err)
}
if result["ABC"] != "def" {
t.Errorf("Expected ABC to be set to def but got: %s", result)
}
if result["GHI"] != "jkl" {
t.Errorf("Expected ABC to be set to def but got: %s", result)
}
}
func TestCheckEnvVarsError(t *testing.T) {
result, err := checkEnvVars([]string{"ABCd=def", "GHI=jkl"})
if err == nil {
t.Errorf("Expected to be an error but was nil")
}
if result != nil {
t.Errorf("Expected result to be nil, but was %s", result)
}
}
func TestRunByBranchName(t *testing.T) {
pwd, _ := os.Getwd()
app := newTestApp(RunCommand)
endpoint := os.Getenv("BARCELONA_ENDPOINT")
testArgs := []string{"bcn", "run", "-b", "test-branch", "--D", "bash"}
httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("POST", endpoint+"/v1/auth/github/login",
httpmock.NewStringResponder(200, "{}"))
resJson, err := readJsonResponse(pwd + "/test/review_group.json")
if err != nil {
t.Fatalf("error running command `loading json %v", err)
}
httpmock.RegisterResponder("GET", endpoint+"/v1/review_groups/test1/apps",
httpmock.NewStringResponder(200, resJson))
resJson, err = readJsonResponse(pwd + "/test/oneoffs.json")
if err != nil {
t.Fatalf("error running command `loading json %v", err)
}
httpmock.RegisterResponder("POST", endpoint+"/v1/heritages/review-heritage/oneoffs",
httpmock.NewStringResponder(200, resJson))
app.Run(testArgs)
}
func TestWrongFlag(t *testing.T) {
app := newTestApp(RunCommand)
testArgs := []string{"bcn", "run", "-B", "not-found", "--D", "bash"}
err := app.Run(testArgs)
if err.Error() != "flag provided but not defined: -B" {
t.Fatalf("error running command `bcn run %v", err)
}
}
func newTestApp(command cli.Command) *cli.App {
a := cli.NewApp()
a.Name = "bcn"
a.Writer = ioutil.Discard
a.Commands = []cli.Command{command}
pwd, _ := os.Getwd()
HeritageConfigFilePath = pwd + "/test/test-barcelona.yml"
return a
}
func readJsonResponse(path string) (string, error) {
jsonFile, err := os.Open(path)
if err != nil {
return "", err
}
byteValue, _ := ioutil.ReadAll(jsonFile)
defer jsonFile.Close()
return string(byteValue), err
}
|
[
"\"BARCELONA_ENDPOINT\""
] |
[] |
[
"BARCELONA_ENDPOINT"
] |
[]
|
["BARCELONA_ENDPOINT"]
|
go
| 1 | 0 | |
league_advisor/match_data_scraper.py
|
# """ This module will scrape match data from RIOT API then format and filter it for data analysis
# #NOTE: USE THIS MODULE ONLY FOR THE FIRST TIME YOU HAVE INSTALL THE PROGRAM OR IF YOU HAVE DELETED THE LOCAL DATA FILES
# #NOTE: DON'T FORGET TO ADD YOUR RIOT API KEY IN .env FILE
# #NOTE: PLEASE BE CAREFUL NOT TO OVERWRITE ALREADY EXISTING DATA FILES WHEN TESTING THIS MODULE
# #NOTE: TO USE THIS MODULE JUST UNCOMMENT THIS MODULE
# """
# import requests
# import json
# from dotenv import load_dotenv
# import os
# import time
# load_dotenv()
# api_key = os.environ.get("api_key")
# class MatchDataScraper:
# """
# This class scrapes match data, stores it locally in a JSON file as a list of dictionaries.
# Methods:
# match_scraper :
# This methods sends a request for RIOT API server and stores the response in a json file locally.
# Please add your RIOT API key to .env file as shown in .env.sample format.
# Arguments: string, match_id
# Return: None
# -------------------------------------------------------------------------------------
# get_match_data_by_id :
# This method feeds match_scraper method with match IDs in an acceptable pace that is within the limits of API hit limits from Match IDs json file.
# Arguments: None
# Return: None
# -------------------------------------------------------------------------------------
# filter_match_data :
# This method filters fetched data into a new lcoal JSON file.
# Arguments: None
# Return: None
# """
# def __init__(self):
# self.flag = True
# self.array = []
# self.teams = {}
# #NOTE: RUN THIS METHOD ONLY FOR THE FIRST TIME YOU HAVE INSTALL THE PROGRAM OR IF YOU HAVE DELETED THE LOCAL DATA FILES
# def match_scraper(self, match_id):
# request = requests.get(f"https://europe.api.riotgames.com/lol/match/v5/matches/{match_id}?api_key={api_key}")
# if not request.status_code == 200:
# request = requests.get(f"https://americas.api.riotgames.com/lol/match/v5/matches/{match_id}?api_key={api_key}")
# if not request.status_code == 200:
# request = requests.get(f"https://asia.api.riotgames.com/lol/match/v5/matches/{match_id}?api_key={api_key}")
# print(request.status_code, match_id)
# response = request.text
# res = json.loads(response)
# if self.flag == True:
# self.array.append(res)
# self.flag = False
# with open("league_advisor/string_assets/match.json", "w") as file:
# json.dump(self.array, file)
# else:
# if self.flag == False:
# with open("league_advisor/string_assets/match.json", mode='w') as f:
# self.array.append(res)
# json.dump(self.array, f)
# return
# #NOTE: RUN THIS METHOD ONLY FOR THE FIRST TIME YOU HAVE INSTALL THE PROGRAM OR IF YOU HAVE DELETED THE LOCAL DATA FILES
# def get_match_data_by_id(self):
# with open("league_advisor/string_assets/games.json", "r") as file:
# data = json.load(file)
# for _ in range(1):
# for _ in range(1):
# for id in data:
# self.match_scraper(id["match_id"])
# time.sleep(1)
# return
# #NOTE: RUN THIS METHOD ONLY FOR THE FIRST TIME YOU HAVE INSTALL THE PROGRAM OR IF YOU HAVE DELETED THE LOCAL DATA FILES
# def filter_match_data(self):
# with open("league_advisor/string_assets/match.json", "r") as file:
# data = json.load(file)
# with open("league_advisor/string_assets/filtered_data.json", "w") as file:
# json.dump(self.array, file)
# with open("league_advisor/string_assets/filtered_data.json", "w") as file:
# for match in data:
# try:
# champion_list = []
# team_items = []
# self.teams = {}
# for participant in match["info"]["participants"]:
# item_list = []
# for i in range(7):
# item_list += [participant[f"item{i}"]]
# champion_list.insert(0, participant["championName"])
# team_items.insert(0, item_list)
# self.teams["team1"] = {
# "win" : match["info"]["teams"][0]["win"],
# "composition" : {
# "champion1": champion_list[0],
# "champion1_items" :team_items[0],
# "champion2": champion_list[1],
# "champion2_items" :team_items[1],
# "champion3": champion_list[2],
# "champion3_items" :team_items[2],
# "champion4": champion_list[3],
# "champion4_items" :team_items[3],
# "champion5": champion_list[4],
# "champion5_items" :team_items[4],
# }
# }
# self.teams["team2"] = {
# "win" : match["info"]["teams"][1]["win"],
# "composition" : {
# "champion6": champion_list[5],
# "champion6_items" :team_items[5],
# "champion7": champion_list[6],
# "champion7_items" :team_items[6],
# "champion8": champion_list[7],
# "champion8_items" :team_items[7],
# "champion9": champion_list[8],
# "champion9_items" :team_items[8],
# "champion10": champion_list[9],
# "champion10_items" :team_items[9],
# }
# }
# self.array.append(self.teams)
# except:
# print("An error occured, please clean your data and try again.")
# continue
# json.dump(self.array, file)
|
[] |
[] |
[
"api_key"
] |
[]
|
["api_key"]
|
python
| 1 | 0 | |
cmd/admission-webhook/main.go
|
// Copyright 2019 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/openshift/generic-admission-server/pkg/cmd"
"github.com/pingcap/tidb-operator/pkg/features"
"github.com/pingcap/tidb-operator/pkg/version"
"github.com/pingcap/tidb-operator/pkg/webhook/pod"
"github.com/pingcap/tidb-operator/pkg/webhook/statefulset"
"github.com/pingcap/tidb-operator/pkg/webhook/strategy"
"k8s.io/component-base/logs"
"k8s.io/klog"
)
var (
printVersion bool
extraServiceAccounts string
minResyncDuration time.Duration
)
func init() {
flag.CommandLine.Init(os.Args[0], flag.ContinueOnError)
flag.BoolVar(&printVersion, "V", false, "Show version and quit")
flag.BoolVar(&printVersion, "version", false, "Show version and quit")
flag.StringVar(&extraServiceAccounts, "extraServiceAccounts", "", "comma-separated, extra Service Accounts the Webhook should control. The full pattern for each common service account is system:serviceaccount:<namespace>:<serviceaccount-name>")
flag.DurationVar(&minResyncDuration, "min-resync-duration", 12*time.Hour, "The resync period in reflectors will be random between MinResyncPeriod and 2*MinResyncPeriod.")
features.DefaultFeatureGate.AddFlag(flag.CommandLine)
}
func main() {
flag.Parse()
logs.InitLogs()
defer logs.FlushLogs()
if printVersion {
version.PrintVersionInfo()
os.Exit(0)
}
version.LogVersionInfo()
flag.CommandLine.VisitAll(func(flag *flag.Flag) {
klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value)
})
// We choose a random resync period between MinResyncPeriod and 2 *
// MinResyncPeriod, so that our pods started at the same time don't list the apiserver simultaneously.
resyncDuration := time.Duration(minResyncDuration.Seconds()*(1+rand.Float64())) * time.Second
ns := os.Getenv("NAMESPACE")
if len(ns) < 1 {
klog.Fatal("ENV NAMESPACE should be set.")
}
pod.AstsControllerServiceAccounts = fmt.Sprintf("system:serviceaccount:%s:advanced-statefulset-controller", ns)
podAdmissionHook := pod.NewPodAdmissionControl(strings.Split(extraServiceAccounts, ","), resyncDuration)
statefulSetAdmissionHook := statefulset.NewStatefulSetAdmissionControl()
strategyAdmissionHook := strategy.NewStrategyAdmissionHook(&strategy.Registry)
cmd.RunAdmissionServer(podAdmissionHook, statefulSetAdmissionHook, strategyAdmissionHook)
}
|
[
"\"NAMESPACE\""
] |
[] |
[
"NAMESPACE"
] |
[]
|
["NAMESPACE"]
|
go
| 1 | 0 | |
builder/build.go
|
package main
import (
"bufio"
"bytes"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"go/build"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"text/template"
"time"
"github.com/cheggaaa/pb"
"github.com/docker/docker/pkg/term"
"github.com/docker/go-units"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/controller/utils"
"github.com/flynn/flynn/host/resource"
"github.com/flynn/flynn/host/types"
"github.com/flynn/flynn/pkg/exec"
"github.com/flynn/flynn/pkg/tufutil"
"github.com/flynn/flynn/pkg/version"
"github.com/flynn/go-docopt"
tuf "github.com/flynn/go-tuf/client"
tufdata "github.com/flynn/go-tuf/data"
"github.com/golang/groupcache/singleflight"
"github.com/tent/canonical-json-go"
"github.com/inconshreveable/log15"
)
var cmdBuild = Command{
Run: runBuild,
Usage: `
usage: flynn-builder build [options]
options:
-x, --version=<version> version to use [default: dev]
-t, --tuf-db=<path> path to TUF database [default: build/tuf.db]
-v, --verbose be verbose
Build Flynn images using builder/manifest.json.
`[1:],
}
type Builder struct {
// baseLayer is used when building an image which has no
// dependencies (e.g. the ubuntu-trusty image)
baseLayer *host.Mountspec
// artifacts is a map of built artifacts and is written to
// build/images.json on success
artifacts map[string]*ct.Artifact
artifactsMtx sync.RWMutex
// envTemplateData is used as the data when interpolating
// environment variable templates
envTemplateData map[string]string
// goInputs is a set of Go input loaders per platform
goInputs map[GoPlatform]*GoInputs
goInputsMtx sync.Mutex
// tufConfig is the TUF config from the manifest
tufConfig *TUFConfig
tufClient *tuf.Client
log log15.Logger
version string
bar *pb.ProgressBar
}
type Manifest struct {
TUFConfig *TUFConfig `json:"tuf,omitempty"`
BaseLayer *host.Mountspec `json:"base_layer,omitempty"`
Images []*Image `json:"images,omitempty"`
Templates map[string]*Image `json:"templates,omitempty"`
Manifests map[string]string `json:"manifests,omitempty"`
}
type TUFConfig struct {
Repository string `json:"repository,omitempty"`
RootKeys []*tufdata.Key `json:"root_keys,omitempty"`
}
type Image struct {
ID string `json:"id,omitempty"`
Base string `json:"base,omitempty"`
Template string `json:"template,omitempty"`
Env map[string]string `json:"env,omitempty"`
Layers []*Layer `json:"layers,omitempty"`
Entrypoint *ct.ImageEntrypoint `json:"entrypoint,omitempty"`
}
type Layer struct {
// Name is the name of the layer used in log output (defaults to the
// image's ID)
Name string `json:"name,omitempty"`
// BuildWith overrides the image used to build the layer (which
// defaults to the image's base image), thus supports using tools
// to build a layer but not putting those tools in the final image
BuildWith string `json:"build_with,omitempty"`
// Inputs is a list of files required to build the layer, each of them
// being hashed to generate the resulting layer ID
Inputs []string `json:"inputs,omitempty"`
// Run is a list of commands to be run to build the layer, each of them
// being hashed to generate the resulting layer ID
Run []string `json:"run,omitempty"`
// Script is added as an input and run with 'bash -e'
Script string `json:"script,omitempty"`
// GoBuild is a set of directories to build using 'go build'.
//
// The go/build package is used to load the required source files which
// are then added as inputs.
GoBuild map[string]string `json:"gobuild,omitempty"`
// CGoBuild is a set of directories to build with cgo enabled.
//
// The go/build package is used to load the required source files which
// are then added as inputs.
CGoBuild map[string]string `json:"cgobuild,omitempty"`
// Copy is a set of inputs to copy into the layer
Copy map[string]string `json:"copy,omitempty"`
// Env is a set of environment variables to set when building the
// layer, each of them being hashed to generate the resulting layer ID
Env map[string]string `json:"env,omitempty"`
// Limits is a set of limits to set on the build job
Limits map[string]string `json:"limits,omitempty"`
// LinuxCapabilities is a list of extra capabilities to set
LinuxCapabilities []string `json:"linux_capabilities,omitempty"`
}
// Build is used to track an image build
type Build struct {
Image *Image
// Err is set if the build fails, in which case all dependent builds
// are aborted
Err error
// Once is used to ensure the build is only started once
Once sync.Once
// StartedAt is the time the build started
StartedAt time.Time
// Abort is set if a dependency fails to build
Abort bool
// Dependencies is a list of builds which this build depends on
Dependencies map[*Build]struct{}
// Dependents is a list of builds which depend on this build
Dependents map[*Build]struct{}
}
func NewBuild(image *Image) *Build {
return &Build{
Image: image,
Dependencies: make(map[*Build]struct{}),
Dependents: make(map[*Build]struct{}),
}
}
func (b *Build) AddDependency(dep *Build) {
b.Dependencies[dep] = struct{}{}
}
func (b *Build) RemoveDependency(dep *Build) {
delete(b.Dependencies, dep)
}
func (b *Build) AddDependent(dep *Build) {
b.Dependents[dep] = struct{}{}
}
func runBuild(args *docopt.Args) error {
tty := term.IsTerminal(os.Stderr.Fd())
manifest, err := loadManifest()
if err != nil {
return err
} else if len(manifest.Images) == 0 {
return errors.New("no images to build")
}
bar, err := NewProgressBar(len(manifest.Images), tty)
if err != nil {
return err
}
bar.Start()
defer bar.Finish()
debugLog := fmt.Sprintf("build/log/build-%d.log", time.Now().UnixNano())
if err := os.MkdirAll(filepath.Dir(debugLog), 0755); err != nil {
return err
}
log := newLogger(tty, debugLog, args.Bool["--verbose"])
log.Info("building Flynn", "version", args.String["--version"], "log", debugLog)
log.Info("initialising TUF client", "db", args.String["--tuf-db"])
tufClient, err := newTUFClient(manifest.TUFConfig, args.String["--tuf-db"])
if err != nil {
return err
}
for _, image := range manifest.Images {
if image.Template != "" {
t, ok := manifest.Templates[image.Template]
if !ok {
return fmt.Errorf("unknown template %q", image.Template)
}
image.Layers = t.Layers
}
}
tufRootKeys, _ := json.Marshal(manifest.TUFConfig.RootKeys)
builder := &Builder{
tufClient: tufClient,
tufConfig: manifest.TUFConfig,
baseLayer: manifest.BaseLayer,
artifacts: make(map[string]*ct.Artifact),
envTemplateData: map[string]string{
"TUFRootKeys": string(tufRootKeys),
"TUFRepository": manifest.TUFConfig.Repository,
"Version": args.String["--version"],
},
goInputs: make(map[GoPlatform]*GoInputs),
log: log,
version: args.String["--version"],
bar: bar,
}
log.Info("building images")
if err := builder.Build(manifest.Images); err != nil {
return err
}
log.Info("writing manifests")
if err := builder.WriteManifests(manifest.Manifests, manifest.TUFConfig.Repository); err != nil {
return err
}
log.Info("writing images")
return builder.WriteImages()
}
func newTUFClient(config *TUFConfig, dbPath string) (*tuf.Client, error) {
local, err := tuf.FileLocalStore(dbPath)
if err != nil {
return nil, fmt.Errorf("error creating local TUF client: %s", err)
}
opts := &tuf.HTTPRemoteOptions{
UserAgent: fmt.Sprintf("flynn-builder/%s", version.String()),
Retries: tufutil.DefaultHTTPRetries,
}
remote, err := tuf.HTTPRemoteStore(config.Repository, opts)
if err != nil {
return nil, fmt.Errorf("error creating remote TUF client: %s", err)
}
client := tuf.NewClient(local, remote)
_, err = client.Update()
if err == nil || tuf.IsLatestSnapshot(err) {
return client, nil
}
if err == tuf.ErrNoRootKeys {
if err := client.Init(config.RootKeys, len(config.RootKeys)); err != nil {
return nil, err
}
_, err = client.Update()
}
return client, err
}
// newLogger returns a log15.Logger which writes to stdout and a log file
func newLogger(tty bool, file string, verbose bool) log15.Logger {
stdoutFormat := log15.LogfmtFormat()
if tty {
stdoutFormat = log15.TerminalFormat()
}
stdoutHandler := log15.StreamHandler(os.Stdout, stdoutFormat)
if !verbose {
stdoutHandler = log15.LvlFilterHandler(log15.LvlInfo, stdoutHandler)
}
log := log15.New()
log.SetHandler(log15.MultiHandler(
log15.Must.FileHandler(file, log15.LogfmtFormat()),
stdoutHandler,
))
return log
}
func loadManifest() (*Manifest, error) {
f, err := os.Open("builder/manifest.json")
if err != nil {
return nil, err
}
defer f.Close()
manifest := &Manifest{}
return manifest, json.NewDecoder(f).Decode(manifest)
}
// Build builds a list of images, ensuring that each image is built after any
// dependent images have been built
func (b *Builder) Build(images []*Image) error {
builds := make(map[string]*Build, len(images))
for _, image := range images {
builds[image.ID] = NewBuild(image)
}
addDependency := func(build *Build, dependsOn string) error {
dep, ok := builds[dependsOn]
if !ok {
return fmt.Errorf("unknown image dependency: %s -> %s", build.Image.ID, dependsOn)
}
build.AddDependency(dep)
dep.AddDependent(build)
return nil
}
for _, build := range builds {
image := build.Image
// determine build dependencies
// TODO: check for circular dependencies
if image.Base != "" {
addDependency(build, image.Base)
}
for _, l := range image.Layers {
// build Go binaries using the Go image
if l.BuildWith == "" && (len(l.GoBuild) > 0 || len(l.CGoBuild) > 0) {
l.BuildWith = "go"
}
if l.BuildWith != "" {
addDependency(build, l.BuildWith)
}
}
}
// build images until there are no pending builds left
done := make(chan *Build, len(builds))
failures := make(map[string]error)
for len(builds) > 0 {
for _, build := range builds {
// if the build has no more pending dependencies, build it
if len(build.Dependencies) == 0 {
build.Once.Do(func() {
// if the build is aborted due to a dependency
// failure, just send it to the done channel
if build.Abort {
b.log.Debug(fmt.Sprintf("%s build abort", build.Image.ID))
done <- build
return
}
b.log.Debug(fmt.Sprintf("%s build start", build.Image.ID))
go func(build *Build) {
build.StartedAt = time.Now()
build.Err = b.BuildImage(build.Image)
done <- build
}(build)
})
}
}
// wait for a build to finish
build := <-done
b.bar.Increment()
if build.Err == nil {
b.log.Debug(fmt.Sprintf("%s build done", build.Image.ID), "duration", time.Since(build.StartedAt))
} else {
b.log.Error(fmt.Sprintf("%s build error", build.Image.ID), "duration", time.Since(build.StartedAt), "err", build.Err)
}
// remove from the pending list
delete(builds, build.Image.ID)
// remove the build as a pending dependency from all
// dependents
for dependent := range build.Dependents {
// if the build failed or was aborted, abort the
// dependent builds
if build.Err != nil || build.Abort {
dependent.Abort = true
}
dependent.RemoveDependency(build)
}
if build.Err != nil {
failures[build.Image.ID] = build.Err
}
}
if len(failures) > 0 {
b.log.Error("the following builds failed:")
for id, err := range failures {
b.log.Error("* "+id, "err", err)
}
return fmt.Errorf("%d builds failed", len(failures))
}
return nil
}
// BuildImage builds the image's layers and adds the resulting artifact to
// b.artifacts
func (b *Builder) BuildImage(image *Image) error {
var layers []*ct.ImageLayer
for _, l := range image.Layers {
name := l.Name
if name == "" {
name = image.ID
}
env := make(map[string]string, len(image.Env)+len(l.Env))
for k, v := range image.Env {
env[k] = v
}
for k, v := range l.Env {
env[k] = v
}
run := make([]string, len(l.Run))
for i, cmd := range l.Run {
run[i] = cmd
}
var inputs []string
// add the script as an input and run with 'bash -e'
if l.Script != "" {
inputs = append(inputs, l.Script)
run = append(run, "bash -e "+l.Script)
}
// add the explicit inputs, expanding globs
for _, input := range l.Inputs {
paths, err := filepath.Glob(input)
if err != nil {
return err
}
inputs = append(inputs, paths...)
}
// if building Go binaries, load Go inputs for the configured
// GOOS / GOARCH and build with 'go build' / 'cgo build'
if len(l.GoBuild) > 0 || len(l.CGoBuild) > 0 {
goInputs := b.GoInputsFor(GoPlatform{OS: env["GOOS"], Arch: env["GOARCH"]})
// add the commands in a predictable order so the
// generated layer ID is deterministic
dirs := make([]string, 0, len(l.GoBuild))
for dir := range l.GoBuild {
dirs = append(dirs, dir)
}
sort.Strings(dirs)
for _, dir := range dirs {
i, err := goInputs.Load(dir)
if err != nil {
return err
}
inputs = append(inputs, i...)
run = append(run, fmt.Sprintf("go build -o %s %s", l.GoBuild[dir], filepath.Join("github.com/flynn/flynn", dir)))
}
dirs = make([]string, 0, len(l.CGoBuild))
for dir := range l.CGoBuild {
dirs = append(dirs, dir)
}
sort.Strings(dirs)
for _, dir := range dirs {
i, err := goInputs.Load(dir)
if err != nil {
return err
}
inputs = append(inputs, i...)
run = append(run, fmt.Sprintf("cgo build -o %s %s", l.CGoBuild[dir], filepath.Join("github.com/flynn/flynn", dir)))
}
}
// copy the l.Copy inputs in a predictable order so the
// generated layer ID is deterministic
copyPaths := make([]string, 0, len(l.Copy))
for path := range l.Copy {
copyPaths = append(copyPaths, path)
}
sort.Strings(copyPaths)
for _, path := range copyPaths {
inputs = append(inputs, path)
dst := l.Copy[path]
run = append(run, fmt.Sprintf("mkdir -p %q && cp %q %q", filepath.Dir(dst), path, dst))
}
// run the build job with either l.BuildWith or image.Base
var artifact *ct.Artifact
var err error
if l.BuildWith != "" {
artifact, err = b.Artifact(l.BuildWith)
} else if image.Base != "" {
artifact, err = b.Artifact(image.Base)
}
if err != nil {
return err
}
// interpolate the environment variables
for k, v := range env {
tmpl, err := template.New("env").Parse(v)
if err != nil {
return fmt.Errorf("error parsing env template %q: %s", v, err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, b.envTemplateData); err != nil {
return fmt.Errorf("error parsing env template %q: %s", v, err)
}
env[k] = buf.String()
}
// generate the layer ID from the layer config, artifact and
// list of inputs
id, err := b.generateLayerID(name, run, env, artifact, inputs...)
if err != nil {
return err
}
start := time.Now()
layer, err := b.BuildLayer(l, id, name, run, env, artifact, inputs)
if err != nil {
return err
}
b.log.Debug(fmt.Sprintf("%s layer done", name), "layer.id", id, "duration", time.Since(start))
layers = append(layers, layer)
}
// generate an artifact based on image.Base and add to b.artifacts
var baseLayers []*ct.ImageLayer
if image.Base != "" {
baseArtifact, err := b.Artifact(image.Base)
if err != nil {
return err
}
for _, rootfs := range baseArtifact.Manifest().Rootfs {
baseLayers = append(baseLayers, rootfs.Layers...)
}
}
manifest := ct.ImageManifest{
Type: ct.ImageManifestTypeV1,
Rootfs: []*ct.ImageRootfs{{
Platform: ct.DefaultImagePlatform,
Layers: append(baseLayers, layers...),
}},
}
if image.Entrypoint != nil {
manifest.Entrypoints = map[string]*ct.ImageEntrypoint{
"_default": image.Entrypoint,
}
}
imageURL := fmt.Sprintf("%s?name=%s&target=/images/%s.json", b.tufConfig.Repository, image.ID, manifest.ID())
artifact := &ct.Artifact{
Type: ct.ArtifactTypeFlynn,
URI: imageURL,
RawManifest: manifest.RawManifest(),
Hashes: manifest.Hashes(),
Size: int64(len(manifest.RawManifest())),
LayerURLTemplate: layerURLTemplate,
Meta: map[string]string{
"manifest.id": manifest.ID(),
"flynn.component": image.ID,
"flynn.system-image": "true",
},
}
b.artifactsMtx.Lock()
b.artifacts[image.ID] = artifact
b.artifactsMtx.Unlock()
// write the artifact to build/image/ID.json
path := filepath.Join("build", "image", image.ID+".json")
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(artifact)
}
var imageArtifactPattern = regexp.MustCompile(`\$image_artifact\[[^\]]+\]`)
// WriteManifests interpolates a set of manifests and writes them to the
// build/manifests directory
func (b *Builder) WriteManifests(manifests map[string]string, tufRepository string) error {
for src, name := range manifests {
dst := filepath.Join("build", "manifests", name)
b.log.Debug("writing manifest", "src", src, "dst", dst)
manifest, err := ioutil.ReadFile(src)
if err != nil {
return err
}
var replaceErr error
manifest = imageArtifactPattern.ReplaceAllFunc(manifest, func(raw []byte) []byte {
name := string(raw[16 : len(raw)-1])
artifact, ok := b.artifacts[name]
if !ok {
replaceErr = fmt.Errorf("unknown image %q", name)
return nil
}
artifact.Meta = map[string]string{
"flynn.component": name,
"flynn.system-image": "true",
}
data, err := json.Marshal(artifact)
if err != nil {
replaceErr = err
return nil
}
return data
})
if replaceErr != nil {
return replaceErr
}
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return err
}
if err := ioutil.WriteFile(dst, manifest, 0644); err != nil {
return err
}
}
return nil
}
// WriteImages writes the built images to build/images.json
func (b *Builder) WriteImages() error {
path := "build/images.json"
tmp, err := os.Create(path + ".tmp")
if err != nil {
return err
}
defer tmp.Close()
if err := json.NewEncoder(tmp).Encode(b.artifacts); err != nil {
os.Remove(tmp.Name())
return err
}
return os.Rename(tmp.Name(), path)
}
func (b *Builder) Artifact(name string) (*ct.Artifact, error) {
b.artifactsMtx.RLock()
defer b.artifactsMtx.RUnlock()
artifact, ok := b.artifacts[name]
if !ok {
return nil, fmt.Errorf("missing %q artifact", name)
}
return artifact, nil
}
// GetCachedLayer gets a layer either from the local /var/lib/flynn/layer-cache
// directory or from the TUF repository, returning a nil layer for a cache miss
func (b *Builder) GetCachedLayer(name, id string) (*ct.ImageLayer, error) {
// first check the local cache
f, err := os.Open(b.layerConfigPath(id))
if err == nil {
defer f.Close()
layer := &ct.ImageLayer{}
return layer, json.NewDecoder(f).Decode(layer)
} else if !os.IsNotExist(err) {
return nil, err
}
// not found locally, check the TUF repo
data, err := tufutil.DownloadString(b.tufClient, fmt.Sprintf("/layers/%s.json", id))
if _, ok := err.(tuf.ErrUnknownTarget); ok {
// cache miss, return a nil layer so it gets generated
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("error getting layer from the TUF repo: %s", err)
}
layer := &ct.ImageLayer{}
if err := json.Unmarshal([]byte(data), layer); err != nil {
return nil, fmt.Errorf("error getting layer from the TUF repo: %s", err)
}
// cache the layer locally
b.log.Info("fetching layer", "layer.name", name, "layer.id", id, "layer.size", units.BytesSize(float64(layer.Length)))
tmp, err := tufutil.Download(b.tufClient, fmt.Sprintf("/layers/%s.squashfs", id))
if err != nil {
return nil, fmt.Errorf("error getting layer from the TUF repo: %s", err)
}
defer tmp.Close()
f, err = os.Create(b.layerPath(id))
if err != nil {
return nil, err
}
defer f.Close()
if _, err := io.Copy(f, tmp); err != nil {
return nil, fmt.Errorf("error writing layer to cache: %s", err)
}
if err := ioutil.WriteFile(b.layerConfigPath(id), []byte(data), 0644); err != nil {
return nil, fmt.Errorf("error writing layer to cache: %s", err)
}
return layer, nil
}
// BuildLayer either returns a cached layer or runs a job to build the layer
func (b *Builder) BuildLayer(l *Layer, id, name string, run []string, env map[string]string, artifact *ct.Artifact, inputs []string) (*ct.ImageLayer, error) {
// try and get the cached layer first
layer, err := b.GetCachedLayer(name, id)
if err != nil {
return nil, err
} else if layer != nil {
return layer, nil
}
// create a shared directory containing the inputs so we can ensure the
// job only accesses declared inputs (thus enforcing the correctness of
// the generated layer ID)
dir, err := ioutil.TempDir("", "flynn-build-mnt")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
if err := os.Chmod(dir, 0755); err != nil {
return nil, err
}
for _, subdir := range []string{"bin", "out", "src"} {
if err := os.MkdirAll(filepath.Join(dir, subdir), 0755); err != nil {
return nil, err
}
}
copyFile := func(srcPath, dstPath string) error {
src, err := os.Open(srcPath)
if err != nil {
return err
}
defer src.Close()
stat, err := src.Stat()
if err != nil {
return err
}
path := filepath.Join(dir, dstPath)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode())
if err != nil {
return err
}
defer dst.Close()
_, err = io.Copy(dst, src)
return err
}
for _, input := range inputs {
if err := copyFile(input, filepath.Join("src", input)); err != nil {
b.log.Error("error copying input", "input", input, "err", err)
return nil, err
}
}
// copy the flynn-builder binary into the shared directory so we can
// run it inside the job
if err := copyFile(os.Args[0], "bin/flynn-builder"); err != nil {
b.log.Error("error copying flynn-builder binary", "err", err)
return nil, err
}
job := &host.Job{
Config: host.ContainerConfig{
Env: env,
DisableLog: true,
},
Resources: resource.Defaults(),
Metadata: map[string]string{
"flynn-controller.app_name": "builder",
"flynn-controller.type": name,
},
}
cmd := exec.Cmd{Job: job}
// run bash inside the job, passing the commands via stdin
job.Config.Args = []string{"/mnt/bin/flynn-builder", "run", "bash", "-exs"}
job.Config.Stdin = true
cmd.Stdin = strings.NewReader(strings.Join(run, "\n"))
// set FLYNN_VERSION which will be assigned to the pkg/version.version
// constant using ldflags when building Go binaries.
//
// This is not treated as an input because we only want to build a new
// binary with the given version if the build inputs have changed.
job.Config.Env["FLYNN_VERSION"] = b.version
// run the job in the host network to avoid a kernel bug which causes
// subsequent jobs to block waiting on the lo network device to become
// free (see https://github.com/docker/docker/issues/5618).
//
// NOTE: this leads to an impure build, jobs sometimes use the state of
// the network to change the installation procedure (e.g. PostgreSQL
// changes the default port to 5433 if something is already listening
// on port 5432 at install time)
job.Config.HostNetwork = true
linuxCapabilities := append(host.DefaultCapabilities, l.LinuxCapabilities...)
job.Config.LinuxCapabilities = &linuxCapabilities
for typ, v := range l.Limits {
limit, err := resource.ParseLimit(resource.Type(typ), v)
if err != nil {
return nil, fmt.Errorf("error parsing limit %q = %q: %s", typ, v, err)
}
job.Resources.SetLimit(resource.Type(typ), limit)
}
// mount the shared directory at /mnt as a 9p filesystem
ln, err := net.Listen("tcp", os.Getenv("EXTERNAL_IP")+":0")
if err != nil {
return nil, err
}
defer ln.Close()
go serveFilesystem(dir, ln)
addr := ln.Addr().(*net.TCPAddr)
job.Config.Mounts = append(job.Config.Mounts, host.Mount{
Device: "9p",
Location: "/mnt",
Target: addr.IP.String(),
Data: fmt.Sprintf("trans=tcp,port=%d", addr.Port),
})
job.Config.WorkingDir = "/mnt/src"
if artifact == nil {
// use the base layer if there is no artifact to build with
job.Mountspecs = []*host.Mountspec{b.baseLayer}
} else {
utils.SetupMountspecs(job, []*ct.Artifact{artifact})
}
// copy output to log file + prefix stdout / stderr with the layer name
logPath := filepath.Join("build/log", name+".log")
if err := os.MkdirAll(filepath.Dir(logPath), 0755); err != nil {
return nil, err
}
logFile, err := os.Create(logPath)
if err != nil {
return nil, err
}
logR, logW := io.Pipe()
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
go io.Copy(logW, stdout)
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
go io.Copy(logW, stderr)
go func() {
defer logFile.Close()
s := bufio.NewScanner(logR)
for s.Scan() {
fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().Format("15:04:05.999"), name, s.Text())
fmt.Fprintln(logFile, s.Text())
}
}()
// run the job
b.log.Info("building layer", "layer.name", name, "layer.id", id)
if err := cmd.Run(); err != nil {
b.log.Error("error running the build job", "name", name, "err", err)
return nil, err
}
// copy the layer to the cache
f, err := os.Open(filepath.Join(dir, "out", "layer.squashfs"))
if err != nil {
return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
}
h := sha512.New512_256()
dst, err := os.Create(b.layerPath(id))
if err != nil {
return nil, fmt.Errorf("error writing to layer cache: %s", err)
}
defer dst.Close()
if _, err := io.Copy(dst, io.TeeReader(f, h)); err != nil {
return nil, fmt.Errorf("error writing to layer cache: %s", err)
}
layer = &ct.ImageLayer{
ID: id,
Type: ct.ImageLayerTypeSquashfs,
Length: stat.Size(),
Hashes: map[string]string{
"sha512_256": hex.EncodeToString(h.Sum(nil)),
},
}
data, err := json.Marshal(layer)
if err != nil {
return nil, fmt.Errorf("error encoding layer config: %s", err)
}
if err := ioutil.WriteFile(b.layerConfigPath(id), data, 0644); err != nil {
return nil, fmt.Errorf("error writing to layer cache: %s", err)
}
return layer, nil
}
func (b *Builder) GoInputsFor(platform GoPlatform) *GoInputs {
b.goInputsMtx.Lock()
defer b.goInputsMtx.Unlock()
if g, ok := b.goInputs[platform]; ok {
return g
}
g := NewGoInputs(platform)
b.goInputs[platform] = g
return g
}
const layerURLTemplate = "file:///var/lib/flynn/layer-cache/{id}.squashfs"
func (b *Builder) layerPath(id string) string {
return fmt.Sprintf("/var/lib/flynn/layer-cache/%s.squashfs", id)
}
func (b *Builder) layerConfigPath(id string) string {
return fmt.Sprintf("/var/lib/flynn/layer-cache/%s.json", id)
}
// generateLayerID generates a layer ID from a set of all inputs required to
// build the layer, which prevents rebuilding a layer if the inputs haven't
// changed.
//
// It does this by constructing a canonicalised JSON object representing the
// inputs and computing the SHA512/256 sum of the resulting bytes.
//
// TODO: consider storing a map of filenames to hashes and cache based
// on the last modified time to avoid unnecessary work.
func (b *Builder) generateLayerID(name string, run []string, env map[string]string, artifact *ct.Artifact, inputs ...string) (id string, err error) {
start := time.Now()
defer func() {
b.log.Debug("generated layer ID", "name", name, "id", id, "duration", time.Since(start))
}()
type fileInput struct {
Path string `json:"path"`
Size int64 `json:"size"`
SHA string `json:"sha"`
}
var layer = struct {
Name string `json:"name"`
Run []string `json:"run,omitempty"`
Env map[string]string `json:"env,omitempty"`
RawManifest json.RawMessage `json:"manifest,omitempty"`
Files []*fileInput `json:"files,omitempty"`
}{
Name: name,
Run: run,
Env: env,
Files: make([]*fileInput, 0, len(inputs)),
}
if artifact != nil {
layer.RawManifest = artifact.RawManifest
}
addFile := func(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return err
}
h := sha512.New512_256()
if _, err := io.Copy(h, f); err != nil {
return err
}
layer.Files = append(layer.Files, &fileInput{
Path: path,
Size: stat.Size(),
SHA: hex.EncodeToString(h.Sum(nil)),
})
return nil
}
for _, input := range inputs {
if err := addFile(input); err != nil {
return "", err
}
}
data, err := cjson.Marshal(layer)
if err != nil {
return "", err
}
sum := sha512.Sum512_256(data)
return hex.EncodeToString(sum[:]), nil
}
// NewProgressBar creates a progress bar which is pinned to the bottom of the
// terminal screen
func NewProgressBar(count int, tty bool) (*pb.ProgressBar, error) {
bar := pb.New(count)
if !tty {
bar.Output = os.Stderr
return bar, nil
}
// replace os.Stdout / os.Stderr with a pipe and copy output to a
// channel so that the progress bar can be wiped before printing output
type stdOutput struct {
Out io.Writer
Text string
}
output := make(chan *stdOutput)
wrap := func(out io.Writer) (*os.File, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
output <- &stdOutput{out, s.Text()}
}
}()
return w, nil
}
stdout := os.Stdout
var err error
os.Stdout, err = wrap(stdout)
if err != nil {
return nil, err
}
stderr := os.Stderr
os.Stderr, err = wrap(stderr)
if err != nil {
return nil, err
}
progress := make(chan string)
bar.Callback = func(out string) { progress <- out }
go func() {
var barText string
for {
select {
case out := <-output:
// if we have printed the bar, replace it with
// spaces then write the output on the same line
if len(barText) > 0 {
spaces := make([]byte, len(barText))
for i := 0; i < len(barText); i++ {
spaces[i] = ' '
}
fmt.Fprint(stderr, "\r", string(spaces), "\r")
}
fmt.Fprintln(out.Out, out.Text)
// re-print the bar on the next line
if len(barText) > 0 {
fmt.Fprint(stderr, "\r"+barText)
}
case out := <-progress:
// print the bar over the previous bar
barText = out
fmt.Fprint(stderr, "\r"+out)
}
}
}()
return bar, nil
}
type GoPlatform struct {
OS string
Arch string
}
// GoInputs determines all the Go files which are required to build a Go
// program contained in a directory.
//
// It skips stdlib files as they are contained within the Go image so do not
// need to be treated as file inputs.
type GoInputs struct {
ctx build.Context
srcDir string
inputs map[string][]string
mtx sync.RWMutex
loader singleflight.Group
}
func NewGoInputs(platform GoPlatform) *GoInputs {
srcDir, _ := os.Getwd()
ctx := build.Default
ctx.CgoEnabled = true
if platform.OS != "" {
ctx.GOOS = platform.OS
}
if platform.Arch != "" {
ctx.GOARCH = platform.Arch
}
return &GoInputs{
ctx: ctx,
srcDir: srcDir,
inputs: make(map[string][]string),
}
}
func (g *GoInputs) Load(dir string) ([]string, error) {
p, err := g.ctx.ImportDir(dir, 0)
if err != nil {
return nil, err
}
inputs := make([]string, len(p.GoFiles))
for i, file := range p.GoFiles {
inputs[i] = filepath.Join(dir, file)
}
for _, pkg := range p.Imports {
imports, err := g.load(pkg)
if err != nil {
return nil, err
}
inputs = append(inputs, imports...)
}
return inputs, nil
}
func (g *GoInputs) load(pkg string) ([]string, error) {
g.mtx.RLock()
cached, ok := g.inputs[pkg]
g.mtx.RUnlock()
if ok {
return cached, nil
}
inputs, err := g.loader.Do(pkg, func() (interface{}, error) {
if pkg == "C" {
return []string{}, nil
}
// load the package
p, err := g.ctx.Import(pkg, g.srcDir, 0)
if err != nil {
return nil, err
}
// skip standard lib packages (they exist in the Go image)
if p.Goroot {
g.mtx.Lock()
g.inputs[pkg] = []string{}
g.mtx.Unlock()
return []string{}, nil
}
// add the source files
files := p.GoFiles
files = append(files, p.CgoFiles...)
files = append(files, p.CFiles...)
files = append(files, p.HFiles...)
files = append(files, p.SFiles...)
files = append(files, p.IgnoredGoFiles...)
inputs := make([]string, len(files))
for i, file := range files {
path, _ := filepath.Rel(g.srcDir, filepath.Join(p.Dir, file))
inputs[i] = path
}
// recursively add imported packages
for _, pkg := range p.Imports {
imports, err := g.load(pkg)
if err != nil {
return nil, err
}
inputs = append(inputs, imports...)
}
return inputs, nil
})
if err != nil {
return nil, err
}
g.mtx.Lock()
g.inputs[pkg] = inputs.([]string)
g.mtx.Unlock()
return inputs.([]string), nil
}
|
[
"\"EXTERNAL_IP\""
] |
[] |
[
"EXTERNAL_IP"
] |
[]
|
["EXTERNAL_IP"]
|
go
| 1 | 0 | |
admin.py
|
import json
import os
import django
from django.contrib.auth import get_user_model
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "portfolio.settings")
django.setup()
from app.models import Blog, Profile, Project, TechPlatform, TechStack
User = get_user_model()
User.objects.create_superuser(os.environ.get('DATABASE_USER'), os.environ.get('ADMIN_EMAIL'),
os.environ.get('DATABASE_PASSWORD'))
# Delete all records
Blog.objects.all().delete()
Profile.objects.all().delete()
Project.objects.all().delete()
TechPlatform.objects.all().delete()
TechStack.objects.all().delete()
# Blogs Data
blogs = json.load(open('database/Blog.json'))
for blog in blogs:
b = Blog(title=blog['title'], thumbnail=blog['thumbnail'], link=blog['link'])
b.save()
# Profile Data
profile_results = json.load(open('database/Profile.json'))
profile = profile_results[0]
Profile(full_name=profile['full_name'], photo=profile['photo'], email=profile['email'],
designation=profile['designation'], about_me=profile['about_me'], copyright=profile['copyright'],
github=profile['github'], twitter=profile['twitter'], linkedin=profile['linkedin'],
facebook=profile['facebook'], instagram=profile['instagram']).save()
# Project Data
projects = json.load(open('database/Projects.json'))
for project in projects:
Project(project_id=project['project_id'], title=project['title'], small_thumbnail=project['small_thumbnail'],
large_thumbnail=project['large_thumbnail'], description=project['description'],
github_link=project['github_link'], youtube_link=project['youtube_link'],
project_link=project['project_link'], tech_stack=project['tech_stack'],
color_code=project['color_code']).save()
# TechPlatform / TechStack
tech_platforms = json.load(open('database/TechPlatform.json'))
tech_stacks = json.load(open('database/TechStack.json'))
for tech_platform in tech_platforms:
t = TechPlatform.objects.create(platform=tech_platform['platform'])
for tech_stack in tech_stacks:
if tech_stack['platform_id'] == tech_platform['platform_id']:
tech = TechStack.objects.create(domain=tech_stack['domain'], domain_url=tech_stack['domain_url'])
tech.domain_id.add(t)
|
[] |
[] |
[
"DATABASE_PASSWORD",
"ADMIN_EMAIL",
"DATABASE_USER"
] |
[]
|
["DATABASE_PASSWORD", "ADMIN_EMAIL", "DATABASE_USER"]
|
python
| 3 | 0 | |
source/Wrap.popclipext/wrap.py
|
import os, re, string, textwrap
print '\n\n'.join(map(lambda x: textwrap.fill(re.sub(r'\s+', ' ', x), 80), string.split(re.sub(r'\n\n+', '\n\n', os.getenv('POPCLIP_TEXT')), '\n\n')))
|
[] |
[] |
[
"POPCLIP_TEXT"
] |
[]
|
["POPCLIP_TEXT"]
|
python
| 1 | 0 | |
misc/makerelease/makerelease.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is a tool for packaging binary releases.
// It supports FreeBSD, Linux, NetBSD, OpenBSD, OS X, and Windows.
package main
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"crypto/sha1"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"code.google.com/p/goauth2/oauth"
storage "code.google.com/p/google-api-go-client/storage/v1"
)
var (
tag = flag.String("tag", "release", "mercurial tag to check out")
toolTag = flag.String("tool", defaultToolTag, "go.tools tag to check out")
tourTag = flag.String("tour", defaultTourTag, "go-tour tag to check out")
repo = flag.String("repo", "https://code.google.com/p/go", "repo URL")
verbose = flag.Bool("v", false, "verbose output")
upload = flag.Bool("upload", false, "upload resulting files to Google Code")
addLabel = flag.String("label", "", "additional label to apply to file when uploading")
includeRace = flag.Bool("race", true, "build race detector packages")
versionOverride = flag.String("version", "", "override version name")
staticToolchain = flag.Bool("static", true, "try to build statically linked toolchain (only supported on ELF targets)")
tokenCache = flag.String("token", defaultCacheFile, "Authentication token cache file")
storageBucket = flag.String("bucket", "golang", "Cloud Storage Bucket")
uploadURL = flag.String("upload_url", defaultUploadURL, "Upload URL")
defaultCacheFile = filepath.Join(os.Getenv("HOME"), ".makerelease-request-token")
defaultUploadURL = "http://golang.org/dl/upload"
)
const (
blogPath = "golang.org/x/blog"
toolPath = "golang.org/x/tools"
tourPath = "code.google.com/p/go-tour"
defaultToolTag = "release-branch.go1.4"
defaultTourTag = "release-branch.go1.4"
)
// Import paths for tool commands.
// These must be the command that cmd/go knows to install to $GOROOT/bin
// or $GOROOT/pkg/tool.
var toolPaths = []string{
"golang.org/x/tools/cmd/cover",
"golang.org/x/tools/cmd/godoc",
"golang.org/x/tools/cmd/vet",
}
var preBuildCleanFiles = []string{
"lib/codereview",
"misc/dashboard/godashboard",
"src/cmd/cov",
"src/cmd/prof",
"src/exp",
"src/old",
}
var cleanFiles = []string{
".hg",
".hgtags",
".hgignore",
"VERSION.cache",
}
var sourceCleanFiles = []string{
"bin",
"pkg",
}
var tourPackages = []string{
"pic",
"tree",
"wc",
}
var tourContent = []string{
"content",
"solutions",
"static",
"template",
}
var blogContent = []string{
"content",
"template",
}
// The os-arches that support the race toolchain.
var raceAvailable = []string{
"darwin-amd64",
"linux-amd64",
"windows-amd64",
}
// The OSes that support building statically linked toolchain
// Only ELF platforms are supported.
var staticLinkAvailable = []string{
"linux",
"freebsd",
"openbsd",
"netbsd",
}
var fileRe = regexp.MustCompile(`^(go[a-z0-9-.]+)\.(src|([a-z0-9]+)-([a-z0-9]+)(?:-([a-z0-9.]+))?)\.(tar\.gz|zip|pkg|msi)$`)
// OAuth2-authenticated HTTP client used to make calls to Cloud Storage.
var oauthClient *http.Client
// Builder key as specified in ~/.gobuildkey
var builderKey string
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [flags] targets...\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
}
if runtime.GOOS == "windows" {
checkWindowsDeps()
}
if *upload {
if err := readCredentials(); err != nil {
log.Fatalln("readCredentials:", err)
}
if err := setupOAuthClient(); err != nil {
log.Fatalln("setupOAuthClient:", err)
}
}
ok := true
for _, targ := range flag.Args() {
var b Build
if m := fileRe.FindStringSubmatch(targ); m != nil {
// targ is a file name; upload it to googlecode.
version := m[1]
if m[2] == "src" {
b.Source = true
} else {
b.OS = m[3]
b.Arch = m[4]
b.Label = m[5]
}
if !*upload {
log.Printf("%s: -upload=false, skipping", targ)
continue
}
if err := b.Upload(version, targ); err != nil {
log.Printf("uploading %s: %v", targ, err)
}
continue
}
if targ == "source" {
b.Source = true
} else {
p := strings.SplitN(targ, "-", 3)
if len(p) < 2 {
log.Println("Ignoring unrecognized target:", targ)
continue
}
b.OS = p[0]
b.Arch = p[1]
if len(p) >= 3 {
b.Label = p[2]
}
if *includeRace {
for _, t := range raceAvailable {
if t == targ || strings.HasPrefix(targ, t+"-") {
b.Race = true
}
}
}
if *staticToolchain {
for _, os := range staticLinkAvailable {
if b.OS == os {
b.static = true
}
}
}
}
if err := b.Do(); err != nil {
log.Printf("%s: %v", targ, err)
ok = false
}
}
if !ok {
os.Exit(1)
}
}
type Build struct {
Source bool // if true, OS and Arch must be empty
Race bool // build race toolchain
OS string
Arch string
Label string
root string
gopath string
static bool // if true, build statically linked toolchain
}
func (b *Build) Do() error {
work, err := ioutil.TempDir("", "makerelease")
if err != nil {
return err
}
defer os.RemoveAll(work)
b.root = filepath.Join(work, "go")
b.gopath = work
// Clone Go distribution and update to tag.
_, err = b.hgCmd(work, "clone", *repo, b.root)
if err != nil {
return err
}
_, err = b.hgCmd(b.root, "update", *tag)
if err != nil {
return err
}
// Remove exp and old packages.
if err := b.clean(preBuildCleanFiles); err != nil {
return err
}
src := filepath.Join(b.root, "src")
if b.Source {
if runtime.GOOS == "windows" {
log.Print("Warning: running make.bash on Windows; source builds are intended to be run on a Unix machine")
}
// Build dist tool only.
_, err = b.run(src, "bash", "make.bash", "--dist-tool")
} else {
// Build.
if b.OS == "windows" {
_, err = b.run(src, "cmd", "/C", "make.bat")
} else {
_, err = b.run(src, "bash", "make.bash")
}
if b.Race {
if err != nil {
return err
}
goCmd := filepath.Join(b.root, "bin", "go")
if b.OS == "windows" {
goCmd += ".exe"
}
_, err = b.run(src, goCmd, "install", "-race", "std")
if err != nil {
return err
}
// Re-install std without -race, so that we're not left
// with a slower, race-enabled cmd/go, etc.
_, err = b.run(src, goCmd, "install", "-a", "std")
// Re-building go command leaves old versions of go.exe as go.exe~ on windows.
// See (*builder).copyFile in $GOROOT/src/cmd/go/build.go for details.
// Remove it manually.
if b.OS == "windows" {
os.Remove(goCmd + "~")
}
}
if err != nil {
return err
}
err = b.extras()
}
if err != nil {
return err
}
// Get version strings.
var (
version string // "weekly.2012-03-04"
fullVersion []byte // "weekly.2012-03-04 9353aa1efdf3"
)
pat := filepath.Join(b.root, "pkg/tool/*/dist*") // trailing * for .exe
m, err := filepath.Glob(pat)
if err != nil {
return err
}
if len(m) == 0 {
return fmt.Errorf("couldn't find dist in %q", pat)
}
fullVersion, err = b.run("", m[0], "version")
if err != nil {
return err
}
fullVersion = bytes.TrimSpace(fullVersion)
v := bytes.SplitN(fullVersion, []byte(" "), 2)
version = string(v[0])
if *versionOverride != "" {
version = *versionOverride
}
// Write VERSION file.
err = ioutil.WriteFile(filepath.Join(b.root, "VERSION"), fullVersion, 0644)
if err != nil {
return err
}
// Clean goroot.
if err := b.clean(cleanFiles); err != nil {
return err
}
if b.Source {
if err := b.clean(sourceCleanFiles); err != nil {
return err
}
}
// Create packages.
base := fmt.Sprintf("%s.%s-%s", version, b.OS, b.Arch)
if b.Label != "" {
base += "-" + b.Label
}
if !strings.HasPrefix(base, "go") {
base = "go." + base
}
var targs []string
switch b.OS {
case "linux", "freebsd", "netbsd", "":
// build tarball
targ := base
if b.Source {
targ = fmt.Sprintf("%s.src", version)
if !strings.HasPrefix(targ, "go") {
targ = "go." + targ
}
}
targ += ".tar.gz"
err = makeTar(targ, work)
targs = append(targs, targ)
case "darwin":
// build tarball
targ := base + ".tar.gz"
err = makeTar(targ, work)
targs = append(targs, targ)
makerelease := filepath.Join(runtime.GOROOT(), "misc/makerelease")
// build pkg
// arrange work so it's laid out as the dest filesystem
etc := filepath.Join(makerelease, "darwin/etc")
_, err = b.run(work, "cp", "-r", etc, ".")
if err != nil {
return err
}
localDir := filepath.Join(work, "usr/local")
err = os.MkdirAll(localDir, 0755)
if err != nil {
return err
}
_, err = b.run(work, "mv", "go", localDir)
if err != nil {
return err
}
// build package
pkgdest, err := ioutil.TempDir("", "pkgdest")
if err != nil {
return err
}
defer os.RemoveAll(pkgdest)
_, err = b.run("", "pkgbuild",
"--identifier", "com.googlecode.go",
"--version", version,
"--scripts", filepath.Join(makerelease, "darwin/scripts"),
"--root", work,
filepath.Join(pkgdest, "com.googlecode.go.pkg"))
if err != nil {
return err
}
targ = base + ".pkg"
_, err = b.run("", "productbuild",
"--distribution", filepath.Join(makerelease, "darwin/Distribution"),
"--resources", filepath.Join(makerelease, "darwin/Resources"),
"--package-path", pkgdest,
targ)
if err != nil {
return err
}
targs = append(targs, targ)
case "windows":
// Create ZIP file.
zip := filepath.Join(work, base+".zip")
err = makeZip(zip, work)
// Copy zip to target file.
targ := base + ".zip"
err = cp(targ, zip)
if err != nil {
return err
}
targs = append(targs, targ)
// Create MSI installer.
win := filepath.Join(runtime.GOROOT(), "misc/makerelease/windows")
installer := filepath.Join(win, "installer.wxs")
appfiles := filepath.Join(work, "AppFiles.wxs")
msi := filepath.Join(work, "installer.msi")
// Gather files.
_, err = b.run(work, "heat", "dir", "go",
"-nologo",
"-gg", "-g1", "-srd", "-sfrag",
"-cg", "AppFiles",
"-template", "fragment",
"-dr", "INSTALLDIR",
"-var", "var.SourceDir",
"-out", appfiles)
if err != nil {
return err
}
// Build package.
_, err = b.run(work, "candle",
"-nologo",
"-dGoVersion="+version,
"-dWixGoVersion="+wixVersion(version),
"-dArch="+b.Arch,
"-dSourceDir=go",
installer, appfiles)
if err != nil {
return err
}
appfiles = filepath.Join(work, "AppFiles.wixobj")
installer = filepath.Join(work, "installer.wixobj")
_, err = b.run(win, "light",
"-nologo",
"-ext", "WixUIExtension",
"-ext", "WixUtilExtension",
installer, appfiles,
"-o", msi)
if err != nil {
return err
}
// Copy installer to target file.
targ = base + ".msi"
err = cp(targ, msi)
targs = append(targs, targ)
}
if err == nil && *upload {
for _, targ := range targs {
err = b.Upload(version, targ)
if err != nil {
return fmt.Errorf("uploading %s: %v", targ, err)
}
}
}
return err
}
var versionRe = regexp.MustCompile(`^go([0-9]+(\.[0-9]+)*)`)
// The Microsoft installer requires version format major.minor.build
// (http://msdn.microsoft.com/en-us/library/aa370859%28v=vs.85%29.aspx).
// Where the major and minor field has a maximum value of 255 and build 65535.
// The offical Go version format is goMAJOR.MINOR.PATCH at $GOROOT/VERSION.
// It's based on the Mercurial tag. Remove prefix and suffix to make the
// installer happy.
func wixVersion(v string) string {
m := versionRe.FindStringSubmatch(v)
if m == nil {
return "0.0.0"
}
return m[1]
}
// extras fetches the go.tools, go.blog, and go-tour repositories,
// builds them and copies the resulting binaries and static assets
// to the new GOROOT.
func (b *Build) extras() error {
defer b.cleanGopath()
if err := b.tools(); err != nil {
return err
}
if err := b.blog(); err != nil {
return err
}
return b.tour()
}
func (b *Build) get(repoPath, revision string) error {
dest := filepath.Join(b.gopath, "src", filepath.FromSlash(repoPath))
if strings.HasPrefix(repoPath, "golang.org/x/") {
// For sub-repos, fetch the old Mercurial repo; bypass "go get".
// DO NOT import this special case into the git tree.
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return err
}
repo := strings.Replace(repoPath, "golang.org/x/", "https://code.google.com/p/go.", 1)
if _, err := b.run(b.gopath, "hg", "clone", repo, dest); err != nil {
return err
}
} else {
// Fetch the packages (without building/installing).
_, err := b.run(b.gopath, filepath.Join(b.root, "bin", "go"),
"get", "-d", repoPath+"/...")
if err != nil {
return err
}
}
// Update the repo to the specified revision.
dest := filepath.Join(b.gopath, "src", filepath.FromSlash(repoPath))
var err error
switch {
case exists(filepath.Join(dest, ".git")):
_, err = b.run(dest, "git", "checkout", revision)
case exists(filepath.Join(dest, ".hg")):
_, err = b.run(dest, "hg", "update", revision)
default:
err = errors.New("unknown version control system")
}
return err
}
func (b *Build) tools() error {
// Fetch the go.tools repository.
if err := b.get(toolPath, *toolTag); err != nil {
return err
}
// Install tools.
args := append([]string{"install"}, toolPaths...)
_, err := b.run(b.gopath, filepath.Join(b.root, "bin", "go"), args...)
if err != nil {
return err
}
// Copy doc.go from go.tools/cmd/$CMD to $GOROOT/src/cmd/$CMD
// while rewriting "package main" to "package documentation".
for _, p := range toolPaths {
d, err := ioutil.ReadFile(filepath.Join(b.gopath, "src",
filepath.FromSlash(p), "doc.go"))
if err != nil {
return err
}
d = bytes.Replace(d, []byte("\npackage main\n"),
[]byte("\npackage documentation\n"), 1)
cmdDir := filepath.Join(b.root, "src", "cmd", path.Base(p))
if err := os.MkdirAll(cmdDir, 0755); err != nil {
return err
}
docGo := filepath.Join(cmdDir, "doc.go")
if err := ioutil.WriteFile(docGo, d, 0644); err != nil {
return err
}
}
return nil
}
func (b *Build) blog() error {
// Fetch the blog repository.
_, err := b.run(b.gopath, filepath.Join(b.root, "bin", "go"), "get", "-d", blogPath+"/blog")
if err != nil {
return err
}
// Copy blog content to $GOROOT/blog.
blogSrc := filepath.Join(b.gopath, "src", filepath.FromSlash(blogPath))
contentDir := filepath.Join(b.root, "blog")
return cpAllDir(contentDir, blogSrc, blogContent...)
}
func (b *Build) tour() error {
// Fetch the go-tour repository.
if err := b.get(tourPath, *tourTag); err != nil {
return err
}
// Build tour binary.
_, err := b.run(b.gopath, filepath.Join(b.root, "bin", "go"),
"install", tourPath+"/gotour")
if err != nil {
return err
}
// Copy all the tour content to $GOROOT/misc/tour.
importPath := filepath.FromSlash(tourPath)
tourSrc := filepath.Join(b.gopath, "src", importPath)
contentDir := filepath.Join(b.root, "misc", "tour")
if err = cpAllDir(contentDir, tourSrc, tourContent...); err != nil {
return err
}
// Copy the tour source code so it's accessible with $GOPATH pointing to $GOROOT/misc/tour.
if err = cpAllDir(filepath.Join(contentDir, "src", importPath), tourSrc, tourPackages...); err != nil {
return err
}
// Copy gotour binary to tool directory as "tour"; invoked as "go tool tour".
return cp(
filepath.Join(b.root, "pkg", "tool", b.OS+"_"+b.Arch, "tour"+ext()),
filepath.Join(b.gopath, "bin", "gotour"+ext()),
)
}
func (b *Build) cleanGopath() {
for _, d := range []string{"bin", "pkg", "src"} {
os.RemoveAll(filepath.Join(b.gopath, d))
}
}
func ext() string {
if runtime.GOOS == "windows" {
return ".exe"
}
return ""
}
func (b *Build) hgCmd(dir string, args ...string) ([]byte, error) {
return b.run(dir, "hg", append([]string{"--config", "extensions.codereview=!"}, args...)...)
}
func (b *Build) run(dir, name string, args ...string) ([]byte, error) {
buf := new(bytes.Buffer)
absName, err := lookPath(name)
if err != nil {
return nil, err
}
cmd := exec.Command(absName, args...)
var output io.Writer = buf
if *verbose {
log.Printf("Running %q %q", absName, args)
output = io.MultiWriter(buf, os.Stdout)
}
cmd.Stdout = output
cmd.Stderr = output
cmd.Dir = dir
cmd.Env = b.env()
if err := cmd.Run(); err != nil {
fmt.Fprintf(os.Stderr, "%s", buf.Bytes())
return nil, fmt.Errorf("%s %s: %v", name, strings.Join(args, " "), err)
}
return buf.Bytes(), nil
}
var cleanEnv = []string{
"GOARCH",
"GOBIN",
"GOHOSTARCH",
"GOHOSTOS",
"GOOS",
"GOROOT",
"GOROOT_FINAL",
"GOPATH",
}
func (b *Build) env() []string {
env := os.Environ()
for i := 0; i < len(env); i++ {
for _, c := range cleanEnv {
if strings.HasPrefix(env[i], c+"=") {
env = append(env[:i], env[i+1:]...)
}
}
}
final := "/usr/local/go"
if b.OS == "windows" {
final = `c:\go`
}
env = append(env,
"GOARCH="+b.Arch,
"GOHOSTARCH="+b.Arch,
"GOHOSTOS="+b.OS,
"GOOS="+b.OS,
"GOROOT="+b.root,
"GOROOT_FINAL="+final,
"GOPATH="+b.gopath,
)
if b.static {
env = append(env, "GO_DISTFLAGS=-s")
}
return env
}
func (b *Build) Upload(version string, filename string) error {
file, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
svc, err := storage.New(oauthClient)
if err != nil {
return err
}
obj := &storage.Object{
Acl: []*storage.ObjectAccessControl{{Entity: "allUsers", Role: "READER"}},
Name: filename,
}
_, err = svc.Objects.Insert(*storageBucket, obj).Media(bytes.NewReader(file)).Do()
if err != nil {
return err
}
sum := fmt.Sprintf("%x", sha1.Sum(file))
kind := "unknown"
switch {
case b.Source:
kind = "source"
case strings.HasSuffix(filename, ".tar.gz"), strings.HasSuffix(filename, ".zip"):
kind = "archive"
case strings.HasSuffix(filename, ".msi"), strings.HasSuffix(filename, ".pkg"):
kind = "installer"
}
req, err := json.Marshal(File{
Filename: filename,
Version: version,
OS: b.OS,
Arch: b.Arch,
Checksum: sum,
Kind: kind,
})
if err != nil {
return err
}
u := fmt.Sprintf("%s?%s", *uploadURL, url.Values{"key": []string{builderKey}}.Encode())
resp, err := http.Post(u, "application/json", bytes.NewReader(req))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("upload status: %v", resp.Status)
}
return nil
}
type File struct {
Filename string
OS string
Arch string
Version string
Checksum string `datastore:",noindex"`
Kind string // "archive", "installer", "source"
}
func setupOAuthClient() error {
config := &oauth.Config{
ClientId: "999119582588-h7kpj5pcm6d9solh5lgrbusmvvk4m9dn.apps.googleusercontent.com",
ClientSecret: "8YLFgOhXIELWbO-NtF3iqIQz",
Scope: storage.DevstorageRead_writeScope,
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
TokenCache: oauth.CacheFile(*tokenCache),
RedirectURL: "oob",
}
transport := &oauth.Transport{Config: config}
if token, err := config.TokenCache.Token(); err != nil {
url := transport.Config.AuthCodeURL("")
fmt.Println("Visit the following URL, obtain an authentication" +
"code, and enter it below.")
fmt.Println(url)
fmt.Print("Enter authentication code: ")
code := ""
if _, err := fmt.Scan(&code); err != nil {
return err
}
if _, err := transport.Exchange(code); err != nil {
return err
}
} else {
transport.Token = token
}
oauthClient = transport.Client()
return nil
}
func (b *Build) clean(files []string) error {
for _, name := range files {
err := os.RemoveAll(filepath.Join(b.root, name))
if err != nil {
return err
}
}
return nil
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func readCredentials() error {
name := os.Getenv("HOME")
if runtime.GOOS == "windows" {
name = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
name = filepath.Join(name, ".gobuildkey")
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
if s.Scan() {
builderKey = s.Text()
}
return s.Err()
}
func cp(dst, src string) error {
sf, err := os.Open(src)
if err != nil {
return err
}
defer sf.Close()
fi, err := sf.Stat()
if err != nil {
return err
}
df, err := os.Create(dst)
if err != nil {
return err
}
defer df.Close()
// Windows doesn't currently implement Fchmod
if runtime.GOOS != "windows" {
if err := df.Chmod(fi.Mode()); err != nil {
return err
}
}
_, err = io.Copy(df, sf)
return err
}
func cpDir(dst, src string) error {
walk := func(srcPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
dstPath := filepath.Join(dst, srcPath[len(src):])
if info.IsDir() {
return os.MkdirAll(dstPath, 0755)
}
return cp(dstPath, srcPath)
}
return filepath.Walk(src, walk)
}
func cpAllDir(dst, basePath string, dirs ...string) error {
for _, dir := range dirs {
if err := cpDir(filepath.Join(dst, dir), filepath.Join(basePath, dir)); err != nil {
return err
}
}
return nil
}
func makeTar(targ, workdir string) error {
f, err := os.Create(targ)
if err != nil {
return err
}
zout := gzip.NewWriter(f)
tw := tar.NewWriter(zout)
err = filepath.Walk(workdir, func(path string, fi os.FileInfo, err error) error {
if !strings.HasPrefix(path, workdir) {
log.Panicf("walked filename %q doesn't begin with workdir %q", path, workdir)
}
name := path[len(workdir):]
// Chop of any leading / from filename, leftover from removing workdir.
if strings.HasPrefix(name, "/") {
name = name[1:]
}
// Don't include things outside of the go subdirectory (for instance,
// the zip file that we're currently writing here.)
if !strings.HasPrefix(name, "go/") {
return nil
}
if *verbose {
log.Printf("adding to tar: %s", name)
}
target, _ := os.Readlink(path)
hdr, err := tar.FileInfoHeader(fi, target)
if err != nil {
return err
}
hdr.Name = name
hdr.Uname = "root"
hdr.Gname = "root"
hdr.Uid = 0
hdr.Gid = 0
// Force permissions to 0755 for executables, 0644 for everything else.
if fi.Mode().Perm()&0111 != 0 {
hdr.Mode = hdr.Mode&^0777 | 0755
} else {
hdr.Mode = hdr.Mode&^0777 | 0644
}
err = tw.WriteHeader(hdr)
if err != nil {
return fmt.Errorf("Error writing file %q: %v", name, err)
}
if fi.IsDir() {
return nil
}
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(tw, r)
return err
})
if err != nil {
return err
}
if err := tw.Close(); err != nil {
return err
}
if err := zout.Close(); err != nil {
return err
}
return f.Close()
}
func makeZip(targ, workdir string) error {
f, err := os.Create(targ)
if err != nil {
return err
}
zw := zip.NewWriter(f)
err = filepath.Walk(workdir, func(path string, fi os.FileInfo, err error) error {
if !strings.HasPrefix(path, workdir) {
log.Panicf("walked filename %q doesn't begin with workdir %q", path, workdir)
}
name := path[len(workdir):]
// Convert to Unix-style named paths, as that's the
// type of zip file that archive/zip creates.
name = strings.Replace(name, "\\", "/", -1)
// Chop of any leading / from filename, leftover from removing workdir.
if strings.HasPrefix(name, "/") {
name = name[1:]
}
// Don't include things outside of the go subdirectory (for instance,
// the zip file that we're currently writing here.)
if !strings.HasPrefix(name, "go/") {
return nil
}
if *verbose {
log.Printf("adding to zip: %s", name)
}
fh, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
fh.Name = name
fh.Method = zip.Deflate
if fi.IsDir() {
fh.Name += "/" // append trailing slash
fh.Method = zip.Store // no need to deflate 0 byte files
}
w, err := zw.CreateHeader(fh)
if err != nil {
return err
}
if fi.IsDir() {
return nil
}
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(w, r)
return err
})
if err != nil {
return err
}
if err := zw.Close(); err != nil {
return err
}
return f.Close()
}
type tool struct {
name string
commonDirs []string
}
var wixTool = tool{
"http://wix.sourceforge.net/, version 3.5",
[]string{`C:\Program Files\Windows Installer XML v3.5\bin`,
`C:\Program Files (x86)\Windows Installer XML v3.5\bin`},
}
var hgTool = tool{
"http://mercurial.selenic.com/wiki/WindowsInstall",
[]string{`C:\Program Files\Mercurial`,
`C:\Program Files (x86)\Mercurial`,
},
}
var gccTool = tool{
"Mingw gcc; http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/",
[]string{`C:\Mingw\bin`},
}
var windowsDeps = map[string]tool{
"gcc": gccTool,
"heat": wixTool,
"candle": wixTool,
"light": wixTool,
"cmd": {"Windows cmd.exe", nil},
"hg": hgTool,
}
func checkWindowsDeps() {
for prog, help := range windowsDeps {
absPath, err := lookPath(prog)
if err != nil {
log.Fatalf("Failed to find necessary binary %q in path or common locations; %s", prog, help)
}
if *verbose {
log.Printf("found windows dep %s at %s", prog, absPath)
}
}
}
func lookPath(prog string) (absPath string, err error) {
absPath, err = exec.LookPath(prog)
if err == nil {
return
}
t, ok := windowsDeps[prog]
if !ok {
return
}
for _, dir := range t.commonDirs {
for _, ext := range []string{"exe", "bat"} {
absPath = filepath.Join(dir, prog+"."+ext)
if _, err1 := os.Stat(absPath); err1 == nil {
err = nil
os.Setenv("PATH", os.Getenv("PATH")+";"+dir)
return
}
}
}
return
}
|
[
"\"HOME\"",
"\"HOME\"",
"\"HOMEDRIVE\"",
"\"HOMEPATH\"",
"\"PATH\""
] |
[] |
[
"HOME",
"PATH",
"HOMEPATH",
"HOMEDRIVE"
] |
[]
|
["HOME", "PATH", "HOMEPATH", "HOMEDRIVE"]
|
go
| 4 | 0 | |
cni-plugin/tests/calico_cni_test.go
|
// Copyright (c) 2015-2021 Tigera, Inc. All rights reserved.
package main_test
import (
"context"
"fmt"
"io"
"math/rand"
"net"
"os"
"os/exec"
"strings"
"syscall"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/plugins/pkg/ns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
log "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
apiv3 "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
"github.com/projectcalico/calico/cni-plugin/internal/pkg/testutils"
"github.com/projectcalico/calico/cni-plugin/internal/pkg/utils"
grpc_dataplane "github.com/projectcalico/calico/cni-plugin/pkg/dataplane/grpc"
"github.com/projectcalico/calico/cni-plugin/pkg/dataplane/grpc/proto"
"github.com/projectcalico/calico/cni-plugin/pkg/dataplane/linux"
libapiv3 "github.com/projectcalico/calico/libcalico-go/lib/apis/v3"
client "github.com/projectcalico/calico/libcalico-go/lib/clientv3"
"github.com/projectcalico/calico/libcalico-go/lib/names"
"github.com/projectcalico/calico/libcalico-go/lib/options"
)
var _ = Describe("CalicoCni", func() {
hostname, _ := names.Hostname()
ctx := context.Background()
calicoClient, _ := client.NewFromEnv()
BeforeEach(func() {
if os.Getenv("DATASTORE_TYPE") == "kubernetes" {
Skip("Don't run non-kubernetes test with Kubernetes Datastore")
}
testutils.WipeDatastore()
// Create the node for these tests. The IPAM code requires a corresponding Calico node to exist.
var err error
n := libapiv3.NewNode()
n.Name, err = names.Hostname()
Expect(err).NotTo(HaveOccurred())
_, err = calicoClient.Nodes().Create(context.Background(), n, options.SetOptions{})
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
if os.Getenv("DATASTORE_TYPE") == "kubernetes" {
// no cleanup needed.
return
}
// Delete the node.
name, err := names.Hostname()
Expect(err).NotTo(HaveOccurred())
_, err = calicoClient.Nodes().Delete(context.Background(), name, options.DeleteOptions{})
Expect(err).NotTo(HaveOccurred())
})
cniVersion := os.Getenv("CNI_SPEC_VERSION")
Context("using host-local IPAM", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("successfully networks the namespace", func() {
containerID, result, contVeth, contAddresses, contRoutes, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "abc123")
Expect(err).ShouldNot(HaveOccurred())
Expect(len(result.IPs)).Should(Equal(1))
ip := result.IPs[0].Address.IP.String()
result.IPs[0].Address.IP = result.IPs[0].Address.IP.To4() // Make sure the IP is respresented as 4 bytes
Expect(result.IPs[0].Address.Mask.String()).Should(Equal("ffffffff"))
// datastore things:
// Profile is created with correct details
profile, err := calicoClient.Profiles().Get(ctx, "net1", options.GetOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(profile.Spec.LabelsToApply).Should(Equal(map[string]string{"net1": ""}))
Expect(profile.Spec.Egress).Should(Equal([]apiv3.Rule{{Action: "Allow"}}))
Expect(profile.Spec.Ingress).Should(Equal([]apiv3.Rule{{Action: "Allow", Source: apiv3.EntityRule{Selector: "has(net1)"}}}))
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
ids := names.WorkloadEndpointIdentifiers{
Node: hostname,
Orchestrator: "cni",
Endpoint: "eth0",
Pod: "",
ContainerID: containerID,
}
wrkload, err := ids.CalculateWorkloadEndpointName(false)
Expect(err).NotTo(HaveOccurred())
Expect(endpoints.Items[0].Name).Should(Equal(wrkload))
Expect(endpoints.Items[0].Namespace).Should(Equal(testutils.TEST_DEFAULT_NS))
mac := contVeth.Attrs().HardwareAddr
Expect(endpoints.Items[0].Spec).Should(Equal(libapiv3.WorkloadEndpointSpec{
InterfaceName: fmt.Sprintf("cali%s", containerID),
IPNetworks: []string{result.IPs[0].Address.String()},
MAC: mac.String(),
Profiles: []string{"net1"},
Node: hostname,
Endpoint: "eth0",
Workload: "",
ContainerID: containerID,
Orchestrator: "cni",
}))
// Routes and interface on host - there's is nothing to assert on the routes since felix adds those.
//fmt.Println(Cmd("ip link show")) // Useful for debugging
hostVethName := "cali" + containerID[:utils.Min(11, len(containerID))] //"cali" + containerID
hostVeth, err := netlink.LinkByName(hostVethName)
Expect(err).ToNot(HaveOccurred())
Expect(hostVeth.Attrs().Flags.String()).Should(ContainSubstring("up"))
Expect(hostVeth.Attrs().MTU).Should(Equal(1500))
Expect(hostVeth.Attrs().HardwareAddr.String()).Should(Equal("ee:ee:ee:ee:ee:ee"))
// Assert hostVeth sysctl values are set to what we expect for IPv4.
err = testutils.CheckSysctlValue(fmt.Sprintf("/proc/sys/net/ipv4/conf/%s/proxy_arp", hostVethName), "1")
Expect(err).ShouldNot(HaveOccurred())
err = testutils.CheckSysctlValue(fmt.Sprintf("/proc/sys/net/ipv4/neigh/%s/proxy_delay", hostVethName), "0")
Expect(err).ShouldNot(HaveOccurred())
err = testutils.CheckSysctlValue(fmt.Sprintf("/proc/sys/net/ipv4/conf/%s/forwarding", hostVethName), "1")
Expect(err).ShouldNot(HaveOccurred())
// Assert the container sysctl values are set to what we expect for IPv4.
targetNs, _ := ns.GetNS(contNs.Path())
err = targetNs.Do(func(_ ns.NetNS) error {
return testutils.CheckSysctlValue("/proc/sys/net/ipv4/ip_forward", "0")
})
Expect(err).ShouldNot(HaveOccurred())
// Assert if the host side route is programmed correctly.
hostRoutes, err := netlink.RouteList(hostVeth, syscall.AF_INET)
Expect(err).ShouldNot(HaveOccurred())
Expect(hostRoutes[0]).Should(Equal(netlink.Route{
LinkIndex: hostVeth.Attrs().Index,
Scope: netlink.SCOPE_LINK,
Dst: &result.IPs[0].Address,
Protocol: syscall.RTPROT_BOOT,
Table: syscall.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST,
Family: syscall.AF_INET,
}))
// Routes and interface in netns
Expect(contVeth.Attrs().Flags.String()).Should(ContainSubstring("up"))
// Assume the first IP is the IPv4 address
Expect(contAddresses[0].IP.String()).Should(Equal(ip))
Expect(contRoutes).Should(SatisfyAll(ContainElement(netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Gw: net.IPv4(169, 254, 1, 1).To4(),
Protocol: syscall.RTPROT_BOOT,
Table: syscall.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST,
Family: syscall.AF_INET,
}),
ContainElement(netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Scope: netlink.SCOPE_LINK,
Dst: &net.IPNet{IP: net.IPv4(169, 254, 1, 1).To4(), Mask: net.CIDRMask(32, 32)},
Protocol: syscall.RTPROT_BOOT,
Table: syscall.RT_TABLE_MAIN,
Type: syscall.RTN_UNICAST,
Family: syscall.AF_INET,
})))
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
// Make sure there are no endpoints anymore
endpoints, err = calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(0))
// Make sure the interface has been removed from the namespace
err = targetNs.Do(func(_ ns.NetNS) error {
_, err = netlink.LinkByName("eth0")
return err
})
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(Equal("Link not found"))
// Make sure the interface has been removed from the host
_, err = netlink.LinkByName("cali" + containerID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).Should(Equal("Link not found"))
})
Context("when the same hostVeth exists", func() {
It("successfully networks the namespace", func() {
containerID := fmt.Sprintf("con%d", rand.Uint32())
if err := testutils.CreateHostVeth(containerID, "", "", hostname); err != nil {
panic(err)
}
_, _, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", containerID)
Expect(err).ShouldNot(HaveOccurred())
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
})
Context("when ready flag is false", func() {
It("errors when ADD is done", func() {
ci, err := calicoClient.ClusterInformation().Get(ctx, "default", options.GetOptions{})
Expect(err).ShouldNot(HaveOccurred())
r := false
ci.Spec.DatastoreReady = &r
_, err = calicoClient.ClusterInformation().Update(ctx, ci, options.SetOptions{})
Expect(err).ShouldNot(HaveOccurred())
_, _, _, _, _, _, err = testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).Should(HaveOccurred())
})
It("errors when DEL is done", func() {
_, _, _, _, _, contNs, err := testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).ShouldNot(HaveOccurred())
ci, err := calicoClient.ClusterInformation().Get(ctx, "default", options.GetOptions{})
Expect(err).ShouldNot(HaveOccurred())
r := false
ci.Spec.DatastoreReady = &r
_, err = calicoClient.ClusterInformation().Update(ctx, ci, options.SetOptions{})
Expect(err).ShouldNot(HaveOccurred())
exitCode, err := testutils.DeleteContainer(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).ShouldNot(Equal(0))
})
})
Context("when ready flag is missing", func() {
It("errors when ADD is done", func() {
_, err := calicoClient.ClusterInformation().Delete(ctx, "default", options.DeleteOptions{})
Expect(err).ShouldNot(HaveOccurred())
_, _, _, _, _, _, err = testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).Should(HaveOccurred())
})
It("errors when DEL is done", func() {
_, _, _, _, _, contNs, err := testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).ShouldNot(HaveOccurred())
_, err = calicoClient.ClusterInformation().Delete(ctx, "default", options.DeleteOptions{})
Expect(err).ShouldNot(HaveOccurred())
exitCode, err := testutils.DeleteContainer(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).ShouldNot(Equal(0))
})
})
})
Context("With IP forwarding enabled", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"container_settings": {
"allow_ip_forwarding": true
},
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("should enable IPv4 forwarding", func() {
containerID := fmt.Sprintf("con%d", rand.Uint32())
_, _, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", containerID)
By("successfully networking the container", func() {
Expect(err).ShouldNot(HaveOccurred())
})
By("asserting IPv4 forwarding is enabled", func() {
targetNs, _ := ns.GetNS(contNs.Path())
err = targetNs.Do(func(_ ns.NetNS) error {
return testutils.CheckSysctlValue("/proc/sys/net/ipv4/ip_forward", "1")
})
Expect(err).ShouldNot(HaveOccurred())
})
By("tearing down the container", func() {
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
})
})
Context("With an invalid dataplane type", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"dataplane_options": {
"type": "invalid-dataplane-type"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("fails with an error", func() {
_, _, _, _, _, _, err := testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).Should(HaveOccurred())
})
})
Context("With a misconfigured gRPC dataplane", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"dataplane_options": {
"type": "grpc",
"socket": "unix:///tmp/xxxx-non-existent-dont-create-this-please.sock"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("fails with an error", func() {
_, _, _, _, _, _, err := testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).Should(HaveOccurred())
})
})
Context("With a gRPC dataplane", func() {
It("communicates with the dataplane", func(done Done) {
var contNs ns.NetNS
var grpcBackend *grpc_dataplane.TestServer
var exitCode int
var err error
socket := fmt.Sprintf("/tmp/cni_grpc_dataplane_test%d.sock", rand.Uint32())
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"dataplane_options": {
"type": "grpc",
"socket": "unix://%s",
"extra": "option"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"), socket)
grpcBackend, err = grpc_dataplane.StartTestServer(socket, true, "00:11:22:33:44:55")
Expect(err).ShouldNot(HaveOccurred())
Expect(grpcBackend).ShouldNot(Equal(nil))
By("sending ADD requests to the gRPC backend")
_, _, _, _, _, contNs, err = testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).ShouldNot(HaveOccurred())
message := <-grpcBackend.Received
addRequest, ok := message.(*proto.AddRequest)
Expect(ok).Should(BeTrue())
Expect(addRequest.Netns).Should(Equal(contNs.Path()))
option, ok := addRequest.DataplaneOptions["extra"]
Expect(ok).Should(BeTrue())
Expect(option).Should(Equal("option"))
Expect(len(addRequest.ContainerIps)).Should(BeNumerically(">=", 1))
By("erroring if the backend fails to cleanup an interface")
grpcBackend.SetResult(false)
exitCode, err = testutils.DeleteContainer(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).ShouldNot(Equal(0))
message = <-grpcBackend.Received
_, ok = message.(*proto.DelRequest)
Expect(ok).Should(BeTrue())
By("sending DEL requests to the gRPC backend")
grpcBackend.SetResult(true)
exitCode, err = testutils.DeleteContainer(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).Should(Equal(0))
message = <-grpcBackend.Received
delRequest, ok := message.(*proto.DelRequest)
Expect(ok).Should(BeTrue())
Expect(delRequest.Netns).Should(Equal(contNs.Path()))
option, ok = delRequest.DataplaneOptions["extra"]
Expect(ok).Should(BeTrue())
Expect(option).Should(Equal("option"))
By("erroring if the backend fails to configure an interface")
grpcBackend.SetResult(false)
_, _, _, _, _, _, err = testutils.CreateContainer(netconf, "", testutils.TEST_DEFAULT_NS, "")
Expect(err).Should(HaveOccurred())
message = <-grpcBackend.Received
_, ok = message.(*proto.AddRequest)
Expect(ok).Should(BeTrue())
grpcBackend.GracefulStop()
err = syscall.Unlink(socket)
if err != nil {
log.Printf("Failed to cleanup test socket %s: %v", socket, err)
}
close(done)
}, 30.0)
})
Context("deprecate hostname for nodename", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"hostname": "named-hostname.somewhere",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("has hostname even though deprecated", func() {
containerID, result, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "abcd1234")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result: %v\n", result)
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
ids := names.WorkloadEndpointIdentifiers{
Node: "named-hostname.somewhere",
Orchestrator: "cni",
Endpoint: "eth0",
Pod: "",
ContainerID: containerID,
}
wrkload, err := ids.CalculateWorkloadEndpointName(false)
Expect(err).NotTo(HaveOccurred())
Expect(endpoints.Items[0].Name).Should(Equal(wrkload))
Expect(endpoints.Items[0].Namespace).Should(Equal(testutils.TEST_DEFAULT_NS))
Expect(endpoints.Items[0].Spec.Node).Should(Equal("named-hostname.somewhere"))
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
netconf2 := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"hostname": "named-hostname",
"nodename": "named-nodename",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("nodename takes precedence over hostname", func() {
containerID, result, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf2, "", testutils.TEST_DEFAULT_NS, "", "abcd")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result: %v\n", result)
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
ids := names.WorkloadEndpointIdentifiers{
Node: "named-nodename",
Orchestrator: "cni",
Endpoint: "eth0",
Pod: "",
ContainerID: containerID,
}
wrkload, err := ids.CalculateWorkloadEndpointName(false)
Expect(err).NotTo(HaveOccurred())
Expect(endpoints.Items[0].Name).Should(Equal(wrkload))
Expect(endpoints.Items[0].Namespace).Should(Equal(testutils.TEST_DEFAULT_NS))
Expect(endpoints.Items[0].Spec.Node).Should(Equal("named-nodename"))
_, err = testutils.DeleteContainerWithId(netconf2, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
})
Context("Mesos Labels", func() {
It("applies mesos labels", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"hostname": "named-hostname.somewhere",
"nodename_file_optional": true,
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"args": {
"org.apache.mesos": {
"network_info": {
"labels": {
"labels": [
{
"key": "k",
"value": "v"
}
]
}
}
}
}
}`, cniVersion, os.Getenv("ETCD_IP"))
containerID, result, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "abcd1234")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result: %v\n", result)
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
Expect(endpoints.Items[0].Labels["k"]).Should(Equal("v"))
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
It("sanitizes dcos label", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"hostname": "named-hostname.somewhere",
"nodename_file_optional": true,
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"args": {
"org.apache.mesos": {
"network_info": {
"labels": {
"labels": [
{
"key": "DCOS_SPACE",
"value": "/a/b/c"
}
]
}
}
}
}
}`, cniVersion, os.Getenv("ETCD_IP"))
containerID, result, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "abcd1234")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result: %v\n", result)
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
Expect(endpoints.Items[0].Labels["DCOS_SPACE"]).Should(Equal("a.b.c"))
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
})
Context("feature flag processing", func() {
It("errors if ip_addrs_no_ipam if not running kubernetes", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"feature_control": {
"ip_addrs_no_ipam": true
},
"etcd_endpoints": "http://%s:2379",
"nodename": "named-nodename",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
containerNs, containerId, err := testutils.CreateContainerNamespace()
Expect(err).ToNot(HaveOccurred())
_, _, _, _, err = testutils.RunCNIPluginWithId(netconf, "", testutils.K8S_TEST_NS, "", containerId, "", containerNs)
Expect(err).To(HaveOccurred())
})
})
Describe("DEL", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
Context("when it was never called for SetUP", func() {
Context("and a namespace does exist", func() {
It("exits with 'success' error code", func() {
contNs, containerID, err := testutils.CreateContainerNamespace()
Expect(err).ShouldNot(HaveOccurred())
exitCode, err := testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).To(Equal(0))
})
})
Context("and no namespace exists", func() {
It("exits with 'success' error code", func() {
exitCode, err := testutils.DeleteContainer(netconf, "/not/a/real/path1234567890", "", testutils.TEST_DEFAULT_NS)
Expect(err).ShouldNot(HaveOccurred())
Expect(exitCode).To(Equal(0))
})
})
})
})
Describe("with calico-ipam enabled, after creating a container", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"datastore_type": "%s",
"log_level": "info",
"nodename_file_optional": true,
"ipam": { "type": "calico-ipam" }
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
var containerID string
var workloadName string
var endpointSpec libapiv3.WorkloadEndpointSpec
var contNs ns.NetNS
var result *current.Result
checkIPAMReservation := func() {
// IPAM reservation should still be in place.
handleID := utils.GetHandleID("net1", containerID, workloadName)
ipamIPs, err := calicoClient.IPAM().IPsByHandle(context.Background(), handleID)
ExpectWithOffset(1, err).NotTo(HaveOccurred())
ExpectWithOffset(1, ipamIPs).To(HaveLen(1),
"There should be an IPAM handle for endpoint")
ExpectWithOffset(1, ipamIPs[0].String()+"/32").To(Equal(endpointSpec.IPNetworks[0]))
}
BeforeEach(func() {
// Create a new ipPool.
testutils.MustCreateNewIPPool(calicoClient, "10.0.0.0/24", false, false, true)
var err error
log.WithField("netconf", netconf).Info("netconf")
containerID, result, _, _, _, contNs, err = testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "badbeef")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result from first ADD: %v\n", result)
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(ctx, options.ListOptions{Namespace: "default"})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).To(HaveLen(1))
ids := names.WorkloadEndpointIdentifiers{
Node: hostname,
Orchestrator: "cni",
Endpoint: "eth0",
Pod: "",
ContainerID: containerID,
}
workloadName, err = ids.CalculateWorkloadEndpointName(false)
Expect(err).NotTo(HaveOccurred())
endpoint := endpoints.Items[0]
Expect(endpoint.Name).Should(Equal(workloadName))
endpointSpec = endpoint.Spec
Expect(endpoint.Namespace).Should(Equal(testutils.TEST_DEFAULT_NS))
Expect(endpoint.Spec.Node).Should(Equal(hostname))
Expect(endpoint.Spec.Endpoint).Should(Equal("eth0"))
Expect(endpoint.Spec.ContainerID).Should(Equal(containerID))
Expect(endpoint.Spec.
Orchestrator).Should(Equal("cni"))
Expect(endpoint.Spec.Workload).Should(BeEmpty())
// IPAM reservation should have been created.
checkIPAMReservation()
})
AfterEach(func() {
_, err := testutils.DeleteContainerWithId(
netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
It("a second ADD for the same container should be a no-op", func() {
// Try to create the same container (so CNI receives the ADD for the same endpoint again)
resultSecondAdd, _, _, _, err := testutils.RunCNIPluginWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", containerID, "eth0", contNs)
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result from second ADD: %v\n", resultSecondAdd)
Expect(resultSecondAdd).Should(Equal(result))
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(context.Background(), options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
Expect(endpoints.Items[0].Spec.Profiles).To(ConsistOf("net1"))
// IPAM reservation should still be in place.
checkIPAMReservation()
})
It("a second ADD with new profile ID should append it", func() {
// Try to create the same container (so CNI receives the ADD for the same endpoint again)
tweaked := strings.Replace(netconf, "net1", "net2", 1)
resultSecondAdd, _, _, _, err := testutils.RunCNIPluginWithId(tweaked, "", "", "", containerID, "", contNs)
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result from second ADD: %v\n", resultSecondAdd)
Expect(resultSecondAdd).Should(Equal(result))
// The endpoint is created in etcd
endpoints, err := calicoClient.WorkloadEndpoints().List(context.Background(), options.ListOptions{})
Expect(err).ShouldNot(HaveOccurred())
Expect(endpoints.Items).Should(HaveLen(1))
Expect(endpoints.Items[0].Spec.Profiles).To(ConsistOf("net1", "net2"))
// IPAM reservation should still be in place.
checkIPAMReservation()
})
Context("with networking rigged to fail", func() {
BeforeEach(func() {
// To prevent the networking atempt from succeeding, rename the old veth.
// This leaves a route and an eth0 in place that the plugin will struggle with.
log.Info("Breaking networking for the created interface")
hostVeth := endpointSpec.InterfaceName
newName := strings.Replace(hostVeth, "cali", "sali", 1)
output, err := exec.Command("ip", "link", "set", hostVeth, "down").CombinedOutput()
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Output: %s", output))
output, err = exec.Command("ip", "link", "set", hostVeth, "name", newName).CombinedOutput()
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Output: %s", output))
output, err = exec.Command("ip", "link", "set", newName, "up").CombinedOutput()
Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Output: %s", output))
})
It("a second ADD for the same container should leave the datastore alone", func() {
// Try to create the same container (so CNI receives the ADD for the same endpoint again)
log.Info("Rerunning CNI plugin")
_, _, _, _, err := testutils.RunCNIPluginWithId(netconf, "", "", "", containerID, "", contNs)
Expect(err).ShouldNot(HaveOccurred())
// IPAM reservation should still be in place.
checkIPAMReservation()
})
})
})
Describe("SetupRoutes works fine when the route is already programmed", func() {
Context("container route already exists on the host", func() {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
},
"nodename_file_optional": true,
"log_level":"info"
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
It("route setup should be resilient to existing route", func() {
By("creating a CNI networked container, which should also install the container route in the host namespace")
containerID, result, _, _, _, contNs, err := testutils.CreateContainerWithId(netconf, "", testutils.TEST_DEFAULT_NS, "", "meep1337")
Expect(err).ShouldNot(HaveOccurred())
log.Printf("Unmarshalled result: %v\n", result)
// CNI plugin generates host side vEth name from containerID if used for "cni" orchestrator.
hostVethName := "cali" + containerID[:utils.Min(11, len(containerID))] //"cali" + containerID
hostVeth, err := netlink.LinkByName(hostVethName)
Expect(err).ToNot(HaveOccurred())
By("setting up the same route CNI plugin installed in the initial run for the hostVeth")
err = linux.SetupRoutes(hostVeth, result)
Expect(err).NotTo(HaveOccurred())
_, err = testutils.DeleteContainerWithId(netconf, contNs.Path(), "", testutils.TEST_DEFAULT_NS, containerID)
Expect(err).ShouldNot(HaveOccurred())
})
})
})
Describe("testConnection tests", func() {
It("successfully connects to the datastore", func(done Done) {
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2379",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
pluginPath := fmt.Sprintf("%s/%s", os.Getenv("BIN"), os.Getenv("PLUGIN"))
c := exec.Command(pluginPath, "-t")
stdin, err := c.StdinPipe()
Expect(err).ToNot(HaveOccurred())
go func() {
defer stdin.Close()
_, _ = io.WriteString(stdin, netconf)
}()
_, err = c.CombinedOutput()
Expect(err).ToNot(HaveOccurred())
close(done)
}, 10)
It("reports it cannot connect to the datastore", func(done Done) {
// wrong port.
netconf := fmt.Sprintf(`
{
"cniVersion": "%s",
"name": "net1",
"type": "calico",
"etcd_endpoints": "http://%s:2370",
"log_level": "info",
"nodename_file_optional": true,
"datastore_type": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.0.0.0/8"
}
}`, cniVersion, os.Getenv("ETCD_IP"), os.Getenv("DATASTORE_TYPE"))
pluginPath := fmt.Sprintf("%s/%s", os.Getenv("BIN"), os.Getenv("PLUGIN"))
c := exec.Command(pluginPath, "-t")
stdin, err := c.StdinPipe()
Expect(err).ToNot(HaveOccurred())
go func() {
defer stdin.Close()
_, _ = io.WriteString(stdin, netconf)
}()
_, err = c.CombinedOutput()
Expect(err).To(HaveOccurred())
close(done)
}, 10)
})
})
|
[
"\"DATASTORE_TYPE\"",
"\"DATASTORE_TYPE\"",
"\"CNI_SPEC_VERSION\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"ETCD_IP\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"BIN\"",
"\"PLUGIN\"",
"\"ETCD_IP\"",
"\"DATASTORE_TYPE\"",
"\"BIN\"",
"\"PLUGIN\""
] |
[] |
[
"CNI_SPEC_VERSION",
"BIN",
"PLUGIN",
"DATASTORE_TYPE",
"ETCD_IP"
] |
[]
|
["CNI_SPEC_VERSION", "BIN", "PLUGIN", "DATASTORE_TYPE", "ETCD_IP"]
|
go
| 5 | 0 | |
examples/httpclient/main.go
|
package main
import (
"context"
"os"
"golang.org/x/oauth2"
"github.com/rxnew/go-oauth2x"
)
func main() {
c := &oauth2.Config{
ClientID: os.Getenv("OAUTH2_CLIENT_ID"),
ClientSecret: os.Getenv("OAUTH2_CLIENT_SECRET"),
Endpoint: oauth2.Endpoint{
AuthURL: os.Getenv("OAUTH2_AUTH_URL"),
TokenURL: os.Getenv("OAUTH2_TOKEN_URL"),
},
}
ctx := context.Background()
cli := oauth2x.NewClient(ctx, c.TokenSource(ctx, nil))
resp, err := cli.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
}
|
[
"\"OAUTH2_CLIENT_ID\"",
"\"OAUTH2_CLIENT_SECRET\"",
"\"OAUTH2_AUTH_URL\"",
"\"OAUTH2_TOKEN_URL\""
] |
[] |
[
"OAUTH2_TOKEN_URL",
"OAUTH2_CLIENT_ID",
"OAUTH2_AUTH_URL",
"OAUTH2_CLIENT_SECRET"
] |
[]
|
["OAUTH2_TOKEN_URL", "OAUTH2_CLIENT_ID", "OAUTH2_AUTH_URL", "OAUTH2_CLIENT_SECRET"]
|
go
| 4 | 0 | |
lxd/instance/drivers/driver_lxc.go
|
package drivers
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/flosch/pongo2"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
liblxc "gopkg.in/lxc/go-lxc.v2"
yaml "gopkg.in/yaml.v2"
"github.com/lxc/lxd/lxd/apparmor"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/cgroup"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/daemon"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/db/query"
"github.com/lxc/lxd/lxd/device"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/instance"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/instance/operationlock"
"github.com/lxc/lxd/lxd/maas"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/seccomp"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
"github.com/lxc/lxd/lxd/template"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/containerwriter"
"github.com/lxc/lxd/shared/idmap"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/netutils"
"github.com/lxc/lxd/shared/osarch"
"github.com/lxc/lxd/shared/units"
)
// Helper functions
func lxcSetConfigItem(c *liblxc.Container, key string, value string) error {
if c == nil {
return fmt.Errorf("Uninitialized go-lxc struct")
}
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
switch key {
case "lxc.uts.name":
key = "lxc.utsname"
case "lxc.pty.max":
key = "lxc.pts"
case "lxc.tty.dir":
key = "lxc.devttydir"
case "lxc.tty.max":
key = "lxc.tty"
case "lxc.apparmor.profile":
key = "lxc.aa_profile"
case "lxc.apparmor.allow_incomplete":
key = "lxc.aa_allow_incomplete"
case "lxc.selinux.context":
key = "lxc.se_context"
case "lxc.mount.fstab":
key = "lxc.mount"
case "lxc.console.path":
key = "lxc.console"
case "lxc.seccomp.profile":
key = "lxc.seccomp"
case "lxc.signal.halt":
key = "lxc.haltsignal"
case "lxc.signal.reboot":
key = "lxc.rebootsignal"
case "lxc.signal.stop":
key = "lxc.stopsignal"
case "lxc.log.syslog":
key = "lxc.syslog"
case "lxc.log.level":
key = "lxc.loglevel"
case "lxc.log.file":
key = "lxc.logfile"
case "lxc.init.cmd":
key = "lxc.init_cmd"
case "lxc.init.uid":
key = "lxc.init_uid"
case "lxc.init.gid":
key = "lxc.init_gid"
case "lxc.idmap":
key = "lxc.id_map"
}
}
if strings.HasPrefix(key, "lxc.prlimit.") {
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
return fmt.Errorf(`Process limits require liblxc >= 2.1`)
}
}
err := c.SetConfigItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set LXC config: %s=%s", key, value)
}
return nil
}
func lxcStatusCode(state liblxc.State) api.StatusCode {
return map[int]api.StatusCode{
1: api.Stopped,
2: api.Starting,
3: api.Running,
4: api.Stopping,
5: api.Aborting,
6: api.Freezing,
7: api.Frozen,
8: api.Thawed,
9: api.Error,
}[int(state)]
}
// Loader functions
func lxcCreate(s *state.State, args db.InstanceArgs) (instance.Instance, error) {
// Create the container struct
c := &lxc{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
node: args.Node,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
dbType: args.Type,
snapshot: args.Snapshot,
stateful: args.Stateful,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
expiryDate: args.ExpiryDate,
}
// Cleanup the zero values
if c.expiryDate.IsZero() {
c.expiryDate = time.Time{}
}
if c.creationDate.IsZero() {
c.creationDate = time.Time{}
}
if c.lastUsedDate.IsZero() {
c.lastUsedDate = time.Time{}
}
ctxMap := log.Ctx{
"project": args.Project,
"name": c.name,
"ephemeral": c.ephemeral,
}
logger.Info("Creating container", ctxMap)
// Load the config
err := c.init()
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
// Validate expanded config
err = instance.ValidConfig(s.OS, c.expandedConfig, false, true)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
err = instance.ValidDevices(s, s.Cluster, c.Type(), c.expandedDevices, true)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, errors.Wrap(err, "Invalid devices")
}
// Retrieve the container's storage pool
_, rootDiskDevice, err := shared.GetRootDiskDevice(c.expandedDevices.CloneNative())
if err != nil {
c.Delete()
return nil, err
}
if rootDiskDevice["pool"] == "" {
c.Delete()
return nil, fmt.Errorf("The container's root device is missing the pool property")
}
storagePool := rootDiskDevice["pool"]
// Get the storage pool ID for the container
poolID, dbPool, err := s.Cluster.StoragePoolGet(storagePool)
if err != nil {
c.Delete()
return nil, err
}
// Fill in any default volume config
volumeConfig := map[string]string{}
err = storagePools.VolumeFillDefault(storagePool, volumeConfig, dbPool)
if err != nil {
c.Delete()
return nil, err
}
// Create a new database entry for the container's storage volume
_, err = s.Cluster.StoragePoolVolumeCreate(args.Project, args.Name, "", db.StoragePoolVolumeTypeContainer, c.IsSnapshot(), poolID, volumeConfig)
if err != nil {
c.Delete()
return nil, err
}
// Initialize the container storage.
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
c.Delete()
s.Cluster.StoragePoolVolumeDelete(args.Project, args.Name, db.StoragePoolVolumeTypeContainer, poolID)
logger.Error("Failed to initialize container storage", ctxMap)
return nil, err
}
c.storagePool = pool
// Setup initial idmap config
var idmap *idmap.IdmapSet
base := int64(0)
if !c.IsPrivileged() {
idmap, base, err = findIdmap(
s,
args.Name,
c.expandedConfig["security.idmap.isolated"],
c.expandedConfig["security.idmap.base"],
c.expandedConfig["security.idmap.size"],
c.expandedConfig["raw.idmap"],
)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
err = c.VolatileSet(map[string]string{"volatile.idmap.next": jsonIdmap})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
err = c.VolatileSet(map[string]string{"volatile.idmap.base": fmt.Sprintf("%v", base)})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
// Invalid idmap cache
c.idmapset = nil
// Set last_state if not currently set
if c.localConfig["volatile.last_state.idmap"] == "" {
err = c.VolatileSet(map[string]string{"volatile.last_state.idmap": "[]"})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
// Re-run init to update the idmap
err = c.init()
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
if !c.IsSnapshot() {
// Add devices to container.
for k, m := range c.expandedDevices {
err = c.deviceAdd(k, m)
if err != nil && err != device.ErrUnsupportedDevType {
c.Delete()
return nil, errors.Wrapf(err, "Failed to add device '%s'", k)
}
}
// Update MAAS (must run after the MAC addresses have been generated).
err = c.maasUpdate(nil)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
logger.Info("Created container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-created",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return c, nil
}
func lxcLoad(s *state.State, args db.InstanceArgs, profiles []api.Profile) (instance.Instance, error) {
// Create the container struct
c := lxcInstantiate(s, args, nil)
// Setup finalizer
runtime.SetFinalizer(c, lxcUnload)
// Expand config and devices
err := c.(*lxc).expandConfig(profiles)
if err != nil {
return nil, err
}
err = c.(*lxc).expandDevices(profiles)
if err != nil {
return nil, err
}
return c, nil
}
// Unload is called by the garbage collector
func lxcUnload(c *lxc) {
runtime.SetFinalizer(c, nil)
if c.c != nil {
c.c.Release()
c.c = nil
}
}
// Create a container struct without initializing it.
func lxcInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices) instance.Instance {
c := &lxc{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
dbType: args.Type,
snapshot: args.Snapshot,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
stateful: args.Stateful,
node: args.Node,
expiryDate: args.ExpiryDate,
}
// Cleanup the zero values
if c.expiryDate.IsZero() {
c.expiryDate = time.Time{}
}
if c.creationDate.IsZero() {
c.creationDate = time.Time{}
}
if c.lastUsedDate.IsZero() {
c.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
c.expandedDevices = expandedDevices
}
return c
}
// The LXC container driver.
type lxc struct {
// Properties
architecture int
dbType instancetype.Type
snapshot bool
creationDate time.Time
lastUsedDate time.Time
ephemeral bool
id int
project string
name string
description string
stateful bool
// Config
expandedConfig map[string]string
expandedDevices deviceConfig.Devices
fromHook bool
localConfig map[string]string
localDevices deviceConfig.Devices
profiles []string
// Cache
c *liblxc.Container
cConfig bool
state *state.State
idmapset *idmap.IdmapSet
// Storage
// Do not use this variable directly, instead use their associated get functions so they
// will be initialised on demand.
storagePool storagePools.Pool
// Clustering
node string
// Progress tracking
op *operations.Operation
expiryDate time.Time
}
// Type returns the instance type.
func (c *lxc) Type() instancetype.Type {
return c.dbType
}
func idmapSize(state *state.State, isolatedStr string, size string) (int64, error) {
isolated := false
if shared.IsTrue(isolatedStr) {
isolated = true
}
var idMapSize int64
if size == "" || size == "auto" {
if isolated {
idMapSize = 65536
} else {
if len(state.OS.IdmapSet.Idmap) != 2 {
return 0, fmt.Errorf("bad initial idmap: %v", state.OS.IdmapSet)
}
idMapSize = state.OS.IdmapSet.Idmap[0].Maprange
}
} else {
size, err := strconv.ParseInt(size, 10, 64)
if err != nil {
return 0, err
}
idMapSize = size
}
return idMapSize, nil
}
var idmapLock sync.Mutex
func findIdmap(state *state.State, cName string, isolatedStr string, configBase string, configSize string, rawIdmap string) (*idmap.IdmapSet, int64, error) {
isolated := false
if shared.IsTrue(isolatedStr) {
isolated = true
}
rawMaps, err := instance.ParseRawIdmap(rawIdmap)
if err != nil {
return nil, 0, err
}
if !isolated {
newIdmapset := idmap.IdmapSet{Idmap: make([]idmap.IdmapEntry, len(state.OS.IdmapSet.Idmap))}
copy(newIdmapset.Idmap, state.OS.IdmapSet.Idmap)
for _, ent := range rawMaps {
err := newIdmapset.AddSafe(ent)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
}
return &newIdmapset, 0, nil
}
size, err := idmapSize(state, isolatedStr, configSize)
if err != nil {
return nil, 0, err
}
mkIdmap := func(offset int64, size int64) (*idmap.IdmapSet, error) {
set := &idmap.IdmapSet{Idmap: []idmap.IdmapEntry{
{Isuid: true, Nsid: 0, Hostid: offset, Maprange: size},
{Isgid: true, Nsid: 0, Hostid: offset, Maprange: size},
}}
for _, ent := range rawMaps {
err := set.AddSafe(ent)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, err
}
}
return set, nil
}
if configBase != "" {
offset, err := strconv.ParseInt(configBase, 10, 64)
if err != nil {
return nil, 0, err
}
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
idmapLock.Lock()
defer idmapLock.Unlock()
cts, err := instance.LoadNodeAll(state, instancetype.Container)
if err != nil {
return nil, 0, err
}
offset := state.OS.IdmapSet.Idmap[0].Hostid + 65536
mapentries := idmap.ByHostid{}
for _, container := range cts {
if container.Type() != instancetype.Container {
continue
}
name := container.Name()
/* Don't change our map Just Because. */
if name == cName {
continue
}
if container.IsPrivileged() {
continue
}
if !shared.IsTrue(container.ExpandedConfig()["security.idmap.isolated"]) {
continue
}
cBase := int64(0)
if container.ExpandedConfig()["volatile.idmap.base"] != "" {
cBase, err = strconv.ParseInt(container.ExpandedConfig()["volatile.idmap.base"], 10, 64)
if err != nil {
return nil, 0, err
}
}
cSize, err := idmapSize(state, container.ExpandedConfig()["security.idmap.isolated"], container.ExpandedConfig()["security.idmap.size"])
if err != nil {
return nil, 0, err
}
mapentries = append(mapentries, &idmap.IdmapEntry{Hostid: int64(cBase), Maprange: cSize})
}
sort.Sort(mapentries)
for i := range mapentries {
if i == 0 {
if mapentries[0].Hostid < offset+size {
offset = mapentries[0].Hostid + mapentries[0].Maprange
continue
}
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
if mapentries[i-1].Hostid+mapentries[i-1].Maprange > offset {
offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange
continue
}
offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange
if offset+size < mapentries[i].Hostid {
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
offset = mapentries[i].Hostid + mapentries[i].Maprange
}
if offset+size < state.OS.IdmapSet.Idmap[0].Hostid+state.OS.IdmapSet.Idmap[0].Maprange {
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
return nil, 0, fmt.Errorf("Not enough uid/gid available for the container")
}
func (c *lxc) init() error {
// Compute the expanded config and device list
err := c.expandConfig(nil)
if err != nil {
return err
}
err = c.expandDevices(nil)
if err != nil {
return err
}
return nil
}
func (c *lxc) initLXC(config bool) error {
// No need to go through all that for snapshots
if c.IsSnapshot() {
return nil
}
// Check if being called from a hook
if c.fromHook {
return fmt.Errorf("You can't use go-lxc from inside a LXC hook")
}
// Check if already initialized
if c.c != nil {
if !config || c.cConfig {
return nil
}
}
// Load the go-lxc struct
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err != nil {
return err
}
// Load cgroup abstraction
cg, err := c.cgroup(cc)
if err != nil {
return err
}
freeContainer := true
defer func() {
if freeContainer {
cc.Release()
}
}()
// Setup logging
logfile := c.LogFilePath()
err = lxcSetConfigItem(cc, "lxc.log.file", logfile)
if err != nil {
return err
}
logLevel := "warn"
if daemon.Debug {
logLevel = "trace"
} else if daemon.Verbose {
logLevel = "info"
}
err = lxcSetConfigItem(cc, "lxc.log.level", logLevel)
if err != nil {
return err
}
if util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
// Default size log buffer
err = lxcSetConfigItem(cc, "lxc.console.buffer.size", "auto")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.console.size", "auto")
if err != nil {
return err
}
// File to dump ringbuffer contents to when requested or
// container shutdown.
consoleBufferLogFile := c.ConsoleBufferLogPath()
err = lxcSetConfigItem(cc, "lxc.console.logfile", consoleBufferLogFile)
if err != nil {
return err
}
}
// Allow for lightweight init
c.cConfig = config
if !config {
if c.c != nil {
c.c.Release()
}
c.c = cc
freeContainer = false
return nil
}
if c.IsPrivileged() {
// Base config
toDrop := "sys_time sys_module sys_rawio"
if !c.state.OS.AppArmorStacking || c.state.OS.AppArmorStacked {
toDrop = toDrop + " mac_admin mac_override"
}
err = lxcSetConfigItem(cc, "lxc.cap.drop", toDrop)
if err != nil {
return err
}
}
// Set an appropriate /proc, /sys/ and /sys/fs/cgroup
mounts := []string{}
if c.IsPrivileged() && !c.state.OS.RunningInUserNS {
mounts = append(mounts, "proc:mixed")
mounts = append(mounts, "sys:mixed")
} else {
mounts = append(mounts, "proc:rw")
mounts = append(mounts, "sys:rw")
}
cgInfo := cgroup.GetInfo()
if cgInfo.Namespacing {
if cgInfo.Layout == cgroup.CgroupsUnified {
mounts = append(mounts, "cgroup:rw:force")
} else {
mounts = append(mounts, "cgroup:mixed")
}
} else {
mounts = append(mounts, "cgroup:mixed")
}
err = lxcSetConfigItem(cc, "lxc.mount.auto", strings.Join(mounts, " "))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.autodev", "1")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.pty.max", "1024")
if err != nil {
return err
}
bindMounts := []string{
"/dev/fuse",
"/dev/net/tun",
"/proc/sys/fs/binfmt_misc",
"/sys/firmware/efi/efivars",
"/sys/fs/fuse/connections",
"/sys/fs/pstore",
"/sys/kernel/debug",
"/sys/kernel/security"}
if c.IsPrivileged() && !c.state.OS.RunningInUserNS {
err = lxcSetConfigItem(cc, "lxc.mount.entry", "mqueue dev/mqueue mqueue rw,relatime,create=dir,optional 0 0")
if err != nil {
return err
}
} else {
bindMounts = append(bindMounts, "/dev/mqueue")
}
for _, mnt := range bindMounts {
if !shared.PathExists(mnt) {
continue
}
if shared.IsDir(mnt) {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none rbind,create=dir,optional 0 0", mnt, strings.TrimPrefix(mnt, "/")))
if err != nil {
return err
}
} else {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file,optional 0 0", mnt, strings.TrimPrefix(mnt, "/")))
if err != nil {
return err
}
}
}
// For lxcfs
templateConfDir := os.Getenv("LXD_LXC_TEMPLATE_CONFIG")
if templateConfDir == "" {
templateConfDir = "/usr/share/lxc/config"
}
if shared.PathExists(fmt.Sprintf("%s/common.conf.d/", templateConfDir)) {
err = lxcSetConfigItem(cc, "lxc.include", fmt.Sprintf("%s/common.conf.d/", templateConfDir))
if err != nil {
return err
}
}
// Configure devices cgroup
if c.IsPrivileged() && !c.state.OS.RunningInUserNS && c.state.OS.CGInfo.Supports(cgroup.Devices, cg) {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.deny", "a")
if err != nil {
return err
}
devices := []string{
"b *:* m", // Allow mknod of block devices
"c *:* m", // Allow mknod of char devices
"c 136:* rwm", // /dev/pts devices
"c 1:3 rwm", // /dev/null
"c 1:5 rwm", // /dev/zero
"c 1:7 rwm", // /dev/full
"c 1:8 rwm", // /dev/random
"c 1:9 rwm", // /dev/urandom
"c 5:0 rwm", // /dev/tty
"c 5:1 rwm", // /dev/console
"c 5:2 rwm", // /dev/ptmx
"c 10:229 rwm", // /dev/fuse
"c 10:200 rwm", // /dev/net/tun
}
for _, dev := range devices {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev)
if err != nil {
return err
}
}
}
if c.IsNesting() {
/*
* mount extra /proc and /sys to work around kernel
* restrictions on remounting them when covered
*/
err = lxcSetConfigItem(cc, "lxc.mount.entry", "proc dev/.lxc/proc proc create=dir,optional 0 0")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.mount.entry", "sys dev/.lxc/sys sysfs create=dir,optional 0 0")
if err != nil {
return err
}
}
// Setup architecture
personality, err := osarch.ArchitecturePersonality(c.architecture)
if err != nil {
personality, err = osarch.ArchitecturePersonality(c.state.OS.Architectures[0])
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.arch", personality)
if err != nil {
return err
}
// Setup the hooks
err = lxcSetConfigItem(cc, "lxc.hook.version", "1")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("/proc/%d/exe callhook %s %d start", os.Getpid(), shared.VarPath(""), c.id))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.stop", fmt.Sprintf("%s callhook %s %d stopns", c.state.OS.ExecPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %d stop", c.state.OS.ExecPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
// Setup the console
err = lxcSetConfigItem(cc, "lxc.tty.max", "0")
if err != nil {
return err
}
// Setup the hostname
err = lxcSetConfigItem(cc, "lxc.uts.name", c.Name())
if err != nil {
return err
}
// Setup devlxd
if c.expandedConfig["security.devlxd"] == "" || shared.IsTrue(c.expandedConfig["security.devlxd"]) {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/lxd none bind,create=dir 0 0", shared.VarPath("devlxd")))
if err != nil {
return err
}
}
// Setup AppArmor
if c.state.OS.AppArmorAvailable {
if c.state.OS.AppArmorConfined || !c.state.OS.AppArmorAdmin {
// If confined but otherwise able to use AppArmor, use our own profile
curProfile := util.AppArmorProfile()
curProfile = strings.TrimSuffix(curProfile, " (enforce)")
err := lxcSetConfigItem(cc, "lxc.apparmor.profile", curProfile)
if err != nil {
return err
}
} else {
// If not currently confined, use the container's profile
profile := apparmor.ProfileFull(c)
/* In the nesting case, we want to enable the inside
* LXD to load its profile. Unprivileged containers can
* load profiles, but privileged containers cannot, so
* let's not use a namespace so they can fall back to
* the old way of nesting, i.e. using the parent's
* profile.
*/
if c.state.OS.AppArmorStacking && !c.state.OS.AppArmorStacked {
profile = fmt.Sprintf("%s//&:%s:", profile, apparmor.Namespace(c))
}
err := lxcSetConfigItem(cc, "lxc.apparmor.profile", profile)
if err != nil {
return err
}
}
}
// Setup Seccomp if necessary
if seccomp.InstanceNeedsPolicy(c) {
err = lxcSetConfigItem(cc, "lxc.seccomp.profile", seccomp.ProfilePath(c))
if err != nil {
return err
}
// Setup notification socket
// System requirement errors are handled during policy generation instead of here
ok, err := seccomp.InstanceNeedsIntercept(c.state, c)
if err == nil && ok {
err = lxcSetConfigItem(cc, "lxc.seccomp.notify.proxy", fmt.Sprintf("unix:%s", shared.VarPath("seccomp.socket")))
if err != nil {
return err
}
}
}
// Setup idmap
idmapset, err := c.NextIdmap()
if err != nil {
return err
}
if idmapset != nil {
lines := idmapset.ToLxcString()
for _, line := range lines {
err := lxcSetConfigItem(cc, "lxc.idmap", line)
if err != nil {
return err
}
}
}
// Setup environment
for k, v := range c.expandedConfig {
if strings.HasPrefix(k, "environment.") {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("%s=%s", strings.TrimPrefix(k, "environment."), v))
if err != nil {
return err
}
}
}
// Setup NVIDIA runtime
if shared.IsTrue(c.expandedConfig["nvidia.runtime"]) {
hookDir := os.Getenv("LXD_LXC_HOOK")
if hookDir == "" {
hookDir = "/usr/share/lxc/hooks"
}
hookPath := filepath.Join(hookDir, "nvidia")
if !shared.PathExists(hookPath) {
return fmt.Errorf("The NVIDIA LXC hook couldn't be found")
}
_, err := exec.LookPath("nvidia-container-cli")
if err != nil {
return fmt.Errorf("The NVIDIA container tools couldn't be found")
}
err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_VISIBLE_DEVICES=none")
if err != nil {
return err
}
nvidiaDriver := c.expandedConfig["nvidia.driver.capabilities"]
if nvidiaDriver == "" {
err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_DRIVER_CAPABILITIES=compute,utility")
if err != nil {
return err
}
} else {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_DRIVER_CAPABILITIES=%s", nvidiaDriver))
if err != nil {
return err
}
}
nvidiaRequireCuda := c.expandedConfig["nvidia.require.cuda"]
if nvidiaRequireCuda == "" {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_CUDA=%s", nvidiaRequireCuda))
if err != nil {
return err
}
}
nvidiaRequireDriver := c.expandedConfig["nvidia.require.driver"]
if nvidiaRequireDriver == "" {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_DRIVER=%s", nvidiaRequireDriver))
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.hook.mount", hookPath)
if err != nil {
return err
}
}
// Memory limits
if c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
// Configure the memory limits
if memory != "" {
var valueInt int64
if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := shared.DeviceTotalMemory()
if err != nil {
return err
}
valueInt = int64((memoryTotal / 100) * percent)
} else {
valueInt, err = units.ParseByteSizeString(memory)
if err != nil {
return err
}
}
if memoryEnforce == "soft" {
err = cg.SetMemorySoftLimit(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryMaxUsage(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
err = cg.SetMemorySwapMax(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
err = cg.SetMemoryMaxUsage(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
}
// Set soft limit to value 10% less than hard limit
err = cg.SetMemorySoftLimit(fmt.Sprintf("%.0f", float64(valueInt)*0.9))
if err != nil {
return err
}
}
}
if c.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) {
// Configure the swappiness
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = cg.SetMemorySwappiness("0")
if err != nil {
return err
}
} else if memorySwapPriority != "" {
priority, err := strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
err = cg.SetMemorySwappiness(fmt.Sprintf("%d", 60-10+priority))
if err != nil {
return err
}
}
}
}
// CPU limits
cpuPriority := c.expandedConfig["limits.cpu.priority"]
cpuAllowance := c.expandedConfig["limits.cpu.allowance"]
if (cpuPriority != "" || cpuAllowance != "") && c.state.OS.CGInfo.Supports(cgroup.CPU, cg) {
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(cpuAllowance, cpuPriority)
if err != nil {
return err
}
if cpuShares != "1024" {
err = cg.SetCPUShare(cpuShares)
if err != nil {
return err
}
}
if cpuCfsPeriod != "-1" {
err = cg.SetCPUCfsPeriod(cpuCfsPeriod)
if err != nil {
return err
}
}
if cpuCfsQuota != "-1" {
err = cg.SetCPUCfsQuota(cpuCfsQuota)
if err != nil {
return err
}
}
}
// Processes
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
processes := c.expandedConfig["limits.processes"]
if processes != "" {
valueInt, err := strconv.ParseInt(processes, 10, 64)
if err != nil {
return err
}
err = cg.SetMaxProcesses(valueInt)
if err != nil {
return err
}
}
}
// Hugepages
if c.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) {
for i, key := range shared.HugePageSizeKeys {
value := c.expandedConfig[key]
if value != "" {
valueInt, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
value = fmt.Sprintf("%d", valueInt)
err = cg.SetMaxHugepages(shared.HugePageSizeSuffix[i], value)
if err != nil {
return err
}
}
}
}
// Setup process limits
for k, v := range c.expandedConfig {
if strings.HasPrefix(k, "limits.kernel.") {
prlimitSuffix := strings.TrimPrefix(k, "limits.kernel.")
prlimitKey := fmt.Sprintf("lxc.prlimit.%s", prlimitSuffix)
err = lxcSetConfigItem(cc, prlimitKey, v)
if err != nil {
return err
}
}
}
// Setup shmounts
if c.state.OS.LXCFeatures["mount_injection_file"] {
err = lxcSetConfigItem(cc, "lxc.mount.auto", fmt.Sprintf("shmounts:%s:/dev/.lxd-mounts", c.ShmountsPath()))
} else {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", c.ShmountsPath()))
}
if err != nil {
return err
}
// Apply raw.lxc
if lxcConfig, ok := c.expandedConfig["raw.lxc"]; ok {
f, err := ioutil.TempFile("", "lxd_config_")
if err != nil {
return err
}
err = shared.WriteAll(f, []byte(lxcConfig))
f.Close()
defer os.Remove(f.Name())
if err != nil {
return err
}
if err := cc.LoadConfigFile(f.Name()); err != nil {
return fmt.Errorf("Failed to load raw.lxc")
}
}
if c.c != nil {
c.c.Release()
}
c.c = cc
freeContainer = false
return nil
}
func (c *lxc) devlxdEventSend(eventType string, eventMessage interface{}) error {
event := shared.Jmap{}
event["type"] = eventType
event["timestamp"] = time.Now()
event["metadata"] = eventMessage
return c.state.DevlxdEvents.Send(strconv.Itoa(c.ID()), eventType, eventMessage)
}
// runHooks executes the callback functions returned from a function.
func (c *lxc) runHooks(hooks []func() error) error {
// Run any post start hooks.
if len(hooks) > 0 {
for _, hook := range hooks {
err := hook()
if err != nil {
return err
}
}
}
return nil
}
// RegisterDevices calls the Register() function on all of the instance's devices.
func (c *lxc) RegisterDevices() {
devices := c.ExpandedDevices()
for _, dev := range devices.Sorted() {
d, _, err := c.deviceLoad(dev.Name, dev.Config)
if err == device.ErrUnsupportedDevType {
continue
}
if err != nil {
logger.Error("Failed to load device to register", log.Ctx{"err": err, "instance": c.Name(), "device": dev.Name})
continue
}
// Check whether device wants to register for any events.
err = d.Register()
if err != nil {
logger.Error("Failed to register device", log.Ctx{"err": err, "instance": c.Name(), "device": dev.Name})
continue
}
}
}
// deviceLoad instantiates and validates a new device and returns it along with enriched config.
func (c *lxc) deviceLoad(deviceName string, rawConfig deviceConfig.Device) (device.Device, deviceConfig.Device, error) {
var configCopy deviceConfig.Device
var err error
// Create copy of config and load some fields from volatile if device is nic or infiniband.
if shared.StringInSlice(rawConfig["type"], []string{"nic", "infiniband"}) {
configCopy, err = c.FillNetworkDevice(deviceName, rawConfig)
if err != nil {
return nil, nil, err
}
} else {
// Othewise copy the config so it cannot be modified by device.
configCopy = rawConfig.Clone()
}
d, err := device.New(c, c.state, deviceName, configCopy, c.deviceVolatileGetFunc(deviceName), c.deviceVolatileSetFunc(deviceName))
// Return device and config copy even if error occurs as caller may still use device.
return d, configCopy, err
}
// deviceAdd loads a new device and calls its Add() function.
func (c *lxc) deviceAdd(deviceName string, rawConfig deviceConfig.Device) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
return d.Add()
}
// deviceStart loads a new device and calls its Start() function. After processing the runtime
// config returned from Start(), it also runs the device's Register() function irrespective of
// whether the container is running or not.
func (c *lxc) deviceStart(deviceName string, rawConfig deviceConfig.Device, isRunning bool) (*deviceConfig.RunConfig, error) {
d, configCopy, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return nil, err
}
if canHotPlug, _ := d.CanHotPlug(); isRunning && !canHotPlug {
return nil, fmt.Errorf("Device cannot be started when container is running")
}
runConf, err := d.Start()
if err != nil {
return nil, err
}
// If runConf supplied, perform any container specific setup of device.
if runConf != nil {
// Shift device file ownership if needed before mounting into container.
// This needs to be done whether or not container is running.
if len(runConf.Mounts) > 0 {
err := c.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// If container is running and then live attach device.
if isRunning {
// Attach mounts if requested.
if len(runConf.Mounts) > 0 {
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err = c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return nil, err
}
}
// Attach network interface if requested.
if len(runConf.NetworkInterface) > 0 {
err = c.deviceAttachNIC(configCopy, runConf.NetworkInterface)
if err != nil {
return nil, err
}
}
// If running, run post start hooks now (if not running LXD will run them
// once the instance is started).
err = c.runHooks(runConf.PostHooks)
if err != nil {
return nil, err
}
}
}
return runConf, nil
}
// deviceStaticShiftMounts statically shift device mount files ownership to active idmap if needed.
func (c *lxc) deviceStaticShiftMounts(mounts []deviceConfig.MountEntryItem) error {
idmapSet, err := c.CurrentIdmap()
if err != nil {
return fmt.Errorf("Failed to get idmap for device: %s", err)
}
// If there is an idmap being applied and LXD not running in a user namespace then shift the
// device files before they are mounted.
if idmapSet != nil && !c.state.OS.RunningInUserNS {
for _, mount := range mounts {
// Skip UID/GID shifting if OwnerShift mode is not static, or the host-side
// DevPath is empty (meaning an unmount request that doesn't need shifting).
if mount.OwnerShift != deviceConfig.MountOwnerShiftStatic || mount.DevPath == "" {
continue
}
err := idmapSet.ShiftFile(mount.DevPath)
if err != nil {
// uidshift failing is weird, but not a big problem. Log and proceed.
logger.Debugf("Failed to uidshift device %s: %s\n", mount.DevPath, err)
}
}
}
return nil
}
// deviceAddCgroupRules live adds cgroup rules to a container.
func (c *lxc) deviceAddCgroupRules(cgroups []deviceConfig.RunConfigItem) error {
cg, err := c.cgroup(nil)
if err != nil {
return err
}
for _, rule := range cgroups {
// Only apply devices cgroup rules if container is running privileged and host has devices cgroup controller.
if strings.HasPrefix(rule.Key, "devices.") && (!c.isCurrentlyPrivileged() || c.state.OS.RunningInUserNS || !c.state.OS.CGInfo.Supports(cgroup.Devices, cg)) {
continue
}
// Add the new device cgroup rule.
err := c.CGroupSet(rule.Key, rule.Value)
if err != nil {
return fmt.Errorf("Failed to add cgroup rule for device")
}
}
return nil
}
// deviceAttachNIC live attaches a NIC device to a container.
func (c *lxc) deviceAttachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem) error {
devName := ""
for _, dev := range netIF {
if dev.Key == "link" {
devName = dev.Value
break
}
}
if devName == "" {
return fmt.Errorf("Device didn't provide a link property to use")
}
// Load the go-lxc struct.
err := c.initLXC(false)
if err != nil {
return err
}
// Add the interface to the container.
err = c.c.AttachInterface(devName, configCopy["name"])
if err != nil {
return fmt.Errorf("Failed to attach interface: %s to %s: %s", devName, configCopy["name"], err)
}
return nil
}
// deviceUpdate loads a new device and calls its Update() function.
func (c *lxc) deviceUpdate(deviceName string, rawConfig deviceConfig.Device, oldDevices deviceConfig.Devices, isRunning bool) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
err = d.Update(oldDevices, isRunning)
if err != nil {
return err
}
return nil
}
// deviceStop loads a new device and calls its Stop() function.
func (c *lxc) deviceStop(deviceName string, rawConfig deviceConfig.Device, stopHookNetnsPath string) error {
d, configCopy, err := c.deviceLoad(deviceName, rawConfig)
// If deviceLoad fails with unsupported device type then return.
if err == device.ErrUnsupportedDevType {
return err
}
// If deviceLoad fails for any other reason then just log the error and proceed, as in the
// scenario that a new version of LXD has additional validation restrictions than older
// versions we still need to allow previously valid devices to be stopped.
if err != nil {
// If there is no device returned, then we cannot proceed, so return as error.
if d == nil {
return fmt.Errorf("Device stop validation failed for '%s': %v", deviceName, err)
}
logger.Errorf("Device stop validation failed for '%s': %v", deviceName, err)
}
canHotPlug, _ := d.CanHotPlug()
// An empty netns path means we haven't been called from the LXC stop hook, so are running.
if stopHookNetnsPath == "" && !canHotPlug {
return fmt.Errorf("Device cannot be stopped when container is running")
}
runConf, err := d.Stop()
if err != nil {
return err
}
if runConf != nil {
// If network interface settings returned, then detach NIC from container.
if len(runConf.NetworkInterface) > 0 {
err = c.deviceDetachNIC(configCopy, runConf.NetworkInterface, stopHookNetnsPath)
if err != nil {
return err
}
}
// Add cgroup rules if requested and container is running.
if len(runConf.CGroups) > 0 && stopHookNetnsPath == "" {
err = c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Detach mounts if requested and container is running.
if len(runConf.Mounts) > 0 && stopHookNetnsPath == "" {
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Run post stop hooks irrespective of run state of instance.
err = c.runHooks(runConf.PostHooks)
if err != nil {
return err
}
}
return nil
}
// deviceDetachNIC detaches a NIC device from a container.
func (c *lxc) deviceDetachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem, stopHookNetnsPath string) error {
// Get requested device name to detach interface back to on the host.
devName := ""
for _, dev := range netIF {
if dev.Key == "link" {
devName = dev.Value
break
}
}
if devName == "" {
return fmt.Errorf("Device didn't provide a link property to use")
}
// If container is running, perform live detach of interface back to host.
if stopHookNetnsPath == "" {
// For some reason, having network config confuses detach, so get our own go-lxc struct.
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err != nil {
return err
}
defer cc.Release()
// Get interfaces inside container.
ifaces, err := cc.Interfaces()
if err != nil {
return fmt.Errorf("Failed to list network interfaces: %v", err)
}
// If interface doesn't exist inside container, cannot proceed.
if !shared.StringInSlice(configCopy["name"], ifaces) {
return nil
}
err = cc.DetachInterfaceRename(configCopy["name"], devName)
if err != nil {
return errors.Wrapf(err, "Failed to detach interface: %s to %s", configCopy["name"], devName)
}
} else {
// Currently liblxc does not move devices back to the host on stop that were added
// after the the container was started. For this reason we utilise the lxc.hook.stop
// hook so that we can capture the netns path, enter the namespace and move the nics
// back to the host and rename them if liblxc hasn't already done it.
// We can only move back devices that have an expected host_name record and where
// that device doesn't already exist on the host as if a device exists on the host
// we can't know whether that is because liblxc has moved it back already or whether
// it is a conflicting device.
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", devName)) {
err := c.detachInterfaceRename(stopHookNetnsPath, configCopy["name"], devName)
if err != nil {
return errors.Wrapf(err, "Failed to detach interface: %s to %s", configCopy["name"], devName)
}
}
}
return nil
}
// deviceHandleMounts live attaches or detaches mounts on a container.
// If the mount DevPath is empty the mount action is treated as unmount.
func (c *lxc) deviceHandleMounts(mounts []deviceConfig.MountEntryItem) error {
for _, mount := range mounts {
if mount.DevPath != "" {
flags := 0
// Convert options into flags.
for _, opt := range mount.Opts {
if opt == "bind" {
flags |= unix.MS_BIND
} else if opt == "rbind" {
flags |= unix.MS_BIND | unix.MS_REC
}
}
shiftfs := false
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic {
shiftfs = true
}
// Mount it into the container.
err := c.insertMount(mount.DevPath, mount.TargetPath, mount.FSType, flags, shiftfs)
if err != nil {
return fmt.Errorf("Failed to add mount for device inside container: %s", err)
}
} else {
relativeTargetPath := strings.TrimPrefix(mount.TargetPath, "/")
if c.FileExists(relativeTargetPath) == nil {
err := c.removeMount(mount.TargetPath)
if err != nil {
return fmt.Errorf("Error unmounting the device path inside container: %s", err)
}
err = c.FileRemove(relativeTargetPath)
if err != nil {
// Only warn here and don't fail as removing a directory
// mount may fail if there was already files inside
// directory before it was mouted over preventing delete.
logger.Warnf("Could not remove the device path inside container: %s", err)
}
}
}
}
return nil
}
// deviceRemove loads a new device and calls its Remove() function.
func (c *lxc) deviceRemove(deviceName string, rawConfig deviceConfig.Device) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
// If deviceLoad fails with unsupported device type then return.
if err == device.ErrUnsupportedDevType {
return err
}
// If deviceLoad fails for any other reason then just log the error and proceed, as in the
// scenario that a new version of LXD has additional validation restrictions than older
// versions we still need to allow previously valid devices to be stopped.
if err != nil {
logger.Errorf("Device remove validation failed for '%s': %v", deviceName, err)
}
return d.Remove()
}
// deviceVolatileGetFunc returns a function that retrieves a named device's volatile config and
// removes its device prefix from the keys.
func (c *lxc) deviceVolatileGetFunc(devName string) func() map[string]string {
return func() map[string]string {
volatile := make(map[string]string)
prefix := fmt.Sprintf("volatile.%s.", devName)
for k, v := range c.localConfig {
if strings.HasPrefix(k, prefix) {
volatile[strings.TrimPrefix(k, prefix)] = v
}
}
return volatile
}
}
// deviceVolatileSetFunc returns a function that can be called to save a named device's volatile
// config using keys that do not have the device's name prefixed.
func (c *lxc) deviceVolatileSetFunc(devName string) func(save map[string]string) error {
return func(save map[string]string) error {
volatileSave := make(map[string]string)
for k, v := range save {
volatileSave[fmt.Sprintf("volatile.%s.%s", devName, k)] = v
}
return c.VolatileSet(volatileSave)
}
}
// deviceResetVolatile resets a device's volatile data when its removed or updated in such a way
// that it is removed then added immediately afterwards.
func (c *lxc) deviceResetVolatile(devName string, oldConfig, newConfig deviceConfig.Device) error {
volatileClear := make(map[string]string)
devicePrefix := fmt.Sprintf("volatile.%s.", devName)
// If the device type has changed, remove all old volatile keys.
// This will occur if the newConfig is empty (i.e the device is actually being removed) or
// if the device type is being changed but keeping the same name.
if newConfig["type"] != oldConfig["type"] || newConfig.NICType() != oldConfig.NICType() {
for k := range c.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
volatileClear[k] = ""
}
return c.VolatileSet(volatileClear)
}
// If the device type remains the same, then just remove any volatile keys that have
// the same key name present in the new config (i.e the new config is replacing the
// old volatile key).
for k := range c.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
devKey := strings.TrimPrefix(k, devicePrefix)
if _, found := newConfig[devKey]; found {
volatileClear[k] = ""
}
}
return c.VolatileSet(volatileClear)
}
// DeviceEventHandler actions the results of a RunConfig after an event has occurred on a device.
func (c *lxc) DeviceEventHandler(runConf *deviceConfig.RunConfig) error {
// Device events can only be processed when the container is running.
if !c.IsRunning() {
return nil
}
if runConf == nil {
return nil
}
// Shift device file ownership if needed before mounting devices into container.
if len(runConf.Mounts) > 0 {
err := c.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return err
}
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err := c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Run any post hooks requested.
err := c.runHooks(runConf.PostHooks)
if err != nil {
return err
}
// Generate uevent inside container if requested.
if len(runConf.Uevents) > 0 {
for _, eventParts := range runConf.Uevents {
ueventArray := make([]string, 4)
ueventArray[0] = "forkuevent"
ueventArray[1] = "inject"
ueventArray[2] = fmt.Sprintf("%d", c.InitPID())
length := 0
for _, part := range eventParts {
length = length + len(part) + 1
}
ueventArray[3] = fmt.Sprintf("%d", length)
ueventArray = append(ueventArray, eventParts...)
_, err := shared.RunCommand(c.state.OS.ExecPath, ueventArray...)
if err != nil {
return err
}
}
}
return nil
}
// Config handling
func (c *lxc) expandConfig(profiles []api.Profile) error {
if profiles == nil && len(c.profiles) > 0 {
var err error
profiles, err = c.state.Cluster.ProfilesGet(c.project, c.profiles)
if err != nil {
return err
}
}
c.expandedConfig = db.ProfilesExpandConfig(c.localConfig, profiles)
return nil
}
func (c *lxc) expandDevices(profiles []api.Profile) error {
if profiles == nil && len(c.profiles) > 0 {
var err error
profiles, err = c.state.Cluster.ProfilesGet(c.project, c.profiles)
if err != nil {
return err
}
}
c.expandedDevices = db.ProfilesExpandDevices(c.localDevices, profiles)
return nil
}
// Start functions
func (c *lxc) startCommon() (string, []func() error, error) {
var ourStart bool
postStartHooks := []func() error{}
// Load the go-lxc struct
err := c.initLXC(true)
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Load go-lxc struct")
}
// Check that we're not already running
if c.IsRunning() {
return "", postStartHooks, fmt.Errorf("The container is already running")
}
// Load any required kernel modules
kernelModules := c.expandedConfig["linux.kernel_modules"]
if kernelModules != "" {
for _, module := range strings.Split(kernelModules, ",") {
module = strings.TrimPrefix(module, " ")
err := util.LoadModule(module)
if err != nil {
return "", postStartHooks, fmt.Errorf("Failed to load kernel module '%s': %s", module, err)
}
}
}
/* Deal with idmap changes */
nextIdmap, err := c.NextIdmap()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Set ID map")
}
diskIdmap, err := c.DiskIdmap()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Set last ID map")
}
if !nextIdmap.Equals(diskIdmap) && !(diskIdmap == nil && c.state.OS.Shiftfs) {
if shared.IsTrue(c.expandedConfig["security.protection.shift"]) {
return "", postStartHooks, fmt.Errorf("Container is protected against filesystem shifting")
}
logger.Debugf("Container idmap changed, remapping")
c.updateProgress("Remapping container filesystem")
ourStart, err = c.mount()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Storage start")
}
storageType, err := c.getStorageType()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Storage type")
}
if diskIdmap != nil {
if storageType == "zfs" {
err = diskIdmap.UnshiftRootfs(c.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.UnshiftBtrfsRootfs(c.RootfsPath(), diskIdmap)
} else {
err = diskIdmap.UnshiftRootfs(c.RootfsPath(), nil)
}
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
}
if nextIdmap != nil && !c.state.OS.Shiftfs {
if storageType == "zfs" {
err = nextIdmap.ShiftRootfs(c.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.ShiftBtrfsRootfs(c.RootfsPath(), nextIdmap)
} else {
err = nextIdmap.ShiftRootfs(c.RootfsPath(), nil)
}
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
}
jsonDiskIdmap := "[]"
if nextIdmap != nil && !c.state.OS.Shiftfs {
idmapBytes, err := json.Marshal(nextIdmap.Idmap)
if err != nil {
return "", postStartHooks, err
}
jsonDiskIdmap = string(idmapBytes)
}
err = c.VolatileSet(map[string]string{"volatile.last_state.idmap": jsonDiskIdmap})
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Set volatile.last_state.idmap config key on container %q (id %d)", c.name, c.id)
}
c.updateProgress("")
}
var idmapBytes []byte
if nextIdmap == nil {
idmapBytes = []byte("[]")
} else {
idmapBytes, err = json.Marshal(nextIdmap.Idmap)
if err != nil {
return "", postStartHooks, err
}
}
if c.localConfig["volatile.idmap.current"] != string(idmapBytes) {
err = c.VolatileSet(map[string]string{"volatile.idmap.current": string(idmapBytes)})
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Set volatile.idmap.current config key on container %q (id %d)", c.name, c.id)
}
}
// Generate the Seccomp profile
if err := seccomp.CreateProfile(c.state, c); err != nil {
return "", postStartHooks, err
}
// Cleanup any existing leftover devices
c.removeUnixDevices()
c.removeDiskDevices()
// Create any missing directories.
err = os.MkdirAll(c.LogPath(), 0700)
if err != nil {
return "", postStartHooks, err
}
err = os.MkdirAll(c.DevicesPath(), 0711)
if err != nil {
return "", postStartHooks, err
}
err = os.MkdirAll(c.ShmountsPath(), 0711)
if err != nil {
return "", postStartHooks, err
}
// Create the devices
nicID := -1
// Setup devices in sorted order, this ensures that device mounts are added in path order.
for _, dev := range c.expandedDevices.Sorted() {
// Start the device.
runConf, err := c.deviceStart(dev.Name, dev.Config, false)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
if runConf == nil {
continue
}
// Process rootfs setup.
if runConf.RootFS.Path != "" {
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
// Set the rootfs backend type if supported (must happen before any other lxc.rootfs)
err := lxcSetConfigItem(c.c, "lxc.rootfs.backend", "dir")
if err == nil {
value := c.c.ConfigItem("lxc.rootfs.backend")
if len(value) == 0 || value[0] != "dir" {
lxcSetConfigItem(c.c, "lxc.rootfs.backend", "")
}
}
}
if util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
rootfsPath := fmt.Sprintf("dir:%s", runConf.RootFS.Path)
err = lxcSetConfigItem(c.c, "lxc.rootfs.path", rootfsPath)
} else {
err = lxcSetConfigItem(c.c, "lxc.rootfs", runConf.RootFS.Path)
}
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
if len(runConf.RootFS.Opts) > 0 {
err = lxcSetConfigItem(c.c, "lxc.rootfs.options", strings.Join(runConf.RootFS.Opts, ","))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
}
if c.state.OS.Shiftfs && !c.IsPrivileged() && diskIdmap == nil {
// Host side mark mount.
err = lxcSetConfigItem(c.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", c.RootfsPath(), c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Container side shift mount.
err = lxcSetConfigItem(c.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", c.RootfsPath(), c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Host side umount of mark mount.
err = lxcSetConfigItem(c.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
}
}
// Pass any cgroups rules into LXC.
if len(runConf.CGroups) > 0 {
for _, rule := range runConf.CGroups {
err = lxcSetConfigItem(c.c, fmt.Sprintf("lxc.cgroup.%s", rule.Key), rule.Value)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device cgroup '%s'", dev.Name)
}
}
}
// Pass any mounts into LXC.
if len(runConf.Mounts) > 0 {
for _, mount := range runConf.Mounts {
if shared.StringInSlice("propagation", mount.Opts) && !util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
return "", postStartHooks, errors.Wrapf(fmt.Errorf("liblxc 3.0 is required for mount propagation configuration"), "Failed to setup device mount '%s'", dev.Name)
}
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic && !c.IsPrivileged() {
if !c.state.OS.Shiftfs {
return "", postStartHooks, errors.Wrapf(fmt.Errorf("shiftfs is required but isn't supported on system"), "Failed to setup device mount '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", mount.DevPath, mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", mount.DevPath, mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
}
mntVal := fmt.Sprintf("%s %s %s %s %d %d", shared.EscapePathFstab(mount.DevPath), shared.EscapePathFstab(mount.TargetPath), mount.FSType, strings.Join(mount.Opts, ","), mount.Freq, mount.PassNo)
err = lxcSetConfigItem(c.c, "lxc.mount.entry", mntVal)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount '%s'", dev.Name)
}
}
}
// Pass any network setup config into LXC.
if len(runConf.NetworkInterface) > 0 {
// Increment nicID so that LXC network index is unique per device.
nicID++
networkKeyPrefix := "lxc.net"
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
networkKeyPrefix = "lxc.network"
}
for _, nicItem := range runConf.NetworkInterface {
err = lxcSetConfigItem(c.c, fmt.Sprintf("%s.%d.%s", networkKeyPrefix, nicID, nicItem.Key), nicItem.Value)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device network interface '%s'", dev.Name)
}
}
}
// Add any post start hooks.
if len(runConf.PostHooks) > 0 {
postStartHooks = append(postStartHooks, runConf.PostHooks...)
}
}
// Rotate the log file
logfile := c.LogFilePath()
if shared.PathExists(logfile) {
os.Remove(logfile + ".old")
err := os.Rename(logfile, logfile+".old")
if err != nil {
return "", postStartHooks, err
}
}
// Storage is guaranteed to be mountable now (must be called after devices setup).
ourStart, err = c.mount()
if err != nil {
return "", postStartHooks, err
}
// Generate the LXC config
configPath := filepath.Join(c.LogPath(), "lxc.conf")
err = c.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return "", postStartHooks, err
}
// Set ownership to match container root
currentIdmapset, err := c.CurrentIdmap()
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
uid := int64(0)
if currentIdmapset != nil {
uid, _ = currentIdmapset.ShiftFromNs(0, 0)
}
err = os.Chown(c.Path(), int(uid), 0)
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// We only need traversal by root in the container
err = os.Chmod(c.Path(), 0100)
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// Update the backup.yaml file
err = c.UpdateBackupFile()
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// If starting stateless, wipe state
if !c.IsStateful() && shared.PathExists(c.StatePath()) {
os.RemoveAll(c.StatePath())
}
// Unmount any previously mounted shiftfs
unix.Unmount(c.RootfsPath(), unix.MNT_DETACH)
return configPath, postStartHooks, nil
}
// detachInterfaceRename enters the container's network namespace and moves the named interface
// in ifName back to the network namespace of the running process as the name specified in hostName.
func (c *lxc) detachInterfaceRename(netns string, ifName string, hostName string) error {
lxdPID := os.Getpid()
// Run forknet detach
_, err := shared.RunCommand(
c.state.OS.ExecPath,
"forknet",
"detach",
netns,
fmt.Sprintf("%d", lxdPID),
ifName,
hostName,
)
// Process forknet detach response
if err != nil {
return err
}
return nil
}
// Start starts the instance.
func (c *lxc) Start(stateful bool) error {
var ctxMap log.Ctx
// Setup a new operation
op, err := operationlock.Create(c.id, "start", false, false)
if err != nil {
return errors.Wrap(err, "Create container start operation")
}
defer op.Done(nil)
if !daemon.SharedMountsSetup {
return fmt.Errorf("Daemon failed to setup shared mounts base: %v. Does security.nesting need to be turned on?", err)
}
// Run the shared start code
configPath, postStartHooks, err := c.startCommon()
if err != nil {
return errors.Wrap(err, "Common start logic")
}
// Ensure that the container storage volume is mounted.
_, err = c.mount()
if err != nil {
return errors.Wrap(err, "Storage start")
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": op.Action(),
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": stateful}
logger.Info("Starting container", ctxMap)
// If stateful, restore now
if stateful {
if !c.stateful {
return fmt.Errorf("Container has no existing state to restore")
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: c.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
err := c.Migrate(&criuMigrationArgs)
if err != nil && !c.IsRunning() {
return errors.Wrap(err, "Migrate")
}
os.RemoveAll(c.StatePath())
c.stateful = false
err = c.state.Cluster.ContainerSetStateful(c.id, false)
if err != nil {
logger.Error("Failed starting container", ctxMap)
return errors.Wrap(err, "Start container")
}
// Run any post start hooks.
err = c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
op.Done(err)
c.Stop(false)
return err
}
logger.Info("Started container", ctxMap)
return nil
} else if c.stateful {
/* stateless start required when we have state, let's delete it */
err := os.RemoveAll(c.StatePath())
if err != nil {
return err
}
c.stateful = false
err = c.state.Cluster.ContainerSetStateful(c.id, false)
if err != nil {
return errors.Wrap(err, "Persist stateful flag")
}
}
name := project.Instance(c.Project(), c.name)
// Start the LXC container
_, err = shared.RunCommand(
c.state.OS.ExecPath,
"forkstart",
name,
c.state.OS.LxcPath,
configPath)
if err != nil && !c.IsRunning() {
// Attempt to extract the LXC errors
lxcLog := ""
logPath := filepath.Join(c.LogPath(), "lxc.log")
if shared.PathExists(logPath) {
logContent, err := ioutil.ReadFile(logPath)
if err == nil {
for _, line := range strings.Split(string(logContent), "\n") {
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
// We only care about errors
if fields[2] != "ERROR" {
continue
}
// Prepend the line break
if len(lxcLog) == 0 {
lxcLog += "\n"
}
lxcLog += fmt.Sprintf(" %s\n", strings.Join(fields[0:], " "))
}
}
}
logger.Error("Failed starting container", ctxMap)
// Return the actual error
return err
}
// Run any post start hooks.
err = c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
op.Done(err)
c.Stop(false)
return err
}
logger.Info("Started container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-started",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// OnHook is the top-level hook handler.
func (c *lxc) OnHook(hookName string, args map[string]string) error {
switch hookName {
case instance.HookStart:
return c.onStart(args)
case instance.HookStopNS:
return c.onStopNS(args)
case instance.HookStop:
return c.onStop(args)
default:
return instance.ErrNotImplemented
}
}
// onStart implements the start hook.
func (c *lxc) onStart(_ map[string]string) error {
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Start the storage for this container
ourStart, err := c.mount()
if err != nil {
return err
}
// Load the container AppArmor profile
err = apparmor.LoadProfile(c.state, c)
if err != nil {
if ourStart {
c.unmount()
}
return err
}
// Template anything that needs templating
key := "volatile.apply_template"
if c.localConfig[key] != "" {
// Run any template that needs running
err = c.templateApplyNow(c.localConfig[key])
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
// Remove the volatile key from the DB
err := c.state.Cluster.ContainerConfigRemove(c.id, key)
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
}
err = c.templateApplyNow("start")
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", c.name, "started")
// Apply network priority
if c.expandedConfig["limits.network.priority"] != "" {
go func(c *lxc) {
c.fromHook = false
err := c.setNetworkPriority()
if err != nil {
logger.Error("Failed to apply network priority", log.Ctx{"container": c.name, "err": err})
}
}(c)
}
// Database updates
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
// Record current state
err = tx.ContainerSetState(c.id, "RUNNING")
if err != nil {
return errors.Wrap(err, "Error updating container state")
}
// Update time container last started time
err = tx.ContainerLastUsedUpdate(c.id, time.Now().UTC())
if err != nil {
return errors.Wrap(err, "Error updating last used")
}
return nil
})
if err != nil {
return err
}
return nil
}
// Stop functions
func (c *lxc) Stop(stateful bool) error {
var ctxMap log.Ctx
// Check that we're not already stopped
if !c.IsRunning() {
return fmt.Errorf("The container is already stopped")
}
// Setup a new operation
op, err := operationlock.Create(c.id, "stop", false, true)
if err != nil {
return err
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": op.Action(),
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": stateful}
logger.Info("Stopping container", ctxMap)
// Handle stateful stop
if stateful {
// Cleanup any existing state
stateDir := c.StatePath()
os.RemoveAll(stateDir)
err := os.MkdirAll(stateDir, 0700)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_DUMP,
StateDir: stateDir,
Function: "snapshot",
Stop: true,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint
err = c.Migrate(&criuMigrationArgs)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed stopping container", ctxMap)
return err
}
c.stateful = true
err = c.state.Cluster.ContainerSetStateful(c.id, true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
op.Done(nil)
logger.Info("Stopped container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-stopped",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
} else if shared.PathExists(c.StatePath()) {
os.RemoveAll(c.StatePath())
}
// Load the go-lxc struct
if c.expandedConfig["raw.lxc"] != "" {
err = c.initLXC(true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
} else {
err = c.initLXC(false)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
}
// Load cgroup abstraction
cg, err := c.cgroup(nil)
if err != nil {
op.Done(err)
return err
}
// Fork-bomb mitigation, prevent forking from this point on
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
// Attempt to disable forking new processes
cg.SetMaxProcesses(0)
} else if c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
// Attempt to freeze the container
freezer := make(chan bool, 1)
go func() {
c.Freeze()
freezer <- true
}()
select {
case <-freezer:
case <-time.After(time.Second * 5):
c.Unfreeze()
}
}
if err := c.c.Stop(); err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed stopping container", ctxMap)
return err
}
logger.Info("Stopped container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-stopped",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// Shutdown stops the instance.
func (c *lxc) Shutdown(timeout time.Duration) error {
var ctxMap log.Ctx
// Check that we're not already stopped
if !c.IsRunning() {
return fmt.Errorf("The container is already stopped")
}
// Setup a new operation
op, err := operationlock.Create(c.id, "stop", true, true)
if err != nil {
return err
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": "shutdown",
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"timeout": timeout}
logger.Info("Shutting down container", ctxMap)
// Load the go-lxc struct
if c.expandedConfig["raw.lxc"] != "" {
err = c.initLXC(true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
} else {
err = c.initLXC(false)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
}
if err := c.c.Shutdown(timeout); err != nil {
op.Done(err)
logger.Error("Failed shutting down container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed shutting down container", ctxMap)
return err
}
logger.Info("Shut down container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-shutdown",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// onStopNS is triggered by LXC's stop hook once a container is shutdown but before the container's
// namespaces have been closed. The netns path of the stopped container is provided.
func (c *lxc) onStopNS(args map[string]string) error {
target := args["target"]
netns := args["netns"]
// Validate target
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
logger.Error("Container sent invalid target to OnStopNS", log.Ctx{"container": c.Name(), "target": target})
return fmt.Errorf("Invalid stop target: %s", target)
}
// Clean up devices.
c.cleanupDevices(netns)
return nil
}
// onStop is triggered by LXC's post-stop hook once a container is shutdown and after the
// container's namespaces have been closed.
func (c *lxc) onStop(args map[string]string) error {
target := args["target"]
// Validate target
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
logger.Error("Container sent invalid target to OnStop", log.Ctx{"container": c.Name(), "target": target})
return fmt.Errorf("Invalid stop target: %s", target)
}
// Pick up the existing stop operation lock created in Stop() function.
op := operationlock.Get(c.id)
if op != nil && op.Action() != "stop" {
return fmt.Errorf("Container is already running a %s operation", op.Action())
}
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Remove directory ownership (to avoid issue if uidmap is re-used)
err := os.Chown(c.Path(), 0, 0)
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
err = os.Chmod(c.Path(), 0100)
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
// Stop the storage for this container
_, err = c.unmount()
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
// Log user actions
if op == nil {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"action": target,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": false}
logger.Info(fmt.Sprintf("Container initiated %s", target), ctxMap)
}
// Record power state
err = c.state.Cluster.ContainerSetState(c.id, "STOPPED")
if err != nil {
logger.Error("Failed to set container state", log.Ctx{"container": c.Name(), "err": err})
}
go func(c *lxc, target string, op *operationlock.InstanceOperation) {
c.fromHook = false
err = nil
// Unlock on return
if op != nil {
defer op.Done(err)
}
// Wait for other post-stop actions to be done
c.IsRunning()
// Unload the apparmor profile
err = apparmor.Destroy(c.state, c)
if err != nil {
logger.Error("Failed to destroy apparmor namespace", log.Ctx{"container": c.Name(), "err": err})
}
// Clean all the unix devices
err = c.removeUnixDevices()
if err != nil {
logger.Error("Unable to remove unix devices", log.Ctx{"container": c.Name(), "err": err})
}
// Clean all the disk devices
err = c.removeDiskDevices()
if err != nil {
logger.Error("Unable to remove disk devices", log.Ctx{"container": c.Name(), "err": err})
}
// Reboot the container
if target == "reboot" {
// Start the container again
err = c.Start(false)
return
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", c.name, "stopped")
// Destroy ephemeral containers
if c.ephemeral {
err = c.Delete()
}
}(c, target, op)
return nil
}
// cleanupDevices performs any needed device cleanup steps when container is stopped.
func (c *lxc) cleanupDevices(netns string) {
for _, dev := range c.expandedDevices.Sorted() {
// Use the device interface if device supports it.
err := c.deviceStop(dev.Name, dev.Config, netns)
if err == device.ErrUnsupportedDevType {
continue
} else if err != nil {
logger.Errorf("Failed to stop device '%s': %v", dev.Name, err)
}
}
}
// Freeze functions.
func (c *lxc) Freeze() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
// Check that we're running
if !c.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
logger.Info("Unable to freeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're not already frozen
if c.IsFrozen() {
return fmt.Errorf("The container is already frozen")
}
logger.Info("Freezing container", ctxMap)
// Load the go-lxc struct
err = c.initLXC(false)
if err != nil {
ctxMap["err"] = err
logger.Error("Failed freezing container", ctxMap)
return err
}
err = c.c.Freeze()
if err != nil {
ctxMap["err"] = err
logger.Error("Failed freezing container", ctxMap)
return err
}
logger.Info("Froze container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-paused",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return err
}
// Unfreeze unfreezes the instance.
func (c *lxc) Unfreeze() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
// Check that we're running
if !c.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
logger.Info("Unable to unfreeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're frozen
if !c.IsFrozen() {
return fmt.Errorf("The container is already running")
}
logger.Info("Unfreezing container", ctxMap)
// Load the go-lxc struct
err = c.initLXC(false)
if err != nil {
logger.Error("Failed unfreezing container", ctxMap)
return err
}
err = c.c.Unfreeze()
if err != nil {
logger.Error("Failed unfreezing container", ctxMap)
}
logger.Info("Unfroze container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-resumed",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return err
}
// Get lxc container state, with 1 second timeout
// If we don't get a reply, assume the lxc monitor is hung
func (c *lxc) getLxcState() (liblxc.State, error) {
if c.IsSnapshot() {
return liblxc.StateMap["STOPPED"], nil
}
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return liblxc.StateMap["STOPPED"], err
}
monitor := make(chan liblxc.State, 1)
go func(c *liblxc.Container) {
monitor <- c.State()
}(c.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return liblxc.StateMap["FROZEN"], fmt.Errorf("Monitor is hung")
}
}
// Render renders the state of the instance.
func (c *lxc) Render() (interface{}, interface{}, error) {
// Ignore err as the arch string on error is correct (unknown)
architectureName, _ := osarch.ArchitectureName(c.architecture)
if c.IsSnapshot() {
// Prepare the ETag
etag := []interface{}{c.expiryDate}
ct := api.InstanceSnapshot{
CreatedAt: c.creationDate,
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices.CloneNative(),
LastUsedAt: c.lastUsedDate,
Name: strings.SplitN(c.name, "/", 2)[1],
Stateful: c.stateful,
}
ct.Architecture = architectureName
ct.Config = c.localConfig
ct.Devices = c.localDevices.CloneNative()
ct.Ephemeral = c.ephemeral
ct.Profiles = c.profiles
ct.ExpiresAt = c.expiryDate
return &ct, etag, nil
}
// Prepare the ETag
etag := []interface{}{c.architecture, c.localConfig, c.localDevices, c.ephemeral, c.profiles}
// FIXME: Render shouldn't directly access the go-lxc struct
cState, err := c.getLxcState()
if err != nil {
return nil, nil, errors.Wrap(err, "Get container stated")
}
statusCode := lxcStatusCode(cState)
ct := api.Instance{
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices.CloneNative(),
Name: c.name,
Status: statusCode.String(),
StatusCode: statusCode,
Location: c.node,
Type: c.Type().String(),
}
ct.Description = c.description
ct.Architecture = architectureName
ct.Config = c.localConfig
ct.CreatedAt = c.creationDate
ct.Devices = c.localDevices.CloneNative()
ct.Ephemeral = c.ephemeral
ct.LastUsedAt = c.lastUsedDate
ct.Profiles = c.profiles
ct.Stateful = c.stateful
return &ct, etag, nil
}
// RenderFull renders the full state of the instance.
func (c *lxc) RenderFull() (*api.InstanceFull, interface{}, error) {
if c.IsSnapshot() {
return nil, nil, fmt.Errorf("RenderFull only works with containers")
}
// Get the Container struct
base, etag, err := c.Render()
if err != nil {
return nil, nil, err
}
// Convert to ContainerFull
ct := api.InstanceFull{Instance: *base.(*api.Instance)}
// Add the ContainerState
ct.State, err = c.RenderState()
if err != nil {
return nil, nil, err
}
// Add the ContainerSnapshots
snaps, err := c.Snapshots()
if err != nil {
return nil, nil, err
}
for _, snap := range snaps {
render, _, err := snap.Render()
if err != nil {
return nil, nil, err
}
if ct.Snapshots == nil {
ct.Snapshots = []api.InstanceSnapshot{}
}
ct.Snapshots = append(ct.Snapshots, *render.(*api.InstanceSnapshot))
}
// Add the ContainerBackups
backups, err := c.Backups()
if err != nil {
return nil, nil, err
}
for _, backup := range backups {
render := backup.Render()
if ct.Backups == nil {
ct.Backups = []api.InstanceBackup{}
}
ct.Backups = append(ct.Backups, *render)
}
return &ct, etag, nil
}
// RenderState renders just the running state of the instance.
func (c *lxc) RenderState() (*api.InstanceState, error) {
cState, err := c.getLxcState()
if err != nil {
return nil, err
}
statusCode := lxcStatusCode(cState)
status := api.InstanceState{
Status: statusCode.String(),
StatusCode: statusCode,
}
if c.IsRunning() {
pid := c.InitPID()
status.CPU = c.cpuState()
status.Memory = c.memoryState()
status.Network = c.networkState()
status.Pid = int64(pid)
status.Processes = c.processesState()
}
status.Disk = c.diskState()
return &status, nil
}
// Snapshots returns the snapshots of the instance.
func (c *lxc) Snapshots() ([]instance.Instance, error) {
var snaps []db.Instance
if c.IsSnapshot() {
return []instance.Instance{}, nil
}
// Get all the snapshots
err := c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
snaps, err = tx.ContainerGetSnapshotsFull(c.Project(), c.name)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
// Build the snapshot list
containers, err := instance.LoadAllInternal(c.state, snaps)
if err != nil {
return nil, err
}
instances := make([]instance.Instance, len(containers))
for k, v := range containers {
instances[k] = instance.Instance(v)
}
return instances, nil
}
// Backups returns the backups of the instance.
func (c *lxc) Backups() ([]backup.Backup, error) {
// Get all the backups
backupNames, err := c.state.Cluster.ContainerGetBackups(c.project, c.name)
if err != nil {
return nil, err
}
// Build the backup list
backups := []backup.Backup{}
for _, backupName := range backupNames {
backup, err := instance.BackupLoadByName(c.state, c.project, backupName)
if err != nil {
return nil, err
}
backups = append(backups, *backup)
}
return backups, nil
}
// Restore restores a snapshot.
func (c *lxc) Restore(sourceContainer instance.Instance, stateful bool) error {
var ctxMap log.Ctx
// Initialize storage interface for the container and mount the rootfs for criu state check.
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return err
}
// Ensure that storage is mounted for state path checks and for backup.yaml updates.
ourStart, err := pool.MountInstance(c, nil)
if err != nil {
return err
}
if ourStart {
defer pool.UnmountInstance(c, nil)
}
// Check for CRIU if necessary, before doing a bunch of filesystem manipulations.
if shared.PathExists(c.StatePath()) {
_, err := exec.LookPath("criu")
if err != nil {
return fmt.Errorf("Failed to restore container state. CRIU isn't installed")
}
}
// Stop the container.
wasRunning := false
if c.IsRunning() {
wasRunning = true
ephemeral := c.IsEphemeral()
if ephemeral {
// Unset ephemeral flag.
args := db.InstanceArgs{
Architecture: c.Architecture(),
Config: c.LocalConfig(),
Description: c.Description(),
Devices: c.LocalDevices(),
Ephemeral: false,
Profiles: c.Profiles(),
Project: c.Project(),
Type: c.Type(),
Snapshot: c.IsSnapshot(),
}
err := c.Update(args, false)
if err != nil {
return err
}
// On function return, set the flag back on.
defer func() {
args.Ephemeral = ephemeral
c.Update(args, true)
}()
}
// This will unmount the container storage.
err := c.Stop(false)
if err != nil {
return err
}
// Ensure that storage is mounted for state path checks and for backup.yaml updates.
ourStart, err := pool.MountInstance(c, nil)
if err != nil {
return err
}
if ourStart {
defer pool.UnmountInstance(c, nil)
}
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"source": sourceContainer.Name()}
logger.Info("Restoring container", ctxMap)
// Restore the rootfs.
err = pool.RestoreInstanceSnapshot(c, sourceContainer, nil)
if err != nil {
return err
}
// Restore the configuration.
args := db.InstanceArgs{
Architecture: sourceContainer.Architecture(),
Config: sourceContainer.LocalConfig(),
Description: sourceContainer.Description(),
Devices: sourceContainer.LocalDevices(),
Ephemeral: sourceContainer.IsEphemeral(),
Profiles: sourceContainer.Profiles(),
Project: sourceContainer.Project(),
Type: sourceContainer.Type(),
Snapshot: sourceContainer.IsSnapshot(),
}
err = c.Update(args, false)
if err != nil {
logger.Error("Failed restoring container configuration", ctxMap)
return err
}
// The old backup file may be out of date (e.g. it doesn't have all the current snapshots of
// the container listed); let's write a new one to be safe.
err = c.UpdateBackupFile()
if err != nil {
return err
}
// If the container wasn't running but was stateful, should we restore it as running?
if stateful == true {
if !shared.PathExists(c.StatePath()) {
return fmt.Errorf("Stateful snapshot restore requested by snapshot is stateless")
}
logger.Debug("Performing stateful restore", ctxMap)
c.stateful = true
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: c.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint.
err := c.Migrate(&criuMigrationArgs)
if err != nil {
return err
}
// Remove the state from the parent container; we only keep this in snapshots.
err2 := os.RemoveAll(c.StatePath())
if err2 != nil {
logger.Error("Failed to delete snapshot state", log.Ctx{"path": c.StatePath(), "err": err2})
}
if err != nil {
logger.Info("Failed restoring container", ctxMap)
return err
}
logger.Debug("Performed stateful restore", ctxMap)
logger.Info("Restored container", ctxMap)
return nil
}
c.state.Events.SendLifecycle(c.project, "container-snapshot-restored",
fmt.Sprintf("/1.0/containers/%s", c.name), map[string]interface{}{
"snapshot_name": c.name,
})
// Restart the container.
if wasRunning {
logger.Info("Restored container", ctxMap)
return c.Start(false)
}
logger.Info("Restored container", ctxMap)
return nil
}
func (c *lxc) cleanup() {
// Unmount any leftovers
c.removeUnixDevices()
c.removeDiskDevices()
// Remove the security profiles
apparmor.DeleteProfile(c.state, c)
seccomp.DeleteProfile(c)
// Remove the devices path
os.Remove(c.DevicesPath())
// Remove the shmounts path
os.RemoveAll(c.ShmountsPath())
}
// Delete deletes the instance.
func (c *lxc) Delete() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
logger.Info("Deleting container", ctxMap)
if shared.IsTrue(c.expandedConfig["security.protection.delete"]) && !c.IsSnapshot() {
err := fmt.Errorf("Container is protected")
logger.Warn("Failed to delete container", log.Ctx{"name": c.Name(), "err": err})
return err
}
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil && err != db.ErrNoSuchObject {
return err
} else if pool != nil {
// Check if we're dealing with "lxd import".
// "lxd import" is used for disaster recovery, where you already have a container
// and snapshots on disk but no DB entry. As such if something has gone wrong during
// the creation of the instance and we are now being asked to delete the instance,
// we should not remove the storage volumes themselves as this would cause data loss.
isImport := false
cName, _, _ := shared.InstanceGetParentAndSnapshotName(c.Name())
importingFilePath := storagePools.InstanceImportingFilePath(c.Type(), pool.Name(), c.Project(), cName)
if shared.PathExists(importingFilePath) {
isImport = true
}
if c.IsSnapshot() {
if !isImport {
// Remove snapshot volume and database record.
err = pool.DeleteInstanceSnapshot(c, nil)
if err != nil {
return err
}
}
} else {
// Remove all snapshots by initialising each snapshot as an Instance and
// calling its Delete function.
err := instance.DeleteSnapshots(c.state, c.Project(), c.Name())
if err != nil {
logger.Error("Failed to delete instance snapshots", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
return err
}
if !isImport {
// Remove the storage volume, snapshot volumes and database records.
err = pool.DeleteInstance(c, nil)
if err != nil {
return err
}
}
}
}
// Perform other cleanup steps if not snapshot.
if !c.IsSnapshot() {
// Remove all backups.
backups, err := c.Backups()
if err != nil {
return err
}
for _, backup := range backups {
err = backup.Delete()
if err != nil {
return err
}
}
// Delete the MAAS entry.
err = c.maasDelete()
if err != nil {
logger.Error("Failed deleting container MAAS record", log.Ctx{"name": c.Name(), "err": err})
return err
}
// Remove devices from container.
for k, m := range c.expandedDevices {
err = c.deviceRemove(k, m)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to remove device '%s'", k)
}
}
// Clean things up.
c.cleanup()
}
// Remove the database record of the instance or snapshot instance.
if err := c.state.Cluster.InstanceRemove(c.project, c.Name()); err != nil {
logger.Error("Failed deleting container entry", log.Ctx{"name": c.Name(), "err": err})
return err
}
logger.Info("Deleted container", ctxMap)
if c.IsSnapshot() {
c.state.Events.SendLifecycle(c.project, "container-snapshot-deleted",
fmt.Sprintf("/1.0/containers/%s", c.name), map[string]interface{}{
"snapshot_name": c.name,
})
} else {
c.state.Events.SendLifecycle(c.project, "container-deleted",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
}
return nil
}
// Rename renames the instance.
func (c *lxc) Rename(newName string) error {
oldName := c.Name()
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"newname": newName}
logger.Info("Renaming container", ctxMap)
// Sanity checks.
err := instance.ValidName(newName, c.IsSnapshot())
if err != nil {
return err
}
if c.IsRunning() {
return fmt.Errorf("Renaming of running container not allowed")
}
// Clean things up.
c.cleanup()
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return errors.Wrap(err, "Load instance storage pool")
}
if c.IsSnapshot() {
_, newSnapName, _ := shared.InstanceGetParentAndSnapshotName(newName)
err = pool.RenameInstanceSnapshot(c, newSnapName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance snapshot")
}
} else {
err = pool.RenameInstance(c, newName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance")
}
}
if !c.IsSnapshot() {
// Rename all the instance snapshot database entries.
results, err := c.state.Cluster.ContainerGetSnapshots(c.project, oldName)
if err != nil {
logger.Error("Failed to get container snapshots", ctxMap)
return err
}
for _, sname := range results {
// Rename the snapshot.
oldSnapName := strings.SplitN(sname, shared.SnapshotDelimiter, 2)[1]
baseSnapName := filepath.Base(sname)
err := c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.InstanceSnapshotRename(c.project, oldName, oldSnapName, baseSnapName)
})
if err != nil {
logger.Error("Failed renaming snapshot", ctxMap)
return err
}
}
}
// Rename the instance database entry.
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
if c.IsSnapshot() {
oldParts := strings.SplitN(oldName, shared.SnapshotDelimiter, 2)
newParts := strings.SplitN(newName, shared.SnapshotDelimiter, 2)
return tx.InstanceSnapshotRename(c.project, oldParts[0], oldParts[1], newParts[1])
}
return tx.InstanceRename(c.project, oldName, newName)
})
if err != nil {
logger.Error("Failed renaming container", ctxMap)
return err
}
// Rename the logging path.
os.RemoveAll(shared.LogPath(newName))
if shared.PathExists(c.LogPath()) {
err := os.Rename(c.LogPath(), shared.LogPath(newName))
if err != nil {
logger.Error("Failed renaming container", ctxMap)
return err
}
}
// Rename the MAAS entry.
if !c.IsSnapshot() {
err = c.maasRename(newName)
if err != nil {
return err
}
}
// Rename the backups.
backups, err := c.Backups()
if err != nil {
return err
}
for _, backup := range backups {
backupName := strings.Split(backup.Name(), "/")[1]
newName := fmt.Sprintf("%s/%s", newName, backupName)
err = backup.Rename(newName)
if err != nil {
return err
}
}
// Set the new name in the struct.
c.name = newName
// Invalidate the go-lxc cache.
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
// Update lease files.
network.UpdateDNSMasqStatic(c.state, "")
logger.Info("Renamed container", ctxMap)
if c.IsSnapshot() {
c.state.Events.SendLifecycle(c.project, "container-snapshot-renamed",
fmt.Sprintf("/1.0/containers/%s", oldName), map[string]interface{}{
"new_name": newName,
"snapshot_name": oldName,
})
} else {
c.state.Events.SendLifecycle(c.project, "container-renamed",
fmt.Sprintf("/1.0/containers/%s", oldName), map[string]interface{}{
"new_name": newName,
})
}
return nil
}
// CGroupSet sets a cgroup value for the instance.
func (c *lxc) CGroupSet(key string, value string) error {
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return err
}
// Make sure the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set cgroups on a stopped container")
}
err = c.c.SetCgroupItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set cgroup %s=\"%s\": %s", key, value, err)
}
return nil
}
// VolatileSet sets volatile config.
func (c *lxc) VolatileSet(changes map[string]string) error {
// Sanity check
for key := range changes {
if !strings.HasPrefix(key, "volatile.") {
return fmt.Errorf("Only volatile keys can be modified with VolatileSet")
}
}
// Update the database
var err error
if c.IsSnapshot() {
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.InstanceSnapshotConfigUpdate(c.id, changes)
})
} else {
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.ContainerConfigUpdate(c.id, changes)
})
}
if err != nil {
return errors.Wrap(err, "Failed to volatile config")
}
// Apply the change locally
for key, value := range changes {
if value == "" {
delete(c.expandedConfig, key)
delete(c.localConfig, key)
continue
}
c.expandedConfig[key] = value
c.localConfig[key] = value
}
return nil
}
// Update applies updated config.
func (c *lxc) Update(args db.InstanceArgs, userRequested bool) error {
// Set sane defaults for unset keys
if args.Project == "" {
args.Project = "default"
}
if args.Architecture == 0 {
args.Architecture = c.architecture
}
if args.Config == nil {
args.Config = map[string]string{}
}
if args.Devices == nil {
args.Devices = deviceConfig.Devices{}
}
if args.Profiles == nil {
args.Profiles = []string{}
}
// Validate the new config
err := instance.ValidConfig(c.state.OS, args.Config, false, false)
if err != nil {
return errors.Wrap(err, "Invalid config")
}
// Validate the new devices without using expanded devices validation (expensive checks disabled).
err = instance.ValidDevices(c.state, c.state.Cluster, c.Type(), args.Devices, false)
if err != nil {
return errors.Wrap(err, "Invalid devices")
}
// Validate the new profiles
profiles, err := c.state.Cluster.Profiles(args.Project)
if err != nil {
return errors.Wrap(err, "Failed to get profiles")
}
checkedProfiles := []string{}
for _, profile := range args.Profiles {
if !shared.StringInSlice(profile, profiles) {
return fmt.Errorf("Requested profile '%s' doesn't exist", profile)
}
if shared.StringInSlice(profile, checkedProfiles) {
return fmt.Errorf("Duplicate profile found in request")
}
checkedProfiles = append(checkedProfiles, profile)
}
// Validate the new architecture
if args.Architecture != 0 {
_, err = osarch.ArchitectureName(args.Architecture)
if err != nil {
return fmt.Errorf("Invalid architecture id: %s", err)
}
}
// Check that volatile and image keys weren't modified
if userRequested {
for k, v := range args.Config {
if strings.HasPrefix(k, "volatile.") && c.localConfig[k] != v {
return fmt.Errorf("Volatile keys are read-only")
}
if strings.HasPrefix(k, "image.") && c.localConfig[k] != v {
return fmt.Errorf("Image keys are read-only")
}
}
for k, v := range c.localConfig {
if strings.HasPrefix(k, "volatile.") && args.Config[k] != v {
return fmt.Errorf("Volatile keys are read-only")
}
if strings.HasPrefix(k, "image.") && args.Config[k] != v {
return fmt.Errorf("Image keys are read-only")
}
}
}
// Get a copy of the old configuration
oldDescription := c.Description()
oldArchitecture := 0
err = shared.DeepCopy(&c.architecture, &oldArchitecture)
if err != nil {
return err
}
oldEphemeral := false
err = shared.DeepCopy(&c.ephemeral, &oldEphemeral)
if err != nil {
return err
}
oldExpandedDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&c.expandedDevices, &oldExpandedDevices)
if err != nil {
return err
}
oldExpandedConfig := map[string]string{}
err = shared.DeepCopy(&c.expandedConfig, &oldExpandedConfig)
if err != nil {
return err
}
oldLocalDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&c.localDevices, &oldLocalDevices)
if err != nil {
return err
}
oldLocalConfig := map[string]string{}
err = shared.DeepCopy(&c.localConfig, &oldLocalConfig)
if err != nil {
return err
}
oldProfiles := []string{}
err = shared.DeepCopy(&c.profiles, &oldProfiles)
if err != nil {
return err
}
oldExpiryDate := c.expiryDate
// Define a function which reverts everything. Defer this function
// so that it doesn't need to be explicitly called in every failing
// return path. Track whether or not we want to undo the changes
// using a closure.
undoChanges := true
defer func() {
if undoChanges {
c.description = oldDescription
c.architecture = oldArchitecture
c.ephemeral = oldEphemeral
c.expandedConfig = oldExpandedConfig
c.expandedDevices = oldExpandedDevices
c.localConfig = oldLocalConfig
c.localDevices = oldLocalDevices
c.profiles = oldProfiles
c.expiryDate = oldExpiryDate
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
c.initLXC(true)
cgroup.TaskSchedulerTrigger("container", c.name, "changed")
}
}()
// Apply the various changes
c.description = args.Description
c.architecture = args.Architecture
c.ephemeral = args.Ephemeral
c.localConfig = args.Config
c.localDevices = args.Devices
c.profiles = args.Profiles
c.expiryDate = args.ExpiryDate
// Expand the config and refresh the LXC config
err = c.expandConfig(nil)
if err != nil {
return errors.Wrap(err, "Expand config")
}
err = c.expandDevices(nil)
if err != nil {
return errors.Wrap(err, "Expand devices")
}
// Diff the configurations
changedConfig := []string{}
for key := range oldExpandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
for key := range c.expandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
// Diff the devices
removeDevices, addDevices, updateDevices, updateDiff := oldExpandedDevices.Update(c.expandedDevices, func(oldDevice deviceConfig.Device, newDevice deviceConfig.Device) []string {
// This function needs to return a list of fields that are excluded from differences
// between oldDevice and newDevice. The result of this is that as long as the
// devices are otherwise identical except for the fields returned here, then the
// device is considered to be being "updated" rather than "added & removed".
if oldDevice["type"] != newDevice["type"] || oldDevice.NICType() != newDevice.NICType() {
return []string{} // Device types aren't the same, so this cannot be an update.
}
d, err := device.New(c, c.state, "", newDevice, nil, nil)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
_, updateFields := d.CanHotPlug()
return updateFields
})
// Do some validation of the config diff
err = instance.ValidConfig(c.state.OS, c.expandedConfig, false, true)
if err != nil {
return errors.Wrap(err, "Invalid expanded config")
}
// Do full expanded validation of the devices diff.
err = instance.ValidDevices(c.state, c.state.Cluster, c.Type(), c.expandedDevices, true)
if err != nil {
return errors.Wrap(err, "Invalid expanded devices")
}
// Run through initLXC to catch anything we missed
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
err = c.initLXC(true)
if err != nil {
return errors.Wrap(err, "Initialize LXC")
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// If apparmor changed, re-validate the apparmor profile
if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) {
err = apparmor.ParseProfile(c.state, c)
if err != nil {
return errors.Wrap(err, "Parse AppArmor profile")
}
}
if shared.StringInSlice("security.idmap.isolated", changedConfig) || shared.StringInSlice("security.idmap.base", changedConfig) || shared.StringInSlice("security.idmap.size", changedConfig) || shared.StringInSlice("raw.idmap", changedConfig) || shared.StringInSlice("security.privileged", changedConfig) {
var idmap *idmap.IdmapSet
base := int64(0)
if !c.IsPrivileged() {
// update the idmap
idmap, base, err = findIdmap(
c.state,
c.Name(),
c.expandedConfig["security.idmap.isolated"],
c.expandedConfig["security.idmap.base"],
c.expandedConfig["security.idmap.size"],
c.expandedConfig["raw.idmap"],
)
if err != nil {
return errors.Wrap(err, "Failed to get ID map")
}
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
return err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
c.localConfig["volatile.idmap.next"] = jsonIdmap
c.localConfig["volatile.idmap.base"] = fmt.Sprintf("%v", base)
// Invalid idmap cache
c.idmapset = nil
}
// Use the device interface to apply update changes.
err = c.updateDevices(removeDevices, addDevices, updateDevices, oldExpandedDevices)
if err != nil {
return err
}
// Update MAAS (must run after the MAC addresses have been generated).
updateMAAS := false
for _, key := range []string{"maas.subnet.ipv4", "maas.subnet.ipv6", "ipv4.address", "ipv6.address"} {
if shared.StringInSlice(key, updateDiff) {
updateMAAS = true
break
}
}
if !c.IsSnapshot() && updateMAAS {
err = c.maasUpdate(oldExpandedDevices.CloneNative())
if err != nil {
return err
}
}
// Apply the live changes
isRunning := c.IsRunning()
if isRunning {
// Live update the container config
for _, key := range changedConfig {
value := c.expandedConfig[key]
if key == "raw.apparmor" || key == "security.nesting" {
// Update the AppArmor profile
err = apparmor.LoadProfile(c.state, c)
if err != nil {
return err
}
} else if key == "security.devlxd" {
if value == "" || shared.IsTrue(value) {
err = c.insertMount(shared.VarPath("devlxd"), "/dev/lxd", "none", unix.MS_BIND, false)
if err != nil {
return err
}
} else if c.FileExists("/dev/lxd") == nil {
err = c.removeMount("/dev/lxd")
if err != nil {
return err
}
err = c.FileRemove("/dev/lxd")
if err != nil {
return err
}
}
} else if key == "linux.kernel_modules" && value != "" {
for _, module := range strings.Split(value, ",") {
module = strings.TrimPrefix(module, " ")
err := util.LoadModule(module)
if err != nil {
return fmt.Errorf("Failed to load kernel module '%s': %s", module, err)
}
}
} else if key == "limits.disk.priority" {
if !c.state.OS.CGInfo.Supports(cgroup.Blkio, cg) {
continue
}
priorityInt := 5
diskPriority := c.expandedConfig["limits.disk.priority"]
if diskPriority != "" {
priorityInt, err = strconv.Atoi(diskPriority)
if err != nil {
return err
}
}
// Minimum valid value is 10
priority := priorityInt * 100
if priority == 0 {
priority = 10
}
cg.SetBlkioWeight(fmt.Sprintf("%d", priority))
if err != nil {
return err
}
} else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") {
// Skip if no memory CGroup
if !c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
continue
}
// Set the new memory limit
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
// Parse memory
if memory == "" {
memory = "-1"
} else if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := shared.DeviceTotalMemory()
if err != nil {
return err
}
memory = fmt.Sprintf("%d", int64((memoryTotal/100)*percent))
} else {
valueInt, err := units.ParseByteSizeString(memory)
if err != nil {
return err
}
memory = fmt.Sprintf("%d", valueInt)
}
// Store the old values for revert
oldMemswLimit := ""
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
oldMemswLimit, err = cg.GetMemorySwapLimit()
if err != nil {
oldMemswLimit = ""
}
}
oldLimit, err := cg.GetMaxMemory()
if err != nil {
oldLimit = ""
}
oldSoftLimit, err := cg.GetMemorySoftLimit()
if err != nil {
oldSoftLimit = ""
}
revertMemory := func() {
if oldSoftLimit != "" {
cg.SetMemorySoftLimit(oldSoftLimit)
}
if oldLimit != "" {
cg.SetMemoryMaxUsage(oldLimit)
}
if oldMemswLimit != "" {
cg.SetMemorySwapMax(oldMemswLimit)
}
}
// Reset everything
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
err = cg.SetMemorySwapMax("-1")
if err != nil {
revertMemory()
return err
}
}
err = cg.SetMemoryMaxUsage("-1")
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySoftLimit("-1")
if err != nil {
revertMemory()
return err
}
// Set the new values
if memoryEnforce == "soft" {
// Set new limit
err = cg.SetMemorySoftLimit(memory)
if err != nil {
revertMemory()
return err
}
} else {
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryMaxUsage(memory)
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySwapMax(memory)
if err != nil {
revertMemory()
return err
}
} else {
err = cg.SetMemoryMaxUsage(memory)
if err != nil {
revertMemory()
return err
}
}
// Set soft limit to value 10% less than hard limit
valueInt, err := strconv.ParseInt(memory, 10, 64)
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySoftLimit(fmt.Sprintf("%.0f", float64(valueInt)*0.9))
if err != nil {
revertMemory()
return err
}
}
if !c.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) {
continue
}
// Configure the swappiness
if key == "limits.memory.swap" || key == "limits.memory.swap.priority" {
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = cg.SetMemorySwappiness("0")
if err != nil {
return err
}
} else {
priority := 0
if memorySwapPriority != "" {
priority, err = strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
}
err = cg.SetMemorySwappiness(fmt.Sprintf("%d", 60-10+priority))
if err != nil {
return err
}
}
}
} else if key == "limits.network.priority" {
err := c.setNetworkPriority()
if err != nil {
return err
}
} else if key == "limits.cpu" {
// Trigger a scheduler re-run
cgroup.TaskSchedulerTrigger("container", c.name, "changed")
} else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" {
// Skip if no cpu CGroup
if !c.state.OS.CGInfo.Supports(cgroup.CPU, cg) {
continue
}
// Apply new CPU limits
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(c.expandedConfig["limits.cpu.allowance"], c.expandedConfig["limits.cpu.priority"])
if err != nil {
return err
}
err = cg.SetCPUShare(cpuShares)
if err != nil {
return err
}
err = cg.SetCPUCfsPeriod(cpuCfsPeriod)
if err != nil {
return err
}
err = cg.SetCPUCfsQuota(cpuCfsQuota)
if err != nil {
return err
}
} else if key == "limits.processes" {
if !c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
continue
}
if value == "" {
err = cg.SetMaxProcesses(-1)
if err != nil {
return err
}
} else {
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
err = cg.SetMaxProcesses(valueInt)
if err != nil {
return err
}
}
} else if strings.HasPrefix(key, "limits.hugepages.") {
if !c.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) {
continue
}
pageType := ""
switch key {
case "limits.hugepages.64KB":
pageType = "64KB"
case "limits.hugepages.1MB":
pageType = "1MB"
case "limits.hugepages.2MB":
pageType = "2MB"
case "limits.hugepages.1GB":
pageType = "1GB"
}
if value != "" {
valueInt, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
value = fmt.Sprintf("%d", valueInt)
}
err = cg.SetMaxHugepages(pageType, value)
if err != nil {
return err
}
}
}
}
// Finally, apply the changes to the database
err = query.Retry(func() error {
tx, err := c.state.Cluster.Begin()
if err != nil {
return err
}
// Snapshots should update only their descriptions and expiry date.
if c.IsSnapshot() {
err = db.InstanceSnapshotUpdate(tx, c.id, c.description, c.expiryDate)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Snapshot update")
}
} else {
err = db.ContainerConfigClear(tx, c.id)
if err != nil {
tx.Rollback()
return err
}
err = db.ContainerConfigInsert(tx, c.id, c.localConfig)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Config insert")
}
err = db.ContainerProfilesInsert(tx, c.id, c.project, c.profiles)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Profiles insert")
}
err = db.DevicesAdd(tx, "instance", int64(c.id), c.localDevices)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Device add")
}
err = db.ContainerUpdate(tx, c.id, c.description, c.architecture, c.ephemeral, c.expiryDate)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Container update")
}
}
if err := db.TxCommit(tx); err != nil {
return err
}
return nil
})
if err != nil {
return errors.Wrap(err, "Failed to update database")
}
// Only update the backup file if it already exists (indicating the instance is mounted).
if shared.PathExists(filepath.Join(c.Path(), "backup.yaml")) {
err := c.UpdateBackupFile()
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "Failed to write backup file")
}
}
// Send devlxd notifications
if isRunning {
// Config changes (only for user.* keys
for _, key := range changedConfig {
if !strings.HasPrefix(key, "user.") {
continue
}
msg := map[string]string{
"key": key,
"old_value": oldExpandedConfig[key],
"value": c.expandedConfig[key],
}
err = c.devlxdEventSend("config", msg)
if err != nil {
return err
}
}
// Device changes
for k, m := range removeDevices {
msg := map[string]interface{}{
"action": "removed",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range updateDevices {
msg := map[string]interface{}{
"action": "updated",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range addDevices {
msg := map[string]interface{}{
"action": "added",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
}
// Success, update the closure to mark that the changes should be kept.
undoChanges = false
var endpoint string
if c.IsSnapshot() {
cName, sName, _ := shared.InstanceGetParentAndSnapshotName(c.name)
endpoint = fmt.Sprintf("/1.0/containers/%s/snapshots/%s", cName, sName)
} else {
endpoint = fmt.Sprintf("/1.0/containers/%s", c.name)
}
c.state.Events.SendLifecycle(c.project, "container-updated", endpoint, nil)
return nil
}
func (c *lxc) updateDevices(removeDevices deviceConfig.Devices, addDevices deviceConfig.Devices, updateDevices deviceConfig.Devices, oldExpandedDevices deviceConfig.Devices) error {
isRunning := c.IsRunning()
// Remove devices in reverse order to how they were added.
for _, dev := range removeDevices.Reversed() {
if isRunning {
err := c.deviceStop(dev.Name, dev.Config, "")
if err == device.ErrUnsupportedDevType {
continue // No point in trying to remove device below.
} else if err != nil {
return errors.Wrapf(err, "Failed to stop device %q", dev.Name)
}
}
err := c.deviceRemove(dev.Name, dev.Config)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to remove device %q", dev.Name)
}
// Check whether we are about to add the same device back with updated config and
// if not, or if the device type has changed, then remove all volatile keys for
// this device (as its an actual removal or a device type change).
err = c.deviceResetVolatile(dev.Name, dev.Config, addDevices[dev.Name])
if err != nil {
return errors.Wrapf(err, "Failed to reset volatile data for device %q", dev.Name)
}
}
// Add devices in sorted order, this ensures that device mounts are added in path order.
for _, dev := range addDevices.Sorted() {
err := c.deviceAdd(dev.Name, dev.Config)
if err == device.ErrUnsupportedDevType {
continue // No point in trying to start device below.
} else if err != nil {
return errors.Wrapf(err, "Failed to add device %q", dev.Name)
}
if isRunning {
_, err := c.deviceStart(dev.Name, dev.Config, isRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
}
}
for _, dev := range updateDevices.Sorted() {
err := c.deviceUpdate(dev.Name, dev.Config, oldExpandedDevices, isRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to update device %q", dev.Name)
}
}
return nil
}
// Export backs up the instance.
func (c *lxc) Export(w io.Writer, properties map[string]string) error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
if c.IsRunning() {
return fmt.Errorf("Cannot export a running instance as an image")
}
logger.Info("Exporting instance", ctxMap)
// Start the storage.
ourStart, err := c.mount()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
if ourStart {
defer c.unmount()
}
// Get IDMap to unshift container as the tarball is created.
idmap, err := c.DiskIdmap()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Create the tarball.
ctw := containerwriter.NewContainerTarWriter(w, idmap)
// Keep track of the first path we saw for each path with nlink>1.
cDir := c.Path()
// Path inside the tar image is the pathname starting after cDir.
offset := len(cDir) + 1
writeToTar := func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
err = ctw.WriteFile(offset, path, fi)
if err != nil {
logger.Debugf("Error tarring up %s: %s", path, err)
return err
}
return nil
}
// Look for metadata.yaml.
fnam := filepath.Join(cDir, "metadata.yaml")
if !shared.PathExists(fnam) {
// Generate a new metadata.yaml.
tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_")
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
defer os.RemoveAll(tempDir)
// Get the instance's architecture.
var arch string
if c.IsSnapshot() {
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(c.name)
parent, err := instance.LoadByProjectAndName(c.state, c.project, parentName)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
arch, _ = osarch.ArchitectureName(parent.Architecture())
} else {
arch, _ = osarch.ArchitectureName(c.architecture)
}
if arch == "" {
arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0])
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Fill in the metadata.
meta := api.ImageMetadata{}
meta.Architecture = arch
meta.CreationDate = time.Now().UTC().Unix()
meta.Properties = properties
data, err := yaml.Marshal(&meta)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
fi, err := os.Lstat(fnam)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
tmpOffset := len(path.Dir(fnam)) + 1
if err := ctw.WriteFile(tmpOffset, fnam, fi); err != nil {
ctw.Close()
logger.Debugf("Error writing to tarfile: %s", err)
logger.Error("Failed exporting instance", ctxMap)
return err
}
} else {
if properties != nil {
// Parse the metadata.
content, err := ioutil.ReadFile(fnam)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
metadata.Properties = properties
// Generate a new metadata.yaml.
tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_")
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
defer os.RemoveAll(tempDir)
data, err := yaml.Marshal(&metadata)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
ctw.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Include metadata.yaml in the tarball.
fi, err := os.Lstat(fnam)
if err != nil {
ctw.Close()
logger.Debugf("Error statting %s during export", fnam)
logger.Error("Failed exporting instance", ctxMap)
return err
}
if properties != nil {
tmpOffset := len(path.Dir(fnam)) + 1
err = ctw.WriteFile(tmpOffset, fnam, fi)
} else {
err = ctw.WriteFile(offset, fnam, fi)
}
if err != nil {
ctw.Close()
logger.Debugf("Error writing to tarfile: %s", err)
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Include all the rootfs files.
fnam = c.RootfsPath()
err = filepath.Walk(fnam, writeToTar)
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Include all the templates.
fnam = c.TemplatesPath()
if shared.PathExists(fnam) {
err = filepath.Walk(fnam, writeToTar)
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
err = ctw.Close()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
logger.Info("Exported instance", ctxMap)
return nil
}
func collectCRIULogFile(c instance.Instance, imagesDir string, function string, method string) error {
t := time.Now().Format(time.RFC3339)
newPath := shared.LogPath(c.Name(), fmt.Sprintf("%s_%s_%s.log", function, method, t))
return shared.FileCopy(filepath.Join(imagesDir, fmt.Sprintf("%s.log", method)), newPath)
}
func getCRIULogErrors(imagesDir string, method string) (string, error) {
f, err := os.Open(path.Join(imagesDir, fmt.Sprintf("%s.log", method)))
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
ret := []string{}
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "Error") || strings.Contains(line, "Warn") {
ret = append(ret, scanner.Text())
}
}
return strings.Join(ret, "\n"), nil
}
// Migrate migrates the instance to another node.
func (c *lxc) Migrate(args *instance.CriuMigrationArgs) error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"statedir": args.StateDir,
"actionscript": args.ActionScript,
"predumpdir": args.PreDumpDir,
"features": args.Features,
"stop": args.Stop}
_, err := exec.LookPath("criu")
if err != nil {
return fmt.Errorf("Unable to perform container live migration. CRIU isn't installed")
}
logger.Info("Migrating container", ctxMap)
prettyCmd := ""
switch args.Cmd {
case liblxc.MIGRATE_PRE_DUMP:
prettyCmd = "pre-dump"
case liblxc.MIGRATE_DUMP:
prettyCmd = "dump"
case liblxc.MIGRATE_RESTORE:
prettyCmd = "restore"
case liblxc.MIGRATE_FEATURE_CHECK:
prettyCmd = "feature-check"
default:
prettyCmd = "unknown"
logger.Warn("Unknown migrate call", log.Ctx{"cmd": args.Cmd})
}
pool, err := c.getStoragePool()
if err != nil {
return err
}
preservesInodes := pool.Driver().Info().PreservesInodes
/* This feature was only added in 2.0.1, let's not ask for it
* before then or migrations will fail.
*/
if !util.RuntimeLiblxcVersionAtLeast(2, 0, 1) {
preservesInodes = false
}
finalStateDir := args.StateDir
var migrateErr error
/* For restore, we need an extra fork so that we daemonize monitor
* instead of having it be a child of LXD, so let's hijack the command
* here and do the extra fork.
*/
if args.Cmd == liblxc.MIGRATE_RESTORE {
// Run the shared start
_, postStartHooks, err := c.startCommon()
if err != nil {
return err
}
/*
* For unprivileged containers we need to shift the
* perms on the images images so that they can be
* opened by the process after it is in its user
* namespace.
*/
idmapset, err := c.CurrentIdmap()
if err != nil {
return err
}
if idmapset != nil {
ourStart, err := c.mount()
if err != nil {
return err
}
storageType, err := c.getStorageType()
if err != nil {
return errors.Wrap(err, "Storage type")
}
if storageType == "zfs" {
err = idmapset.ShiftRootfs(args.StateDir, storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.ShiftBtrfsRootfs(args.StateDir, idmapset)
} else {
err = idmapset.ShiftRootfs(args.StateDir, nil)
}
if ourStart {
_, err2 := c.unmount()
if err != nil {
return err
}
if err2 != nil {
return err2
}
}
}
configPath := filepath.Join(c.LogPath(), "lxc.conf")
if args.DumpDir != "" {
finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir)
}
_, migrateErr = shared.RunCommand(
c.state.OS.ExecPath,
"forkmigrate",
c.name,
c.state.OS.LxcPath,
configPath,
finalStateDir,
fmt.Sprintf("%v", preservesInodes))
if migrateErr == nil {
// Run any post start hooks.
err := c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
c.Stop(false)
return err
}
}
} else if args.Cmd == liblxc.MIGRATE_FEATURE_CHECK {
err := c.initLXC(true)
if err != nil {
return err
}
opts := liblxc.MigrateOptions{
FeaturesToCheck: args.Features,
}
migrateErr = c.c.Migrate(args.Cmd, opts)
if migrateErr != nil {
logger.Info("CRIU feature check failed", ctxMap)
return migrateErr
}
return nil
} else {
err := c.initLXC(true)
if err != nil {
return err
}
script := ""
if args.ActionScript {
script = filepath.Join(args.StateDir, "action.sh")
}
if args.DumpDir != "" {
finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir)
}
// TODO: make this configurable? Ultimately I think we don't
// want to do that; what we really want to do is have "modes"
// of criu operation where one is "make this succeed" and the
// other is "make this fast". Anyway, for now, let's choose a
// really big size so it almost always succeeds, even if it is
// slow.
ghostLimit := uint64(256 * 1024 * 1024)
opts := liblxc.MigrateOptions{
Stop: args.Stop,
Directory: finalStateDir,
Verbose: true,
PreservesInodes: preservesInodes,
ActionScript: script,
GhostLimit: ghostLimit,
}
if args.PreDumpDir != "" {
opts.PredumpDir = fmt.Sprintf("../%s", args.PreDumpDir)
}
if !c.IsRunning() {
// otherwise the migration will needlessly fail
args.Stop = false
}
migrateErr = c.c.Migrate(args.Cmd, opts)
}
collectErr := collectCRIULogFile(c, finalStateDir, args.Function, prettyCmd)
if collectErr != nil {
logger.Error("Error collecting checkpoint log file", log.Ctx{"err": collectErr})
}
if migrateErr != nil {
log, err2 := getCRIULogErrors(finalStateDir, prettyCmd)
if err2 == nil {
logger.Info("Failed migrating container", ctxMap)
migrateErr = fmt.Errorf("%s %s failed\n%s", args.Function, prettyCmd, log)
}
return migrateErr
}
logger.Info("Migrated container", ctxMap)
return nil
}
// DeferTemplateApply sets volatile key to apply template on next start. Used when instance's
// volume isn't mounted.
func (c *lxc) DeferTemplateApply(trigger string) error {
err := c.VolatileSet(map[string]string{"volatile.apply_template": trigger})
if err != nil {
return errors.Wrap(err, "Failed to set apply_template volatile key")
}
return nil
}
func (c *lxc) templateApplyNow(trigger string) error {
// If there's no metadata, just return
fname := filepath.Join(c.Path(), "metadata.yaml")
if !shared.PathExists(fname) {
return nil
}
// Parse the metadata
content, err := ioutil.ReadFile(fname)
if err != nil {
return errors.Wrap(err, "Failed to read metadata")
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
return errors.Wrapf(err, "Could not parse %s", fname)
}
// Find rootUID and rootGID
idmapset, err := c.DiskIdmap()
if err != nil {
return errors.Wrap(err, "Failed to set ID map")
}
rootUID := int64(0)
rootGID := int64(0)
// Get the right uid and gid for the container
if idmapset != nil {
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
// Figure out the container architecture
arch, err := osarch.ArchitectureName(c.architecture)
if err != nil {
arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0])
if err != nil {
return errors.Wrap(err, "Failed to detect system architecture")
}
}
// Generate the container metadata
containerMeta := make(map[string]string)
containerMeta["name"] = c.name
containerMeta["architecture"] = arch
if c.ephemeral {
containerMeta["ephemeral"] = "true"
} else {
containerMeta["ephemeral"] = "false"
}
if c.IsPrivileged() {
containerMeta["privileged"] = "true"
} else {
containerMeta["privileged"] = "false"
}
// Go through the templates
for tplPath, tpl := range metadata.Templates {
var w *os.File
// Check if the template should be applied now
found := false
for _, tplTrigger := range tpl.When {
if tplTrigger == trigger {
found = true
break
}
}
if !found {
continue
}
// Open the file to template, create if needed
fullpath := filepath.Join(c.RootfsPath(), strings.TrimLeft(tplPath, "/"))
if shared.PathExists(fullpath) {
if tpl.CreateOnly {
continue
}
// Open the existing file
w, err = os.Create(fullpath)
if err != nil {
return errors.Wrap(err, "Failed to create template file")
}
} else {
// Create the directories leading to the file
shared.MkdirAllOwner(path.Dir(fullpath), 0755, int(rootUID), int(rootGID))
// Create the file itself
w, err = os.Create(fullpath)
if err != nil {
return err
}
// Fix ownership and mode
w.Chown(int(rootUID), int(rootGID))
w.Chmod(0644)
}
defer w.Close()
// Read the template
tplString, err := ioutil.ReadFile(filepath.Join(c.TemplatesPath(), tpl.Template))
if err != nil {
return errors.Wrap(err, "Failed to read template file")
}
// Restrict filesystem access to within the container's rootfs
tplSet := pongo2.NewSet(fmt.Sprintf("%s-%s", c.name, tpl.Template), template.ChrootLoader{Path: c.RootfsPath()})
tplRender, err := tplSet.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}")
if err != nil {
return errors.Wrap(err, "Failed to render template")
}
configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value {
val, ok := c.expandedConfig[confKey.String()]
if !ok {
return confDefault
}
return pongo2.AsValue(strings.TrimRight(val, "\r\n"))
}
// Render the template
tplRender.ExecuteWriter(pongo2.Context{"trigger": trigger,
"path": tplPath,
"container": containerMeta,
"instance": containerMeta,
"config": c.expandedConfig,
"devices": c.expandedDevices,
"properties": tpl.Properties,
"config_get": configGet}, w)
}
return nil
}
// FileExists returns whether file exists inside instance.
func (c *lxc) FileExists(path string) error {
// Setup container storage if needed
var ourStart bool
var err error
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
// Check if the file exists in the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"exists",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
path,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkcheckfile response
if stderr != "" {
if strings.HasPrefix(stderr, "error:") {
return fmt.Errorf(strings.TrimPrefix(strings.TrimSuffix(stderr, "\n"), "error: "))
}
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
logger.Debugf("forkcheckfile: %s", line)
}
}
if err != nil {
return err
}
return nil
}
// FilePull gets a file from the instance.
func (c *lxc) FilePull(srcpath string, dstpath string) (int64, int64, os.FileMode, string, []string, error) {
// Check for ongoing operations (that may involve shifting).
op := operationlock.Get(c.id)
if op != nil {
op.Wait()
}
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return -1, -1, 0, "", nil, err
}
}
// Get the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"pull",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
srcpath,
dstpath,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return -1, -1, 0, "", nil, err
}
}
uid := int64(-1)
gid := int64(-1)
mode := -1
fileType := "unknown"
var dirEnts []string
var errStr string
// Process forkgetfile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return -1, -1, 0, "", nil, os.ErrNotExist
}
return -1, -1, 0, "", nil, fmt.Errorf(errStr)
}
// Extract the uid
if strings.HasPrefix(line, "uid: ") {
uid, err = strconv.ParseInt(strings.TrimPrefix(line, "uid: "), 10, 64)
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
// Extract the gid
if strings.HasPrefix(line, "gid: ") {
gid, err = strconv.ParseInt(strings.TrimPrefix(line, "gid: "), 10, 64)
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
// Extract the mode
if strings.HasPrefix(line, "mode: ") {
mode, err = strconv.Atoi(strings.TrimPrefix(line, "mode: "))
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
if strings.HasPrefix(line, "type: ") {
fileType = strings.TrimPrefix(line, "type: ")
continue
}
if strings.HasPrefix(line, "entry: ") {
ent := strings.TrimPrefix(line, "entry: ")
ent = strings.Replace(ent, "\x00", "\n", -1)
dirEnts = append(dirEnts, ent)
continue
}
logger.Debugf("forkgetfile: %s", line)
}
if err != nil {
return -1, -1, 0, "", nil, err
}
// Unmap uid and gid if needed
if !c.IsRunning() {
idmapset, err := c.DiskIdmap()
if err != nil {
return -1, -1, 0, "", nil, err
}
if idmapset != nil {
uid, gid = idmapset.ShiftFromNs(uid, gid)
}
}
return uid, gid, os.FileMode(mode), fileType, dirEnts, nil
}
// FilePush sends a file into the instance.
func (c *lxc) FilePush(fileType string, srcpath string, dstpath string, uid int64, gid int64, mode int, write string) error {
// Check for ongoing operations (that may involve shifting).
op := operationlock.Get(c.id)
if op != nil {
op.Wait()
}
var rootUID int64
var rootGID int64
var errStr string
// Map uid and gid if needed
if !c.IsRunning() {
idmapset, err := c.DiskIdmap()
if err != nil {
return err
}
if idmapset != nil {
uid, gid = idmapset.ShiftIntoNs(uid, gid)
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
}
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
defaultMode := 0640
if fileType == "directory" {
defaultMode = 0750
}
// Push the file to the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"push",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
srcpath,
dstpath,
fileType,
fmt.Sprintf("%d", uid),
fmt.Sprintf("%d", gid),
fmt.Sprintf("%d", mode),
fmt.Sprintf("%d", rootUID),
fmt.Sprintf("%d", rootGID),
fmt.Sprintf("%d", int(os.FileMode(defaultMode)&os.ModePerm)),
write,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkgetfile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return os.ErrNotExist
}
return fmt.Errorf(errStr)
}
}
if err != nil {
return err
}
return nil
}
// FileRemove removes a file inside the instance.
func (c *lxc) FileRemove(path string) error {
var errStr string
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
// Remove the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"remove",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
path,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkremovefile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return os.ErrNotExist
}
return fmt.Errorf(errStr)
}
}
if err != nil {
return err
}
return nil
}
// Console attaches to the instance console.
func (c *lxc) Console() (*os.File, chan error, error) {
chDisconnect := make(chan error, 1)
args := []string{
c.state.OS.ExecPath,
"forkconsole",
project.Instance(c.Project(), c.Name()),
c.state.OS.LxcPath,
filepath.Join(c.LogPath(), "lxc.conf"),
"tty=0",
"escape=-1"}
idmapset, err := c.CurrentIdmap()
if err != nil {
return nil, nil, err
}
var rootUID, rootGID int64
if idmapset != nil {
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
master, slave, err := shared.OpenPty(rootUID, rootGID)
if err != nil {
return nil, nil, err
}
cmd := exec.Cmd{}
cmd.Path = c.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = slave
cmd.Stdout = slave
cmd.Stderr = slave
err = cmd.Start()
if err != nil {
return nil, nil, err
}
go func() {
err = cmd.Wait()
master.Close()
slave.Close()
}()
go func() {
<-chDisconnect
cmd.Process.Kill()
}()
return master, chDisconnect, nil
}
// ConsoleLog returns console log.
func (c *lxc) ConsoleLog(opts liblxc.ConsoleLogOptions) (string, error) {
msg, err := c.c.ConsoleLog(opts)
if err != nil {
return "", err
}
return string(msg), nil
}
// Exec executes a command inside the instance.
func (c *lxc) Exec(req api.InstanceExecPost, stdin *os.File, stdout *os.File, stderr *os.File) (instance.Cmd, error) {
// Prepare the environment
envSlice := []string{}
for k, v := range req.Environment {
envSlice = append(envSlice, fmt.Sprintf("%s=%s", k, v))
}
// Setup logfile
logPath := filepath.Join(c.LogPath(), "forkexec.log")
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
if err != nil {
return nil, err
}
// Prepare the subcommand
cname := project.Instance(c.Project(), c.Name())
args := []string{
c.state.OS.ExecPath,
"forkexec",
cname,
c.state.OS.LxcPath,
filepath.Join(c.LogPath(), "lxc.conf"),
req.Cwd,
fmt.Sprintf("%d", req.User),
fmt.Sprintf("%d", req.Group),
}
args = append(args, "--")
args = append(args, "env")
args = append(args, envSlice...)
args = append(args, "--")
args = append(args, "cmd")
args = append(args, req.Command...)
cmd := exec.Cmd{}
cmd.Path = c.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = nil
cmd.Stdout = logFile
cmd.Stderr = logFile
// Mitigation for CVE-2019-5736
useRexec := false
if c.expandedConfig["raw.idmap"] != "" {
err := instance.AllowedUnprivilegedOnlyMap(c.expandedConfig["raw.idmap"])
if err != nil {
useRexec = true
}
}
if shared.IsTrue(c.expandedConfig["security.privileged"]) {
useRexec = true
}
if useRexec {
cmd.Env = append(os.Environ(), "LXC_MEMFD_REXEC=1")
}
// Setup communication PIPE
rStatus, wStatus, err := shared.Pipe()
defer rStatus.Close()
if err != nil {
return nil, err
}
cmd.ExtraFiles = []*os.File{stdin, stdout, stderr, wStatus}
err = cmd.Start()
if err != nil {
wStatus.Close()
return nil, err
}
wStatus.Close()
attachedPid := -1
if err := json.NewDecoder(rStatus).Decode(&attachedPid); err != nil {
logger.Errorf("Failed to retrieve PID of executing child process: %s", err)
return nil, err
}
instCmd := &lxcCmd{
cmd: &cmd,
attachedChildPid: attachedPid,
}
return instCmd, nil
}
func (c *lxc) cpuState() api.InstanceStateCPU {
cpu := api.InstanceStateCPU{}
// CPU usage in seconds
cg, err := c.cgroup(nil)
if err != nil {
return cpu
}
if !c.state.OS.CGInfo.Supports(cgroup.CPUAcct, cg) {
return cpu
}
value, err := cg.GetCPUAcctUsage()
if err != nil {
cpu.Usage = -1
return cpu
}
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
cpu.Usage = -1
return cpu
}
cpu.Usage = valueInt
return cpu
}
func (c *lxc) diskState() map[string]api.InstanceStateDisk {
disk := map[string]api.InstanceStateDisk{}
for _, dev := range c.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" {
continue
}
if dev.Config["path"] != "/" {
continue
}
var usage int64
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
logger.Error("Error loading storage pool", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
continue
}
usage, err = pool.GetInstanceUsage(c)
if err != nil {
if err != storageDrivers.ErrNotSupported {
logger.Error("Error getting disk usage", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
}
continue
}
disk[dev.Name] = api.InstanceStateDisk{Usage: usage}
}
return disk
}
func (c *lxc) memoryState() api.InstanceStateMemory {
memory := api.InstanceStateMemory{}
cg, err := c.cgroup(nil)
if err != nil {
return memory
}
if !c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
return memory
}
// Memory in bytes
value, err := cg.GetMemoryUsage()
valueInt, err1 := strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.Usage = valueInt
}
// Memory peak in bytes
if c.state.OS.CGInfo.Supports(cgroup.MemoryMaxUsage, cg) {
value, err = cg.GetMemoryMaxUsage()
valueInt, err1 = strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.UsagePeak = valueInt
}
}
if c.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) {
// Swap in bytes
if memory.Usage > 0 {
value, err := cg.GetMemorySwapUsage()
valueInt, err1 := strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.SwapUsage = valueInt - memory.Usage
}
}
// Swap peak in bytes
if memory.UsagePeak > 0 {
value, err = cg.GetMemorySwMaxUsage()
valueInt, err1 = strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.SwapUsagePeak = valueInt - memory.UsagePeak
}
}
}
return memory
}
func (c *lxc) networkState() map[string]api.InstanceStateNetwork {
result := map[string]api.InstanceStateNetwork{}
pid := c.InitPID()
if pid < 1 {
return result
}
couldUseNetnsGetifaddrs := c.state.OS.NetnsGetifaddrs
if couldUseNetnsGetifaddrs {
nw, err := netutils.NetnsGetifaddrs(int32(pid))
if err != nil {
couldUseNetnsGetifaddrs = false
logger.Error("Failed to retrieve network information via netlink", log.Ctx{"container": c.name, "pid": pid})
} else {
result = nw
}
}
if !couldUseNetnsGetifaddrs {
// Get the network state from the container
out, err := shared.RunCommand(
c.state.OS.ExecPath,
"forknet",
"info",
fmt.Sprintf("%d", pid))
// Process forkgetnet response
if err != nil {
logger.Error("Error calling 'lxd forkgetnet", log.Ctx{"container": c.name, "err": err, "pid": pid})
return result
}
// If we can use netns_getifaddrs() but it failed and the setns() +
// netns_getifaddrs() succeeded we should just always fallback to the
// setns() + netns_getifaddrs() style retrieval.
c.state.OS.NetnsGetifaddrs = false
nw := map[string]api.InstanceStateNetwork{}
err = json.Unmarshal([]byte(out), &nw)
if err != nil {
logger.Error("Failure to read forkgetnet json", log.Ctx{"container": c.name, "err": err})
return result
}
result = nw
}
// Get host_name from volatile data if not set already.
for name, dev := range result {
if dev.HostName == "" {
dev.HostName = c.localConfig[fmt.Sprintf("volatile.%s.host_name", name)]
result[name] = dev
}
}
return result
}
func (c *lxc) processesState() int64 {
// Return 0 if not running
pid := c.InitPID()
if pid == -1 {
return 0
}
cg, err := c.cgroup(nil)
if err != nil {
return 0
}
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
value, err := cg.GetProcessesUsage()
if err != nil {
return -1
}
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return -1
}
return valueInt
}
pids := []int64{int64(pid)}
// Go through the pid list, adding new pids at the end so we go through them all
for i := 0; i < len(pids); i++ {
fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i])
fcont, err := ioutil.ReadFile(fname)
if err != nil {
// the process terminated during execution of this loop
continue
}
content := strings.Split(string(fcont), " ")
for j := 0; j < len(content); j++ {
pid, err := strconv.ParseInt(content[j], 10, 64)
if err == nil {
pids = append(pids, pid)
}
}
}
return int64(len(pids))
}
// getStoragePool returns the current storage pool handle. To avoid a DB lookup each time this
// function is called, the handle is cached internally in the lxc struct.
func (c *lxc) getStoragePool() (storagePools.Pool, error) {
if c.storagePool != nil {
return c.storagePool, nil
}
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return nil, err
}
c.storagePool = pool
return c.storagePool, nil
}
// getStorageType returns the storage type of the instance's storage pool.
func (c *lxc) getStorageType() (string, error) {
pool, err := c.getStoragePool()
if err != nil {
return "", err
}
return pool.Driver().Info().Name, nil
}
// StorageStart mounts the instance's rootfs volume. Deprecated.
func (c *lxc) StorageStart() (bool, error) {
return c.mount()
}
// mount the instance's rootfs volume if needed.
func (c *lxc) mount() (bool, error) {
pool, err := c.getStoragePool()
if err != nil {
return false, err
}
if c.IsSnapshot() {
ourMount, err := pool.MountInstanceSnapshot(c, nil)
if err != nil {
return false, err
}
return ourMount, nil
}
ourMount, err := pool.MountInstance(c, nil)
if err != nil {
return false, err
}
return ourMount, nil
}
// StorageStop unmounts the instance's rootfs volume. Deprecated.
func (c *lxc) StorageStop() (bool, error) {
return c.unmount()
}
// unmount the instance's rootfs volume if needed.
func (c *lxc) unmount() (bool, error) {
pool, err := c.getStoragePool()
if err != nil {
return false, err
}
if c.IsSnapshot() {
unmounted, err := pool.UnmountInstanceSnapshot(c, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
unmounted, err := pool.UnmountInstance(c, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
// Mount handling
func (c *lxc) insertMountLXD(source, target, fstype string, flags int, mntnsPID int, shiftfs bool) error {
pid := mntnsPID
if pid <= 0 {
// Get the init PID
pid = c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't insert mount into stopped container")
}
}
// Create the temporary mount target
var tmpMount string
var err error
if shared.IsDir(source) {
tmpMount, err = ioutil.TempDir(c.ShmountsPath(), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
} else {
f, err := ioutil.TempFile(c.ShmountsPath(), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
tmpMount = f.Name()
f.Close()
}
defer os.Remove(tmpMount)
// Mount the filesystem
err = unix.Mount(source, tmpMount, fstype, uintptr(flags), "")
if err != nil {
return fmt.Errorf("Failed to setup temporary mount: %s", err)
}
defer unix.Unmount(tmpMount, unix.MNT_DETACH)
// Setup host side shiftfs as needed
if shiftfs {
err = unix.Mount(tmpMount, tmpMount, "shiftfs", 0, "mark,passthrough=3")
if err != nil {
return fmt.Errorf("Failed to setup host side shiftfs mount: %s", err)
}
defer unix.Unmount(tmpMount, unix.MNT_DETACH)
}
// Move the mount inside the container
mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount))
pidStr := fmt.Sprintf("%d", pid)
_, err = shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxd-mount", pidStr, mntsrc, target, fmt.Sprintf("%v", shiftfs))
if err != nil {
return err
}
return nil
}
func (c *lxc) insertMountLXC(source, target, fstype string, flags int) error {
cname := project.Instance(c.Project(), c.Name())
configPath := filepath.Join(c.LogPath(), "lxc.conf")
if fstype == "" {
fstype = "none"
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxc-mount", cname, c.state.OS.LxcPath, configPath, source, target, fstype, fmt.Sprintf("%d", flags))
if err != nil {
return err
}
return nil
}
func (c *lxc) insertMount(source, target, fstype string, flags int, shiftfs bool) error {
if c.state.OS.LXCFeatures["mount_injection_file"] && !shiftfs {
return c.insertMountLXC(source, target, fstype, flags)
}
return c.insertMountLXD(source, target, fstype, flags, -1, shiftfs)
}
func (c *lxc) removeMount(mount string) error {
// Get the init PID
pid := c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't remove mount from stopped container")
}
if c.state.OS.LXCFeatures["mount_injection_file"] {
configPath := filepath.Join(c.LogPath(), "lxc.conf")
cname := project.Instance(c.Project(), c.Name())
if !strings.HasPrefix(mount, "/") {
mount = "/" + mount
}
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxc-umount", cname, c.state.OS.LxcPath, configPath, mount)
if err != nil {
return err
}
} else {
// Remove the mount from the container
pidStr := fmt.Sprintf("%d", pid)
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxd-umount", pidStr, mount)
if err != nil {
return err
}
}
return nil
}
// InsertSeccompUnixDevice inserts a seccomp device.
func (c *lxc) InsertSeccompUnixDevice(prefix string, m deviceConfig.Device, pid int) error {
if pid < 0 {
return fmt.Errorf("Invalid request PID specified")
}
rootLink := fmt.Sprintf("/proc/%d/root", pid)
rootPath, err := os.Readlink(rootLink)
if err != nil {
return err
}
uid, gid, _, _, err := seccomp.TaskIDs(pid)
if err != nil {
return err
}
idmapset, err := c.CurrentIdmap()
if err != nil {
return err
}
nsuid, nsgid := idmapset.ShiftFromNs(uid, gid)
m["uid"] = fmt.Sprintf("%d", nsuid)
m["gid"] = fmt.Sprintf("%d", nsgid)
if !path.IsAbs(m["path"]) {
cwdLink := fmt.Sprintf("/proc/%d/cwd", pid)
prefixPath, err := os.Readlink(cwdLink)
if err != nil {
return err
}
prefixPath = strings.TrimPrefix(prefixPath, rootPath)
m["path"] = filepath.Join(rootPath, prefixPath, m["path"])
} else {
m["path"] = filepath.Join(rootPath, m["path"])
}
idmapSet, err := c.CurrentIdmap()
if err != nil {
return err
}
d, err := device.UnixDeviceCreate(c.state, idmapSet, c.DevicesPath(), prefix, m, true)
if err != nil {
return fmt.Errorf("Failed to setup device: %s", err)
}
devPath := d.HostPath
tgtPath := d.RelativePath
// Bind-mount it into the container
defer os.Remove(devPath)
return c.insertMountLXD(devPath, tgtPath, "none", unix.MS_BIND, pid, false)
}
func (c *lxc) removeUnixDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-Unix devices
if !strings.HasPrefix(f.Name(), "forkmknod.unix.") && !strings.HasPrefix(f.Name(), "unix.") && !strings.HasPrefix(f.Name(), "infiniband.unix.") {
continue
}
// Remove the entry
devicePath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(devicePath)
if err != nil {
logger.Error("Failed removing unix device", log.Ctx{"err": err, "path": devicePath})
}
}
return nil
}
// FillNetworkDevice takes a nic or infiniband device type and enriches it with automatically
// generated name and hwaddr properties if these are missing from the device.
func (c *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfig.Device, error) {
var err error
newDevice := m.Clone()
// Function to try and guess an available name
nextInterfaceName := func() (string, error) {
devNames := []string{}
// Include all static interface names
for _, dev := range c.expandedDevices.Sorted() {
if dev.Config["name"] != "" && !shared.StringInSlice(dev.Config["name"], devNames) {
devNames = append(devNames, dev.Config["name"])
}
}
// Include all currently allocated interface names
for k, v := range c.expandedConfig {
if !strings.HasPrefix(k, "volatile.") {
continue
}
fields := strings.SplitN(k, ".", 3)
if len(fields) != 3 {
continue
}
if fields[2] != "name" || shared.StringInSlice(v, devNames) {
continue
}
devNames = append(devNames, v)
}
// Attempt to include all existing interfaces
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err == nil {
defer cc.Release()
interfaces, err := cc.Interfaces()
if err == nil {
for _, name := range interfaces {
if shared.StringInSlice(name, devNames) {
continue
}
devNames = append(devNames, name)
}
}
}
i := 0
name := ""
for {
if m["type"] == "infiniband" {
name = fmt.Sprintf("ib%d", i)
} else {
name = fmt.Sprintf("eth%d", i)
}
// Find a free device name
if !shared.StringInSlice(name, devNames) {
return name, nil
}
i++
}
}
updateKey := func(key string, value string) error {
tx, err := c.state.Cluster.Begin()
if err != nil {
return err
}
err = db.ContainerConfigInsert(tx, c.id, map[string]string{key: value})
if err != nil {
tx.Rollback()
return err
}
err = db.TxCommit(tx)
if err != nil {
return err
}
return nil
}
// Fill in the MAC address
if !shared.StringInSlice(m.NICType(), []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" {
configKey := fmt.Sprintf("volatile.%s.hwaddr", name)
volatileHwaddr := c.localConfig[configKey]
if volatileHwaddr == "" {
// Generate a new MAC address
volatileHwaddr, err = instance.DeviceNextInterfaceHWAddr()
if err != nil {
return nil, err
}
// Update the database
err = query.Retry(func() error {
err := updateKey(configKey, volatileHwaddr)
if err != nil {
// Check if something else filled it in behind our back
value, err1 := c.state.Cluster.ContainerConfigGet(c.id, configKey)
if err1 != nil || value == "" {
return err
}
c.localConfig[configKey] = value
c.expandedConfig[configKey] = value
return nil
}
c.localConfig[configKey] = volatileHwaddr
c.expandedConfig[configKey] = volatileHwaddr
return nil
})
if err != nil {
return nil, err
}
}
newDevice["hwaddr"] = volatileHwaddr
}
// Fill in the name
if m["name"] == "" {
configKey := fmt.Sprintf("volatile.%s.name", name)
volatileName := c.localConfig[configKey]
if volatileName == "" {
// Generate a new interface name
volatileName, err := nextInterfaceName()
if err != nil {
return nil, err
}
// Update the database
err = updateKey(configKey, volatileName)
if err != nil {
// Check if something else filled it in behind our back
value, err1 := c.state.Cluster.ContainerConfigGet(c.id, configKey)
if err1 != nil || value == "" {
return nil, err
}
c.localConfig[configKey] = value
c.expandedConfig[configKey] = value
} else {
c.localConfig[configKey] = volatileName
c.expandedConfig[configKey] = volatileName
}
}
newDevice["name"] = volatileName
}
return newDevice, nil
}
func (c *lxc) removeDiskDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-disk devices
if !strings.HasPrefix(f.Name(), "disk.") {
continue
}
// Always try to unmount the host side
_ = unix.Unmount(filepath.Join(c.DevicesPath(), f.Name()), unix.MNT_DETACH)
// Remove the entry
diskPath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(diskPath)
if err != nil {
logger.Error("Failed to remove disk device path", log.Ctx{"err": err, "path": diskPath})
}
}
return nil
}
// Network I/O limits
func (c *lxc) setNetworkPriority() error {
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set network priority on stopped container")
}
// Don't bother if the cgroup controller doesn't exist
if !c.state.OS.CGInfo.Supports(cgroup.NetPrio, cg) {
return nil
}
// Extract the current priority
networkPriority := c.expandedConfig["limits.network.priority"]
if networkPriority == "" {
networkPriority = "0"
}
networkInt, err := strconv.Atoi(networkPriority)
if err != nil {
return err
}
// Get all the interfaces
netifs, err := net.Interfaces()
if err != nil {
return err
}
// Check that we at least succeeded to set an entry
success := false
var lastError error
for _, netif := range netifs {
err = cg.SetNetIfPrio(fmt.Sprintf("%s %d", netif.Name, networkInt))
if err == nil {
success = true
} else {
lastError = err
}
}
if !success {
return fmt.Errorf("Failed to set network device priority: %s", lastError)
}
return nil
}
// IsStateful returns is instance is stateful.
func (c *lxc) IsStateful() bool {
return c.stateful
}
// IsEphemeral returns if instance is ephemeral.
func (c *lxc) IsEphemeral() bool {
return c.ephemeral
}
// IsFrozen returns if instance is frozen.
func (c *lxc) IsFrozen() bool {
return c.State() == "FROZEN"
}
// IsNesting returns if instance is nested.
func (c *lxc) IsNesting() bool {
return shared.IsTrue(c.expandedConfig["security.nesting"])
}
func (c *lxc) isCurrentlyPrivileged() bool {
if !c.IsRunning() {
return c.IsPrivileged()
}
idmap, err := c.CurrentIdmap()
if err != nil {
return c.IsPrivileged()
}
return idmap == nil
}
// IsPrivileged returns if instance is privileged.
func (c *lxc) IsPrivileged() bool {
return shared.IsTrue(c.expandedConfig["security.privileged"])
}
// IsRunning returns if instance is running.
func (c *lxc) IsRunning() bool {
state := c.State()
return state != "BROKEN" && state != "STOPPED"
}
// IsSnapshot returns if instance is a snapshot.
func (c *lxc) IsSnapshot() bool {
return c.snapshot
}
// Architecture returns architecture of instance.
func (c *lxc) Architecture() int {
return c.architecture
}
// CreationDate returns creation date of instance.
func (c *lxc) CreationDate() time.Time {
return c.creationDate
}
// LastUsedDate returns last used date time of instance.
func (c *lxc) LastUsedDate() time.Time {
return c.lastUsedDate
}
// ExpandedConfig returns expanded config.
func (c *lxc) ExpandedConfig() map[string]string {
return c.expandedConfig
}
// ExpandedDevices returns expanded devices config.
func (c *lxc) ExpandedDevices() deviceConfig.Devices {
return c.expandedDevices
}
// ID gets instances's ID.
func (c *lxc) ID() int {
return c.id
}
// InitPID returns PID of init process.
func (c *lxc) InitPID() int {
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return -1
}
return c.c.InitPid()
}
// LocalConfig returns local config.
func (c *lxc) LocalConfig() map[string]string {
return c.localConfig
}
// LocalDevices returns local device config.
func (c *lxc) LocalDevices() deviceConfig.Devices {
return c.localDevices
}
// CurrentIdmap returns current IDMAP.
func (c *lxc) CurrentIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.idmap.current"]
if !ok {
return c.DiskIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// DiskIdmap returns DISK IDMAP.
func (c *lxc) DiskIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.last_state.idmap"]
if !ok {
return nil, nil
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// NextIdmap returns next IDMAP.
func (c *lxc) NextIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.idmap.next"]
if !ok {
return c.CurrentIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// Location returns instance location.
func (c *lxc) Location() string {
return c.node
}
// Project returns instance project.
func (c *lxc) Project() string {
return c.project
}
// Name returns instance name.
func (c *lxc) Name() string {
return c.name
}
// Description returns instance description.
func (c *lxc) Description() string {
return c.description
}
// Profiles returns instance profiles.
func (c *lxc) Profiles() []string {
return c.profiles
}
// State returns instance state.
func (c *lxc) State() string {
state, err := c.getLxcState()
if err != nil {
return api.Error.String()
}
return state.String()
}
// Path instance path.
func (c *lxc) Path() string {
return storagePools.InstancePath(c.Type(), c.Project(), c.Name(), c.IsSnapshot())
}
// DevicesPath devices path.
func (c *lxc) DevicesPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.VarPath("devices", name)
}
// ShmountsPath shared mounts path.
func (c *lxc) ShmountsPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.VarPath("shmounts", name)
}
// LogPath log path.
func (c *lxc) LogPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.LogPath(name)
}
// LogFilePath log file path.
func (c *lxc) LogFilePath() string {
return filepath.Join(c.LogPath(), "lxc.log")
}
// ConsoleBufferLogPath console buffer log path.
func (c *lxc) ConsoleBufferLogPath() string {
return filepath.Join(c.LogPath(), "console.log")
}
// RootfsPath root filesystem path.
func (c *lxc) RootfsPath() string {
return filepath.Join(c.Path(), "rootfs")
}
// TemplatesPath templates path.
func (c *lxc) TemplatesPath() string {
return filepath.Join(c.Path(), "templates")
}
// StatePath state path.
func (c *lxc) StatePath() string {
/* FIXME: backwards compatibility: we used to use Join(RootfsPath(),
* "state"), which was bad. Let's just check to see if that directory
* exists.
*/
oldStatePath := filepath.Join(c.RootfsPath(), "state")
if shared.IsDir(oldStatePath) {
return oldStatePath
}
return filepath.Join(c.Path(), "state")
}
// StoragePool storage pool name.
func (c *lxc) StoragePool() (string, error) {
poolName, err := c.state.Cluster.InstancePool(c.Project(), c.Name())
if err != nil {
return "", err
}
return poolName, nil
}
// SetOperation handles progress tracking.
func (c *lxc) SetOperation(op *operations.Operation) {
c.op = op
}
// ExpiryDate sets expiry date.
func (c *lxc) ExpiryDate() time.Time {
if c.IsSnapshot() {
return c.expiryDate
}
// Return zero time if the container is not a snapshot
return time.Time{}
}
func (c *lxc) updateProgress(progress string) {
if c.op == nil {
return
}
meta := c.op.Metadata()
if meta == nil {
meta = make(map[string]interface{})
}
if meta["container_progress"] != progress {
meta["container_progress"] = progress
c.op.UpdateMetadata(meta)
}
}
// Internal MAAS handling.
func (c *lxc) maasInterfaces(devices map[string]map[string]string) ([]maas.ContainerInterface, error) {
interfaces := []maas.ContainerInterface{}
for k, m := range devices {
if m["type"] != "nic" {
continue
}
if m["maas.subnet.ipv4"] == "" && m["maas.subnet.ipv6"] == "" {
continue
}
m, err := c.FillNetworkDevice(k, m)
if err != nil {
return nil, err
}
subnets := []maas.ContainerInterfaceSubnet{}
// IPv4
if m["maas.subnet.ipv4"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv4"],
Address: m["ipv4.address"],
}
subnets = append(subnets, subnet)
}
// IPv6
if m["maas.subnet.ipv6"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv6"],
Address: m["ipv6.address"],
}
subnets = append(subnets, subnet)
}
iface := maas.ContainerInterface{
Name: m["name"],
MACAddress: m["hwaddr"],
Subnets: subnets,
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
func (c *lxc) maasUpdate(oldDevices map[string]map[string]string) error {
// Check if MAAS is configured
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
// Check if there's something that uses MAAS
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
var oldInterfaces []maas.ContainerInterface
if oldDevices != nil {
oldInterfaces, err = c.maasInterfaces(oldDevices)
if err != nil {
return err
}
}
if len(interfaces) == 0 && len(oldInterfaces) == 0 {
return nil
}
// See if we're connected to MAAS
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if exists {
if len(interfaces) == 0 && len(oldInterfaces) > 0 {
return c.state.MAAS.DeleteContainer(project.Instance(c.project, c.name))
}
return c.state.MAAS.UpdateContainer(project.Instance(c.project, c.name), interfaces)
}
return c.state.MAAS.CreateContainer(project.Instance(c.project, c.name), interfaces)
}
func (c *lxc) maasRename(newName string) error {
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if !exists {
return c.maasUpdate(nil)
}
return c.state.MAAS.RenameContainer(project.Instance(c.project, c.name), project.Instance(c.project, newName))
}
func (c *lxc) maasDelete() error {
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if !exists {
return nil
}
return c.state.MAAS.DeleteContainer(project.Instance(c.project, c.name))
}
func (c *lxc) cgroup(cc *liblxc.Container) (*cgroup.CGroup, error) {
rw := lxcCgroupReadWriter{}
if cc != nil {
rw.cc = cc
rw.conf = true
} else {
rw.cc = c.c
}
cg, err := cgroup.New(&rw)
if err != nil {
return nil, err
}
cg.UnifiedCapable = liblxc.HasApiExtension("cgroup2")
return cg, nil
}
type lxcCgroupReadWriter struct {
cc *liblxc.Container
conf bool
cgroup2 bool
}
func (rw *lxcCgroupReadWriter) Get(version cgroup.Backend, controller string, key string) (string, error) {
if rw.conf {
lxcKey := fmt.Sprintf("lxc.cgroup.%s", key)
if version == cgroup.V2 {
lxcKey = fmt.Sprintf("lxc.cgroup2.%s", key)
}
return strings.Join(rw.cc.ConfigItem(lxcKey), "\n"), nil
}
return strings.Join(rw.cc.CgroupItem(key), "\n"), nil
}
func (rw *lxcCgroupReadWriter) Set(version cgroup.Backend, controller string, key string, value string) error {
if rw.conf {
if version == cgroup.V1 {
return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup.%s", key), value)
}
return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup2.%s", key), value)
}
return rw.cc.SetCgroupItem(key, value)
}
// UpdateBackupFile writes the instance's backup.yaml file to storage.
func (c *lxc) UpdateBackupFile() error {
pool, err := c.getStoragePool()
if err != nil {
return err
}
return pool.UpdateInstanceBackupFile(c, nil)
}
// SaveConfigFile generates the LXC config file on disk.
func (c *lxc) SaveConfigFile() error {
err := c.initLXC(true)
if err != nil {
return errors.Wrapf(err, "Failed to generate LXC config")
}
// Generate the LXC config.
configPath := filepath.Join(c.LogPath(), "lxc.conf")
err = c.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return errors.Wrapf(err, "Failed to save LXC config to file %q", configPath)
}
return nil
}
|
[
"\"LXD_LXC_TEMPLATE_CONFIG\"",
"\"LXD_LXC_HOOK\""
] |
[] |
[
"LXD_LXC_TEMPLATE_CONFIG",
"LXD_LXC_HOOK"
] |
[]
|
["LXD_LXC_TEMPLATE_CONFIG", "LXD_LXC_HOOK"]
|
go
| 2 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.