コード例 #1
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
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.", )
コード例 #2
0
ファイル: host_config.py プロジェクト: m3rlinux/checkmk
class FailedHosts(BaseSchema):
    succeeded_hosts = fields.Nested(
        response_schemas.HostConfigCollection(),
        description="The list of succeeded host objects",
    )
    failed_hosts = fields.Dict(
        keys=fields.String(description="Name of the host"),
        values=fields.List(fields.String(description="The error messages")),
        description="Detailed error messages on hosts failing the action",
    )
コード例 #3
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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.Boolean(description="Whether this is a demo version or not.", example=False)
コード例 #4
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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.",
    )
コード例 #5
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.", )
コード例 #6
0
ファイル: bi.py プロジェクト: LinuxHaus/checkmk
class BIAggregationStateResponseSchema(Schema):
    aggregations = fields.Dict(
        description="The Aggregation state",
        example={},
    )
    missing_sites = fields.List(
        fields.String(),
        description="The missing sites",
        example=["beta", "heute"],
    )
    missing_aggr = fields.List(
        fields.String(), description="the missing aggregations", example=["Host heute"]
    )
コード例 #7
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
class Version(LinkSchema):
    specVersion = fields.String(
        description=
        ('The "major.minor" parts of the version of the spec supported by this '
         'implementation, e.g. "1.0"'),
        required=False,
    )
    implVersion = fields.String(
        description=
        ("(optional) Version of the implementation itself (format is specific to "
         "the implementation)"),
        required=False,
    )
    additionalCapabilities = fields.Nested(VersionCapabilities)
コード例 #8
0
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).",
    )
コード例 #9
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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",
    )
コード例 #10
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
class DomainObject(Linkable):
    domainType: gui_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: gui_fields.Field = fields.Dict(
        description=
        "The container for external resources, like linked foreign objects or actions.",
    )
    extensions: gui_fields.Field = fields.Dict(
        description="All the attributes of the domain object.")
コード例 #11
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
class DomainObjectCollection(Linkable):
    id = fields.String(
        description="The name of this collection.",
        load_default="all",
    )
    domainType: gui_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: gui_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.")
コード例 #12
0
 def openapi_field(self) -> gui_fields.Field:
     return fields.List(
         fields.String(validate=fields.ValidateAnyOfValidators([
             fields.ValidateIPv4(),
             gui_fields.ValidateHostName(),
         ])),
         description="A list of IPv4 addresses.",
     )
コード例 #13
0
 def openapi_field(self) -> gui_fields.Field:
     return fields.String(
         description="An IPv4 address.",
         validate=fields.ValidateAnyOfValidators([
             fields.ValidateIPv4(),
             gui_fields.ValidateHostName(),
         ]),
     )
コード例 #14
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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,
    )
コード例 #15
0
 def openapi_field(self) -> gui_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(),
         ]),
     )
コード例 #16
0
 def openapi_field(self) -> gui_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"
          ),
     )
コード例 #17
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
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,
    )
コード例 #18
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
class ActionResultBase(Linkable):
    resultType: gui_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.",
    )
コード例 #19
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}
コード例 #20
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
class HostConfigSchemaInternal(BaseSchema):
    site = fields.String(
        required=True,
        description="The site the host is monitored on.",
    )
    is_cluster = fields.Boolean(
        required=True,
        description="Indicates if the host is a cluster host.",
    )
コード例 #21
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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",
    )
コード例 #22
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 = gui_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 = gui_fields.PythonString(
        description="The raw parameter value for this rule.",
        example='{"ignore_fs_types": ["tmpfs"]}',
    )
    conditions = fields.Nested(
        RuleConditions,
        description="Conditions.",
    )
コード例 #23
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
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'}]",
    )
コード例 #24
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
class FolderExtensions(BaseSchema):
    path = fields.String(
        description="The full path of this folder, slash delimited.", )
    attributes = gui_fields.attributes_field(
        "folder",
        "view",
        description=(
            "The folder's attributes. Hosts placed in this folder will inherit "
            "these attributes."),
    )
コード例 #25
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,
        allow_none=True,
    )
    target_phase = fields.String(
        description="The target phase of the service.",
        enum=sorted(SERVICE_DISCOVERY_PHASES.keys()),
        example="monitored",
        required=True,
    )
コード例 #26
0
ファイル: fields.py プロジェクト: tribe29/checkmk
class RulesetExtensions(base.BaseSchema):
    name = fields.String(
        description="The name of the ruleset",
        example="host_groups",
    )
    folder = gui_fields.FolderField(required=True, example="~router")
    number_of_rules = fields.Integer(
        description="The number of rules of this ruleset.",
        example=5,
    )
コード例 #27
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
class ConcreteUserContactOption(BaseSchema):
    email = fields.String(
        required=True,
        description="The mail address of the user.",
        example="*****@*****.**",
    )
    fallback_contact = fields.Boolean(
        description="In case none of the notification rules handle a certain event a notification "
        "will be sent to the specified email",
        required=False,
    )
コード例 #28
0
ファイル: response_schemas.py プロジェクト: m3rlinux/checkmk
class ConcreteUserInterfaceAttributes(BaseSchema):
    interface_theme = fields.String(
        required=False,
        description="The theme of the interface",
        enum=["default", "dark", "light"],
        example="default",
    )
    sidebar_position = fields.String(
        required=False,
        description="The position of the sidebar",
        enum=["left", "right"],
        example="right",
    )
    navigation_bar_icons = fields.String(
        required=False,
        description=
        "This option decides if icons in the navigation bar should show/hide the "
        "respective titles",
        enum=["hide", "show"],
        example="hide",
    )
    mega_menu_icons = fields.String(
        required=False,
        description=
        "This option decides if colored icon should be shown foe every entry in the "
        "mega menus or alternatively only for the headlines (the 'topics')",
        enum=["topic", "entry"],
        example="topic",
    )
    show_mode = fields.String(
        required=False,
        description=
        "This option decides what show mode should be used for unvisited menus."
        " Alternatively, this option can also be used to enforce show more removing the three dots "
        "for all menus.",
        enum=[
            "default", "default_show_less", "default_show_more",
            "enforce_show_more"
        ],
        example="default",
    )
コード例 #29
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,
        load_default=False,
    )
コード例 #30
0
ファイル: response_schemas.py プロジェクト: LinuxHaus/checkmk
class ApiError(BaseSchema):
    """This is the base class for all API errors."""

    code = fields.Integer(
        description="The HTTP status code.",
        required=True,
        example=404,
    )
    message = fields.String(
        description="Detailed information on what exactly went wrong.",
        required=True,
        example="The resource could not be found.",
    )
    title = fields.String(
        description="A summary of the problem.",
        required=True,
        example="Not found",
    )
    _fields = fields.Dict(
        data_key="fields",  # mypy, due to attribute "fields" being used in marshmallow.Schema
        keys=fields.String(description="The field name"),
        values=fields.List(fields.String(description="The error messages")),
        description="Detailed error messages on all fields failing validation.",
        required=False,
    )
    ext: fields.Field = fields.Dict(
        keys=fields.String(description="The key name"),
        values=fields.String(description="The value"),
        description="Additional information about the error.",
        required=False,
    )