move flatten dict key to common utils
[yardstick.git] / yardstick / common / utils.py
index 7035f33..7633777 100644 (file)
@@ -23,6 +23,8 @@ import logging
 import os
 import subprocess
 import sys
+import collections
+import six
 from functools import reduce
 
 import yaml
@@ -81,7 +83,10 @@ def import_modules_from_package(package):
                 continue
             new_package = ".".join(root.split(os.sep)).split("....")[1]
             module_name = "%s.%s" % (new_package, filename[:-3])
-            try_append_module(module_name, sys.modules)
+            try:
+                try_append_module(module_name, sys.modules)
+            except ImportError:
+                logger.exception("unable to import %s", module_name)
 
 
 def parse_yaml(file_path):
@@ -167,3 +172,43 @@ def parse_ini_file(path):
                       s)} for s in parser.sections()})
 
     return config
+
+
+def get_port_mac(sshclient, port):
+    cmd = "ifconfig |grep HWaddr |grep %s |awk '{print $5}' " % port
+    status, stdout, stderr = sshclient.execute(cmd)
+
+    if status:
+        raise RuntimeError(stderr)
+    return stdout.rstrip()
+
+
+def get_port_ip(sshclient, port):
+    cmd = "ifconfig %s |grep 'inet addr' |awk '{print $2}' " \
+        "|cut -d ':' -f2 " % port
+    status, stdout, stderr = sshclient.execute(cmd)
+
+    if status:
+        raise RuntimeError(stderr)
+    return stdout.rstrip()
+
+
+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()):
+        return data
+
+    for k, v in six.iteritems(data):
+        if isinstance(v, collections.Mapping):
+            for n_k, n_v in six.iteritems(v):
+                next_data["%s.%s" % (k, n_k)] = n_v
+        # use list because iterable is too generic
+        elif isinstance(v, list):
+            for index, item in enumerate(v):
+                next_data["%s%d" % (k, index)] = item
+        else:
+            next_data[k] = v
+
+    return flatten_dict_key(next_data)