# Path: collectors/lib/utils.py
# PY3 = sys.version_info[0] > 2
# USER = "nobody"
# def drop_privileges(user=USER):
# def is_sockfile(path):
# def err(msg):
#     def is_numeric(value):
#     def is_numeric(value):
# 
# Path: collectors/lib/hadoop_http.py
# class HadoopHttp(object):
#     def __init__(self, service, daemon, host, port, uri="/jmx"):
#         self.service = service
#         self.daemon = daemon
#         self.port = port
#         self.host = host
#         self.uri = uri
#         self.server = HTTPConnection(self.host, self.port)
#         self.server.auto_open = True
# 
#     def request(self):
#         try:
#             self.server.request('GET', self.uri)
#             resp = self.server.getresponse().read()
#         except:
#             resp = '{}'
#         finally:
#             self.server.close()
#         return json.loads(resp)
# 
#     def poll(self):
#         """
#         Get metrics from the http server's /jmx page, and transform them into normalized tupes
# 
#         @return: array of tuples ([u'Context', u'Array'], u'metricName', value)
#         """
#         json_arr = self.request().get('beans', [])
#         kept = []
#         for bean in json_arr:
#             if (not bean['name']) or (not "name=" in bean['name']):
#                 continue
#             #split the name string
#             context = bean['name'].split("name=")[1].split(",sub=")
#             # Create a set that keeps the first occurrence
#             context = list(OrderedDict.fromkeys(context).keys())
#             # lower case and replace spaces.
#             context = [c.lower().replace(" ", "_") for c in context]
#             # don't want to include the service or daemon twice
#             context = [c for c in context if c != self.service and c != self.daemon]
# 
#             for key, value in bean.items():
#                for m, n in recurse(key, value):
#                     if m in EXCLUDED_KEYS:
#                         continue
#                     if not is_numeric(n):
#                         continue
#                     kept.append((context, m, n))
#         return kept
# 
#     def emit_metric(self, context, current_time, metric_name, value, tag_dict=None):
#         if not tag_dict:
#             print("%s.%s.%s.%s %d %d" % (self.service, self.daemon, ".".join(context), metric_name, current_time, float(value)))
#         else:
#             tag_string = " ".join([k + "=" + v for k, v in tag_dict.items()])
#             print ("%s.%s.%s.%s %d %d %s" % \
#                   (self.service, self.daemon, ".".join(context), metric_name, current_time, float(value), tag_string))
#         # flush to protect against subclassed collectors that output few metrics not having enough output to trigger
#         # buffer flush within 10 mins, which then get killed by TCollector due to "inactivity"
#         sys.stdout.flush()
# 
#     def emit(self):
#         pass


import sys
import time
    import json
from collectors.lib import utils
from collectors.lib.hadoop_http import HadoopHttp
REPLACEMENTS = {
    "rpcdetailedactivityforport": ["rpc_activity"],
    "rpcactivityforport": ["rpc_activity"]
}


class HadoopJournalNode(HadoopHttp):
    """
    Class that will retrieve metrics from an Apache Hadoop JournalNode's jmx page.

    This requires Apache Hadoop 1.0+ or Hadoop 2.0+.
    Anything that has the jmx page will work but the best results will com from Hadoop 2.1.0+
    """

    def __init__(self):
        super(HadoopJournalNode, self).__init__('hadoop', 'journalnode', 'localhost', 8480)

    def emit(self):
        current_time = int(time.time())
        metrics = self.poll()
        for context, metric_name, value in metrics:
            for k, v in REPLACEMENTS.items():
                if any(c.startswith(k) for c in context):
                    context = v
            self.emit_metric(context, current_time, metric_name, value)


def main(args):
    utils.drop_privileges()
    if json is None:

# Path: collectors/lib/utils.py
# PY3 = sys.version_info[0] > 2
# USER = "nobody"
# def drop_privileges(user=USER):
# def is_sockfile(path):
# def err(msg):
#     def is_numeric(value):
#     def is_numeric(value):
# 
# Path: collectors/lib/hadoop_http.py
# class HadoopHttp(object):
#     def __init__(self, service, daemon, host, port, uri="/jmx"):
#         self.service = service
#         self.daemon = daemon
#         self.port = port
#         self.host = host
#         self.uri = uri
#         self.server = HTTPConnection(self.host, self.port)
#         self.server.auto_open = True
# 
#     def request(self):
#         try:
#             self.server.request('GET', self.uri)
#             resp = self.server.getresponse().read()
#         except:
#             resp = '{}'
#         finally:
#             self.server.close()
#         return json.loads(resp)
# 
#     def poll(self):
#         """
#         Get metrics from the http server's /jmx page, and transform them into normalized tupes
# 
#         @return: array of tuples ([u'Context', u'Array'], u'metricName', value)
#         """
#         json_arr = self.request().get('beans', [])
#         kept = []
#         for bean in json_arr:
#             if (not bean['name']) or (not "name=" in bean['name']):
#                 continue
#             #split the name string
#             context = bean['name'].split("name=")[1].split(",sub=")
#             # Create a set that keeps the first occurrence
#             context = list(OrderedDict.fromkeys(context).keys())
#             # lower case and replace spaces.
#             context = [c.lower().replace(" ", "_") for c in context]
#             # don't want to include the service or daemon twice
#             context = [c for c in context if c != self.service and c != self.daemon]
# 
#             for key, value in bean.items():
#                for m, n in recurse(key, value):
#                     if m in EXCLUDED_KEYS:
#                         continue
#                     if not is_numeric(n):
#                         continue
#                     kept.append((context, m, n))
#         return kept
# 
#     def emit_metric(self, context, current_time, metric_name, value, tag_dict=None):
#         if not tag_dict:
#             print("%s.%s.%s.%s %d %d" % (self.service, self.daemon, ".".join(context), metric_name, current_time, float(value)))
#         else:
#             tag_string = " ".join([k + "=" + v for k, v in tag_dict.items()])
#             print ("%s.%s.%s.%s %d %d %s" % \
#                   (self.service, self.daemon, ".".join(context), metric_name, current_time, float(value), tag_string))
#         # flush to protect against subclassed collectors that output few metrics not having enough output to trigger
#         # buffer flush within 10 mins, which then get killed by TCollector due to "inactivity"
#         sys.stdout.flush()
# 
#     def emit(self):
#         pass


# Path: collectors/0/hadoop_journalnode.py
import sys
import time
    import json
from collectors.lib import utils
from collectors.lib.hadoop_http import HadoopHttp

REPLACEMENTS = {
    "rpcdetailedactivityforport": ["rpc_activity"],
    "rpcactivityforport": ["rpc_activity"]
}


class HadoopJournalNode(HadoopHttp):
    """
    Class that will retrieve metrics from an Apache Hadoop JournalNode's jmx page.

    This requires Apache Hadoop 1.0+ or Hadoop 2.0+.
    Anything that has the jmx page will work but the best results will com from Hadoop 2.1.0+
    """

    def __init__(self):
        super(HadoopJournalNode, self).__init__('hadoop', 'journalnode', 'localhost', 8480)

    def emit(self):
        current_time = int(time.time())
        metrics = self.poll()
        for context, metric_name, value in metrics:
            for k, v in REPLACEMENTS.items():
                if any(c.startswith(k) for c in context):
                    context = v
            self.emit_metric(context, current_time, metric_name, value)


def main(args):
    utils.drop_privileges()
    if json is None:

        utils.err("This collector requires the `json' Python module.")