Add API(v2) to create influxdb
[yardstick.git] / yardstick / common / utils.py
index 7633777..92bb7b7 100644 (file)
@@ -24,10 +24,14 @@ import os
 import subprocess
 import sys
 import collections
-import six
+import socket
+import random
 from functools import reduce
+from contextlib import closing
 
 import yaml
+import six
+from flask import jsonify
 from six.moves import configparser
 from oslo_utils import importutils
 from oslo_serialization import jsonutils
@@ -123,6 +127,14 @@ def makedirs(d):
             raise
 
 
+def remove_file(path):
+    try:
+        os.remove(path)
+    except OSError as e:
+        if e.errno != errno.ENOENT:
+            raise
+
+
 def execute_command(cmd):
     exec_msg = "Executing command: '%s'" % cmd
     logger.debug(exec_msg)
@@ -197,7 +209,8 @@ def flatten_dict_key(data):
     next_data = {}
 
     # use list, because iterable is too generic
-    if not any(isinstance(v, (collections.Mapping, list)) for v in data.values()):
+    if not any(isinstance(v, (collections.Mapping, list))
+               for v in data.values()):
         return data
 
     for k, v in six.iteritems(data):
@@ -212,3 +225,52 @@ def flatten_dict_key(data):
             next_data[k] = v
 
     return flatten_dict_key(next_data)
+
+
+def translate_to_str(obj):
+    if isinstance(obj, collections.Mapping):
+        return {str(k): translate_to_str(v) for k, v in obj.items()}
+    elif isinstance(obj, list):
+        return [translate_to_str(ele) for ele in obj]
+    elif isinstance(obj, six.text_type):
+        return str(obj)
+    return obj
+
+
+def result_handler(status, data):
+    result = {
+        'status': status,
+        'result': data
+    }
+    return jsonify(result)
+
+
+def change_obj_to_dict(obj):
+    dic = {}
+    for k, v in vars(obj).items():
+        try:
+            vars(v)
+        except TypeError:
+            dic.update({k: v})
+    return dic
+
+
+def set_dict_value(dic, keys, value):
+    return_dic = dic
+
+    for key in keys.split('.'):
+
+        return_dic.setdefault(key, {})
+        if key == keys.split('.')[-1]:
+            return_dic[key] = value
+        else:
+            return_dic = return_dic[key]
+    return dic
+
+
+def get_free_port(ip):
+    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
+        while True:
+            port = random.randint(5000, 10000)
+            if s.connect_ex((ip, port)) != 0:
+                return port