def post(self, request, *args, **kwargs): ret = BaseResponse() if request.version == 'v1': try: username = request.data.get("username") passwd = request.data.get("passwd") user = repository_models.AdminInfo.objects.filter( username=username, password=passwd).first() if not user: ret.data = "用户名或密码错误" return JsonResponse(ret.dict) # 获取权限 init_permission(user, request._request) ret.data = { 'session_key': request.session.session_key, 'conn': '登陆成功' } ret.code = "20000" except Exception as error: print("post-error", error) ret.error = error ret.data = "rds录入失败" ret.code = "5000" return JsonResponse(ret.dict)
def hostdelete(pk): response = BaseResponse() # 返回值用的类 server_obj = Server.objects.filter(pk=pk).first() hostname = str(server_obj.hostname) # 查询zabbix主机配置信息 hostgetconfig = { "output": "extend", "filter": { "host": [ hostname, ] } } hostget_ret = zabbixtoconfig.hostget(params=hostgetconfig) result_list = hostget_ret.get('result') delete_config = [] # zabbix删除配置 # 获取查询zabbix主机数据 hostid for i in result_list: delete_config.append(i.get('hostid')) delete_ret = zabbixtoconfig.hostdelete(params=delete_config) logger.debug('delete_ret:%s hostname:%s pk:%s delete_config:%s deletestr:%s ' % (delete_ret, hostname, pk, delete_config, delete_ret)) response.code = 20000 response.data = delete_ret return response.dict
def get(self, request, *args, **kwargs): # response = {'code':1000,'data':None,'error':None} ret = BaseResponse() if request.version == 'v1': try: sessionobj = sessionmodels.Session.objects.filter( session_key=request.session.session_key).first() ret.data = { 'test': 'get', 'sessionkey': sessionobj.session_key, 'expire_date': sessionobj.expire_date } except Exception as error: print("get-error", error) ret.code = 500 ret.error = '获取数据失败' return JsonResponse(ret.dict)
def hostcreate(hostname): hostname = hostname response = BaseResponse() # 返回值用的类 # 创建zabbix主机配置信息 createhost = { "host": hostname, "interfaces": [{ "type": 1, "main": 1, "useip": 1, "ip": "192.168.56.77", "dns": "", "port": "10050" }], "groups": [{ "groupid": "1" }], "templates": [{ "templateid": "10001" }], "inventory_mode": 0, "inventory": { "macaddress_a": "01234", "macaddress_b": "56768" } } createhost_ret = zabbixtoconfig.hostcreate(params=createhost) # 获取 token response.code = 20000 response.data = '%s' % (createhost_ret) logger.debug('createhost_ret:%s' % (createhost_ret)) return response.dict
def get(self, request, *args, **kwargs): # response = {'code':1000,'data':None,'error':None} ret = BaseResponse() if request.version == 'v1': try: print('request.version', request.version) # 从数据库获取数据 queryset = models.Rdslist.objects.all() print('queryset', queryset) # 分页 page = StandardResultsSetPagination() rds_list = page.paginate_queryset(queryset, request, self) print('rds_list', rds_list) # 分页之后的结果执行序列化 ser = RedisListModelSerializer(instance=rds_list, many=True) ret.data = ser.data except Exception as error: print("get-error", error) ret.code = 500 ret.error = '获取数据失败' return JsonResponse(ret.dict)
def kubernetes_configmaps(postcontent, pk): response = BaseResponse() # 返回值用的类 # pk 数据库主键ID-编辑不条目,id不同 conn_obj = models.Configcenter.objects.filter(pk=pk).first() conftypename = conn_obj.get_conftype_id_display() publish_status_id = conn_obj.publish_status_id print('asdasdddddddddddddddddddddddddddd%s' % conftypename) k8sconfigobj = conn_obj.configrelation.all() kubecrt = [] # 获取k8s连接配置 for i in k8sconfigobj: allocationjson = yaml.safe_load(stream=i.allocation) kubecrt.append(allocationjson) for k8scrt in kubecrt: postcontentjson = yaml.safe_load(stream=postcontent) # 转换成json数据 configname = postcontentjson.get("metadata").get("name") # 获取配置文件名 print(configname) crt = k8scrt.get("crt") key = k8scrt.get("key") ulr = k8scrt.get("ulr") namespace = k8scrt.get("namespace") # kubernetes 入口 k8sapiobj = Kubernetesapi( host=ulr, cert_file=crt, key_file=key, ) if conftypename == 'configmaps': # 生成修改的configmap配置 apiVersion = postcontentjson.get("apiVersion") data = postcontentjson.get("data") kind = postcontentjson.get("kind") cmetadata = copy.deepcopy(postcontentjson.get("metadata")) cmetadata['namespace'] = namespace # 查看configmaps配置是否存在 newfun = getattr(k8sapiobj, 'mlist_namespaced_config_map') retfunc = newfun(namespace=namespace, field_selector='metadata.name=%s' % (configname)) print('namespace::::::::::::::::::::::::::: %s --------- %s' % (cmetadata, namespace)) body = kubernetes.client.V1ConfigMap( # 以下赋值都是json数据 api_version=apiVersion, kind=kind, metadata=cmetadata, data=data) # 如果不存在 if not retfunc.items: # 创建 configmaps 配置文件 k8sapiobj.mcreate_namespaced_config_map(body=body, namespace=namespace) else: # 如果存在 则 修改 configmaps 配置文件 k8sapiobj.mreplace_namespaced_config_map(body=body, namespace=namespace, name=configname) response.code = 20000 response.data = postcontent # 失效状态删除configmaps if (str(publish_status_id) == "2") and retfunc.items: # body = kubernetes.client.V1DeleteOptions(api_version=apiVersion,kind=kind) # print('body:::::::::::::::%s' % (body)) k8sapiobj.mdelete_namespaced_config_map(name=configname, namespace=namespace, body={}) response.code = 20000 response.data = '删除%s' % (configname) return response.dict
def post(self, request, *args, **kwargs): ret = BaseResponse() if request.version == 'v1': try: postdata = self.request.data print('postdata', postdata) authkey = postdata.get("auth") sessionobj = sessionmodels.Session.objects.filter( session_key=authkey).first() if not sessionobj: ret.code = 20050 ret.error = '你未登陆系统' return JsonResponse(ret.dict) # 如果不是列表数据格式,直接退出 if not isinstance(postdata, dict): ret.code = 50002 ret.error = 'post提交数据类型不正确' return JsonResponse(ret.dict) craeterdsdict = [] for rdsdict in postdata.get("postdata"): # type:dict # 判断提交的key数据是否正常 keyjudge = [ 'InstanceName', 'InstanceId', 'ConnectionDomain', 'PrivateIp', 'NetworkType', 'Engine', 'EngineVersion' ] for k in keyjudge: if not k in rdsdict: ret.code = 50002 ret.error = 'post提交数据参数 %s 不存在' % (k) return JsonResponse(ret.dict) InstanceIdjudge = rdsdict.get('InstanceId') print('InstanceIdjudge', InstanceIdjudge) rdsjudge = models.Redislist.objects.filter( InstanceId=InstanceIdjudge) print('rdsjudge', rdsjudge) if not rdsjudge: # 打散 添加 待插入列表中 craeterdsdict.append(models.Redislist(**rdsdict)) # 判断需要写入的列表是否未空 if not craeterdsdict: ret.code = 20002 ret.data = '没有需要创建的新数据' return JsonResponse(ret.dict) # 批量写入数据 print('craeterdsdict', craeterdsdict) models.Redislist.objects.bulk_create(craeterdsdict) ret.data = "rds录入成功%s" % (craeterdsdict) ret.code = "20000" except Exception as error: print("post-error", error) ret.error = error ret.data = "rds录入失败" ret.code = "5000" return JsonResponse(ret.dict)
def kubernetes_configmaps(pk): response = BaseResponse() # 返回值用的类 # pk 数据库主键ID-编辑不条目,id不同 k8sconfigmap_orm_obj = K8sConfigmap.objects.filter(pk=pk).first() # 获取自用配置 selfconf_content_yaml = k8sconfigmap_orm_obj.content_object.allocation selfconf_content_json = yaml.safe_load(selfconf_content_yaml) # 存活 失效 publish_status_id = str(k8sconfigmap_orm_obj.publish_status_id) # 发布模式(新老环境发布) publish_mode_id = str(k8sconfigmap_orm_obj.publish_mode_id) # 新老环境 newoldtest = ["newtest", "oldtest"] # 新环境 newtest = ["newtest", ] # 老环境 oldtest = ["oldtest", ] # 获取 编辑成功的 configmaps 配置文件内容 content = k8sconfigmap_orm_obj.content contentjson = yaml.safe_load(stream=content) # 转换成json数据 configname = contentjson.get("metadata").get("name") # 获取配置文件名 # 生成修改的configmap配置 apiVersion = contentjson.get("apiVersion") data = contentjson.get("data") kind = contentjson.get("kind") metadata = contentjson.get("metadata") kubecrtdict = {} # 获取k8s连接配置 for keyname in newoldtest: # k8s 新老环境 名字 kukecltcrtjson = selfconf_content_json.get(keyname) # kubecrtdict[keycrt] = kukecltcrt ulr = kukecltcrtjson.get("ulr") crt = kukecltcrtjson.get("crt") key = kukecltcrtjson.get("key") namespace = kukecltcrtjson.get("namespace") k8sapi = Kubernetesapi(host=ulr, cert_file=crt, key_file=key, ) kubecrtdict[keyname] = {"k8sapi": k8sapi, "namespace": namespace} print("kubecrt %s %s %s %s %s" % (ulr, crt, key, namespace, k8sapi)) def comfigmap_crud(env_list): for oldnewkey in env_list: # k8s api 集群入口 k8sapiobj = kubecrtdict.get(oldnewkey).get("k8sapi") mnamespace = kubecrtdict.get(oldnewkey).get("namespace") # 查看configmaps配置是否存在 newfun = getattr(k8sapiobj, 'mlist_namespaced_config_map') retfunc = newfun(namespace=mnamespace, field_selector='metadata.name=%s' % (configname)) # print(retfunc) copymetadata = copy.deepcopy(metadata) copymetadata["namespace"] = mnamespace body = kubernetes.client.V1ConfigMap( # 以下赋值都是json数据 api_version=apiVersion, kind=kind, metadata=copymetadata, data=data ) # 配置文件不存在 创建 if not retfunc.items and (publish_status_id == "1"): # 创建 configmaps 配置文件 ret = k8sapiobj.mcreate_namespaced_config_map(body=body, namespace=mnamespace) # print(ret) response.code = 20000 response.data = content # 配置文件存在 修改 if retfunc.items and (publish_status_id == "1"): # 修改 configmaps 配置文件 ret = k8sapiobj.mreplace_namespaced_config_map(body=body, namespace=mnamespace, name=configname) # print(ret) response.code = 20000 response.data = content # 失效状态删除configmaps if (publish_status_id == "2") and retfunc.items: # body = kubernetes.client.V1DeleteOptions(api_version=apiVersion,kind=kind) # print('body:::::::::::::::%s' % (body)) print(k8sapiobj.mdelete_namespaced_config_map(name=configname, namespace=mnamespace, body={})) response.code = 20000 response.data = '删除%s' % (configname) # 新老测试环境更新 if publish_mode_id == "1": # 新老环境更新 comfigmap_crud(newoldtest) return response.dict if publish_mode_id == "2": # 新环境更新 comfigmap_crud(newtest) return response.dict if publish_mode_id == "3": # 老环境更新 comfigmap_crud(oldtest) return response.dict response.data = '%s' % ("未执行任何更新操作") return response.dict