core.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. dever-manage tools
  5. name:Core.py
  6. author:rabin
  7. """
  8. import time
  9. import datetime
  10. import os
  11. import sys
  12. import getopt
  13. import ConfigParser
  14. import commands
  15. import re
  16. import subprocess
  17. import urlparse
  18. class Args(object):
  19. @classmethod
  20. def init(self):
  21. self.action = ''
  22. self.name = ''
  23. self.index = ''
  24. self.param = ''
  25. self.argv()
  26. @classmethod
  27. def argv(self):
  28. slen = len(sys.argv)
  29. if slen >= 2:
  30. self.action = sys.argv[1]
  31. if slen >= 3:
  32. self.name = sys.argv[2]
  33. if slen >= 4:
  34. self.param = sys.argv[3]
  35. self.options()
  36. if self.action == '':
  37. print 'action error'
  38. sys.exit()
  39. @classmethod
  40. def options(self):
  41. try:
  42. options, args = getopt.getopt(sys.argv[1:], "ha:n:p:", ['help', "action=", "name=", "param="])
  43. for name, value in options:
  44. if name in ('-h', '--help'):
  45. self.usage()
  46. elif name in ('-a', '--action'):
  47. self.method = value
  48. elif name in ('-n', '--name'):
  49. Args.name = value
  50. elif name in ('-p', '--param'):
  51. self.param = value
  52. except getopt.GetoptError:
  53. self.usage()
  54. @classmethod
  55. def usage(self):
  56. print File.read(Core.path, 'usage')
  57. sys.exit()
  58. class Env(object):
  59. dm_use = 'base.use'
  60. dm_store = 'base.store'
  61. dm_val = 'val.'
  62. data = {}
  63. @staticmethod
  64. def key(name):
  65. return name.split('.')
  66. @classmethod
  67. def init(self, name):
  68. if not self.data:
  69. self.data = Config.runtime()
  70. return self.key(name)
  71. @classmethod
  72. def read(self, name):
  73. key, name = self.init(name)
  74. if key in self.data and name in self.data[key]:
  75. return self.data[key][name]
  76. else:
  77. return False
  78. @classmethod
  79. def write(self, name, value):
  80. key, name = self.init(name)
  81. self.data[key][name] = value
  82. Config.runtime(key, name, value)
  83. return value
  84. @classmethod
  85. def use(self, value=None):
  86. if value:
  87. return self.write(self.dm_use, value)
  88. return self.read(self.dm_use)
  89. @classmethod
  90. def store(self, value=None):
  91. if value:
  92. return self.write(self.dm_store, value)
  93. return self.read(self.dm_store)
  94. @classmethod
  95. def val(self, name='', value=None):
  96. name = self.dm_val + name.capitalize()
  97. if value:
  98. return self.write(name, value)
  99. return self.read(name)
  100. class Config(object):
  101. @classmethod
  102. def runtime(self, key='', name='', value=''):
  103. runtime = Core.path + 'data/runtime.conf'
  104. if File.exists(runtime):
  105. config = ConfigParser.ConfigParser()
  106. config.read(runtime)
  107. if key and name:
  108. config.set(key, name, value)
  109. config.write(open(runtime, 'w'))
  110. else:
  111. result = {}
  112. for item in config.sections():
  113. result[item] = self.readOption(config, item)
  114. return result
  115. else:
  116. print runtime + ' is not exists'
  117. sys.exit()
  118. @classmethod
  119. def core(self, path):
  120. core = Core.path + path + 'core.conf'
  121. if File.exists(core):
  122. config = ConfigParser.ConfigParser()
  123. config.read(core)
  124. result = {}
  125. for item in config.sections():
  126. result[item] = self.readOption(config, item)
  127. return result
  128. else:
  129. print core + ' is not exists'
  130. sys.exit()
  131. @classmethod
  132. def read(self, path):
  133. if '-' in Args.name:
  134. temp = Args.name.split('-')
  135. Args.name = temp[0]
  136. Args.index = temp[1]
  137. filename = Core.path + path + 'conf/' + Args.name + '.conf'
  138. if File.exists(filename):
  139. config = ConfigParser.ConfigParser()
  140. config.read(filename)
  141. result = {}
  142. result['server'] = []
  143. result['config'] = {}
  144. result['base'] = {}
  145. for item in config.sections():
  146. if item == 'base':
  147. result['base'] = self.readOption(config, item)
  148. else:
  149. result['server'].append(item)
  150. result['config'][item] = self.readOption(config, item)
  151. result['base']['path'] = Core.replace('{base}', Core.path, result['base']['path'])
  152. return result
  153. else:
  154. print filename + ' is not exists'
  155. sys.exit()
  156. @staticmethod
  157. def readOption(config, type):
  158. value = config.options(type)
  159. result = {}
  160. for item in value:
  161. result[item] = config.get(type, item)
  162. return result
  163. class Alias(object):
  164. @classmethod
  165. def delete(self, config, name):
  166. result = self.get(config, name)
  167. for key in result:
  168. action = self.action(name, key)
  169. if action[0] != 'sh' and File.exists(action[1]):
  170. content = File.get(action[1])
  171. string = 'docker exec -it ' + name + ' ' + action[0] + ' $@'
  172. if string in content:
  173. content = content.replace(string, '')
  174. File.write(action[1], content.strip())
  175. if 'docker' not in content:
  176. Core.popen('rm -rf ' + action[1], bg=True)
  177. Core.popen('rm -rf ' + action[2], bg=True)
  178. #Core.popen('rm -rf ' + action[1], bg=True)
  179. #Core.popen('rm -rf ' + action[2], bg=True)
  180. @classmethod
  181. def add(self, config, name, content, type):
  182. result = self.get(config, name)
  183. for key in result:
  184. action = self.action(name, key)
  185. old = ''
  186. if File.exists(action[1]):
  187. old = File.get(action[1])
  188. env = '#!/usr/bin/env sh \nset -e\n'
  189. if type != 'call':
  190. if action[0] == 'sh':
  191. content = env + self.define(name) + \
  192. 'else\n' + \
  193. 'docker exec -it ' + name + ' ' + action[0] + ' $@\n' + \
  194. 'fi'
  195. elif old:
  196. content = 'docker exec -it ' + name + ' ' + action[0] + ' $@'
  197. if content not in old:
  198. content = old + '\n' + content
  199. else:
  200. content = ''
  201. else:
  202. content = env + 'docker exec -it ' + name + ' ' + action[0] + ' $@'
  203. else:
  204. content = env + ' $@'
  205. if content:
  206. File.write(action[1], content)
  207. Core.popen('ln -sf ' + action[1] + ' ' + action[2])
  208. @staticmethod
  209. def define(name):
  210. conf = ['logs', 'inspect', 'restart', 'stop', 'rm', 'rmb', 'run', 'uprun', 'show']
  211. result = ''
  212. for key in conf:
  213. control = 'elif'
  214. shell = 'dm ' + key + ' ' + name + '\n'
  215. if key == 'logs':
  216. control = 'if'
  217. result = result + control + ' [ "$1" = "'+key+'" ];then\n' + shell
  218. return result
  219. @classmethod
  220. def get(self, config, name):
  221. self.path = Core.path + 'data/alias/'
  222. result = []
  223. default = 'sh->' + name
  224. if 'alias' in config:
  225. config['alias'] = config['alias'] + ',' + default
  226. if ',' in config['alias']:
  227. result = config['alias'].split(',');
  228. else:
  229. result = [config['alias']]
  230. else:
  231. result = [default]
  232. return result
  233. @classmethod
  234. def action(self, name, key):
  235. file = key
  236. if '->' in key:
  237. temp = key.split('->')
  238. key = temp[0]
  239. file = temp[1]
  240. link = '/usr/bin/' + file
  241. file = self.path + file
  242. return [key, file, link]
  243. class File(object):
  244. @staticmethod
  245. def write(file, content):
  246. handle = open(file, 'w')
  247. handle.write(content)
  248. handle.close()
  249. Core.popen('chmod +x ' + file)
  250. @staticmethod
  251. def read(path, name):
  252. handle = open(path + name, 'r')
  253. content = handle.read()
  254. handle.close()
  255. return content
  256. @staticmethod
  257. def get(file):
  258. handle = open(file, 'r')
  259. content = handle.read()
  260. handle.close()
  261. return content
  262. @staticmethod
  263. def path():
  264. return os.path.split(os.path.realpath(__file__))[0] + '/'
  265. @staticmethod
  266. def exists(name):
  267. return os.path.exists(name)
  268. @staticmethod
  269. def rename(old, new):
  270. return os.rename(old, new)
  271. @staticmethod
  272. def remove(file):
  273. return os.remove(file)
  274. @staticmethod
  275. def mkdir(path):
  276. if File.exists(path) == False:
  277. os.mkdir(path)
  278. return path
  279. @staticmethod
  280. def mkdirs(path):
  281. if File.exists(path) == False:
  282. os.makedirs(path)
  283. return path
  284. class Git(object):
  285. @staticmethod
  286. def update(git, path):
  287. if File.exists(path) == False:
  288. Core.popen('git clone ' + git + ' ' + path, True)
  289. print 'init:' + path + ' finished!'
  290. else:
  291. Core.popen('cd ' + path + ' && git pull', bg=True)
  292. print 'update:' + path + ' finished!'
  293. class Core(object):
  294. path = ''
  295. @classmethod
  296. def getClass(self, name, path=''):
  297. obj = self.getObject(name, path)
  298. if path:
  299. if not hasattr(obj, name):
  300. print 'error ' + name
  301. sys.exit()
  302. obj = getattr(obj, name)
  303. name = name.capitalize()
  304. if not hasattr(obj, name):
  305. print 'error ' + name
  306. sys.exit()
  307. return getattr(obj, name)
  308. @staticmethod
  309. def getObject(name, path = ''):
  310. return __import__(path + name)
  311. @staticmethod
  312. def getMethod(obj, name):
  313. if not hasattr(obj, name):
  314. print 'error ' + name
  315. sys.exit()
  316. return getattr(obj, name)
  317. @classmethod
  318. def shell(self, command, sub=False, bg=False):
  319. shell = self.path + 'src/shell/' + command.replace('.', '/', 1)
  320. return self.popen(shell, sub, bg)
  321. @staticmethod
  322. def popen(command, sub=False, bg=False):
  323. string = command
  324. if bg == True:
  325. command = command + ' 1>/dev/null 2>&1 &'
  326. if sub == False:
  327. process = os.popen(command)
  328. output = process.read()
  329. process.close()
  330. return output
  331. else:
  332. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  333. output = ''
  334. print string
  335. while True:
  336. output = popen.stdout.readline()
  337. print output
  338. if popen.poll() is not None:
  339. break
  340. return output
  341. @classmethod
  342. def install(self, soft):
  343. print 'install ' + soft + '...'
  344. if soft == 'docker':
  345. self.shell('install.docker', True)
  346. else:
  347. self.shell('install.package ' + soft, True)
  348. @classmethod
  349. def check(self, soft):
  350. result = int(Core.popen('which '+soft+' | wc -l'))
  351. if result != 0:
  352. return 1
  353. else:
  354. self.install(soft)
  355. return 0
  356. @staticmethod
  357. def replace(old, new, string):
  358. if old in string:
  359. string = string.replace(old, new)
  360. return string
  361. @staticmethod
  362. def isset(v):
  363. try :
  364. type(eval(v))
  365. except :
  366. return 0
  367. else :
  368. return 1