r"""
Copyright &copy; 2026 NetApp Inc.
All rights reserved.

This file has been automatically generated based on the ONTAP REST API documentation.

## Overview
The Counter Manager subsystem allows both manual and automated processes to access statistical information about various aspects of the ONTAP system. The information is most often utilized to assess the current performance of the system.
####
The data architecture is broken down into four components:

* Tables
* Rows
* Counters / Properties
* Aggregation
### Tables
A table represents a collection of statistics that are grouped according to a common feature or function. An example counter manager table is for network adapters. This table would contain statistics related to the network adapter's performance such as the number of packets, rate of flow and error counters.
####
A table is described by its schema which includes a detailed description about the various statistics included, their format and their purpose.
####
The table catalog is a collection of all the statistical tables that the ONTAP REST interface supports, which can be queried to find information about a data point of interest.
### Rows
Each table is populated with a list of rows. Each row is identified by a unique key and represents a specific statistical entity within the system. For example, a system may contain multiple network adapters that are represented by several records in the network adapter table.
### Counter / Property
A counter is the basic 'numeric' statistical unit of the architecture.
####
A property is the basic 'string' statistical unit of the architecture.
####
Counter values can be organized as singular values or into multi-dimensional arrays. An array can be one or two dimensional; formatted as a list of label / value pairs. Additional detail can be found in the "counter" model definition.
####
A table schema definition consists of multiple counters and properties.
####
Counters are classified according to their type. The available type options are the following:

* average
* rate
* raw
* delta
* percent
####
Average and percent counters specify a secondary counter called the 'denominator' in the schema. The client must use the provided and secondary counters to compute the final intended value.
####
For example:
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterRow

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    resource = CounterRow("qos_detail", id="<instance-id>")
    resource.get(fields="counters", **{"counters.name": "visits|wait_time"})
    print(resource)

```

####
**Note:** In the above example, the average is calculated since boot-time. Sample periods are discussed in more detail below.
#### Counter Computations
The statistics available through the counter tables gives you information about a specific point in time. This data can be useful, but more often you are interested in the statistics over a period of time.
####
The procedure for calculating a statistic over a period of time involves the following:

* Collect a data sample at the beginning of the period. If the counter requires a denominator, this should be collected at the same time.
* Collect a second data sample at the end of the period. If the counter requires a denominator, collect a second sample at the same time.
* Calculate the final result using the collected information and the formula associated with the counter type below
####
**Note:** All counters that are not of type 'raw' will require some computation to be useful.
```
-------------------
T1, T2 : The start and ending time of the sample period
C1, C2 : The counter value at the start and ending time of the period
D1, D2 : The denominator value at the start and ending time of the period
-------------------
Percentage = ((C2 - C1) x 100) / (D2 - D1)
Rate = (C2 - C1) / (T2 - T1)
Average = (C2 - C1) / (D2 - D1)
Delta = C2 - C1
-------------------
```
### Aggregation
An aggregation is a logical container that consolidates the information from multiple entities into a single entity. There are two methods of aggregating tables:

* Automatic
* Combination.
#### Automatic
Tables with automatic aggregation are generated by consolidating all entities with matching identifiers. The underlying tables that contribute to the aggregated table are referenced by the following syntax: {table_name}:constituent.
#### Combination
Tables with combination aggregation are generated by consolidating all entities according to a unique field in the definition. The name of the combination table uses the following syntax: {table name}:{aggregation_name}.
####
An example combination table is 'volume:svm' table. This table aggregates all the volume statistics associated with a given vserver into a single table.
####
### Multi-Dimensional Arrays
Numeric counters can be scalar, one-dimensional or two dimensional values. Scalars are the most common values which consist of a single numeric value. A one-dimensional array is commonly used to present histograms such as the following table:
```
< 1s     :  3
< 5s     : 10
< 60s    :  1
```
####
A counter endpoint response that contains the above table would be formatted as follows:
####
```
{
  "name": "Sample One-Dimensional Counter",
  "labels": [ "< 1s", "< 5s", "< 60s" ],
  "values": [3, 10, 1]
}
```
####
A two-dimensional array is used to report information about more complex relationships. An example data set is below:
####
```
              New      Used
-----------------------------
Car             1         2
Truck           3         4
Motorcycle      5         6
```
####
A counter endpoint response that contains the above table would be formatted as follows:
####
```
{
  "name": "Sample Two-Dimensional Counter",
  "labels": [ "New", "Used" ],
  "counters": [
    {
      "label": "Car",
      "values": [1, 2]
    },
    {
      "label": "Truck",
      "values": [3, 4]
    },
    {
      "label": "Motorcycle",
      "values": [5, 6]
    }
  ]
}
```
####
## Filtering / Querying
The counter endpoints adhere to the same behavior as other endpoints, with exception of how queries are handled for nested array fields.
####
The default behavior when processing a nested array query is to return the entire array content on a match. The counter endpoints' behavior will only return entries in the array that match the query.
####
Counter responses can contain a significant amount of data. This behavior improves the response by only returning the information requested and eliminating extra work for the client.
####
For example:
```
Given the following array:
  "list": [ "fruit_apple", "color_red" ]
When you apply the following query:
  list=fruit*
The default query behavior will return the array as:
  "list": [ "fruit_apple", "color_red" ]
The counter endpoints will return the array as:
  "list": [ "fruit_apple" ]
```
####
---
## Examples
### Retrieving a table schema definition
This example retrieves the table description and schema definition for the qos_detail table.
####
---
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterTable

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    resource = CounterTable(name="qos_detail")
    resource.get(fields="*")
    print(resource)

```
<div class="try_it_out">
<input id="example1_try_it_out" type="checkbox", class="try_it_out_check">
<label for="example1_try_it_out" class="try_it_out_button">Try it out</label>
<div id="example1_result" class="try_it_out_content">
```
CounterTable(
    {
        "counter_schemas": [
            {
                "name": "in_latency_path",
                "type": "raw",
                "description": "Determines whether or not service center-based statistics are in the latency path.",
                "unit": "none",
            },
            {
                "name": "node.name",
                "type": "string",
                "description": "System node name",
                "unit": "none",
            },
            {
                "name": "resource.name",
                "type": "string",
                "description": "Name of the associated resource.",
                "unit": "none",
            },
            {
                "name": "service_time",
                "denominator": {"name": "visits"},
                "type": "average",
                "description": "The workload's average service time per visit to the service center.",
                "unit": "microsec",
            },
            {
                "name": "visits",
                "type": "rate",
                "description": "The number of visits that the workload made to the service center; measured in visits per second.",
                "unit": "per_sec",
            },
            {
                "name": "wait_time",
                "denominator": {"name": "visits"},
                "type": "average",
                "description": "The workload's average wait time per visit to the service center.",
                "unit": "microsec",
            },
        ],
        "_links": {"self": {"href": "/api/cluster/counter/tables/qos_detail"}},
        "name": "qos_detail",
        "description": "The qos_detail table that provides service center-based statistical information. Note: This table returns a large number of rows. Querying by row name and using wild cards may improve response times.",
    }
)

```
</div>
</div>

####
---
### Query for tables that contain a keyword in the description
This example retrieves all table definitions contain the word "security" in their description.
####
---
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterTable

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    print(
        list(
            CounterTable.get_collection(
                fields="name,description", description="*security*"
            )
        )
    )

```
<div class="try_it_out">
<input id="example2_try_it_out" type="checkbox", class="try_it_out_check">
<label for="example2_try_it_out" class="try_it_out_button">Try it out</label>
<div id="example2_result" class="try_it_out_content">
```
[
    CounterTable(
        {
            "_links": {"self": {"href": "/api/cluster/counter/tables/csm_global"}},
            "name": "csm_global",
            "description": "This table reports global statistics of the Cluster Session Manager. The counters report the processing overhead of SpinNP cryptography, both encryption and decryption, as carried out by CSM as it handles cross-cluster data traffic, mostly on behalf of their data protection operations. For example, a customer might seek to know the processor time being consumed by these cryptographic operations in support of their cross-cluster traffic. That data might help them evaluate the performance impact of these security operations.",
        }
    ),
    CounterTable(
        {
            "_links": {"self": {"href": "/api/cluster/counter/tables/file_directory"}},
            "name": "file_directory",
            "description": "This table reports how many times file-directory jobs were triggered to the set the file-security ACLS or SLAG ACLS. This counter gives an indication how frequently the feature is being used to set the ACLS on file-directory/volume.",
        }
    ),
]

```
</div>
</div>

####
---
### Query for a specific property within all table rows.
This example requests the property named 'node.name' for all 'wafl' table rows.
####
**Note:** The properties array content excludes any entries that do not match the provided query.
####
---
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterRow

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    print(
        list(
            CounterRow.get_collection(
                "wafl", fields="properties", **{"properties.name": "node.name"}
            )
        )
    )

```
<div class="try_it_out">
<input id="example3_try_it_out" type="checkbox", class="try_it_out_check">
<label for="example3_try_it_out" class="try_it_out_button">Try it out</label>
<div id="example3_result" class="try_it_out_content">
```
[
    CounterRow(
        {
            "_links": {
                "self": {"href": "/api/cluster/counter/tables/wafl/rows/<instance id>"}
            },
            "id": "<instance id>",
            "properties": [{"value": "<node name>", "name": "node.name"}],
        }
    )
]

```
</div>
</div>

---
### Query for a list of properties that match a wildcard on a specific row.
This example queries for all properties associated with a row of the volume table.
####
**Note:** The properties array content excludes any entries that do not match the provided query.
####
---
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterRow

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    resource = CounterRow("volume", id="<instance-id>")
    resource.get(fields="properties", **{"properties.name": "svm*"})
    print(resource)

```
<div class="try_it_out">
<input id="example4_try_it_out" type="checkbox", class="try_it_out_check">
<label for="example4_try_it_out" class="try_it_out_button">Try it out</label>
<div id="example4_result" class="try_it_out_content">
```
CounterRow(
    {
        "_links": {
            "self": {"href": "/api/cluster/counter/tables/volume/rows/<instance-id>/"}
        },
        "id": "<instance-id>",
        "counter_table": {"name": "volume"},
        "properties": [
            {"value": "<svm-name>", "name": "svm.name"},
            {"value": "4774d11c-a606-11ec-856f-005056bb7b59", "name": "svm.uuid"},
        ],
    }
)

```
</div>
</div>

---
### Query for a list of counters in a specific table row
This example queries for an explicit list of counters within a single row of the wafl table.
####
**Note:** The counters array content excludes any entries that do not match the provided query.
####
---
```python
from netapp_ontap import HostConnection
from netapp_ontap.resources import CounterRow

with HostConnection("<mgmt-ip>", username="admin", password="password", verify=False):
    resource = CounterRow("wafl", id="<instance-id>")
    resource.get(fields="counters", **{"counters.name": "memory_used|memory_free"})
    print(resource)

```
<div class="try_it_out">
<input id="example5_try_it_out" type="checkbox", class="try_it_out_check">
<label for="example5_try_it_out" class="try_it_out_button">Try it out</label>
<div id="example5_result" class="try_it_out_content">
```
CounterRow(
    {
        "counters": [
            {"value": 541, "name": "memory_used"},
            {"value": 786, "name": "memory_free"},
        ],
        "_links": {
            "self": {"href": "/api/cluster/counter/tables/wafl/rows/<instance-id>"}
        },
        "id": "<instance-id>",
        "counter_table": {"name": "wafl"},
    }
)

```
</div>
</div>
"""

import asyncio
from datetime import datetime
import inspect
from typing import Callable, Iterable, List, Optional, Union
from marshmallow import fields as marshmallow_fields, EXCLUDE  # type: ignore

import netapp_ontap
from netapp_ontap.resource import Resource, ResourceSchema, ResourceSchemaMeta, ImpreciseDateTime, Size, lazy_import_schema
from netapp_ontap.raw_resource import RawResource

from netapp_ontap import NetAppResponse, HostConnection
from netapp_ontap.validations import enum_validation, len_validation, integer_validation
from netapp_ontap.error import NetAppRestError


__all__ = ["CounterTable", "CounterTableSchema"]
__pdoc__ = {
    "CounterTableSchema.resource": False,
    "CounterTableSchema.opts": False,
}

class CounterTableSchema(ResourceSchema, metaclass=ResourceSchemaMeta):
    """The fields of the CounterTable object"""

    links = marshmallow_fields.Nested(
                lambda: lazy_import_schema("netapp_ontap.models.self_link", "SelfLinkSchema"),
                data_key="_links",
                unknown=EXCLUDE,
                allow_none=True
            )
    r""" The links field of the counter_table."""

    counter_schemas = marshmallow_fields.List(
                marshmallow_fields.Nested(
                    lambda: lazy_import_schema("netapp_ontap.models.counter_schema", "CounterSchemaSchema"),
                    unknown=EXCLUDE,
                    allow_none=True
                ),
                data_key="counter_schemas",
                allow_none=True
            )
    r""" Array of counter schema definitions."""

    description = marshmallow_fields.Str(
        data_key="description",
        allow_none=True,
    )
    r""" Description of the table."""

    name = marshmallow_fields.Str(
        data_key="name",
        allow_none=True,
    )
    r""" Table name."""

    @property
    def resource(self):
        return CounterTable

    gettable_fields = [
        "links",
        "counter_schemas",
        "description",
        "name",
    ]
    """links,counter_schemas,description,name,"""

    patchable_fields = [
    ]
    """"""

    postable_fields = [
    ]
    """"""

class CounterTable(Resource):
    r""" Information for a single counter table. """

    _schema = CounterTableSchema
    _path = "/api/cluster/counter/tables"
    _keys = ["name"]

    @classmethod
    def get_collection(
        cls,
        *args,
        connection: HostConnection = None,
        max_records: int = None,
        **kwargs
    ) -> Iterable["Resource"]:
        r"""Returns a collection of counter tables and their schema definitions.

### Learn more
* [`DOC /cluster/counter/tables`](#docs-cluster-cluster_counter_tables)"""
        return super()._get_collection(*args, connection=connection, max_records=max_records, **kwargs)

    get_collection.__func__.__doc__ += "\n\n---\n" + inspect.cleandoc(Resource._get_collection.__doc__)

    @classmethod
    def count_collection(
        cls,
        *args,
        connection: HostConnection = None,
        **kwargs
    ) -> int:
        """Returns a count of all CounterTable resources that match the provided query"""
        return super()._count_collection(*args, connection=connection, **kwargs)

    count_collection.__func__.__doc__ += "\n\n---\n" + inspect.cleandoc(Resource._count_collection.__doc__)


    @classmethod
    def fast_get_collection(
        cls,
        *args,
        connection: HostConnection = None,
        max_records: int = None,
        **kwargs
    ) -> Iterable["RawResource"]:
        """Returns a list of RawResources that represent CounterTable resources that match the provided query"""
        return super()._get_collection(
            *args, connection=connection, max_records=max_records, raw=True, **kwargs
        )

    fast_get_collection.__func__.__doc__ += "\n\n---\n" + inspect.cleandoc(Resource._get_collection.__doc__)




    @classmethod
    def find(cls, *args, connection: HostConnection = None, **kwargs) -> Resource:
        r"""Returns a collection of counter tables and their schema definitions.

### Learn more
* [`DOC /cluster/counter/tables`](#docs-cluster-cluster_counter_tables)"""
        return super()._find(*args, connection=connection, **kwargs)

    find.__func__.__doc__ += "\n\n---\n" + inspect.cleandoc(Resource._find.__doc__)

    def get(self, **kwargs) -> NetAppResponse:
        r"""Returns the information about a single counter table.

### Learn more
* [`DOC /cluster/counter/tables`](#docs-cluster-cluster_counter_tables)"""
        return super()._get(**kwargs)

    get.__doc__ += "\n\n---\n" + inspect.cleandoc(Resource._get.__doc__)





