Пример #1
0
 def setTemplate(self, name: str, template: str) -> None:
     """
     :param name: 模板名字
     :param template:  模板内容
     :return:
     """
     body = {
         'apiVersion': 'v1',
         'data': {
             'template': template
         },
         'kind': 'ConfigMap',
         'metadata': {
             'name': name,
         }
     }
     try:
         api_response = self.api_instance.create_namespaced_config_map(
             self.namespace,
             body,
         )
         return True
     except ApiException as e:
         logecho.info(e)
         return False
Пример #2
0
 def deleteTemplate(self, name):
     try:
         api_response = self.api_instance.delete_namespaced_config_map(
             name, self.namespace)
         return True
     except ApiException as e:
         logecho.info(e)
         return False
Пример #3
0
    def getInto(self, templateName: str) -> dict:
        """
        :return:  获取注入的body
        """
        template = intoTemplate.get()
        logecho.info("注入的模板")
        logecho.info(template)
        if templateName in template.keys():
            return template[templateName]

        return None
Пример #4
0
 def post(self):
     name = request.form.get("name")
     template = json.loads(request.form.get("template"))
     if name != None and template != None:
         try:
             intoTemplate.set(name, template)
             return {'code': '0', 'msg': 'Null'}
         except Exception as e:
             logecho.info(e)
             return {'code': '1', 'msg': '添加模板错误'}
     return {'code': '1', 'msg': '参数缺失'}
Пример #5
0
 def post(self):
     kind = request.form.get("type")
     rule = json.loads(request.form.get("rule"))
     if kind != None and rule != None:
         try:
             Rule.set(rule, kind)
             return {'code': '0', 'msg': 'Null'}
         except Exception as e:
             logecho.info(e)
             return {'code': '1', 'msg': '添加注入规则报错'}
     return {'code': '1', 'msg': '参数缺失'}
Пример #6
0
 def get(self):
     try:
         field_selector = "metadata.name=={}".format(self.ruleName)
         api_response = self.api_instance.list_namespaced_config_map(
             self.namespace, pretty='true', field_selector=field_selector)
         # 长度等于0表示没有这个模板
         if len(api_response.items) == 0:
             return None
         return json.loads(api_response.items[0].data[self.ruleName])
     except ApiException as e:
         logecho.info(e)
         return None
Пример #7
0
 def toExecute(
     self,
     operaton,
     kind,
     body,
 ):
     """
     :operaton: 操作的类型
     :kind:操作的资源对象
     :return: true or false
     """
     print(operaton)
     print(kind)
     body = json.loads(body.replace('\'', '"')[1:-1])
     if hasattr(resource, kind):
         hand = getattr(resource, kind)()
         if hasattr(hand, operaton):
             if operaton == "create":
                 if getattr(hand, operaton)(body):
                     logecho.info("{}成功".format(operaton))
                     return True
                 else:
                     logecho.info("{}失败".format(operaton))
                     return False
         logecho.info("{}失败,没有找到对应的资源方法".format(operaton))
         return False
     logecho.info("{}失败,没有找到对应的资源类".format(operaton))
     return False
Пример #8
0
 def toResourceTest(self, ):
     """
     主要用于自动检测yaml文件内容是否合法,以及对应的资源类型。
     :return:  资源类型
     """
     body = self.body.replace("\'", "\"")
     body = body[1:-1]
     print(body)
     try:
         s = json.loads(body)
         return s['kind']
     except Exception as e:
         logecho.info(e)
         return False
Пример #9
0
 def toInto(self):
     """
     :return: 注入
     """
     # 需要注入的containers
     into = []
     jsonpath = []
     try:
         needInto = self.filtration()
         if len(needInto) == 0:
             return None
     except Exception as e:
         logecho.info(e)
         return None
     # 用户自己定义的资源
     for i in self.sourceBody:
         into.append(i)
     if "containers" in needInto.keys():
         for containers in needInto["containers"]:
             into.append(containers)
         containersPath = self.intoPath["containers"]
         containersPath["value"] = into
         logecho.info(containersPath)
         jsonpath.append(containersPath)
     logecho.info(jsonpath)
     jsonpath = json.dumps(jsonpath)
     logecho.info(jsonpath)
     body = base64.b64encode(jsonpath.encode('utf8'))
     body = str(body, encoding='utf8')
     return body
Пример #10
0
 def create(body: json):
     """
     :return:
     """
     namespace = body['metadata']['namespace']
     api_instance = kubernetes.client.CoreV1Api(
         kubernetes.client.ApiClient(configuration))
     try:
         api_response = api_instance.create_namespaced_service(
             namespace, body)
         return True
     except ApiException as e:
         logecho.info(
             "Exception when calling CoreV1Api->create_namespaced_service: %s\n"
             % e)
         return False
Пример #11
0
 def getTemplateList(self):
     try:
         configMapList = []
         field_selector = "data=={}".format('template')
         api_response = self.api_instance.list_namespaced_config_map(
             self.namespace,
             pretty='true',
         )
         for i in api_response.items:
             for k in i.data.keys():
                 if k == 'template':
                     configMapList.append(i.metadata.name)
         return configMapList
     except ApiException as e:
         logecho.info(e)
         return []
Пример #12
0
 def getTemplate(self, name: str) -> json:
     """
     :param name: 模板名字
     :return:模板
     """
     try:
         field_selector = "metadata.name=={}".format(name)
         api_response = self.api_instance.list_namespaced_config_map(
             self.namespace, pretty='true', field_selector=field_selector)
         #长度等于0表示没有这个模板
         if len(api_response.items) == 0:
             return None
         return api_response.items[0].data['template']
     except ApiException as e:
         logecho.info(e)
         return None
Пример #13
0
 def post(self, name, operaton):
     action = ['create']
     if operaton not in action:
         return {'code': '1', 'msg': '不支持的操作{}'.format(operaton)}
     body = dbMap.getTemplate(name)
     if body is None:
         return {'code': '1', 'msg': '模板没有找到'}
     op = pipline(body)
     ##解析模板中资源类型
     kind = op.toResourceTest()
     logecho.info(kind)
     if kind:
         #解析模板中的参数
         parameter = op.toParameterTest()
         if len(parameter) > 0:
             data = request.form
             for i in parameter:
                 if i not in data:
                     return {"code": "模板中{}参数缺失".format(i)}
             # # 渲染
             try:
                 _t = jinja2.Template(body)
                 _text = _t.render(data)
                 _text.encode('utf-8')
                 body = _text
                 if op.toExecute(
                         operaton,
                         kind,
                         body,
                 ):
                     return {'code': '0', 'msg': '创建成功'}
                 return {'code': '1', 'msg': '后台异常'}
             except Exception as e:
                 logecho.info(e)
                 return {'code': '1', 'msg': '后台异常'}
         else:
             op.toExecute(
                 operaton,
                 kind,
                 body,
             )
     else:
         logecho.info("模板解析错误")
         return {"code": "1", "msg": "模板解析错误"}
Пример #14
0
 def filtration(self) -> dict:
     """
     :return:  根据注入条件匹配注入的body。
     """
     intoBody = []
     Body = {}
     rule = Rule.get()
     logecho.info("注入规则")
     logecho.info(rule)
     logecho.info(self.namespace)
     logecho.info(self.name)
     ###先判断容器注入
     for i in rule["containers"]:
         #
         if i.get("name") == self.name or i.get(
                 "namespace") == self.namespace:
             logecho.info("要注入的模板名字")
             template = self.getInto(i.get("template"))
             logecho.info(template)
             if template == None:
                 continue
             intoBody.append(template)
             Body["containers"] = intoBody
             break
     logecho.info(Body)
     return Body