"Fossies" - the Fresh Open Source Software Archive

Member "monasca-api-3.1.0/devstack/files/schema/influxdb_setup.py" (27 Sep 2019, 4541 Bytes) of package /linux/misc/openstack/monasca-api-3.1.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 last Fossies "Diffs" side-by-side code changes report: 3.1.0_vs_4.0.0.

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