Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
for job in config.get('jobs') or []:
name = job['name']
job['name'] = "{}.{}".format(MASTER_NAMESPACE, name)
job['namespace'] = MASTER_NAMESPACE
jobs[name] = job
config['jobs'] = jobs
return kls.create(config)
except Exception as e:
raise ValueError(f"Config MASTER {e}").with_traceback(
e.__traceback__
)
class NamedTronConfig(ConfigRecord):
namespace = field(type=str, mandatory=True)
nodes = field(type=(PVector, PSet), initial=v(), factory=freeze)
command_context = field(type=PMap, initial=m(), factory=freeze)
jobs = field(type=JobMap, initial=JobMap(), factory=JobMap.from_config)
def __invariant__(self):
not_sane = jobs_actions_sanity(self, self.nodes)
if not_sane:
return not_sane
return (True, "all ok")
@classmethod
def from_config(kls, config):
""" Given a parsed config file (should be only basic literals and
containers), return an immutable, fully populated series of namedtuples and
FrozenDicts with all defaults filled in, all valid values, and no unused
values. Throws a ValueError if any part of the input dict is invalid.
env['m'] = m
env['pmap'] = pmap
env['s'] = s
env['pset'] = pset
env['l'] = l
env['plist'] = plist
env['b'] = b
env['pbag'] = pbag
env['dq'] = dq
env['pdeque'] = pdeque
env['thaw'] = thaw
env['freeze'] = freeze
env['immutable'] = immutable
env['PVector'] = PVector
env['PMap'] = PMap
env['PSet'] = PSet
env['PList'] = PList
env['PBag'] = PBag
if not IS_PYPY:
env['union'] = union
env['options'] = options
env['optional'] = optional
env['only'] = only
env['predicate'] = predicate
env[Number.__name__] = Number
env['append'] = MutableSequence.append
# env['clear'] = MutableSequence.clear # not supported (pypy)
env['seq_count'] = MutableSequence.count
env['extend'] = MutableSequence.extend
env['insert'] = MutableSequence.insert
env['pop'] = MutableSequence.pop
env['remove'] = MutableSequence.remove
:param subobj_b: The desired output sub object.
:returns: An iterable of ``_IDiffChange`` s that will turn ``subobj_a``
into ``subobj_b``.
"""
if subobj_a == subobj_b:
return pvector([])
elif isinstance(subobj_a, PClass) and isinstance(subobj_b, PClass):
a_dict = subobj_a._to_dict()
b_dict = subobj_b._to_dict()
return _create_diffs_for_mappings(current_path, a_dict, b_dict)
elif isinstance(subobj_a, PMap) and isinstance(subobj_b, PMap):
return _create_diffs_for_mappings(
current_path, subobj_a, subobj_b)
elif isinstance(subobj_a, PSet) and isinstance(subobj_b, PSet):
return _create_diffs_for_sets(
current_path, subobj_a, subobj_b)
# If the objects are not equal, and there is no intelligent way to recurse
# inside the objects to make a smaller diff, simply set the current path
# to the object in b.
if len(current_path) > 0:
return pvector([
_Set(
path=current_path[:-1],
key=current_path[-1],
value=subobj_b
)
])
# Or if there's no path we're replacing the root object to which subsequent
# ``_IDiffChange`` operations will be applied.
else:
"""
Raised when Otter creates more servers than a launch configuration
specifies.
"""
pass
class UndershootError(AssertionError):
"""
Raised when Otter removes more servers than a launch configuration
specifies.
"""
pass
@attributes([Attribute("servers", instance_of=PSet),
Attribute("lb_connections", instance_of=PSet)],
apply_immutable=True)
class GroupState(object):
"""
The externally visible state of a group at a point in time.
:attr pset servers: Set of the servers in the group.
:attr pset lb_nodes: Set of the load balancer nodes in the group.
"""
def measure_progress(prev_state, curr_state, desired_state):
"""
How many steps have been made towards the desired state between
the previous and current states?
_sentinel = object()
class _IEvolvable(Interface):
"""
An interface to mark classes that provide a ``Pyrsistent`` style
``evolver`` method.
"""
def evolver():
"""
:returns: A mutable version of the underlying object.
"""
classImplements(PSet, _IEvolvable)
classImplements(PMap, _IEvolvable)
classImplements(PClass, _IEvolvable)
class _ISetType(Interface):
"""
The operations that can be performed when transforming a ``PSet`` object.
"""
def add(item):
"""
Add ``item`` to set.
"""
def remove(item):
"""
Remove ``item`` from set.
Raised when Otter creates more servers than a launch configuration
specifies.
"""
pass
class UndershootError(AssertionError):
"""
Raised when Otter removes more servers than a launch configuration
specifies.
"""
pass
@attributes([Attribute("servers", instance_of=PSet),
Attribute("lb_connections", instance_of=PSet)],
apply_immutable=True)
class GroupState(object):
"""
The externally visible state of a group at a point in time.
:attr pset servers: Set of the servers in the group.
:attr pset lb_nodes: Set of the load balancer nodes in the group.
"""
def measure_progress(prev_state, curr_state, desired_state):
"""
How many steps have been made towards the desired state between
the previous and current states?
XXX: The NovaServer instances we get from GroupState don't
error = exc_tuple[1]
failures = []
retries = []
for excp in error.errors:
if isinstance(excp, rcv3.ServerUnprocessableError):
retries.append(ErrorReason.String(excp.message))
else:
failures.append(ErrorReason.String(excp.message))
if failures:
return StepResult.FAILURE, failures
else:
return StepResult.RETRY, retries
@implementer(IStep)
@attributes([Attribute('lb_node_pairs', instance_of=PSet)])
class BulkRemoveFromRCv3(object):
"""
Some connections must be removed between some combination of nodes
and RackConnect v3.0 load balancers.
See http://docs.rcv3.apiary.io/#delete-%2Fv3%2F{tenant_id}
%2Fload_balancer_pools%2Fnodes.
:param list lb_node_pairs: A list of ``lb_id, node_id`` tuples of
connections to be removed.
"""
def as_effect(self):
"""
Produce a :obj:`Effect` to remove some nodes from some RCv3 load
balancers.
"""
:ivar str flavor_id: The ID of the flavor the server was launched with
:ivar PSet desired_lbs: An immutable mapping of load balancer IDs to lists
of :class:`CLBDescription` instances.
:var dict json: JSON dict received from Nova from which this server
is created
"""
id = attr.ib()
state = attr.ib(validator=_validate_state)
created = attr.ib()
image_id = attr.ib()
flavor_id = attr.ib()
# type(pvector()) is pvectorc.PVector, which != pyrsistent.PVector
links = attr.ib(default=attr.Factory(pvector),
validator=instance_of(type(pvector())))
desired_lbs = attr.ib(default=attr.Factory(pset),
validator=instance_of(PSet))
servicenet_address = attr.ib(default='',
validator=instance_of(string_types))
json = attr.ib(default=attr.Factory(pmap), validator=instance_of(PMap))
@classmethod
def from_server_details_json(cls, server_json):
"""
Create a :obj:`NovaServer` instance from a server details JSON
dictionary, although without any 'server' or 'servers' initial resource
key.
See
http://docs.rackspace.com/servers/api/v2/cs-devguide/content/
Get_Server_Details-d1e2623.html
:return: :obj:`NovaServer` instance
:param obj: The object to serialize.
:returns: An object that is shallowly JSON serializable.
"""
if isinstance(obj, PRecord):
result = dict(obj)
result[_CLASS_MARKER] = obj.__class__.__name__
return result
elif isinstance(obj, PClass):
result = obj._to_dict()
result[_CLASS_MARKER] = obj.__class__.__name__
return result
elif isinstance(obj, PMap):
return {_CLASS_MARKER: u"PMap", u"values": dict(obj).items()}
elif isinstance(obj, (PSet, PVector, set)):
return list(obj)
elif isinstance(obj, FilePath):
return {_CLASS_MARKER: u"FilePath",
u"path": obj.path.decode("utf-8")}
elif isinstance(obj, UUID):
return {_CLASS_MARKER: u"UUID",
"hex": unicode(obj)}
elif isinstance(obj, datetime):
if obj.tzinfo is None:
raise ValueError(
"Datetime without a timezone: {}".format(obj))
return {_CLASS_MARKER: u"datetime",
"seconds": timegm(obj.utctimetuple())}
return obj