├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── docs └── source │ ├── conf.py │ ├── index.rst │ └── type_utils.rst ├── environment_tools ├── __init__.py ├── config.py └── type_utils.py ├── requirements-dev.txt ├── setup.py ├── tests ├── __init__.py └── test_type_utils.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = 4 | . 5 | omit = 6 | .tox/* 7 | /usr/* 8 | */tmp* 9 | setup.py 10 | # Don't complain if non-runnable code isn't run 11 | */__main__.py 12 | 13 | [report] 14 | exclude_lines = 15 | # Have to re-enable the standard pragma 16 | \#\s*pragma: no cover 17 | 18 | # Don't complain if tests don't hit defensive assertion code: 19 | ^\s*raise AssertionError\b 20 | ^\s*raise NotImplementedError\b 21 | ^\s*return NotImplemented\b 22 | ^\s*raise$ 23 | 24 | # Don't complain if non-runnable code isn't run: 25 | ^if __name__ == ['"]__main__['"]:$ 26 | 27 | [html] 28 | directory = coverage-html 29 | 30 | # vim:ft=dosini 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | *.so 3 | *.sw[nop] 4 | .#* 5 | .DS_Store 6 | ._* 7 | \#*\# 8 | build 9 | dist 10 | *~ 11 | *.log 12 | precomputed 13 | .pydevproject 14 | .project 15 | *.sublime-* 16 | virtualenv_run 17 | .tox 18 | apollo.egg-info/ 19 | __pycache__ 20 | .idea/ 21 | .coverage 22 | environment_tools.egg-info 23 | .cache/ 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3.5 3 | env: 4 | - TOXENV=py27 5 | - TOXENV=py35 6 | install: pip install tox 7 | script: tox 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Yelp Inc 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all docs test tests coverage clean 2 | 3 | BIND_FILES ?= undefined 4 | 5 | all: 6 | @true 7 | 8 | docs: 9 | tox -e docs 10 | 11 | test: 12 | tox 13 | 14 | tests: test 15 | coverage: test 16 | 17 | clean: 18 | rm -rf docs/build/* 19 | rm -rf environment_tools.egg-info/ 20 | rm -rf .coverage 21 | rm -rf .tox 22 | rm -rf virtualenv_run 23 | find . -name '*.pyc' -delete 24 | find . -name '__pycache__' -delete 25 | 26 | super-clean: 27 | git clean -ffdx 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The "environment_tools" library 2 | =============================== 3 | 4 | [![Build Status](https://travis-ci.org/Yelp/environment_tools.svg?branch=master)](https://travis-ci.org/Yelp/environment_tools) 5 | 6 | Utilities for working with hierarchical environments, such as datacenters and 7 | AWS regions grouped into logical environments, like prod, staging, dev. 8 | 9 | This library primary reads two files: `location_types.json` and 10 | `location_mapping.json`. 11 | 12 | Examples 13 | -------- 14 | 15 | An example environment might have a `location_types.json` that looks like this: 16 | 17 | ```json 18 | ["ecosystem", "superregion", "region", "habitat"] 19 | ``` 20 | 21 | These go from least specific (largest) to most specific (smallest). The 22 | smaller location types (like habitat) are entirely enclosed within the larger 23 | types. 24 | 25 | The `location_mapping.json` file should list every location in a tree 26 | structure, with the largest groupings (`ecosystem`, in the example above) as 27 | the root key, and the smaller structures nested as subkeys. The smallest 28 | location types (`habitat` in the example) should have an empty dictionary as 29 | their value. 30 | 31 | Example `location_mapping.json`: 32 | 33 | ```json 34 | { 35 | "prod_ecosystem": { 36 | "pnw-prod_superregion": { 37 | "uswest2-prod_region": { 38 | "uswest2aprod_habitat": {}, 39 | "uswest2bprod_habitat": {}, 40 | "uswest2cprod_habitat": {} 41 | }, 42 | "pdx-prod_region": { 43 | "pdx1_habitat": {}, 44 | } 45 | }, 46 | "nova-prod_superregion": { 47 | "useast1-prod_region": { 48 | "useast1aprod_habitat": {}, 49 | "useast1bprod_habitat": {}, 50 | "useast1cprod_habitat": {} 51 | }, 52 | "iad-prod_region": { 53 | "iad1_habitat": {}, 54 | "iad2_habitat": {} 55 | } 56 | } 57 | }, 58 | "deva_ecosystem": { 59 | "norcal-deva_superregion": { 60 | "uswest1-deva_region": { 61 | "uswest1adeva_habitat": {}, 62 | "uswest1bdeva_habitat": {} 63 | } 64 | } 65 | } 66 | } 67 | ``` 68 | 69 | In this example, our production `ecosystem` has two `superregion`s, each 70 | containing an AWS region and one or more physical datacenters (pdx1, iad1, 71 | iad2). 72 | 73 | Our `deva` ecosystem is much simpler, containing only one superregion with one 74 | AWS region. 75 | 76 | Picking location types 77 | ---------------------- 78 | 79 | At Yelp, we defined the `ecosystem` as one distinct copy of our infrastructure. 80 | All of production is one `ecosystem`, and then each staging environment or dev 81 | environment is its own `ecosystem`. In general, an application running within 82 | one `ecosystem` should talk only to hosts and applications running within the 83 | same `ecosystem`. 84 | 85 | To subdivide, we have `habitat`s for each AWS availability zone or physical 86 | datacenter cage within an ecosystem. AWS regions become `region`s, and we 87 | define `region`s around physical datacenters. Regions are then grouped 88 | together into `superregion`s, according to some latency bound. 89 | 90 | Note that one physical datacenter or AZ can house multiple `habitat`s: there 91 | could be a `uswest1aprod` and a `uswest1adevb`, which are distinct from one 92 | another. 93 | 94 | An application can then operate at the level of the hierarchy that makes the 95 | most sense for its latency and resource requirements. A service with extremely 96 | tight latency requirements might choose to operate at the `habitat` level, 97 | speaking only with other instances within the same habitat. A service with 98 | looser SLAs might operate at the `superregion` level, giving it more 99 | flexibility of where to run. 100 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | extensions = [ 4 | 'sphinx.ext.autodoc', 5 | 'sphinx.ext.intersphinx', 6 | 'sphinx.ext.viewcode', 7 | 'sphinx.ext.coverage' 8 | ] 9 | 10 | # Add any paths that contain templates here, relative to this directory. 11 | templates_path = ['_templates'] 12 | 13 | # The suffix of source filenames. 14 | source_suffix = '.rst' 15 | 16 | # The encoding of source files. 17 | #source_encoding = 'utf-8-sig' 18 | 19 | # The master toctree document. 20 | master_doc = 'index' 21 | 22 | # General information about the project. 23 | project = u'environment_tools' 24 | copyright = u'Yelp Inc' 25 | 26 | from environment_tools import version 27 | release = version 28 | 29 | exclude_patterns = [] 30 | 31 | pygments_style = 'sphinx' 32 | 33 | 34 | # -- Options for HTML output --------------------------------------------------- 35 | 36 | html_theme = 'sphinxdoc' 37 | 38 | 39 | # Example configuration for intersphinx: refer to the Python standard library. 40 | intersphinx_mapping = {'http://docs.python.org/': None} 41 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Environment Tools 2 | ================= 3 | 4 | This module provides utilities to enable developers to reason about datacenter 5 | topologies. 6 | 7 | Relevant Modules 8 | ---------------- 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | type_utils 13 | -------------------------------------------------------------------------------- /docs/source/type_utils.rst: -------------------------------------------------------------------------------- 1 | Type Utilities 2 | ============== 3 | The type_utils module contains methods and members relevant to reasoning about 4 | datacenter types. 5 | 6 | .. automodule:: environment_tools.type_utils 7 | :members: 8 | :undoc-members: 9 | -------------------------------------------------------------------------------- /environment_tools/__init__.py: -------------------------------------------------------------------------------- 1 | version = __version__ = '1.2.2' 2 | -------------------------------------------------------------------------------- /environment_tools/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import json 3 | import os 4 | 5 | import networkx as nx 6 | 7 | DATA_DIRECTORY = '/usr/share/yelp_location' 8 | OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' 9 | 10 | 11 | # FIXME - we're moving from distributing location information 12 | # via our configs system to via just baking the package 13 | # into AMIs, but to do that we want to be able to read 14 | # both whilst we transition - with the existing mechanism 15 | # taking preference 16 | def _read_data_json(filename): 17 | path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) 18 | if not os.path.isfile(path): 19 | path = os.path.join(DATA_DIRECTORY, filename) 20 | with open(path) as f: 21 | return json.load(f) 22 | 23 | 24 | def _convert_mapping_to_graph(dict_mapping): 25 | """ Converts the dictionary datacenter layout to a networkx.DiGraph object 26 | 27 | :param dict_mapping: A dict read out of the location_mapping datafile 28 | 29 | :returns: A :class:`networkx.DiGraph` object that is a graph representation 30 | of the provided mapping. Edges flow from the highest level of the 31 | hierarhcy to the lowest level of the hierarchy 32 | :rtype: :class:`networkx.DiGraph` 33 | """ 34 | graph = nx.DiGraph() 35 | 36 | # Recursively walk the DAG, adding edges as we go 37 | # to the closed graph object 38 | def _visit(root, subdict): 39 | edges = [(root, key) for key in subdict] 40 | graph.add_edges_from(edges) 41 | for key, value in subdict.items(): 42 | _visit(key, value) 43 | 44 | # We don't have a "root" node at the top of the DAG, 45 | # so this just kicks off the recursive process 46 | for key, value in dict_mapping.items(): 47 | _visit(key, value) 48 | 49 | return graph 50 | -------------------------------------------------------------------------------- /environment_tools/type_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from collections import namedtuple 3 | import os 4 | import networkx as nx 5 | 6 | from environment_tools.config import _read_data_json 7 | from environment_tools.config import _convert_mapping_to_graph 8 | 9 | 10 | # See https://github.com/Yelp/environment_tools/issues/2, for reasons that 11 | # are unclear, creating the DiGraph on every call to this function has 12 | # been observed to cause application memory leaks. It's probably wrong to 13 | # do this work on every call to location_graph anyways, so let's just cache it 14 | # This cache takes the form of a tuple(dict, DiGraph) so that if the json 15 | # changes we can invalidate the cache immediately. 16 | GraphCache = namedtuple('GraphCache', ('source', 'graph')) 17 | _location_graph_cache = GraphCache(None, None) 18 | 19 | 20 | def location_graph(use_cache=True): 21 | global _location_graph_cache 22 | 23 | location_mapping = _read_data_json('location_mapping.json') 24 | if not use_cache: 25 | return _convert_mapping_to_graph(location_mapping) 26 | 27 | if (_location_graph_cache.source != location_mapping): 28 | _location_graph_cache = GraphCache( 29 | source=location_mapping, 30 | graph=_convert_mapping_to_graph(location_mapping) 31 | ) 32 | return _location_graph_cache.graph 33 | 34 | 35 | def available_location_types(): 36 | """ List location types supported 37 | 38 | :returns: list of strings that represent the hierarchy of location types 39 | The first type is always the most broad. The last is always the most 40 | specific. 41 | :rtype: list 42 | """ 43 | return _read_data_json('location_types.json') 44 | 45 | 46 | def compare_types(typ_1, typ_2): 47 | """ Compare the two provided location types 48 | 49 | Types are considered 'more general' if they are higher up in the hierarchy. 50 | For example: 51 | compare_types('runtimeenv', 'habitat') # runtimeenvs contain habitats 52 | -> negative number 53 | compare_types('habitat', 'ecosystem') # habitats are contained by 54 | -> positive number # ecosystems 55 | 56 | :returns : A negative, zero, or positive number if typ_1 is more general, 57 | equally general, or less general than typ_2. 58 | """ 59 | i_1, i_2 = map(available_location_types().index, (typ_1, typ_2)) 60 | return i_1 - i_2 61 | 62 | 63 | def convert_location_type(location, source_type, desired_type): 64 | """ Converts the provided location into the desired location_type 65 | 66 | This will perform a DFS on the location graph to find connected components 67 | to the supplied node and then filter by the desired location_type. 68 | Basically if we consider our datacenter layout a DAG, then this method will 69 | search any nodes connected to the source location looking for the proper 70 | type. 71 | 72 | Examples: 73 | Assume available_location_types() is ['ecosystem', 'region', 'habitat'], 74 | and the location graph is: 75 | - prod 76 | - uswest1-prod 77 | - uswest1aprod 78 | - uswest1bprod 79 | 80 | # convert a habitat to the containing ecosystem 81 | convert_location_type('uswest1aprod', 'habitat', 'ecosystem') -> ['prod'] 82 | # convert a region to the member habitats 83 | convert_location_type('uswest1-prod', 'region', 'habitat') -> 84 | ['uswest1aprod', 'uswest1bprod'] 85 | 86 | :param location: A string that represents a location, e.g. "devc" 87 | :param source_type: A string that should exist inside the list returned 88 | by available_location_types. This is the type of the provided location 89 | and is optional. This exists because the names in the DAG may not be 90 | unique across all levels, and providing this type will disambiguate 91 | between which "devc" you mean (ecosystem or habitat). 92 | :param desired_type: A string that should exist inside the 93 | list returned by available_location_types. This is the desired type 94 | that the caller wants. 95 | :returns: locations, A list of locations that are of the location_type. 96 | These will be connected components filtered by type. Note that 97 | these results are sorted for calling consistency before returning. 98 | :rtype: list of strings 99 | """ 100 | search_node = '{0}_{1}'.format(location, source_type) 101 | 102 | direction = compare_types(desired_type, source_type) 103 | candidates = set() 104 | if direction < 0: 105 | # We are converting "up", and have to walk the tree backwards 106 | reversed_graph = nx.reverse(location_graph()) 107 | candidates |= set(nx.dfs_preorder_nodes(reversed_graph, search_node)) 108 | else: 109 | candidates |= set(nx.dfs_preorder_nodes(location_graph(), search_node)) 110 | 111 | # Only return results that are of the correct type 112 | result = filter(lambda x: x.endswith('_' + desired_type), candidates) 113 | return sorted([loc[:loc.rfind('_')] for loc in result]) 114 | 115 | 116 | def get_current_location(location_type): 117 | """ Returns the local node's location that is of the specified type 118 | 119 | :param location_type: A string that should exist inside the list returned 120 | by available_location_types. e.g. "habitat" 121 | 122 | :returns: location, A string that is the current node's value for the 123 | provided location type. 124 | :rtype: string 125 | """ 126 | assert location_type in available_location_types() 127 | file_path = os.path.join('/', 'nail', 'etc', location_type) 128 | with open(file_path) as f: 129 | return f.read().strip() 130 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | flake8 3 | mock 4 | pytest 5 | six 6 | # For python3.5 compatibility 7 | zipp<3.1.0 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup 5 | 6 | from environment_tools import version 7 | 8 | setup( 9 | name='environment_tools', 10 | version=version, 11 | description='Utilities for working with hierarchical environments', 12 | packages=['environment_tools'], 13 | install_requires=['networkx >= 1.9.1'], 14 | license='Copyright Yelp 2015, All Rights Reserved', 15 | ) 16 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yelp/environment_tools/bf729d3399822b445f7b7221ae46e5e634f2dac7/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_type_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import mock 3 | import six 4 | 5 | from environment_tools.config import _convert_mapping_to_graph 6 | import environment_tools.type_utils 7 | from environment_tools.type_utils import available_location_types 8 | from environment_tools.type_utils import convert_location_type 9 | from environment_tools.type_utils import compare_types 10 | from environment_tools.type_utils import get_current_location 11 | from environment_tools.type_utils import location_graph 12 | 13 | from pytest import yield_fixture 14 | 15 | 16 | class TestTypeUtils: 17 | @yield_fixture 18 | def mock_data(self): 19 | fake_data = { 20 | 'location_types.json': ['environment', 'region', 'az'], 21 | 'location_mapping.json': { 22 | 'prod_environment': { 23 | 'usnorth1-prod_region': { 24 | 'usnorth1aprod_az': {}, 25 | 'usnorth1bprod_az': {}, 26 | }, 27 | 'usnorth2-prod_region': { 28 | 'usnorth2aprod_az': {}, 29 | 'usnorth2bprod_az': {}, 30 | 'usnorth2cprod_az': {}, 31 | }, 32 | }, 33 | 'dev_environment': { 34 | 'usnorth1-dev_region': { 35 | 'usnorth1adev_az': {}, 36 | 'usnorth1bdev_az': {}, 37 | }, 38 | }, 39 | }, 40 | } 41 | with mock.patch('environment_tools.type_utils._read_data_json', 42 | side_effect=fake_data.get) as mock_fake_data: 43 | empty_graph = environment_tools.type_utils.GraphCache(None, None) 44 | environment_tools.type_utils._location_graph_cache = empty_graph 45 | yield mock_fake_data 46 | environment_tools.type_utils._location_graph_cache = empty_graph 47 | 48 | def test_location_graph_cache(self, mock_data): 49 | mock_convert = mock.Mock(spec=_convert_mapping_to_graph) 50 | mock_convert.return_value = 'fake_graph' 51 | with mock.patch( 52 | 'environment_tools.type_utils._convert_mapping_to_graph', 53 | mock_convert): 54 | for i in range(5): 55 | assert location_graph() == 'fake_graph' 56 | assert mock_convert.call_count == 1 57 | assert location_graph(use_cache=False) == 'fake_graph' 58 | assert mock_convert.call_count == 2 59 | 60 | def test_available_location_types(self, mock_data): 61 | location_types = available_location_types() 62 | assert isinstance(location_types, list) 63 | assert len(location_types) > 0 64 | 65 | def test_compare_types(self, mock_data): 66 | assert compare_types('environment', 'az') < 0 67 | assert compare_types('az', 'az') == 0 68 | assert compare_types('az', 'region') > 0 69 | 70 | def test_down_convert(self, mock_data): 71 | down_convert = convert_location_type('prod', 'environment', 'az') 72 | assert isinstance(down_convert, list) 73 | assert len(down_convert) > 1 74 | for result in down_convert: 75 | assert isinstance(result, str) 76 | 77 | def test_up_convert(self, mock_data): 78 | up = convert_location_type('usnorth1bprod', 'az', 'environment') 79 | assert up == ['prod'] 80 | 81 | up = convert_location_type('usnorth1aprod', 'az', 'region') 82 | assert up == ['usnorth1-prod'] 83 | 84 | def test_same_convert(self, mock_data): 85 | same = convert_location_type('usnorth2cprod', 'az', 'az') 86 | assert same == ['usnorth2cprod'] 87 | 88 | def test_get_current_location(self, mock_data): 89 | mock_open = mock.mock_open(read_data='test ') 90 | 91 | if six.PY2: 92 | open_module = '__builtin__.open' 93 | else: 94 | open_module = 'builtins.open' 95 | 96 | with mock.patch(open_module, mock_open): 97 | assert get_current_location('az') == 'test' 98 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py36,py37 3 | 4 | [testenv] 5 | deps = -rrequirements-dev.txt 6 | commands = 7 | coverage erase 8 | coverage run -m pytest {posargs:tests} 9 | coverage report -m 10 | flake8 environment_tools tests setup.py 11 | 12 | [testenv:devenv] 13 | basepython = /usr/bin/python3.7 14 | envdir = virtualenv_run 15 | commands = 16 | 17 | [testenv:docs] 18 | basepython = /usr/bin/python3.7 19 | deps = sphinx 20 | changedir = docs 21 | commands = sphinx-build -b html -d build/doctrees source build/html 22 | --------------------------------------------------------------------------------