disk.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from flask import Blueprint, request
  4. import json
  5. from uuid import uuid4
  6. import jimit as ji
  7. from models import Guest, DiskState
  8. from models.initialize import dev_table
  9. from models import Config
  10. from models import Disk
  11. from models import Rules
  12. from models import Utils
  13. from models.status import StorageMode
  14. from base import Base
  15. __author__ = 'James Iter'
  16. __date__ = '2017/4/24'
  17. __contact__ = 'james.iter.cn@gmail.com'
  18. __copyright__ = '(c) 2017 by James Iter.'
  19. blueprint = Blueprint(
  20. 'api_disk',
  21. __name__,
  22. url_prefix='/api/disk'
  23. )
  24. blueprints = Blueprint(
  25. 'api_disks',
  26. __name__,
  27. url_prefix='/api/disks'
  28. )
  29. disk_base = Base(the_class=Disk, the_blueprint=blueprint, the_blueprints=blueprints)
  30. @Utils.dumps2response
  31. def r_create():
  32. args_rules = [
  33. Rules.DISK_SIZE.value,
  34. Rules.REMARK.value,
  35. Rules.DISK_ON_HOST.value,
  36. Rules.QUANTITY.value
  37. ]
  38. config = Config()
  39. config.id = 1
  40. config.get()
  41. if config.storage_mode in [StorageMode.shared_mount.value, StorageMode.ceph.value,
  42. StorageMode.glusterfs.value]:
  43. request.json['on_host'] = 'shared_storage'
  44. try:
  45. ji.Check.previewing(args_rules, request.json)
  46. ret = dict()
  47. ret['state'] = ji.Common.exchange_state(20000)
  48. size = request.json['size']
  49. quantity = request.json['quantity']
  50. on_host = request.json['on_host']
  51. if size < 1:
  52. ret['state'] = ji.Common.exchange_state(41255)
  53. return ret
  54. while quantity:
  55. quantity -= 1
  56. disk = Disk()
  57. disk.guest_uuid = ''
  58. disk.size = size
  59. disk.uuid = uuid4().__str__()
  60. disk.remark = request.json.get('remark', '')
  61. disk.on_host = on_host
  62. disk.sequence = -1
  63. disk.format = 'qcow2'
  64. disk.path = config.storage_path + '/' + disk.uuid + '.' + disk.format
  65. disk.quota(config=config)
  66. message = {
  67. '_object': 'disk',
  68. 'action': 'create',
  69. 'uuid': disk.uuid,
  70. 'storage_mode': config.storage_mode,
  71. 'dfs_volume': config.dfs_volume,
  72. 'hostname': disk.on_host,
  73. 'image_path': disk.path,
  74. 'size': disk.size
  75. }
  76. if disk.on_host == 'shared_storage':
  77. available_hosts = Guest.get_available_hosts()
  78. if available_hosts.__len__() == 0:
  79. ret['state'] = ji.Common.exchange_state(50351)
  80. return ret
  81. # 在可用计算节点中平均分配任务
  82. chosen_host = available_hosts[quantity % available_hosts.__len__()]
  83. message['hostname'] = chosen_host['hostname']
  84. Guest.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  85. disk.create()
  86. return ret
  87. except ji.PreviewingError, e:
  88. return json.loads(e.message)
  89. @Utils.dumps2response
  90. def r_resize(uuid, size):
  91. args_rules = [
  92. Rules.UUID.value,
  93. Rules.DISK_SIZE_STR.value
  94. ]
  95. try:
  96. ji.Check.previewing(args_rules, {'uuid': uuid, 'size': size})
  97. disk = Disk()
  98. disk.uuid = uuid
  99. disk.get_by('uuid')
  100. ret = dict()
  101. ret['state'] = ji.Common.exchange_state(20000)
  102. if disk.size >= size:
  103. ret['state'] = ji.Common.exchange_state(41257)
  104. return ret
  105. config = Config()
  106. config.id = 1
  107. config.get()
  108. message = {
  109. '_object': 'disk',
  110. 'action': 'resize',
  111. 'uuid': disk.uuid,
  112. 'guest_uuid': disk.guest_uuid,
  113. 'storage_mode': config.storage_mode,
  114. 'size': int(size),
  115. 'dfs_volume': config.dfs_volume,
  116. 'hostname': disk.on_host,
  117. 'image_path': disk.path,
  118. 'passback_parameters': {'size': size}
  119. }
  120. if disk.on_host == 'shared_storage':
  121. message['hostname'] = Guest.get_lightest_host()['hostname']
  122. if disk.guest_uuid.__len__() == 36:
  123. message['device_node'] = dev_table[disk.sequence]
  124. Guest.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  125. return ret
  126. except ji.PreviewingError, e:
  127. return json.loads(e.message)
  128. @Utils.dumps2response
  129. def r_delete(uuids):
  130. args_rules = [
  131. Rules.UUIDS.value
  132. ]
  133. try:
  134. ji.Check.previewing(args_rules, {'uuids': uuids})
  135. ret = dict()
  136. ret['state'] = ji.Common.exchange_state(20000)
  137. disk = Disk()
  138. # 检测所指定的 UUDIs 磁盘都存在
  139. for uuid in uuids.split(','):
  140. disk.uuid = uuid
  141. disk.get_by('uuid')
  142. if disk.state != DiskState.idle.value:
  143. ret['state'] = ji.Common.exchange_state(41256)
  144. return ret
  145. config = Config()
  146. config.id = 1
  147. config.get()
  148. # 执行删除操作
  149. for uuid in uuids.split(','):
  150. disk.uuid = uuid
  151. disk.get_by('uuid')
  152. message = {
  153. '_object': 'disk',
  154. 'action': 'delete',
  155. 'uuid': disk.uuid,
  156. 'storage_mode': config.storage_mode,
  157. 'dfs_volume': config.dfs_volume,
  158. 'hostname': disk.on_host,
  159. 'image_path': disk.path
  160. }
  161. if disk.on_host == 'shared_storage':
  162. message['hostname'] = Guest.get_lightest_host()['hostname']
  163. Guest.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  164. return ret
  165. except ji.PreviewingError, e:
  166. return json.loads(e.message)
  167. def add_device(func):
  168. from functools import wraps
  169. @wraps(func)
  170. def _add_device(*args, **kwargs):
  171. ret = func(*args, **kwargs)
  172. if ret['data'].__len__() > 0:
  173. if isinstance(ret['data'], list):
  174. for i, item in enumerate(ret['data']):
  175. ret['data'][i][u'device'] = u'/dev/' + dev_table[item['sequence']]
  176. elif isinstance(ret['data'], dict):
  177. ret['data'][u'device'] = u'/dev/' + dev_table[ret['data']['sequence']]
  178. else:
  179. raise json.dumps(ret)
  180. return ret
  181. return _add_device
  182. @Utils.dumps2response
  183. @add_device
  184. def r_get(uuids):
  185. return disk_base.get(ids=uuids, ids_rule=Rules.UUIDS.value, by_field='uuid')
  186. @Utils.dumps2response
  187. @add_device
  188. def r_get_by_filter():
  189. return disk_base.get_by_filter()
  190. @Utils.dumps2response
  191. @add_device
  192. def r_content_search():
  193. return disk_base.content_search()
  194. @Utils.dumps2response
  195. def r_update(uuids):
  196. ret = dict()
  197. ret['state'] = ji.Common.exchange_state(20000)
  198. ret['data'] = list()
  199. args_rules = [
  200. Rules.UUIDS.value
  201. ]
  202. if 'remark' in request.json:
  203. args_rules.append(
  204. Rules.REMARK.value
  205. )
  206. if 'iops' in request.json:
  207. args_rules.append(
  208. Rules.IOPS.value
  209. )
  210. if 'iops_rd' in request.json:
  211. args_rules.append(
  212. Rules.IOPS_RD.value
  213. )
  214. if 'iops_wr' in request.json:
  215. args_rules.append(
  216. Rules.IOPS_WR.value
  217. )
  218. if 'iops_max' in request.json:
  219. args_rules.append(
  220. Rules.IOPS_MAX.value
  221. )
  222. if 'iops_max_length' in request.json:
  223. args_rules.append(
  224. Rules.IOPS_MAX_LENGTH.value
  225. )
  226. if 'bps' in request.json:
  227. args_rules.append(
  228. Rules.BPS.value
  229. )
  230. if 'bps_rd' in request.json:
  231. args_rules.append(
  232. Rules.BPS_RD.value
  233. )
  234. if 'bps_wr' in request.json:
  235. args_rules.append(
  236. Rules.BPS_WR.value
  237. )
  238. if 'bps_max' in request.json:
  239. args_rules.append(
  240. Rules.BPS_MAX.value
  241. )
  242. if 'bps_max_length' in request.json:
  243. args_rules.append(
  244. Rules.BPS_MAX_LENGTH.value
  245. )
  246. if args_rules.__len__() < 2:
  247. return ret
  248. request.json['uuids'] = uuids
  249. need_update_quota = False
  250. need_update_quota_parameters = ['iops', 'iops_rd', 'iops_wr', 'iops_max', 'iops_max_length',
  251. 'bps', 'bps_rd', 'bps_wr', 'bps_max', 'bps_max_length']
  252. if filter(lambda p: p in request.json, need_update_quota_parameters).__len__() > 0:
  253. need_update_quota = True
  254. try:
  255. ji.Check.previewing(args_rules, request.json)
  256. disk = Disk()
  257. # 检测所指定的 UUDIs 磁盘都存在
  258. for uuid in uuids.split(','):
  259. disk.uuid = uuid
  260. disk.get_by('uuid')
  261. for uuid in uuids.split(','):
  262. disk.uuid = uuid
  263. disk.get_by('uuid')
  264. disk.remark = request.json.get('remark', disk.remark)
  265. disk.iops = request.json.get('iops', disk.iops)
  266. disk.iops_rd = request.json.get('iops_rd', disk.iops_rd)
  267. disk.iops_wr = request.json.get('iops_wr', disk.iops_wr)
  268. disk.iops_max = request.json.get('iops_max', disk.iops_max)
  269. disk.iops_max_length = request.json.get('iops_max_length', disk.iops_max_length)
  270. disk.bps = request.json.get('bps', disk.bps)
  271. disk.bps_rd = request.json.get('bps_rd', disk.bps_rd)
  272. disk.bps_wr = request.json.get('bps_wr', disk.bps_wr)
  273. disk.bps_max = request.json.get('bps_max', disk.bps_max)
  274. disk.bps_max_length = request.json.get('bps_max_length', disk.bps_max_length)
  275. disk.update()
  276. disk.get()
  277. if disk.sequence >= 0 and need_update_quota:
  278. message = {
  279. '_object': 'disk',
  280. 'action': 'quota',
  281. 'uuid': disk.uuid,
  282. 'guest_uuid': disk.guest_uuid,
  283. 'hostname': disk.on_host,
  284. 'disks': [
  285. {
  286. 'sequence': disk.sequence,
  287. 'iops': disk.iops,
  288. 'iops_rd': disk.iops_rd,
  289. 'iops_wr': disk.iops_wr,
  290. 'iops_max': disk.iops_max,
  291. 'iops_max_length': disk.iops_max_length,
  292. 'bps': disk.bps,
  293. 'bps_rd': disk.bps_rd,
  294. 'bps_wr': disk.bps_wr,
  295. 'bps_max': disk.bps_max,
  296. 'bps_max_length': disk.bps_max_length
  297. }
  298. ]
  299. }
  300. Guest.emit_instruction(message=json.dumps(message))
  301. ret['data'].append(disk.__dict__)
  302. return ret
  303. except ji.PreviewingError, e:
  304. return json.loads(e.message)
  305. @Utils.dumps2response
  306. def r_distribute_count():
  307. from models import Disk
  308. rows, count = Disk.get_all()
  309. ret = dict()
  310. ret['state'] = ji.Common.exchange_state(20000)
  311. ret['data'] = {
  312. 'kind': {'system': 0, 'data_mounted': 0, 'data_idle': 0},
  313. 'total_size': 0,
  314. 'disks': rows.__len__()
  315. }
  316. for disk in rows:
  317. if disk['sequence'] == 0:
  318. ret['data']['kind']['system'] += 1
  319. elif disk['sequence'] < 0:
  320. ret['data']['kind']['data_idle'] += 1
  321. else:
  322. ret['data']['kind']['data_mounted'] += 1
  323. ret['data']['total_size'] += disk['size']
  324. return ret