ppctl.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. from __future__ import print_function
  4. import os
  5. import commands
  6. import httplib, urllib
  7. import json
  8. import time
  9. from kubernetes.client.rest import ApiException
  10. from pprint import pprint
  11. from kubernetes import client, config
  12. import sys, getopt, random
  13. from aliyunsdkcore.client import AcsClient
  14. from aliyunsdkcore.acs_exception.exceptions import ClientException
  15. from aliyunsdkcore.acs_exception.exceptions import ServerException
  16. from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
  17. from aliyunsdkalidns.request.v20150109.DeleteDomainRecordRequest import DeleteDomainRecordRequest
  18. JNLP_ENV = os.getenv('JNLP_ENV')
  19. JNLP_TAG = os.getenv('JNLP_TAG')
  20. JNLP_CONTAINER_PORT = os.getenv('JNLP_CONTAINER_PORT')
  21. # JNLP_WAR = os.getenv('JNLP_WAR')
  22. JNLP_INGRESS = os.getenv('JNLP_INGRESS')
  23. JNLP_IMAGE = os.getenv('JNLP_IMAGE')
  24. JNLP_CONTROL_NAME = os.getenv('DRONE_REPO_NAME')
  25. JNLP_STORAGE_CLASS = os.getenv('JNLP_STORAGE_CLASS')
  26. JNLP_DOMAIN = os.getenv('JNLP_DOMAIN')
  27. JNLP_CONTROL = os.getenv('JNLP_CONTROL')
  28. JNLP_REPLICAS = os.getenv('JNLP_REPLICAS')
  29. JNLP_STORAGE_CAPACITY = os.getenv('JNLP_STORAGE_CAPACITY')
  30. JNLP_MOUNT_PATH = os.getenv('JNLP_MOUNT_PATH')
  31. JNLP_SVC_MODE = os.getenv('JNLP_SVC_MODE')
  32. NGINX_SVC = str(JNLP_ENV) + '/' + str(JNLP_CONTROL_NAME) + '-svc:' + str(JNLP_CONTAINER_PORT)
  33. NGINX_PORT = os.getenv('JNLP_CONTAINER_PORT')
  34. RECORD_NAME = os.getenv('JNLP_ENV') + "-" + os.getenv('DRONE_REPO_NAME')
  35. INGRESS_LIST = ["10.26.30.12", "10.26.29.54", "10.26.30.102", "10.26.30.13"]
  36. NGINX_RECORD_IP = random.sample(INGRESS_LIST, 1)[0]
  37. # 生成deploy.yaml文件
  38. def deployYamlCreate():
  39. tmpctl = '''
  40. config=`env|grep JNLP`
  41. template=`cat ./deploy-tmp.yaml`
  42. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./deploy.yaml
  43. '''
  44. f1 = open("tempshell.sh","w")
  45. f1.writelines(tmpctl)
  46. f1.close()
  47. status,output = commands.getstatusoutput("sh tempshell.sh && rm -f tempshell.sh")
  48. print("code:" + str(status) + str(output) + "; create deploy.yaml success !!!")
  49. return status,output
  50. # 生成Dockerfile文件
  51. def DockerfileCreate():
  52. tmp = '''
  53. onfig=`env|grep JNLP`
  54. template=`cat ./Dockerfile`
  55. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./Dockerfile
  56. '''
  57. f2 = open("tmp.sh","w")
  58. f2.writelines(tmp)
  59. f2.close()
  60. status,output = commands.getstatusoutput("sh tmp.sh && rm -f tmp.sh")
  61. print("code:" + str(status) + str(output) + "; create Dockerfile success !!!")
  62. return
  63. # 更新haproxy configmap.json配置文件,生成TCP服务转发记录
  64. def updateConfigMap(file):
  65. if JNLP_SVC_MODE == "tcp":
  66. data = {}
  67. data[NGINX_PORT] = NGINX_SVC
  68. status, output = commands.getstatusoutput("kubectl get cm tcp-services -n ingress-nginx -o=json")
  69. tempdict = eval(output)
  70. tempdict['data'][NGINX_PORT] = NGINX_SVC
  71. newdata = tempdict['data']
  72. print(newdata,status)
  73. old_str = "CMDATA"
  74. new_str = str(newdata).replace("'",'"')
  75. with open(file, "r") as f1,open("%s.bak" % file, "w" ) as f2:
  76. for line in f1:
  77. if old_str in line:
  78. line = line.replace(old_str, new_str)
  79. f2.write(line)
  80. os.remove(file)
  81. os.rename("%s.bak" % file, file)
  82. cmStatus = "1"
  83. else:
  84. print("****** Nginx Tcp Services Configmap.json Do Not Update ******")
  85. cmStatus = "0"
  86. return cmStatus
  87. # 部署应用到kubernetes平台
  88. def deployToKube():
  89. cmStatus = updateConfigMap("configmap.json")
  90. appStatus = commands.getoutput("kubectl get sts $JNLP_CONTROL_NAME -n $JNLP_NAMESPACE|grep $JNLP_CONTROL_NAME|wc -l")
  91. if appStatus == "1" and cmStatus == "1":
  92. print("Warning:" + JNLP_CONTROL_NAME + " is already, i will update it and update nginx tcp proxy !!!")
  93. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  94. print("===>>> kubectl apply output <<<===")
  95. print(apply_out)
  96. elif appStatus == "1" and cmStatus == "0":
  97. print("Warning:" + JNLP_CONTROL_NAME + " is already, i will update it !!!")
  98. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  99. print("===>>> kubectl apply output <<<===")
  100. print(apply_out)
  101. elif appStatus != "1" and cmStatus == "1":
  102. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  103. print("===>>> kubectl apply output <<<===")
  104. print(apply_out)
  105. print("===>>> apply is successfull <<<===")
  106. else:
  107. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  108. print("===>>> kubectl apply output <<<===")
  109. print(apply_out)
  110. print("===>>> apply app successfull <<<===")
  111. return
  112. # 部署应用状态获取
  113. def deployStatus():
  114. kubeconfig = config.kube_config.load_kube_config(config_file="/root/.kube/config")
  115. appsv1_api_instance = client.AppsV1Api(kubeconfig)
  116. namespace = JNLP_ENV
  117. stsname = JNLP_CONTROL_NAME
  118. pretty = "true"
  119. for x in range(20):
  120. try:
  121. sts_response = appsv1_api_instance.read_namespaced_stateful_set_status(stsname, namespace, pretty=pretty)
  122. if sts_response.status.replicas == sts_response.status.ready_replicas :
  123. print("===>>> " +stsname + " is RUNNING <<<===")
  124. chk_status = 1
  125. break
  126. else:
  127. if x < 20:
  128. time.sleep(15)
  129. else:
  130. chk_status = 0
  131. print(stsname + " status check fail !!! , Please contact kubernetes systen administrator")
  132. except ApiException as e:
  133. print("Exception when calling CoreV1Api->list_namespaced_pod: %s\n" % e)
  134. return chk_status
  135. # DNS解析
  136. # 域名由jenkins项目名+命名空间+dns域组合而成
  137. # 如果域名已存在,不会再更新
  138. def dnsAllocation():
  139. if JNLP_INGRESS == "nginx":
  140. httpClient = httplib.HTTPConnection("opsadmin.evbj.easou.com", 80, timeout=30)
  141. headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
  142. params = urllib.urlencode({'method': 'add', 'type': 'record', 'domain_id': 24, 'record_type': 'A', 'record_name': RECORD_NAME ,'record_ip': NGINX_RECORD_IP , 'record_ttl': 180})
  143. httpClient.request("POST", "/dns/dnsapi/?token=c2d1856be235a3207cd03b6f4d3c4094", params, headers)
  144. response = httpClient.getresponse().read()
  145. jstr = json.loads(response)
  146. nsStatus = jstr['status']
  147. print(NGINX_RECORD_IP)
  148. if nsStatus == "-501":
  149. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " is already exist")
  150. elif nsStatus == "0":
  151. httpClient = httplib.HTTPConnection("opsadmin.evbj.easou.com", 80, timeout=30)
  152. httpClient.request("POST", "/dns/mkconfig/?token=c2d1856be235a3207cd03b6f4d3c4094")
  153. response = httpClient.getresponse().read()
  154. jstr = json.loads(response)
  155. upStatus = jstr['status']
  156. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " " +upStatus + " add successfull !!!")
  157. else:
  158. print("*****Please contact DNS systen administrator*****")
  159. else :
  160. print(">>> Ingress error, Only nginx !!! <<<")
  161. return
  162. def cloudDns():
  163. if JNLP_INGRESS == "nginx":
  164. client = AcsClient('LTAI4LibOCW5ilIa', 'NiA9OumXJDHp4TwLwXWcCKGoDgDjms', 'cn-hangzhou')
  165. # add record
  166. request = AddDomainRecordRequest()
  167. request.set_accept_format('json')
  168. request.set_Value("scofield888888")
  169. request.set_Type("txt")
  170. request.set_RR("_dnsauth.8888")
  171. request.set_DomainName("appeasou.com")
  172. response = client.do_action_with_exception(request)
  173. print(response)
  174. else :
  175. print(">>> Ingress error, Only nginx !!! <<<")
  176. return
  177. def main(argv=None):
  178. if argv is None:
  179. args = sys.argv[1:]
  180. for opt_name in args :
  181. if opt_name in ('-a','--apply'):
  182. print("===>>> deploy app to kubernetes <<<===")
  183. deployToKube()
  184. time.sleep(10)
  185. sys.exit()
  186. if opt_name in ('-b','--build'):
  187. print("===>>> create deploy.yaml <<<===")
  188. deployYamlCreate()
  189. sys.exit()
  190. if opt_name in ('-c','--check'):
  191. print("===>>> app status check <<<===")
  192. deployStatus()
  193. sys.exit()
  194. if opt_name in ('-d','--dns'):
  195. print("===>>> update dns resolve <<<===")
  196. cloudDns()
  197. sys.exit()
  198. return
  199. if __name__ == "__main__":
  200. main()