8000 Make --stacks flag build dependencies by ejholmes · Pull Request #282 · cloudtools/stacker · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Make --stacks flag build dependencies #282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions stacker/actions/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,9 @@ def _handle_missing_parameters(self, params, required_params,

return params.items()

def _generate_plan(self, tail=False):
def _generate_plan(self, tail=False, stack_names=None):
plan = Plan(description="Create/Update stacks")
plan.build(self.context.get_stacks())
plan.build(self.context.get_stacks(), stack_names=stack_names)
return plan

def pre_run(self, outline=False, *args, **kwargs):
Expand All @@ -282,13 +282,14 @@ def pre_run(self, outline=False, *args, **kwargs):
util.handle_hooks("pre_build", pre_build, self.provider.region,
self.context)

def run(self, outline=False, tail=False, dump=False, *args, **kwargs):
def run(self, outline=False, tail=False,
dump=False, stack_names=None, *args, **kwargs):
"""Kicks off the build/update of the stacks in the stack_definitions.

This is the main entry point for the Builder.

"""
plan = self._generate_plan(tail=tail)
plan = self._generate_plan(tail=tail, stack_names=stack_names)
if not outline and not dump:
plan.outline(logging.DEBUG)
logger.debug("Launching stacks: %s", ", ".join(plan.keys()))
Expand Down
13 changes: 7 additions & 6 deletions stacker/commands/stacker/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ def add_arguments(self, parser):
"the config.")
parser.add_argument("--stacks", action="append",
metavar="STACKNAME", type=str,
help="Only work on the stacks given. Can be "
"specified more than once. If not specified "
"then stacker will work on all stacks in the "
"config file.")
help="Only work on the given stacks, and their "
"dependencies. Can be specified more than "
"once. If not specified then stacker will "
"work on all stacks in the config file.")
parser.add_argument("-t", "--tail", action="store_true",
help="Tail the CloudFormation logs while working"
"with stacks")
Expand All @@ -49,7 +49,8 @@ def run(self, options, **kwargs):
action = build.Action(options.context, provider=options.provider)
action.execute(outline=options.outline,
tail=options.tail,
dump=options.dump)
dump=options.dump,
stack_names=options.stacks)

def get_context_kwargs(self, options, **kwargs):
return {"stack_names": options.stacks, "force_stacks": options.force}
return {"force_stacks": options.force}
9 changes: 1 addition & 8 deletions stacker/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ class Context(object):
namespace (str): A unique namespace for the stacks being built.
environment (dict): A dictionary used to pass in information about
the environment. Useful for templating.
stack_names (list): A list of stack_names to operate on. If not passed,
usually all stacks defined in the config will be operated on.
parameters (dict): Parameters from the command line passed down to each
blueprint to parameterize the templates.
mappings (dict): Used as Cloudformation mappings for the blueprint.
Expand All @@ -42,7 +40,6 @@ class Context(object):
"""

def __init__(self, environment, # pylint: disable-msg=too-many-arguments
stack_names=None,
parameters=None, mappings=None, config=None,
force_stacks=None):
try:
Expand All @@ -51,7 +48,6 @@ def __init__(self, environment, # pylint: disable-msg=too-many-arguments
raise MissingEnvironment(["namespace"])

self.environment = environment
self.stack_names = stack_names or []
self.parameters = parameters or {}
self.mappings = mappings or {}
self.namespace_delimiter = "-"
Expand Down Expand Up @@ -83,10 +79,7 @@ def load_config(self, conf_string):
register_lookup_handler(key, handler)

def _get_stack_definitions(self):
if not self.stack_names:
return self.config["stacks"]
return [s for s in self.config["stacks"] if s["name"] in
self.stack_names]
return self.config["stacks"]

def get_stacks(self):
"""Get the stacks for the current action.
Expand Down
22 changes: 22 additions & 0 deletions stacker/dag/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,28 @@ def all_downstreams(self, node, graph=None):
lambda node: node
in nodes_seen, self.topological_sort(graph=graph))

def filter(self, nodes, graph=None):
""" Returns a new DAG with only the given nodes and their
dependencies.
"""

if graph is None:
graph = self.graph
dag = DAG()

# Add only the nodes we need.
for node in nodes:
dag.add_node_if_not_exists(node)
for edge in self.all_downstreams(node, graph=graph):
dag.add_node_if_not_exists(edge)

# Now, rebuild the graph for each node that's present.
for node, edges in graph.items():
if node in dag.graph:
dag.graph[node] = edges

return dag

def all_leaves(self, graph=None):
""" Return a list of all leaves (nodes with no downstreams) """
if graph is None:
Expand Down
11 changes: 10 additions & 1 deletion stacker/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ def __init__(self, description, reverse=False, sleep_func=sleep):
self._sleep_func = sleep_func
self.id = uuid.uuid4()

def build(self, stacks):
def build(self, stacks, stack_names=None):
""" Builds an internal dag from the stacks and their dependencies.

Args:
stacks (list): a list of :class:`stacker.stack.Stack` objects
to build the plan with.
stack_names (list): a list of stack names to filter on.
"""
dag = DAG()

Expand All @@ -138,6 +139,14 @@ def build(self, stacks):
except DAGValidationError as e:
raise GraphError(e, stack.fqn, dep)

if stack_names:
nodes = []
for stack_name in stack_names:
for stack in stacks:
if stack.name == stack_name:
nodes.append(stack.fqn)
dag = dag.filter(nodes)

self._dag = dag
return None

Expand Down
10 changes: 0 additions & 10 deletions stacker/tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,11 @@ def test_context_environment_namespace_required(self):
def test_context_optional_keys_set(self):
context = Context(
environment=self.environment,
stack_names=["stack"],
mappings={},
config={},
)
for key in ["mappings", "config"]:
self.assertEqual(getattr(context, key), {})
self.assertEqual(context.stack_names, ["stack"])

def test_context_get_stacks_specific_stacks(self):
context = Context(
environment=self.environment,
config=self.config,
stack_names=["stack2"],
)
self.assertEqual(len(context.get_stacks()), 1)

def test_context_get_stacks(self):
context = Context(self.environment, config=self.config)
Expand Down
8 changes: 8 additions & 0 deletions stacker/tests/test_dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ def test_predecessors():
assert set(dag.predecessors('d')) == set(['b', 'c'])


@with_setup(start_with_graph)
def test_filter():
dag2 = dag.filter(['b', 'c'])
assert dag2.graph == {'b': set('d'),
'c': set('d'),
'd': set()}


@with_setup(start_with_graph)
def test_all_leaves():
assert dag.all_leaves() == ['d']
Expand Down
24 changes: 24 additions & 0 deletions stacker/tests/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,30 @@ def fn(stack, status=None):

self.assertEqual(steps, ['namespace-vpc.1', 'namespace-bastion.1'])

def test_execute_plan_named_stacks(self):
vpc = Stack(
definition=generate_definition('vpc', 1),
context=self.context)
bastion = Stack(
definition=generate_definition('bastion', 1, requires=[vpc.fqn]),
context=self.context)
db = Stack(
definition=generate_definition('db', 1, requires=[vpc.fqn]),
context=self.context)

plan = Plan(description="Test", sleep_func=None)
plan.build([vpc, bastion, db], stack_names=['db.1'])

steps = []

def fn(stack, status=None):
steps.append(stack.fqn)
return COMPLETE

plan.execute(fn)

self.assertEqual(steps, ['namespace-vpc.1', 'namespace-db.1'])

def test_execute_plan_reverse(self):
vpc = Stack(
definition=generate_definition('vpc', 1),
Expand Down
0