Exemple #1
0
class ObjectActionMember(ObjectMemberBase):
    memberType = fields.Constant("action")
    parameters = fields.Dict()
    name = fields.String(example="frobnicate_foo")
    title = fields.String(
        description="A human readable title of this object. Can be used for "
        "user interfaces.", )
Exemple #2
0
class ObjectMemberBase(Linkable):
    id = fields.String(required=True)
    disabledReason = fields.String(
        description=
        ('Provides the reason (or the literal "disabled") why an object property or '
         "collection is un-modifiable, or, in the case of an action, unusable (and "
         "hence no links to mutate that member's state, or invoke the action, are "
         "provided)."),
        allow_none=True,
    )
    invalidReason = fields.String(
        description=
        ('Provides the reason (or the literal "invalid") why a proposed value for a '
         "property, collection or action argument is invalid. Appears within an "
         "argument representation 2.9 returned as a response."),
        example="invalid",
        allow_none=True,
    )
    x_ro_invalidReason = fields.String(
        dump_to="x-ro-invalidReason",
        description=
        ("Provides the reason why a SET OF proposed values for properties or arguments "
         "is invalid."),
        allow_none=True,
    )
Exemple #3
0
class ObjectPropertyMember(ObjectMemberBase):
    memberType = fields.Constant("property")
    name = fields.String(example="important")
    value = fields.String(example="the value")
    title = fields.String(
        description="A human readable title of this object. Can be used for "
        "user interfaces.", )
Exemple #4
0
class ConcreteTimePeriod(BaseSchema):
    alias = fields.String(description="The alias of the time period",
                          example="alias")
    active_time_ranges = fields.List(
        fields.Nested(ConcreteTimeRangeActive),
        description="The days for which time ranges were specified",
        example={
            "day": "all",
            "time_ranges": [{
                "start": "12:00",
                "end": "14:00"
            }]
        },
    )
    exceptions = fields.List(
        fields.Nested(ConcreteTimePeriodException),
        description="Specific day exclusions with their list of time ranges",
        example=[{
            "date": "2020-01-01",
            "time_ranges": [{
                "start": "14:00",
                "end": "18:00"
            }]
        }],
    )
    exclude = fields.List(  # type: ignore[assignment]
        fields.String(description="Name of excluding time period",
                      example="holidays"),
        description=
        "The collection of time period aliases whose periods are excluded",
    )
Exemple #5
0
class TagConditionConditionSchemaBase(TagConditionSchemaBase):
    """Convert Rulesets to Checkmk structure and back

    Examples:

        >>> tcs = TagConditionConditionSchemaBase()
        >>> tcs.dump([{'hurz': {'$or': ['a', 'b', 'c']}}], many=True)
        [{'key': 'hurz', 'operator': 'one_of', 'value': ['a', 'b', 'c']}]

        >>> tcs.dump({'hurz': {'$or': ['a', 'b', 'c']}})
        {'key': 'hurz', 'operator': 'one_of', 'value': ['a', 'b', 'c']}

        >>> tcs.dump({'hurz': {'$or': 'h'}})
        Traceback (most recent call last):
        ...
        marshmallow.exceptions.ValidationError: Invalid type: 'h'

    """

    cast_to_dict = True

    allowed_operators = ("one_of", "none_of")
    operator_type = "collection"

    # field defined in superclass
    operator = fields.String(
        description="If the matched tag should be one of the given values, or not.",
        enum=list(allowed_operators),  # Our serializer only wants to know lists.
    )
    value = fields.List(
        fields.String(description="The value of a tag."),
        description="A list of values for the tag.",
    )
Exemple #6
0
class ObjectCollectionMember(ObjectMemberBase):
    memberType = fields.Constant("collection")
    value = fields.List(fields.Nested(LinkSchema()))
    name = fields.String(example="important_values")
    title = fields.String(
        description="A human readable title of this object. Can be used for "
        "user interfaces.", )
class MovieSchema(Schema):
    title = fields.String(required=True)
    director = fields.String(required=True)
    year = fields.Integer(required=True)

    @post_load
    def make_movie(self, data, **kwargs):
        return Movie(**data)
class ObjectProperty(Linkable):
    id = fields.String(description="The unique name of this property, local to this domain type.")
    value = fields.List(
        fields.String(),
        description="The value of the property. In this case a list.",
    )
    extensions = fields.Dict(
        description="Additional attributes alongside the property.",
    )
class User(Linkable):
    userName = fields.String(description="A unique user name.")
    friendlyName = fields.String(
        required=True,
        description="The user's name in a form suitable to be rendered in a UI.",
    )
    email = fields.String(description="(optional) the user's email address, if known.")
    roles = fields.List(
        fields.String(),
        description="List of unique role names that apply to this user (can be empty).",
    )
class InstalledVersions(BaseSchema):
    site = fields.String(
        description="The site where this API call was made on.", example="production"
    )
    group = fields.String(
        description="The Apache WSGI application group this call was made on.", example="de"
    )
    rest_api = fields.Dict(description="The REST-API version", example={"revision": "1.0.0"})
    versions = fields.Dict(description="Some version numbers", example={"checkmk": "1.8.0p1"})
    edition = fields.String(description="The Checkmk edition.", example="raw")
    demo = fields.Bool(description="Whether this is a demo version or not.", example=False)
class FolderSchema(Linkable):
    domainType = fields.Constant("folder_config", description="The domain type of the object.")
    id = fields.String(description="The full path of the folder, tilde-separated.")
    title = fields.String(description="The human readable title for this folder.")
    members = fields.Nested(
        FolderMembers(),
        description="Specific collections or actions applicable to this object.",
    )
    extensions = fields.Nested(
        FolderExtensions(),
        description="Data and Meta-Data of this object.",
    )
Exemple #12
0
class TagConditionScalarSchemaBase(TagConditionSchemaBase):
    """

    Examples:

        >>> t = TagConditionScalarSchemaBase()
        >>> t.dump({"criticality": "prod"})
        {'key': 'criticality', 'operator': 'is', 'value': 'prod'}

        >>> t.dump([{"criticality": "prod"}], many=True)
        [{'key': 'criticality', 'operator': 'is', 'value': 'prod'}]

        >>> t.dump([{"criticality": {"$ne": "prod"}}], many=True)
        [{'key': 'criticality', 'operator': 'is_not', 'value': 'prod'}]

        >>> t.dump({"criticality": {"$or": "prod"}})
        Traceback (most recent call last):
        ...
        marshmallow.exceptions.ValidationError: Operator 'one_of' not allowed in this context.

        >>> t.dump({"criticality": {"$nor": "prod"}})
        Traceback (most recent call last):
        ...
        marshmallow.exceptions.ValidationError: Operator 'none_of' not allowed in this context.

        >>> t.dump({"criticality": {"foo": "prod"}})
        Traceback (most recent call last):
        ...
        marshmallow.exceptions.ValidationError: Unknown operator: 'foo'

        Converting it back is also possible:

        >>> t.load({'key': 'criticality', 'operator': 'is_not', 'value': 'prod'})
        {'criticality': {'$ne': 'prod'}}

        >>> t.load([{'key': 'criticality', 'operator': 'is_not', 'value': 'prod'}], many=True)
        [{'criticality': {'$ne': 'prod'}}]

    """

    cast_to_dict = True
    allowed_operators = ("is", "is_not")
    operator_type = "scalar"

    # field defined in superclass
    operator = fields.String(
        description="If the tag's value should match what is given under the field `value`.",
        enum=list(allowed_operators),  # Our serializer only wants to know lists.
    )
    value = fields.String(
        description="The value of a tag.",
    )
class DomainObject(Linkable):
    domainType: fields.Field = fields.String(
        required=True,
        description='The "domain-type" of the object.',
    )
    # Generic things to ease development. Should be changed for more concrete schemas.
    id = fields.String(
        description="The unique identifier for this domain-object type.",
    )
    title = fields.String(
        description="A human readable title of this object. Can be used for " "user interfaces.",
    )
    members: fields.Field = fields.Dict(
        description="The container for external resources, like linked foreign objects or actions.",
    )
    extensions: fields.Field = fields.Dict(description="All the attributes of the domain object.")
class DomainObjectCollection(Linkable):
    id = fields.String(
        description="The name of this collection.",
        load_default="all",
    )
    domainType: fields.Field = fields.String(
        description="The domain type of the objects in the collection."
    )
    title = fields.String(
        description="A human readable title of this object. Can be used for " "user interfaces.",
    )
    value: fields.Field = fields.Nested(
        CollectionItem,
        description="The collection itself. Each entry in here is part of the collection.",
        many=True,
    )
    extensions = fields.Dict(description="Additional attributes alongside the collection.")
class LinkSchema(BaseSchema):
    """A Link representation according to A-24 (2.7)"""

    domainType = fields.Constant("link", required=True)
    rel = fields.String(
        description=(
            "Indicates the nature of the relationship of the related resource to the "
            "resource that generated this representation"
        ),
        required=True,
        example="self",
    )
    href = fields.String(
        description=(
            "The (absolute) address of the related resource. Any characters that are "
            "invalid in URLs must be URL encoded."
        ),
        required=True,
        example="https://.../api_resource",
    )
    method = fields.String(
        description="The HTTP method to use to traverse the link (get, post, put or delete)",
        required=True,
        pattern="GET|PUT|POST|DELETE",
        example="GET",
    )
    type = fields.String(
        description="The content-type that the linked resource will return",
        required=True,
        example="application/json",
    )
    title = fields.String(
        description=(
            "string that the consuming application may use to render the link without "
            "having to traverse the link in advance"
        ),
        allow_none=True,
        example="The object itself",
    )
    body_params = fields.Dict(
        description=(
            "A map of values that shall be sent in the request body. If this is present,"
            "the request has to be sent with a content-type of 'application/json'."
        ),
        required=False,
    )
 def openapi_field(self) -> fields.Field:
     return fields.List(
         fields.String(validate=validators.ValidateAnyOfValidators([
             fields.ValidateIPv4(),
             validators.ValidateHostName(),
         ])),
         description="A list of IPv4 addresses.",
     )
 def openapi_field(self) -> fields.Field:
     return fields.String(
         description="An IPv4 address.",
         validate=validators.ValidateAnyOfValidators([
             fields.ValidateIPv4(),
             validators.ValidateHostName(),
         ]),
     )
 def openapi_field(self) -> fields.Field:
     return fields.String(
         description=
         "Address (IPv4 or IPv6) under which the management board can be reached.",
         validate=fields.ValidateAnyOfValidators([
             fields.ValidateIPv4(),
             fields.ValidateIPv6(),
         ]),
     )
 def openapi_field(self) -> fields.Field:
     return fields.String(
         enum=["pull-agent", "push-agent"],
         description=
         ("This configures the communication direction of this host.\n"
          " * `pull-agent` (default) - The server will try to contact the monitored host and pull the data by initializing a TCP connection\n"
          " * `push-agent` - the host is expected to send the data to the monitoring server without being triggered\n"
          ),
     )
Exemple #20
0
class ActionResultBase(Linkable):
    resultType: fields.Field = fields.String(
        enum=['object', 'scalar'],
        description="The type of the result.",
    )
    extensions = fields.Dict(
        example={'some': 'values'},
        description="Some attributes alongside the result.",
    )
class UserSchema(BaseSchema):
    id = fields.Integer(dump_only=True)
    name = fields.String(description="The user's name")
    created = fields.DateTime(
        dump_only=True,
        format="iso8601",
        dump_default=dt.datetime.utcnow,
        doc_default="The current datetime",
    )
Exemple #22
0
class UpdateDiscoveryPhase(BaseSchema):
    check_type = fields.String(
        description='The name of the check which this service uses.',
        example='df',
        required=True,
    )
    service_item = fields.String(
        description=
        'The value uniquely identifying the service on a given host.',
        example='/home',
        required=True,
    )
    target_phase = fields.String(
        description='The target phase of the service.',
        enum=sorted(SERVICE_DISCOVERY_PHASES.keys()),
        example='monitored',
        required=True,
    )
Exemple #23
0
class TagConditionSchemaBase(base.BaseSchema):

    allowed_operators: typing.Tuple[str, str]
    operator_type: str

    key = fields.String(
        description="The name of the tag.",
    )

    @pre_dump(pass_many=False)
    def convert_to_api(
        self,
        data,
        many=False,
        **kwargs,
    ):
        rv = {}
        for key, value in data.items():
            operator = _unpack_operator(value)
            if operator not in self.allowed_operators:
                raise ValidationError(f"Operator {operator!r} not allowed in this context.")
            try:
                unpacked = _unpack_value(value)
            except ValueError as exc:
                raise ValidationError(str(exc), field_name=key) from exc

            if self.operator_type == "collection":
                if not isinstance(unpacked, list):
                    raise ValidationError(f"Invalid type: {unpacked!r}", field_name=key)

            rv.update(
                {
                    "key": key,
                    "operator": operator,
                    "value": unpacked,
                }
            )
            # Just to make the point clear.
            break

        return rv

    @post_load(pass_many=False)
    def convert_back(
        self,
        data,
        many=False,
        **kwargs,
    ):
        if self.operator_type == "collection":
            value = _collection_value(data["value"], data["operator"])
        elif self.operator_type == "scalar":
            value = _scalar_value(data["value"], data["operator"])
        else:
            raise RuntimeError(f"Unsupported type: {self.operator_type}")

        return {data["key"]: value}
Exemple #24
0
class MoveFolder(BaseSchema):
    destination = fields.String(
        description=
        ("The folder-id of the folder to which this folder shall be moved to. May "
         "be 'root' for the root-folder."),
        pattern="[a-fA-F0-9]{32}|root",
        example="root",
        required=True,
    )
Exemple #25
0
class ActionResultBase(Linkable):
    resultType: fields.Field = fields.String(
        enum=["object", "scalar"],
        description="The type of the result.",
    )
    extensions = fields.Dict(
        example={"some": "values"},
        description="Some attributes alongside the result.",
    )
Exemple #26
0
class RuleExtensions(base.BaseSchema):
    """Serializes the 'extensions' part of the Rule Domain Object.

    Examples:

        >>> ext = RuleExtensions()
        >>> from cmk.gui.utils.script_helpers import application_and_request_context
        >>> with application_and_request_context():
        ...     ext.load({
        ...        'folder': '/',
        ...     })
        {'folder': Folder('', 'Main')}

        >>> with application_and_request_context():
        ...     rv = ext.load({
        ...        'folder': '/',
        ...        'conditions': {
        ...            'service_description': {'match_on': ['foo'],
        ...                                               'operator': 'none_of',},
        ...            'host_tag': [{'key': 'criticality', 'operator': 'is', 'value': 'prod'}],
        ...        }
        ...     })
        ...     rv
        {'folder': Folder('', 'Main'), \
'conditions': {\
'host_tag': {'criticality': 'prod'},\
 'service_description': {'$nor': [{'$regex': 'foo'}]}\
}}

        >>> ext.dump(rv)
        {'folder': '/', 'conditions': {\
'host_tag': [{'key': 'criticality', 'operator': 'is', 'value': 'prod'}], \
'service_description': {'match_on': ['foo'], 'operator': 'none_of'}}}

    """

    cast_to_dict = True

    ruleset = fields.String(description="The name of the ruleset.")
    folder = fields.FolderField(required=True, example="~router")
    folder_index = fields.Integer(
        description="The position of this rule in the chain in this folder.",
    )
    properties = fields.Nested(
        RuleProperties,
        description="Property values of this rule.",
        example={},
    )
    value_raw = fields.PythonString(
        description="The raw parameter value for this rule.",
        example='{"ignore_fs_types": ["tmpfs"]}',
    )
    conditions = fields.Nested(
        RuleConditions,
        description="Conditions.",
    )
Exemple #27
0
class FolderExtensions(BaseSchema):
    path = fields.String(
        description="The full path of this folder, slash delimited.", )
    attributes = fields.attributes_field(
        "folder",
        "update",
        description=(
            "The folder's attributes. Hosts placed in this folder will inherit "
            "these attributes."),
    )
Exemple #28
0
class RulesetExtensions(base.BaseSchema):
    name = fields.String(
        description="The name of the ruleset",
        example="host_groups",
    )
    folder = fields.FolderField(required=True, example="~router")
    number_of_rules = fields.Integer(
        description="The number of rules of this ruleset.",
        example=5,
    )
class ConcreteTimePeriodException(BaseSchema):
    date = fields.String(
        example="2020-01-01",
        format="date",
        description="The date of the time period exception." "8601 profile",
    )
    time_ranges = fields.List(
        fields.Nested(ConcreteTimeRange),
        example="[{'start': '14:00', 'end': '18:00'}]",
    )
Exemple #30
0
class RuleProperties(base.BaseSchema):
    cast_to_dict = True

    description = fields.String(
        description="A description for this rule to inform other users about its intent.",
        example="This rule is here to foo the bar hosts.",
    )
    comment = fields.String(
        description="Any comment string.",
        example="Created yesterday due to foo hosts behaving weird.",
    )
    documentation_url = fields.URL(
        attribute="docu_url",
        description="An URL (e.g. an internal Wiki entry) which explains this rule.",
        example="http://example.com/wiki/ConfiguringFooBarHosts",
    )
    disabled = fields.Boolean(
        description="When set to False, the rule will be evaluated. Default is False.",
        example=False,
        missing=False,
    )