def retrieve(self, request, *args, **kwargs): instance = self.get_object() minion_id = instance.minion_id with requests.Session() as s: saltapi = SaltAPI(session=s) response_data = saltapi.test_api(tgt=minion_id) # 失败或者成功都返回给前端,前端通过status判断执行是否完成, # 通过results内容{'192.168.68.51': False, '192.168.68.1': True}判断ping成功还是失败 return Response(response_data)
def create(self, request, *args, **kwargs): # 单minion更新 serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) minion_id = request.data.get('minion_id') with requests.Session() as s: saltapi = SaltAPI(session=s) response_data = saltapi.test_api(tgt=minion_id) if response_data['status'] is False: logger.error(response_data) return Response(response_data) else: # 结果类似:{'192.168.68.51': False, '192.168.68.1': True, '192.168.68.50-master': True} # 所以直接if判断true false if response_data['results'][minion_id]: try: grains_data = saltapi.grains_itmes_api(tgt=minion_id) # 这里获取了所有minion的grains内容,如果以后表字段有增加就从这里取方便 value = grains_data['results']['return'][0][minion_id] try: value['ipv4'].remove('127.0.0.1') except Exception as e: pass try: MinionList.objects.filter( minion_id=minion_id).update( minion_status='在线', ip=value.get('ipv4'), sn=value.get('serialnumber'), cpu_num=value.get('num_cpus'), cpu_model=value.get('cpu_model'), sys=value.get('kernel'), kernel=value.get('kernelrelease'), product_name=value.get('productname'), ipv4_address=value.get('ip4_interfaces'), mac_address=value.get('hwaddr_interfaces'), localhost=value.get('localhost'), mem_total=value.get('mem_total'), minion_version=value.get('saltversion'), system_issue=value.get('os') + value.get('osrelease'), update_time=datetime.datetime.now()) except Exception as e: # 有出现过某个minion的依赖文件被删除了但是minion进程还在,导致grains.items没有结果返回 # 这样就会出现vlaue不是一个字典而是是一个str正常value内容是{'ipv4':'xxxxx'}异常时候会是'grains.items is false' # 具体是什么str没记住哈哈,不过由于不少字典而又用了get来获取字典值所以会触发try的错误,也就有了下面的操作 MinionList.objects.filter( minion_id=minion_id).update( minion_status='异常', update_time=datetime.datetime.now()) except Exception as e: logger.error('单minion更新数据出错1,请检查' + str(e)) return Response({ 'results': '单minion更新数据出错1,请检查' + str(e), 'status': False }) else: try: # minion离线 MinionList.objects.filter(minion_id=minion_id).update( minion_status='离线', update_time=datetime.datetime.now()) except Exception as e: logger.error('单minion更新数据出错2,请检查' + str(e)) return Response({ 'results': '单minion更新数据出错2,请检查' + str(e), 'status': False }) return Response({'results': '更新成功', 'status': True})