"Fossies" - the Fresh Open Source Software Archive

Member "monasca-api-4.0.0/devstack/files/schema/influxdb_setup.py" (13 May 2020, 4654 Bytes) of package /linux/misc/openstack/monasca-api-4.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "influxdb_setup.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 3.1.0_vs_4.0.0.

    1 #
    2 # (C) Copyright 2015,2016 Hewlett Packard Enterprise Development LP
    3 #
    4 # Licensed under the Apache License, Version 2.0 (the "License");
    5 # you may not use this file except in compliance with the License.
    6 # You may obtain 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,
   12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   13 # implied.
   14 # See the License for the specific language governing permissions and
   15 # limitations under the License.
   16 #
   17 
   18 """A simple script to setup influxdb user and roles. At some point this should
   19    become a more full featured module.  Also this assumes that none of the
   20    python based influxdb clients are available on this system.
   21 """
   22 
   23 import json
   24 import sys
   25 
   26 from oslo_utils.encodeutils import safe_decode
   27 from oslo_utils.encodeutils import safe_encode
   28 from six.moves import urllib
   29 import six.moves.urllib.parse as urlparse
   30 
   31 ADMIN = 'root'
   32 ADMIN_PASS = 'root'
   33 DBNAME = 'mon'
   34 USERS = {}
   35 USERS['mon_api'] = 'password'
   36 USERS['mon_persister'] = 'password'
   37 
   38 URL = 'http://127.0.0.1:8086'
   39 
   40 SHARDSPACE_NAME = 'persister_all'
   41 REPLICATION = 1
   42 RETENTION = '90d'
   43 
   44 
   45 def format_response(req):
   46     try:
   47         json_value = json.loads(req.read())
   48         if (len(json_value['results'][0]) > 0 and
   49                 'series' in json_value['results'][0] and
   50                 'values' in json_value['results'][0]['series'][0]):
   51             return json_value['results'][0]['series'][0]['values']
   52         else:
   53             return []
   54     except KeyError:
   55         print("Query returned a non-successful result: {0}".format(json_value['results']))
   56         raise
   57 
   58 
   59 def influxdb_get(uri, query, db=None):
   60     """Runs a query via HTTP GET and returns the response as a Python list."""
   61 
   62     getparams = {"q": query}
   63     if db:
   64         getparams['db'] = db
   65 
   66     try:
   67         params = urlparse.urlencode(getparams)
   68         uri = "{}&{}".format(uri, params)
   69         req = urllib.request.urlopen(uri)
   70         return format_response(req)
   71 
   72     except KeyError:
   73         sys.exit(1)
   74 
   75 
   76 def influxdb_get_post(uri, query, db=None):
   77     """Runs a query using HTTP GET or POST and returns the response as a Python list.
   78        At some InfluxDB release several ops changed from using GET to POST. For example,
   79        CREATE DATABASE. To maintain backward compatibility, this function first trys the
   80        query using POST and if that fails it retries again using GET.
   81     """
   82 
   83     query_params = {"q": query}
   84     if db:
   85         query_params['db'] = db
   86 
   87     try:
   88         encoded_params = safe_encode(urlparse.urlencode(query_params))
   89         try:
   90             req = urllib.request.urlopen(uri, encoded_params)
   91             return format_response(req)
   92 
   93         except urllib.error.HTTPError:
   94             uri = "{}&{}".format(uri, encoded_params)
   95             req = urllib.request.urlopen(uri)
   96             return format_response(req)
   97 
   98     except KeyError:
   99         sys.exit(1)
  100 
  101 
  102 def main(argv=None):
  103     """If necessary, create the database, retention policy, and users"""
  104     auth_str = '?u=%s&p=%s' % (ADMIN, ADMIN_PASS)
  105     api_uri = "{0}/query{1}".format(URL, auth_str)
  106 
  107     # List current databases
  108     dbs = influxdb_get(uri=api_uri, query="SHOW DATABASES")
  109     if [DBNAME] not in dbs:
  110         print("Creating database '{}'".format(DBNAME))
  111         influxdb_get_post(uri=api_uri, query="CREATE DATABASE {0}".format(DBNAME))
  112         print("...created!")
  113 
  114     # Check retention policy
  115     policies = influxdb_get(uri=api_uri,
  116                             query="SHOW RETENTION POLICIES ON {0}".format(DBNAME))
  117     if not any(pol[0] == SHARDSPACE_NAME for pol in policies):
  118         # Set retention policy
  119         policy = ("CREATE RETENTION POLICY {0} ON {1} DURATION {2} "
  120                   "REPLICATION {3} DEFAULT".format(SHARDSPACE_NAME,
  121                                                    DBNAME,
  122                                                    RETENTION,
  123                                                    REPLICATION)
  124                   )
  125         influxdb_get_post(uri=api_uri, db=DBNAME, query=policy)
  126 
  127     # Create the users
  128     users = influxdb_get(uri=api_uri, query="SHOW USERS", db=DBNAME)
  129     for name, password in USERS.items():
  130         if not any(user[0] == name for user in users):
  131             influxdb_get_post(uri=api_uri,
  132                               query=safe_decode("CREATE USER {0} WITH PASSWORD '{1}'"
  133                                                 .format(name, password)),
  134                               db=DBNAME)
  135 
  136 
  137 if __name__ == "__main__":
  138     sys.exit(main())