|
| 1 | +# Copyright 2016: Mirantis Inc. |
| 2 | +# All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 | +# not use this file except in compliance with the License. You may obtain |
| 6 | +# a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | +# License for the specific language governing permissions and limitations |
| 14 | +# under the License. |
| 15 | + |
| 16 | +import json |
| 17 | +import logging |
| 18 | + |
| 19 | +import elasticsearch |
| 20 | + |
| 21 | +from runbook import config |
| 22 | + |
| 23 | + |
| 24 | +LOG = logging.getLogger("storage") |
| 25 | + |
| 26 | +ES_MAPPINGS = { |
| 27 | + "mappings": { |
| 28 | + "runbook": { |
| 29 | + "_all": {"enabled": False}, |
| 30 | + "properties": { |
| 31 | + "runbook": {"type": "binary"}, |
| 32 | + "description": {"type": "text"}, |
| 33 | + "name": {"type": "keyword"}, |
| 34 | + "type": {"type": "keyword"}, |
| 35 | + } |
| 36 | + }, |
| 37 | + "run": { |
| 38 | + "_all": {"enabled": False}, |
| 39 | + "properties": { |
| 40 | + "date": {"type": "date"}, |
| 41 | + "user": {"type": "string"}, |
| 42 | + "output": {"type": "binary"}, |
| 43 | + "return_code": {"type": "integer"}, |
| 44 | + "status": {"type": "keyword"}, |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +ES_CLIENT = None |
| 51 | + |
| 52 | + |
| 53 | +def get_elasticsearch(api_type): |
| 54 | + """Configures or returns already configured ES client.""" |
| 55 | + global ES_CLIENT |
| 56 | + if not ES_CLIENT: |
| 57 | + nodes = config.get_config(api_type)["backend"]["connection"] |
| 58 | + ES_CLIENT = elasticsearch.Elasticsearch(nodes) |
| 59 | + return ES_CLIENT |
| 60 | + |
| 61 | + |
| 62 | +def ensure_index(index, api_type): |
| 63 | + """Esures index exists in es.""" |
| 64 | + es = get_elasticsearch(api_type) |
| 65 | + |
| 66 | + try: |
| 67 | + if not es.indices.exists(index): |
| 68 | + mapping = json.dumps(ES_MAPPINGS) |
| 69 | + LOG.info("Creating Elasticsearch index: {}".format(index)) |
| 70 | + es.indices.create(index, body=mapping) |
| 71 | + except elasticsearch.exceptions.ElasticsearchException: |
| 72 | + LOG.exception("Was unable to get or create index: {}".format(index)) |
| 73 | + raise |
| 74 | + |
| 75 | + |
| 76 | +def configure_regions(api_type="writer"): |
| 77 | + """Ensure there are indices for every region we have configured.""" |
| 78 | + |
| 79 | + for region in config.get_config(api_type)["regions"]: |
| 80 | + ensure_index("ms_{}_{}".format("runbooks", region), api_type) |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + configure_regions() |
0 commit comments