# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 timger
# +Author timger
# +Gtalk&Email yishenggudou@gmail.com
#    +Msn yishenggudou@msn.cn
#    +Weibo @timger http://t.sina.com/zhanghaibo
#    +twitter @yishenggudou http://twitter.com/yishenggudou
#    Licensed under the MIT License, Version 2.0 (the "License");
__author__ = 'timger'
import urlparse
import urllib
import requests
from functools import partial
import json


class oozie(object):
    def __init__(self, oozie_host=None):
        self.oozie_host = oozie_host or 'http://10.100.1.215:11000/'
        self.yarn_host = 'com.hunantv.datanode2'
        self.headers={"Content-Type": "application/json"}

    def get_api(self, path, params):
        url = urlparse.urljoin(self.oozie_host, path)
        url = "{0}?{1}".format(url, urllib.urlencode(params))
        print url
        body = requests.get(url).text
        return json.loads(body)


    def oozie_admin_status(self):
        _ = partial(self.get_api, '/oozie/v1/admin/status', {})
        return _()

    def oozie_os_env(self):
        _ = partial(self.get_api, "/oozie/v1/admin/os-env", {})
        return _()

    def oozie_jobs(self):
        _ = partial(self.get_api, "/oozie/v1/jobs", {})
        return _()

    @property
    def fail_jobs(self):
        _ = o.oozie_jobs()
        return filter(lambda x:not (x['status'] in ['SUCCEEDED','RUNNING']), _['workflows'])


    @property
    def yarn_is_ok(self):
        import xml.etree.ElementTree as ET
        url = "http://{0}:8088/ws/v1/cluster/metrics".format(self.yarn_host)
        xml_string = requests.get(url).text
        root = ET.fromstring(xml_string)
        availableMB = int(root.find('availableMB').text)
        reservedMB = int(root.find('reservedMB').text)
        totalMB = int(root.find('totalMB').text)
        allocatedMB = int(root.find('allocatedMB').text)
        def check(availableMB,  reservedMB, totalMB, allocatedMB):
            pass

    @property
    def oozie_is_ok(self):
        pass


    @property
    def runing_jobs(self):
        url = "http://{0}:8088/ws/v1/cluster/apps".format(self.yarn_host)
        json_string = requests.get(url, headers=self.headers).text
        return json.loads(json_string)


    @property
    def job_progress(self, app_id, job_id,):
        url = "http://<proxy http address:port>/proxy/application_1326232085508_0004/ws/v1/mapreduce/jobs/job_1326232085508_4_4"


if __name__ == "__main__":
    o = oozie()
    print o.fail_jobs