def query_event(task_name, username, proxy): data = {'task_name': task_name, 'username': username} data = json.dumps(data) api = APIRequest('{0}/v1.0/permission/event'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_post(data) logger.info('推送用户事件查询结果result:%s'%result) return result
def update_asset_info(need_update_asset, name, proxy=None): """ 更新资产信息 """ g_lock = threading.Lock() try: g_lock.acquire() proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name) update_proxy_asset = list(set(proxy_asset) & set(need_update_asset)) host_list = [ asset.networking.all()[0].ip_address for asset in update_proxy_asset ] if host_list: resource = gen_resource(update_proxy_asset) data = { 'mod_name': 'setup', 'resource': resource, 'hosts': host_list, 'mod_args': '', 'run_action': 'sync', 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) logger.debug(u'更新操作结果result:%s code:%s' % (result, code)) if code == 200 and result['messege']['success']: asset_ansible_update(update_proxy_asset, result, name) except Exception as e: raise ServerError(e) finally: g_lock.release()
def add_user(self, username, proxy, groups, web_username): """ add a host user. username: 系统用户名 web_username: 网站用户名 """ self.run_action = 'async' self.run_type = 'ad-hoc' if groups.strip(): module_args = 'name=%s shell=/bin/bash groups=%s' % (username, groups) else: module_args = 'name=%s shell=/bin/bash' % username data = {'mod_name': 'user', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': username, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, # 标记, 执行ansible ad-hoc命令还是执行playbook 'isTemplate': self.isTemplate } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def asset_operator(asset_list, status, username, proxy=None): """ 重启,关机,重装系统 """ g_lock = threading.Lock() try: g_lock.acquire() proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name) need_delete_asset = set(asset_list) & set(proxy_asset) systems = [item.name for item in need_delete_asset] profile = asset_list[0].profile if status == 'rebuild': data = {'rebuild': 'true', 'profile': profile, 'systems': systems} else: data = {'power': status, 'systems': systems} data = json.dumps(data) api = APIRequest('{0}/v1.0/system/action'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_post(data) logger.debug(u"操作结果result:%s codes:%s" % (result, codes)) task = Task() task.task_name = result['task_name'] task.username = username task.status = result['messege'] task.start_time = datetime.datetime.now() task.url = '{0}/v1.0/system/action'.format(proxy.url) task.save() task_queue.put( dict(task_name=result['task_name'], task_user=username, task_proxy=proxy.proxy_name)) except Exception as e: raise ServerError(e) finally: g_lock.release()
def update_asset_info(need_update_asset, name, proxy=None): """ 更新资产信息 """ g_lock = threading.Lock() try: g_lock.acquire() proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name) update_proxy_asset = list(set(proxy_asset) & set(need_update_asset)) host_list = [asset.networking.all()[0].ip_address for asset in update_proxy_asset] if host_list: resource = gen_resource(update_proxy_asset) data = {'mod_name': 'setup', 'resource': resource, 'hosts': host_list, 'mod_args': '', 'run_action': 'sync', 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) logger.debug(u'更新操作结果result:%s code:%s' % (result,code)) if code == 200 and result['messege']['success']: asset_ansible_update(update_proxy_asset, result, name) except Exception as e: raise ServerError(e) finally: g_lock.release()
def adv_task_action(request, res, *args, **kwargs): if request.method == 'POST': task_id = request.POST.get('task_id') action = request.POST.get('action') task = Task.objects.get(id=task_id) try: # TODO 先获取记录是否存在,存在的话就是新建 # 构建参数 param = {'action': action} # 调用proxy接口, api = APIRequest('{0}/v1.0/job/{1}/action/'.format(task.task_proxy.url, task.task_uuid), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_post(json.dumps(param)) if code != 200: raise ServerError(result['messege']) else: if action == 'pause': task.task_statu = '01' else: task.task_statu = '00' task.save() except ServerError, e: error = e.message res['flag'] = False res['content'] = error except Exception, e: res['flag'] = False res['content'] = e[1]
def add_user(self, username, proxy, groups, web_username): """ add a host user. username: 系统用户名 web_username: 网站用户名 """ self.run_action = 'async' self.run_type = 'ad-hoc' if groups.strip(): module_args = 'name=%s shell=/bin/bash groups=%s' % (username, groups) else: module_args = 'name=%s shell=/bin/bash' % username data = { 'mod_name': 'user', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': username, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, # 标记, 执行ansible ad-hoc命令还是执行playbook 'isTemplate': self.isTemplate } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def query_event(task_name, username, proxy): data = {'task_name': task_name, 'username': username} data = json.dumps(data) api = APIRequest('{0}/v1.0/permission/event'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_post(data) logger.info('推送用户事件查询结果result:%s' % result) return result
def role_proxy_operator(user_name, obj_name, data, proxy=None, obj_uuid='all', action='add'): """ 保存,更新, 删除数据,并把操作结果保存到Task表中 obj_name: PermRole, PermSudo """ result = res_info = msg_name = '' g_lock = threading.Lock() # 线程锁 if obj_name == 'PermRole': msg_name = u'系统用户' elif obj_name == 'PermSudo': msg_name = u'SUDO别名' g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid) try: g_lock.acquire() # 在每个proxy上(add/update/delete) role/sudo,并返回结果 api = APIRequest(g_url, proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) pdata = json.loads(data) res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'update': result, codes = api.req_put(data) pdata = json.loads(data) res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'delete': result, codes = api.req_del(data) pdata = json.loads(data) res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) logger.info('role_proxy_%s:%s'%(action, result['messege'])) # 生成唯一的事件名称,用于从数据库中查询执行结果 if 'name' not in json.dumps(data): raise ValueError('role_proxy_operator: data["name"]不存在') task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex # 将事件添加到消息队列中 task_queue.put({'server': task_name, 'username': user_name}) # 将执行结果保存到数据库中 role_task = Task() role_task.task_name = task_name role_task.proxy_name = proxy.proxy_name role_task.role_name = json.loads(data)['name'] role_task.username = user_name role_task.status = 'complete' role_task.content = res_info role_task.url = g_url role_task.start_time = datetime.datetime.now() role_task.action = action role_task.role_uuid = obj_uuid role_task.role_data = data role_task.result = result['messege'] role_task.save() except Exception as e: logger.error("[role_proxy_operator] %s"%e) finally: g_lock.release() return result
def task_action(request, res, *args, **kwargs): if request.method == 'POST': task_id = request.POST.get('task_id') action = request.POST.get('action') task = Task.objects.get(id=task_id) try: # 先从Proxy获取是否存在,若不存在则新建 api = APIRequest('{0}/v1.0/job/{1}'.format(task.task_proxy.url, task.task_uuid), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_get() # 构建参数 param = {'action': action} if code == 200: # 调用proxy接口, api = APIRequest('{0}/v1.0/job/{1}/action/'.format(task.task_proxy.url, task.task_uuid), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_post(json.dumps(param)) if code != 200: raise ServerError(result['messege']) else: if action == 'pause': task.task_statu = '01' else: task.task_statu = '00' task.save() elif code == 404: logger.info("task [%s] have been deleted" % task.task_uuid) # 不存在时,若启用则创建,若禁用则直接修改为禁用 if action == 'pause': # 停用,直接修改为禁用 task.task_statu = '01' task.save() elif action == 'resume': res['flag'] = False res['content'] = '触发器已过期,请使用编辑功能编辑触发器' return HttpResponse(json.dumps(res)) except ServerError, e: logger.error("action error %s" % str(e)) error = e.message res['flag'] = False res['content'] = error except Exception, e: logger.error("error %s" % str(e)) res['flag'] = False res['content'] = e[1]
def download(request): if request.method == 'POST': # 上传到本地目录 res = {'result': False} try: path = request.POST.get('path') proxy = request.POST.get('proxy') proxy_host = request.POST.get('proxy_host') params = {'action': 'download_ansible'} # 通过proxy处理文件 proxy_obj = Proxy.objects.get(id=proxy) hosts = [] if not proxy_host: raise RuntimeError("没有可执行主机") else: hosts.append(Asset.objects.get(id=int(proxy_host))) host_list = [] resource = [] params['path'] = path # 构建inventory 和 构建主机list for host in hosts: host_list.append(host.networking.all()[0].ip_address) tmp_d = dict() tmp_d['hostname'] = host.networking.all()[0].ip_address tmp_d['port'] = host.port tmp_d['username'] = host.username tmp_d['password'] = CRYPTOR.decrypt(host.password) # 用于前端确定选择的asset tmp_d['id'] = host.id resource.append(tmp_d) params['host_list'] = host_list params['resource'] = resource api = APIRequest( '{0}/v1.0/download'.format(proxy_obj.url), proxy_obj.username, CRYPTOR.decrypt(proxy_obj.password)) result, code = api.req_post(json.dumps(params)) if code != 200: res['message'] = result['message'] else: res['result'] = True link = "{0}/v1.0/download?link_id={1}".format(proxy_obj.url, result['link']) res['link'] = link logger.info("link => {0}".format(res)) except Exception, e: logger.info(traceback.format_exc()) res['message'] = '失败' return HttpResponse(json.dumps(res))
def del_key(self, user, key_path, proxy): """ push the ssh authorized key to target. """ module_args = 'user="******" key="{{ lookup("file", "%s") }}" state="absent"' % (user, key_path) data = {'mod_name': 'authorized_key', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': user } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR(proxy.password)) result, code = api.req_post(data) return result
def del_user(self, username, proxy, web_username): """ delete a host user. """ module_args = 'name=%s groups='' state=absent remove=yes move_home=yes force=yes' % username data = {'mod_name': 'user', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': username, 'web_username': web_username, 'run_action': 'sync', # run_action参数表示同步还是异步执行 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def del_user_sudo(self, role_uuid, proxy, web_username): """ delete a role sudo item """ filename = 'role-%s'%role_uuid module_args = "name=/etc/sudoers.d/%s state=absent" %filename data = {'mod_name': 'file', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'web_username': web_username, 'run_action': 'sync', 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def del_key(self, user, key_path, proxy): """ push the ssh authorized key to target. """ module_args = 'user="******" key="{{ lookup("file", "%s") }}" state="absent"' % ( user, key_path) data = { 'mod_name': 'authorized_key', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': user } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR(proxy.password)) result, code = api.req_post(data) return result
def del_user(self, username, proxy, web_username): """ delete a host user. """ module_args = 'name=%s groups=' ' state=absent remove=yes move_home=yes force=yes' % username data = { 'mod_name': 'user', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': username, 'web_username': web_username, 'run_action': 'sync', # run_action参数表示同步还是异步执行 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def del_user_sudo(self, role_uuid, proxy, web_username): """ delete a role sudo item """ filename = 'role-%s' % role_uuid module_args = "name=/etc/sudoers.d/%s state=absent" % filename data = { 'mod_name': 'file', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'web_username': web_username, 'run_action': 'sync', 'run_type': 'ad-hoc' } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def push_sudo(self, role, sudo_uuids, proxy, web_username): """ use template to render pushed sudoers file """ self.run_action = 'async' self.run_type = 'playbook' data = {'resource': self.resource, 'hosts': self.host_list, 'sudo_uuids': sudo_uuids, 'role_name': role.name, 'role_uuid': role.uuid_id, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, 'isTemplate': True } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def push_key(self, user, key_path, proxy, web_username): """ push the ssh authorized key to target. """ self.run_action = 'async' self.run_type = 'ad-hoc' module_args = 'user="******" key="{{ lookup("file", "%s") }}" state=present' % (user, key_path) data = {'mod_name': 'authorized_key', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': user, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, 'isTemplate': self.isTemplate } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'): """ 保存,更新, 删除数据 obj_name: 'PermRole' obj_uuid: role.uuid_id """ info = '' try: api = APIRequest('{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) elif action == 'update': result, codes = api.req_put(data) elif action == 'delete': result, codes = api.req_del(data) if result is not None: info = result['messege'] except Exception as e: info = 'error' logger.error("[save_or_delete] %s"%e) return info
def push_sudo(self, role, sudo_uuids, proxy, web_username): """ use template to render pushed sudoers file """ self.run_action = 'async' self.run_type = 'playbook' data = { 'resource': self.resource, 'hosts': self.host_list, 'sudo_uuids': sudo_uuids, 'role_name': role.name, 'role_uuid': role.uuid_id, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, 'isTemplate': True } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def asset_operator(asset_list, status, username, proxy=None): """ 重启,关机,重装系统 """ g_lock = threading.Lock() try: g_lock.acquire() proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name) need_delete_asset = set(asset_list) & set(proxy_asset) systems = [item.name for item in need_delete_asset] profile = asset_list[0].profile if status == 'rebuild': data = { 'rebuild': 'true', 'profile': profile, 'systems': systems } else: data = { 'power': status, 'systems': systems } data = json.dumps(data) api = APIRequest('{0}/v1.0/system/action'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, codes = api.req_post(data) logger.debug(u"操作结果result:%s codes:%s"%(result, codes)) task = Task() task.task_name = result['task_name'] task.username = username task.status = result['messege'] task.start_time = datetime.datetime.now() task.url = '{0}/v1.0/system/action'.format(proxy.url) task.save() task_queue.put(dict(task_name=result['task_name'], task_user=username, task_proxy=proxy.proxy_name)) except Exception as e: raise ServerError(e) finally: g_lock.release()
def push_key(self, user, key_path, proxy, web_username): """ push the ssh authorized key to target. """ self.run_action = 'async' self.run_type = 'ad-hoc' module_args = 'user="******" key="{{ lookup("file", "%s") }}" state=present' % ( user, key_path) data = { 'mod_name': 'authorized_key', 'resource': self.resource, 'hosts': self.host_list, 'mod_args': module_args, 'role_name': user, 'web_username': web_username, 'run_action': self.run_action, 'run_type': self.run_type, 'isTemplate': self.isTemplate } data = json.dumps(data) api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password)) result, code = api.req_post(data) return result
def save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'): """ 保存,更新, 删除数据 obj_name: 'PermRole' obj_uuid: role.uuid_id """ info = '' try: api = APIRequest( '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) elif action == 'update': result, codes = api.req_put(data) elif action == 'delete': result, codes = api.req_del(data) if result is not None: info = result['messege'] except Exception as e: info = 'error' logger.error("[save_or_delete] %s" % e) return info
def adv_task_edit(request, res, *args, **kwargs): if request.method == 'POST': param = {} # 触发器 trigger_kwargs = request.POST.get('trigger') comment = request.POST.get('comment') task_id = int(request.POST.get('task_id')) try: task = Task.objects.get(id=task_id) # 构建trigger trigger_kwargs = json.loads(trigger_kwargs) start_date = trigger_kwargs.pop('start_date') end_date = trigger_kwargs.get('end_date') if end_date: trigger_kwargs.pop('end_date') if not trigger_kwargs: start_date_2_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') trigger_kwargs['year'] = start_date_2_date.year trigger_kwargs['month'] = start_date_2_date.month trigger_kwargs['day'] = start_date_2_date.day trigger_kwargs['hour'] = start_date_2_date.hour trigger_kwargs['minute'] = start_date_2_date.minute trigger_kwargs['second'] = start_date_2_date.second trigger_kwargs['start_date'] = start_date if end_date: trigger_kwargs['end_date'] = end_date param['trigger_kwargs'] = trigger_kwargs # 先从Proxy获取是否存在,若不存在则新建 api = APIRequest('{0}/v1.0/job/{1}'.format(task.task_proxy.url, task.task_uuid), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_get() if code == 404: param['job_id'] = task.task_uuid param['task_name'] = task.task_type param['task_kwargs'] = json.loads(task.task_kwargs) # 任务已经完全结束,再次编辑时,proxy端需要重新创建 api = APIRequest('{0}/v1.0/job'.format(task.task_proxy.url), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_post(json.dumps(param)) if code != 200: raise ServerError(result['messege']) else: task.trigger_kwargs = json.dumps(trigger_kwargs) task.comment = comment task.is_get_last = '00' task.task_statu = '00' task.save() elif code == 200: api = APIRequest('{0}/v1.0/job/{1}'.format(task.task_proxy.url, task.task_uuid), task.task_proxy.username, CRYPTOR.decrypt(task.task_proxy.password)) result, code = api.req_put(json.dumps(param)) if code != 200: raise ServerError(result['messege']) else: task.trigger_kwargs = json.dumps(trigger_kwargs) task.comment = comment task.save() except: logger.error(traceback.format_exc()) res['flag'] = False res['content'] = "update error" else: res['flag'] = True return HttpResponse(json.dumps(res)) elif request.method == "GET": task_id = request.GET.get('task_id') task = Task.objects.get(id=task_id).to_dict() proxy_list = [proxy.to_dict() for proxy in Proxy.objects.all().order_by('create_time')] task['task_proxy'] = task['task_proxy'].to_dict() res['task'] = task res['proxys'] = proxy_list res['task_types'] = Task.TYPES[1:] return HttpResponse(json.dumps(res))
def adv_task_add(request, res, *args): if request.method == 'POST': param = {} # 触发器 trigger_kwargs = request.POST.get('trigger') task_name = request.POST.get('task_type') task_content = request.POST.get('task_content') # 文件内容 task_host = request.POST.getlist('task_host[]') # 前端上送list时 proxy = request.POST.get('proxy') comment = request.POST.get('comment') try: # 构建trigger init_trigger = trigger_kwargs = json.loads(trigger_kwargs) start_date = trigger_kwargs.pop('start_date') if not trigger_kwargs: start_date_2_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') trigger_kwargs['year'] = start_date_2_date.year trigger_kwargs['month'] = start_date_2_date.month trigger_kwargs['day'] = start_date_2_date.day trigger_kwargs['hour'] = start_date_2_date.hour trigger_kwargs['minute'] = start_date_2_date.minute trigger_kwargs['second'] = start_date_2_date.second trigger_kwargs['start_date'] = start_date param['trigger_kwargs'] = trigger_kwargs hosts = [] # 没有选中主机,则认为是全选,取选中proxy下的所有 proxy_obj = Proxy.objects.get(id=proxy) param['task_name'] = task_name task_kwargs = {} if not task_host: hosts = Asset.objects.all().filter(proxy=proxy_obj) if not hosts: # 没有可执行主机 raise ServerError("no exec host") else: for host_id in task_host: hosts.append(Asset.objects.get(id=host_id)) host_list = [] resource = [] # 构建inventory 和 构建主机list for host in hosts: host_list.append(host.networking.all()[0].ip_address) tmp_d = dict() tmp_d['hostname'] = host.networking.all()[0].ip_address tmp_d['port'] = host.port tmp_d['username'] = host.username tmp_d['password'] = CRYPTOR.decrypt(host.password) # 用于前端确定选择的asset tmp_d['id'] = host.id resource.append(tmp_d) task_kwargs['host_list'] = host_list task_kwargs['resource'] = resource task_kwargs['content'] = task_content param['task_kwargs'] = task_kwargs # 调用proxy接口,创建任务 api = APIRequest('{0}/v1.0/job'.format(proxy_obj.url), proxy_obj.username, CRYPTOR.decrypt(proxy_obj.password)) result, code = api.req_post(json.dumps(param)) if code != 200: raise ServerError(result['messege']) else: task = Task(task_type=task_name, task_proxy=proxy_obj, task_kwargs=json.dumps(task_kwargs), trigger_kwargs=json.dumps(trigger_kwargs), channal='00', comment=comment, task_uuid=result['job']['job_id'], create_time=datetime.now()) task.save() except ServerError, e: error = e.message res['flag'] = False res['content'] = error except Exception, e: logger.error(traceback.format_exc()) res['flag'] = False res['content'] = e[1]
def asset_add(request,res, *args): """ Asset add view 添加资产 """ response = {'success': False, 'error': ''} res['operator'] = u'添加资产' if request.method == 'POST': try: hostname = request.POST.get('name', '') if Asset.objects.filter(name=unicode(hostname)): error = u'该主机名 %s 已存在!' % hostname raise ServerError(error) name = request.POST.get('name') port = request.POST.get('port') username = request.POST.get('username') pwd = request.POST.get('password') hostname = request.POST.get('hostname', '') power_address = request.POST.get('power_address') power_username = request.POST.get('power_username') ency_password = request.POST.get('power_password') mac_address = request.POST.get('mac_address') ip_address = request.POST.get('ip_address') if '' in [name, port, username, pwd, hostname, power_address, power_username, ency_password, mac_address, ip_address]: raise ServerError(u'必要参数为空') timestamp = int(time.time()) id_unique = name + '_'+ str(timestamp) fields = { "id_unique": id_unique, "name": request.POST.get('name'), "hostname": request.POST.get('hostname'), "profile": request.POST.get('profile'), "gateway": request.POST.get('gateway'), "power_type": request.POST.get('power_type'), "netboot_enabled": request.POST.get('is_enabled'), "power_address": request.POST.get('power_address'), "power_user": request.POST.get('power_username'), "power_pass": request.POST.get('power_password'), "interfaces": { "{0}".format(request.POST.get('net_name', 'eth0')): { "mac_address": request.POST.get('mac_address'), "ip_address": request.POST.get('ip_address'), "if_gateway": request.POST.get('per_gateway'), "mtu": request.POST.get('mtu'), "netmask": request.POST.get('subnet_mask'), "static": 1, }, } } data = json.dumps(fields) select_proxy = get_object(Proxy, id=int(request.POST.get('proxy'))) pro_username = select_proxy.username pro_password = select_proxy.password pro_url = select_proxy.url try: api = APIRequest('{0}/v1.0/system/'.format(pro_url), pro_username, CRYPTOR.decrypt(pro_password)) result, codes = api.req_post(data) except Exception as e: res['flag'] = 'false' res['content'] = e.message response['error'] = e.message else: if codes == 200: asset_info = Asset() asset_info.id_unique = id_unique asset_info.name = request.POST.get('name', '') asset_info.profile = request.POST.get('profile', '') asset_info.status = request.POST.get('status', '1') asset_info.kickstart = request.POST.get('kickstart', '') asset_info.port = int(request.POST.get('port',22)) asset_info.username = request.POST.get('username', 'root') pwd = request.POST.get('password', '') asset_info.password = CRYPTOR.encrypt(pwd) asset_info.idc_id = int(request.POST.get('idc', '1')) asset_info.cabinet = request.POST.get('cabinet', '') asset_info.number = request.POST.get('number', '') asset_info.machine_status = int(request.POST.get('machine_status', 1)) asset_info.asset_type = int(request.POST.get('asset_type', 1)) asset_info.product_serial = request.POST.get('sn', '') asset_info.comment = request.POST.get('comment', '') asset_info.proxy_id = int(request.POST.get('proxy', '1')) nt_g = NetWorkingGlobal() nt_g.hostname = request.POST.get('hostname', '') nt_g.gateway = request.POST.get('gateway','') nt_g.name_servers = request.POST.get('name_servers', '') nt_g.save() asset_info.networking_g_id = nt_g.id pm = PowerManage() pm.power_type = request.POST.get('power_type') pm.power_address = request.POST.get('power_address') pm.power_username = request.POST.get('power_username') ency_password = CRYPTOR.encrypt(request.POST.get('power_password', '')) pm.power_password = ency_password pm.save() asset_info.power_manage_id = pm.id asset_info.proxy_id = int(request.POST.get('proxy', 1)) is_active = True if request.POST.get('is_active', '1') == '1' else False is_enabled = True if request.POST.get('is_enabled', '1') == '1' else False asset_info.netboot_enabled = is_enabled asset_info.is_active = is_active asset_info.save() net = NetWorking() net.net_name = request.POST.get('net_name', 'eth0') net.mac_address = request.POST.get('mac_address', '') net.ip_address = request.POST.get('ip_address','') net.dns_name = request.POST.get('dns_name', '') net.mtu = request.POST.get('mtu', '') net.per_gateway = request.POST.get('per_gateway', '') net.static = request.POST.get('static', '') net.static_routes = request.POST.get('static_routes', '') net.subnet_mask = request.POST.get('subnet_mask', '') net.save() asset_info.networking.add(net) group_id = request.POST.getlist('group') for item in group_id: group = AssetGroup.objects.get(id=int(item)) asset_info.group.add(group) asset_info.save() res['content'] = u'创建主机成功' response['success'] = True response['error'] = result['messege'] else: res['flag'] = 'false' res['content'] = u"创建机器失败:%s"%result['messege'] response['error'] = u"创建机器失败:%s"%result['messege'] except ServerError as e: res['flag'] = 'false' res['content'] = e.message response['error'] = e.message return HttpResponse(json.dumps(response), content_type='application/json')
def role_proxy_operator(user_name, obj_name, data, proxy=None, obj_uuid='all', action='add'): """ 保存,更新, 删除数据,并把操作结果保存到Task表中 obj_name: PermRole, PermSudo """ result = res_info = msg_name = '' g_lock = threading.Lock() # 线程锁 if obj_name == 'PermRole': msg_name = u'系统用户' elif obj_name == 'PermSudo': msg_name = u'SUDO别名' g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid) try: g_lock.acquire() # 在每个proxy上(add/update/delete) role/sudo,并返回结果 api = APIRequest(g_url, proxy.username, CRYPTOR.decrypt(proxy.password)) if action == 'add': result, codes = api.req_post(data) pdata = json.loads(data) res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'update': result, codes = api.req_put(data) pdata = json.loads(data) res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) elif action == 'delete': result, codes = api.req_del(data) pdata = json.loads(data) res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'], result['messege']) logger.info('role_proxy_%s:%s' % (action, result['messege'])) # 生成唯一的事件名称,用于从数据库中查询执行结果 if 'name' not in json.dumps(data): raise ValueError('role_proxy_operator: data["name"]不存在') task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex # 将事件添加到消息队列中 task_queue.put({'server': task_name, 'username': user_name}) # 将执行结果保存到数据库中 role_task = Task() role_task.task_name = task_name role_task.proxy_name = proxy.proxy_name role_task.role_name = json.loads(data)['name'] role_task.username = user_name role_task.status = 'complete' role_task.content = res_info role_task.url = g_url role_task.start_time = datetime.datetime.now() role_task.action = action role_task.role_uuid = obj_uuid role_task.role_data = data role_task.result = result['messege'] role_task.save() except Exception as e: logger.error("[role_proxy_operator] %s" % e) finally: g_lock.release() return result