#!/usr/bin/python3
import sys
import urllib.request
from string import Template
#-----------------VAR-----------------------------
#-----------------FUN-----------------------------
def main():
    buf = ""
    namespace = sys.argv[1]
    file_pod_targets = "/etc/prometheus/conf/pod/"+namespace+"-pod-targets.yml"
    str_pod_targets = Template('''
- targets:
  - ${ip}:${port}
  labels:
    ip: ${ip}
    app: ${app}
    group: ${group}
    namespace: ${namespace}
    ''')
    with open("/root/.kube/.pod") as f:
        for i in f.readlines():
            try: 
                l = i.split()
                ip = l[0]
                app = l[1]
                group = l[2]
                ports = ["7999"]
                for port in ports:
                    url = "http://"+ip+":"+port+"/actuator/prometheus"
                    try:
                      req = urllib.request.urlopen(url,timeout=7)
                      content = req.read().decode('utf-8')
                      if req.getcode() == 200 and "TYPE" in content and app != "<none>":
                          buf += str_pod_targets.substitute(app=app,ip=ip,group=group,namespace=namespace,port=port)
                          break
                    except:
                      pass
            except:
                pass
    if len(buf) > 100:
        with open(file_pod_targets,'w') as f: f.write(buf.strip()+'\n')
#-----------------PROG----------------------------
if __name__ == '__main__':
    main()
