예제 #1
0
def check_parameter():
    """Get all techniques from ncf folder passed as parameter, or default ncf folder if not defined"""
    try:
        if not "value" in request.json:
            return format_error(
                ncf.NcfError(
                    "No value metadata provided in the request body."), "",
                400)
        else:
            parameter_value = request.json['value']

        if not "constraints" in request.json:
            return format_error(
                ncf.NcfError(
                    "No constraints metadata provided in the request body."),
                "", 400)
        else:
            parameter_constraints = request.json['constraints']

        # We need to get path from url params, if not present put "" as default value
        check = ncf_constraints.check_parameter(parameter_value,
                                                parameter_constraints)
        resp = jsonify(check)
        return resp
    except Exception as e:
        return format_error(e, "checking parameter", 500)
예제 #2
0
def generate_technique_content(technique, methods):
  """Generate technique CFEngine file as string from its metadata"""

  content = []
  for metadata_key in [ 'name', 'description', 'version' ]:
    # Add commentary for each new line in the metadata
    metadata_value = technique[metadata_key].replace("\n", "\n# ")
    content.append('# @'+ metadata_key +" "+ metadata_value)
  content.append('')
  content.append('bundle agent '+ technique['bundle_name'])
  content.append('{')
  content.append('  vars:')
  content.append('    "class_prefix" string => canonify(join("_", "this.callers_promisers"));')
  content.append('')
  content.append('  methods:')

  # Handle method calls
  for method_call in technique["method_calls"]:
    method_name = method_call["method_name"]
    regex = re.compile(r'(?<!\\)"', flags=re.UNICODE )
    # Treat each argument of the method_call
    if 'args' in method_call:
      for index, arg in enumerate(method_call['args']):
        arg_constraint = ncf_constraints.default_constraint
        if method_name in methods:
          parameter = methods[method_name]["parameter"][index]
          arg_constraint = parameter.get("constraints", {})
        if arg is None:
          raise NcfError("Parameter '"+ parameter["name"] +"' of method '"+ method_name +"' in technique '"+ technique['bundle_name'] + " is not defined, please enter a value")
        check = ncf_constraints.check_parameter(arg, arg_constraint)
        if not check['result']:
          error_constraint = "'"+"', '".join(check['errors'])+"'"
          raise NcfError("Invalid value for parameter '"+ parameter["name"] +"' of method '"+ method_name +"' in technique '"+ technique['bundle_name'] +"', invalid value is '"+ arg+"', doesn't match constraints: " + error_constraint)
      args = ['"%s"'%regex.sub(r'\\"', arg) for arg in method_call['args'] ]
      arg_value = ', '.join(args)
    else:
      arg_value = ""
    class_context = canonify_class_context(method_call['class_context'])

    if 'promiser' in method_call:
      promiser = method_call['promiser']
    else:
      promiser = "method_call"
    content.append('    "'+promiser+'" usebundle => '+method_call['method_name']+'('+arg_value+'),')
    content.append('      ifvarclass => concat("'+class_context+'");')

  content.append('}')

  # Join all lines with \n to get a pretty CFEngine file
  result =  '\n'.join(content)+"\n"

  return result 
예제 #3
0
파일: views.py 프로젝트: Normation/ncf
def check_parameter():
  """Get all techniques from ncf folder passed as parameter, or default ncf folder if not defined"""
  try:
    if not "value" in request.json:
      return format_error(ncf.NcfError("No value metadata provided in the request body."), "", 400)
    else:
       parameter_value = request.json['value']

    if not "constraints" in request.json:
      return format_error(ncf.NcfError("No constraints metadata provided in the request body."), "", 400)
    else:
      parameter_constraints = request.json['constraints']
 
    # We need to get path from url params, if not present put "" as default value
    check = ncf_constraints.check_parameter(parameter_value,parameter_constraints)
    resp = jsonify( check )
    return resp
  except Exception as e:
    return format_error(e, "checking parameter", 500)
예제 #4
0
def generate_technique_content(technique, methods):
    """Generate technique CFEngine file as string from its metadata"""

    content = []
    for metadata_key in ['name', 'description', 'version']:
        # Add commentary for each new line in the metadata
        metadata_value = technique[metadata_key].replace("\n", "\n# ")
        content.append('# @' + metadata_key + " " + metadata_value)

    bundle_param = ""
    if len(technique["parameter"]) > 0:
        bundle_param = "(" + ", ".join(
            [canonify(param["name"])
             for param in technique["parameter"]]) + ")"
    for parameter in technique["parameter"]:
        if not "id" in parameter:
            parameter["id"] = str(uuid.uuid4())
        content.append('# @parameter ' + json.dumps(parameter))

    content.append('')
    content.append('bundle agent ' + technique['bundle_name'] + bundle_param)
    content.append('{')

    content.append('  methods:')

    # Handle method calls
    for method_call in technique["method_calls"]:
        method_name = method_call["method_name"]
        method_info = methods[method_name]
        # regex to match quote characters not preceded by a backslash
        regex = re.compile(r'(?<!\\)"', flags=re.UNICODE)
        # Treat each argument of the method_call
        if 'args' in method_call:
            for index, arg in enumerate(method_call['args']):
                arg_constraint = ncf_constraints.default_constraint
                if method_name in methods:
                    parameter = method_info["parameter"][index]
                    arg_constraint = parameter.get("constraints", {})
                if arg is None:
                    raise NcfError("Parameter '" + parameter["name"] +
                                   "' of method '" + method_name +
                                   "' in technique '" +
                                   technique['bundle_name'] +
                                   " is not defined, please enter a value")
                check = ncf_constraints.check_parameter(arg, arg_constraint)
                if not check['result']:
                    error_constraint = "'" + "', '".join(check['errors']) + "'"
                    raise NcfError("Invalid value for parameter '" +
                                   parameter["name"] + "' of method '" +
                                   method_name + "' in technique '" +
                                   technique['bundle_name'] +
                                   "', invalid value is '" + arg +
                                   "', doesn't match constraints: " +
                                   error_constraint)
            args = [
                '"%s"' % regex.sub(r'\\"', arg) for arg in method_call['args']
            ]
            arg_value = ', '.join(args)
        else:
            arg_value = ""
        class_context = canonify_class_context(method_call['class_context'])

        if 'promiser' in method_call:
            promiser = method_call['promiser']
        else:
            promiser = "method_call"

        # Set bundle context, first escape paramters
        class_parameter_id = method_info["class_parameter_id"] - 1
        class_parameter_name = regex.sub(r'\\"', method_info["name"])
        class_parameter_value = regex.sub(
            r'\\"', method_call["args"][class_parameter_id])
        technique_name = regex.sub(r'\\"', technique["name"])
        content.append(
            '    "' + promiser +
            '_context" usebundle => _current_technique_report_info("' +
            technique_name + '", "' + class_parameter_name + '", "' +
            class_parameter_value + '");')

        # Append method call
        content.append('    "' + promiser + '" usebundle => ' + method_name +
                       '(' + arg_value + '),')
        content.append('      ifvarclass => concat("' + class_context + '");')

    content.append('}')

    # Join all lines with \n to get a pretty CFEngine file
    result = '\n'.join(content) + "\n"

    return result
예제 #5
0
파일: ncf.py 프로젝트: armeniaca/ncf
def generate_technique_content(technique, methods):
    """Generate technique CFEngine file as string from its metadata"""

    content = []
    for metadata_key in ['name', 'description', 'version']:
        # Add commentary for each new line in the metadata
        metadata_value = technique[metadata_key].replace("\n", "\n# ")
        content.append('# @' + metadata_key + " " + metadata_value)
    content.append('')
    content.append('bundle agent ' + technique['bundle_name'])
    content.append('{')
    content.append('  vars:')
    content.append(
        '    "class_prefix" string => canonify(join("_", "this.callers_promisers"));'
    )
    content.append('')
    content.append('  methods:')

    # Handle method calls
    for method_call in technique["method_calls"]:
        method_name = method_call["method_name"]
        regex = re.compile(r'(?<!\\)"', flags=re.UNICODE)
        # Treat each argument of the method_call
        if 'args' in method_call:
            for index, arg in enumerate(method_call['args']):
                arg_constraint = ncf_constraints.default_constraint
                if method_name in methods:
                    parameter = methods[method_name]["parameter"][index]
                    arg_constraint = parameter.get("constraints", {})
                if arg is None:
                    raise NcfError("Parameter '" + parameter["name"] +
                                   "' of method '" + method_name +
                                   "' in technique '" +
                                   technique['bundle_name'] +
                                   " is not defined, please enter a value")
                check = ncf_constraints.check_parameter(arg, arg_constraint)
                if not check['result']:
                    error_constraint = "'" + "', '".join(check['errors']) + "'"
                    raise NcfError("Invalid value for parameter '" +
                                   parameter["name"] + "' of method '" +
                                   method_name + "' in technique '" +
                                   technique['bundle_name'] +
                                   "', invalid value is '" + arg +
                                   "', doesn't match constraints: " +
                                   error_constraint)
            args = [
                '"%s"' % regex.sub(r'\\"', arg) for arg in method_call['args']
            ]
            arg_value = ', '.join(args)
        else:
            arg_value = ""
        class_context = canonify_class_context(method_call['class_context'])

        if 'promiser' in method_call:
            promiser = method_call['promiser']
        else:
            promiser = "method_call"
        content.append('    "' + promiser + '" usebundle => ' +
                       method_call['method_name'] + '(' + arg_value + '),')
        content.append('      ifvarclass => concat("' + class_context + '");')

    content.append('}')

    # Join all lines with \n to get a pretty CFEngine file
    result = '\n'.join(content) + "\n"

    return result
예제 #6
0
파일: ncf.py 프로젝트: Normation/ncf
def generate_technique_content(technique, methods):
  """Generate technique CFEngine file as string from its metadata"""

  content = []
  for metadata_key in [ 'name', 'description', 'version' ]:
    # Add commentary for each new line in the metadata
    metadata_value = technique[metadata_key].replace("\n", "\n# ")
    content.append('# @'+ metadata_key +" "+ metadata_value)

  bundle_param = ""
  if len(technique["parameter"]) > 0:
    bundle_param = "("+", ".join([canonify(param["name"]) for param in technique["parameter"] ])+")"
  for parameter in technique["parameter"]:
    if not "id" in parameter:
      parameter["id"] = str(uuid.uuid4())
    content.append('# @parameter '+ json.dumps(parameter))

  content.append('')
  content.append('bundle agent '+ technique['bundle_name']+bundle_param)
  content.append('{')

  
  content.append('  methods:')

  # Handle method calls
  report_unique_id = 0
  for method_call in technique["method_calls"]:
    method_name = method_call["method_name"]
    method_info = methods[method_name]
    # regex to match quote characters not preceded by a backslash
    regex = re.compile(r'(?<!\\)"', flags=re.UNICODE )
    # Treat each argument of the method_call
    if 'args' in method_call:
      for index, arg in enumerate(method_call['args']):
        arg_constraint = ncf_constraints.default_constraint
        if method_name in methods:
          parameter = method_info["parameter"][index]
          arg_constraint = parameter.get("constraints", {})
        if arg is None:
          raise NcfError("Parameter '"+ parameter["name"] +"' of method '"+ method_name +"' in technique '"+ technique['bundle_name'] + " is not defined, please enter a value")
        check = ncf_constraints.check_parameter(arg, arg_constraint)
        if not check['result']:
          error_constraint = "'"+"', '".join(check['errors'])+"'"
          raise NcfError("Invalid value for parameter '"+ parameter["name"] +"' of method '"+ method_name +"' in technique '"+ technique['bundle_name'] +"', invalid value is '"+ arg+"', doesn't match constraints: " + error_constraint)
      args = ['"%s"'%regex.sub(r'\\"', arg) for arg in method_call['args'] ]
      arg_value = ', '.join(args)
    else:
      arg_value = ""
    class_context = canonify_class_context(method_call['class_context'])

    if 'component' in method_call:
      promiser = regex.sub(r'\\"', method_call["component"])
    else:
      promiser = regex.sub(r'\\"', method_name)

    # Set bundle context, first escape paramters
    content.append('    "'+promiser+'_context_' + str(report_unique_id) + '" usebundle => '+ generate_reporting_context(method_info, method_call) + ";")
    report_unique_id += 1

    # Append method call
    content.append('    "'+promiser+'" usebundle => '+method_name+'('+arg_value+'),')
    content.append('      ifvarclass => concat("'+class_context+'");')

  content.append('}')

  # Join all lines with \n to get a pretty CFEngine file
  result =  '\n'.join(content)+"\n"

  return result