Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 440 lines (411 sloc) 27.017 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
import datetime
import fnmatch
import logging
import re
import string
import shutil
import traceback
import os
import sys

import cluster_stats
import diskqueue_stats
import node_stats
import stats_buffer
import threshold
import prescription
import util_cli as util

from Cheetah.Template import Template

capsules = [
    (node_stats.NodeCapsule, "node_stats", "NodeCapsule"),
    (cluster_stats.ClusterCapsule, "cluster_stats", "ClusterCapsule"),
    (diskqueue_stats.DiskQueueCapsule, "diskqueue_stats", "DiskQueueCapsule"),
]

globals = {
    "versions" : "1.0",
    "report_time" : datetime.datetime.now(),
    "cluster_health" : "ok",
    "scale" : "all",
}

TEMPLATE_FILE = "template.tmpl"
CHART_FILE = "chart.tmpl"

node_list = {}
bucket_list = {}
cluster_symptoms = {}
bucket_symptoms = {}
bucket_node_symptoms = {}
bucket_node_status = {}
node_symptoms = {}
indicator_error = {}
indicator_warn = {}
node_disparate = {}
sizing_symptoms = {}

class UtilTool:
    def isdict(self, obj):
        return isinstance(obj, dict)

    def islist(self, obj):
        return isinstance(obj, list)

    def statsClass(self, status, hasOkStatus=True):
        if status == "Error":
            return ["status-error", "Immediate action needed"]
        elif status == "Warning":
            return ["status-warning", "Attention needed"]
        else:
            if hasOkStatus:
                return ["status-ok", "OK"]
            else:
                return ["", "OK"]

    def activeTab(self, tab):
        if tab == globals["scale"]:
            return "active"
        else:
            return ""

class StatsAnalyzer:
    def __init__(self, log):
        self.log = log

    def init(self):
        for bucket in stats_buffer.buckets.iterkeys():
            bucket_type = stats_buffer.bucket_info[bucket]['bucketType']
            bucket_list[bucket] = {"status":"OK", "type":bucket_type, "anchor":None}
            bucket_symptoms[bucket] = []
            bucket_node_symptoms[bucket] = {}
            bucket_node_status[bucket] = {}

        for node in stats_buffer.nodes.iterkeys():
            node_list[node] = {}
            sizing_symptoms[node] = {}
 
    def run_analysis(self, scale):
        self.init()

        for capsule, package_name, capsule_name in capsules:
            for pill in capsule:
                self.log.debug(pill['name'])
                for counter in pill['ingredients']:
                    try:
                        #eval_str = "{0}.{1}().run(counter, scale, threshold.{2})".format(package_name, counter['code'], capsule_name)
                        #print eval_str
                        result = eval("%s.%s().run(counter, scale, threshold.%s)" % (package_name, counter['code'], capsule_name))
                        self.log.debug(counter)
                        if pill.has_key("clusterwise") and pill["clusterwise"] :
                            if isinstance(result, dict):
                                if result.has_key("cluster"):
                                    cluster_symptoms[counter["name"]] = {"description" : counter["description"], "value":result["cluster"]}
                                else:
                                    cluster_symptoms[counter["name"]] = {"description" : counter["description"], "value":result}
                            else:
                                cluster_symptoms[counter["name"]] = {"description" : counter["description"], "value":result}
                            if counter.has_key("formula"):
                                cluster_symptoms[counter["name"]]["formula"] = counter["formula"]
                            else:
                                cluster_symptoms[counter["name"]]["formula"] = "N/A"
                        if pill.has_key("perBucket") and pill["perBucket"] :
                            for bucket, values in result.iteritems():
                                if bucket == "cluster" or bucket == "_sizing":
                                    continue
                                bucket_status = "OK"
                                node_error = []
                                node_warn = []
                                for val in values:
                                    if val[0] == "error":
                                        bucket_status = "Error"
                                        for node in val[1]:
                                            node_error.append(node["node"])
                                        break
                                    if val[0] == "warn":
                                        bucket_status = "Warning"
                                        for node in val[1]:
                                            node_warn.append(node["node"])
                                        break
                                for val in values:
                                    if val[0] == "variance" or val[0] == "error" or val[0] == "warn":
                                        continue
                                    elif val[0] == "total":
                                        if counter.has_key("formula"):
                                            bucket_symptoms[bucket].append({"description":counter["description"],
                                                                            "value":val[1],
                                                                            "status":bucket_status,
                                                                            "formula":counter["formula"]})
                                        else:
                                            bucket_symptoms[bucket].append({"description":counter["description"],
                                                                            "value":val[1],
                                                                            "status":bucket_status,
                                                                            "formula":"N/A"})
                                    else:
                                        if bucket_node_symptoms[bucket].has_key(val[0]) == False:
                                            bucket_node_symptoms[bucket][val[0]] = []
                                        counter_status = "OK"
                                        if val[0] in node_warn:
                                            counter_status = "Warning"
                                        if val[0] in node_error:
                                            counter_status = "Error"
                                            
                                        if isinstance(val[1], dict) and val[1].has_key("counter"):
                                            description = "%s - %s" % (counter["description"], val[1]["counter"])
                                        else:
                                            description = counter["description"]
                                        if counter.has_key("formula"):
                                            bucket_node_symptoms[bucket][val[0]].append({"description" : description,
                                                                                         "value" : val[1],
                                                                                         "status":counter_status,
                                                                                         "formula":counter["formula"]})
                                        else:
                                            bucket_node_symptoms[bucket][val[0]].append({"description" : description,
                                                                                         "value" : val[1],
                                                                                         "status":counter_status,
                                                                                         "formula":"N/A"})
                        if pill.has_key("perNode") and pill["perNode"] :
                            if counter.has_key("formula"):
                                node_symptoms[counter["name"]] = {"description" : counter["description"],
                                                                  "value":result,
                                                                  "formula":counter["formula"]}
                            else:
                                node_symptoms[counter["name"]] = {"description" : counter["description"], "value":result}
                        if pill.has_key("nodewise") and pill["nodewise"]:
                            for node, values in result.iteritems():
                                node_list[node] = {"description": counter["description"], "value": values}
                        if pill.has_key("sizing") and pill["sizing"]:
                            if result:
                                if result.has_key("_sizing"):
                                    sizing_result = result["_sizing"]
                                else:
                                    sizing_result = result
                                for node, value in sizing_result.iteritems():
                                    if not sizing_symptoms[node].has_key(counter["category"]):
                                        sizing_symptoms[node][counter["category"]] = []
                                    withchart = False
                                    if counter.has_key("chart"):
                                        withchart = counter["chart"]
                                    chart_id = "c_%s_%s" % (counter["name"], node)
                                    if counter.has_key("unit"):
                                        unit = counter["unit"]
                                    else:
                                        unit = ""
                                    sizing_symptoms[node][counter["category"]].append(
                                                                 {"description": counter["description"],
                                                                  "unit": unit,
                                                                  "value": value,
                                                                  "category": counter["category"],
                                                                  "chart": withchart,
                                                                  "chart_id": re.sub('[.:]', '_', chart_id),
                                                                  })

                        if pill.has_key("nodeDisparate") and pill["nodeDisparate"] :
                            for bucket,values in result.iteritems():
                                if bucket == "cluster" or bucket == "_sizing":
                                    continue
                                for val in values:
                                    if val[0] == "total":
                                        continue;
                                    if val[0] == "variance" and val[1] != 0:
                                        node_disparate[counter["name"]] = {"description" : counter["description"], "bucket": bucket, "value":values}
                        if pill.has_key("indicator") and pill["indicator"]:
                            if len(result) > 0:
                                cause = impact = action = "To be defined"
                                try:
                                    cause = prescription.Capsules[pill['name']]["cause"]
                                    impact = prescription.Capsules[pill['name']]["impact"]
                                    action = prescription.Capsules[pill['name']]["action"]
                                except Exception, e:
                                    print e
                                for bucket,values in result.iteritems():
                                    if type(values) is dict:
                                        if values.has_key("error"):
                                            if indicator_error.has_key(counter["name"]) == False:
                                                indicator_error[counter["name"]] = []
                                            if counter.has_key("formula"):
                                                indicator_error[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":values["error"],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula" : counter["formula"],
                                                                           })
                                            else:
                                                indicator_error[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":values["error"],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula": "N/A",
                                                                           })
                                            for val in values["error"]:
                                                bucket_node_status[bucket][val["node"]] = "Error"
                                                bucket_list[bucket]["status"] = "Error"
                                                bucket_list[bucket]["anchor"] = "counter_%s_%s_%s" % (bucket, val["node"], counter["name"])
                                        if values.has_key("warn"):
                                            if indicator_warn.has_key(counter["name"]) == False:
                                                indicator_warn[counter["name"]] = []
                                            if counter.has_key("formula"):
                                                indicator_warn[counter["name"]].append({"description" : counter["description"],
                                                                           "bucket": bucket,
                                                                           "value":values["warn"],
                                                                           "cause" : cause,
                                                                           "impact" : impact,
                                                                           "action" : action,
                                                                           "formula" : counter["formula"],
                                                                          })
                                            else:
                                                indicator_warn[counter["name"]].append({"description" : counter["description"],
                                                                           "bucket": bucket,
                                                                           "value":values["warn"],
                                                                           "cause" : cause,
                                                                           "impact" : impact,
                                                                           "action" : action,
                                                                           "formula": "N/A",
                                                                          })
                                            for node in values["warn"]:
                                                node_val = None
                                                if type(node) is dict:
                                                    node_val = node["node"]
                                                else:
                                                    node_val = node[0]
                                                if bucket_node_status[bucket].has_key(node_val) == False:
                                                    bucket_node_status[bucket][node_val] = "Warning"
                                                if bucket_list[bucket]["status"] == "OK":
                                                    bucket_list[bucket]["status"] = "Warning"
                                                    bucket_list[bucket]["anchor"] = "counter_%s_%s_%s" % (bucket, node_val, counter["name"])
                                    elif type(values) is list:
                                        for val in values:
                                            if val[0] == "error":
                                                if indicator_error.has_key(counter["name"]) == False:
                                                    indicator_error[counter["name"]] = []
                                                if counter.has_key("formula"):
                                                    indicator_error[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":val[1],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula": counter["formula"],
                                                                           })
                                                else:
                                                    indicator_error[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":val[1],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula" : "N/A",
                                                                           })
                                                for node in val[1]:
                                                    bucket_node_status[bucket][node["node"]] = "Error"
                                                    bucket_list[bucket]["status"] = "Error"
                                                    bucket_list[bucket]["anchor"] = "counter_%s_%s_%s" % (bucket, node["node"], counter["name"])
                                            elif val[0] == "warn":
                                                if indicator_warn.has_key(counter["name"]) == False:
                                                    indicator_warn[counter["name"]] = []
                                                if counter.has_key("formula"):
                                                    indicator_warn[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":val[1],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula": counter["formula"],
                                                                           })
                                                else:
                                                    indicator_warn[counter["name"]].append({"description" : counter["description"],
                                                                            "bucket": bucket,
                                                                            "value":val[1],
                                                                            "cause" : cause,
                                                                            "impact" : impact,
                                                                            "action" : action,
                                                                            "formula" : "N/A",
                                                                           })
                                                for node in val[1]:
                                                    if bucket_node_status[bucket].has_key(node["node"]) == False:
                                                        bucket_node_status[bucket][node["node"]] = "Warning"
                                                    if bucket_list[bucket]["status"] == "OK":
                                                        bucket_list[bucket]["status"] = "Warning"
                                                        bucket_list[bucket]["anchor"] = "counter_%s_%s_%s" % (bucket, node["node"], counter["name"])
                    except Exception, err:
                        self.log.error("Exception launched when processing counter: %s" % counter["name"])
                        traceback.print_exc()

        if len(indicator_error) > 0:
            globals["cluster_health"] = "Error"
        elif len(indicator_warn) > 0:
            globals["cluster_health"] = "Warning"
        else:
            globals["cluster_health"] = "OK"

    def run_report(self, verbose, scale_set, scale, debug, output_dir):
        reports_dir = os.path.join(os.path.dirname(sys.argv[0]), 'reports')
        txtfile = os.path.join(output_dir, scale + ".txt")
        htmlfile = os.path.join(output_dir, scale + ".html")

        dict = {
            "util": UtilTool(),
            "globals" : globals,
            "cluster_symptoms" : cluster_symptoms,
            "bucket_symptoms" : bucket_symptoms,
            "bucket_node_symptoms" : bucket_node_symptoms,
            "bucket_node_status" : bucket_node_status,
            "node_symptoms" : node_symptoms,
            "sizing_symptoms": sizing_symptoms,
            "node_list" : node_list,
            "bucket_list" : bucket_list,
            "indicator_warn" : indicator_warn,
            "indicator_warn_exist" : len(indicator_warn) > 0,
            "indicator_error" : indicator_error,
            "indicator_error_exist" : len(indicator_error) > 0,
            "verbose" : verbose,
            "scale_set" : scale_set,
            "debug" : debug,
            "sizing": None,
        }
        globals["scale"] = scale

        # read the current version number
        for fname in [os.path.join(os.path.dirname(sys.argv[0]), '..', '..', 'VERSION.txt'), \
                      os.path.join(os.path.dirname(sys.argv[0]), '..', 'VERSION.txt'), \
                      os.path.join(os.path.dirname(sys.argv[0]), 'VERSION.txt')]:
            try:
                f = open(fname, 'r')
                globals["versions"] = string.strip(f.read())
                f.close()
            except Exception:
                pass

        f = open(txtfile, 'w')
        report = {}
        report["Report Time"] = globals["report_time"].strftime("%Y-%m-%d %H:%M:%S")
        report["Nodelist Overview"] = node_list
        report["Sizing Report"] = sizing_symptoms
        report["Cluster Overview"] = cluster_symptoms
        report["Bucket Metrics"] = bucket_symptoms
        report["Bucket Node Metrics"] = bucket_node_symptoms
        report["Key indicators"] = (indicator_error, indicator_warn)
        report["Node disparate"] = node_disparate

        print >> f, util.pretty_print(report)
        f.close()

        #print util.pretty_print(bucket_node_symptoms)

        f = open(htmlfile, 'w')
        print >> f, Template(file=os.path.join(reports_dir, TEMPLATE_FILE), searchList=[dict])
        f.close()

        #generate charts if any
        for node in node_list:
            for category, values in sizing_symptoms[node].iteritems():
                for sizing in values:
                    if sizing["chart"]:
                        dict["sizing"] = sizing
                        htmlfile = os.path.join(output_dir, sizing["chart_id"] + ".html")
                        f = open(htmlfile, "w")
                        print >> f, Template(file=os.path.join(reports_dir, CHART_FILE), searchList=[dict])
                        f.close()

        # generate array/list of available reports for use via AJAX
        available_reports = [os.path.splitext(n)[0]
                             for n in fnmatch.filter(os.listdir('./reports/'),
                                                     '*.html')]
        f = open(os.path.join(output_dir, 'all.json'), 'w')
        print >> f, util.pretty_print(available_reports)
        f.close()

        #Need to copy support files for final report
        normalize_report_dir = os.path.normpath(reports_dir)
        normalize_output_dir = os.path.normpath(os.path.dirname(output_dir))
        if normalize_output_dir != normalize_report_dir:
            for item in os.listdir(normalize_report_dir):
                if not item in [TEMPLATE_FILE, CHART_FILE]:
                    s = os.path.join(normalize_report_dir, item)
                    d = os.path.join(normalize_output_dir, item)
                    try:
                        if os.path.isfile(s):
                            shutil.copy2(s, d)
                        else:
                            shutil.copytree(s, d)
                    except Exception:
                        pass

        sys.stderr.write("\nThe run finished successfully. \nPlease find html output at '%s' and text output at '%s'.\n" % \
            (htmlfile, txtfile))
Something went wrong with that request. Please try again.