Skip to content

Commit

Permalink
ref: Migrate event_list module to ListModule base (#561)
Browse files Browse the repository at this point in the history
* Migrate event_list module to ListModule base

* Respect number of pages in get_all_paginated(...)
  • Loading branch information
lgarber-akamai authored Aug 20, 2024
1 parent 77d59ba commit 4eca745
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 122 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Name | Description |
[linode.cloud.database_engine_list](./docs/modules/database_engine_list.md)|List and filter on Managed Database engine types.|
[linode.cloud.database_list](./docs/modules/database_list.md)|List and filter on Linode Managed Databases.|
[linode.cloud.domain_list](./docs/modules/domain_list.md)|List and filter on Domains.|
[linode.cloud.event_list](./docs/modules/event_list.md)|List and filter on Linode events.|
[linode.cloud.event_list](./docs/modules/event_list.md)|List and filter on Events.|
[linode.cloud.firewall_list](./docs/modules/firewall_list.md)|List and filter on Firewalls.|
[linode.cloud.image_list](./docs/modules/image_list.md)|List and filter on Images.|
[linode.cloud.instance_list](./docs/modules/instance_list.md)|List and filter on Instances.|
Expand Down
14 changes: 7 additions & 7 deletions docs/modules/event_list.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# event_list

List and filter on Linode events.
List and filter on Events.

- [Minimum Required Fields](#minimum-required-fields)
- [Examples](#examples)
Expand Down Expand Up @@ -40,21 +40,21 @@ List and filter on Linode events.
| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list events in. **(Choices: `desc`, `asc`; Default: `asc`)** |
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order events by. |
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting events. |
| `count` | <center>`int`</center> | <center>Optional</center> | The number of results to return. If undefined, all results will be returned. |
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list Events in. **(Choices: `desc`, `asc`; Default: `asc`)** |
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order Events by. |
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting Events. |
| `count` | <center>`int`</center> | <center>Optional</center> | The number of Events to return. If undefined, all results will be returned. |

### filters

| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `name` | <center>`str`</center> | <center>**Required**</center> | The name of the field to filter on. Valid filterable attributes can be found here: https://techdocs.akamai.com/linode-api/reference/get-events |
| `name` | <center>`str`</center> | <center>**Required**</center> | The name of the field to filter on. Valid filterable fields can be found [here](https://techdocs.akamai.com/linode-api/reference/get-events). |
| `values` | <center>`list`</center> | <center>**Required**</center> | A list of values to allow for this field. Fields will pass this filter if at least one of these values matches. |

## Return Values

- `events` - The returned events.
- `events` - The returned Events.

- Sample Response:
```json
Expand Down
8 changes: 6 additions & 2 deletions plugins/module_utils/linode_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,13 +283,13 @@ def get_all_paginated(
result = []
current_page = 1
page_size = 100
num_pages = 1
num_pages: Optional[int] = None

if num_results is not None and num_results < page_size:
# Clamp the page size
page_size = max(min(num_results, 100), 25)

while current_page <= num_pages and (
while (num_pages is None or current_page <= num_pages) and (
num_results is None or len(result) < num_results
):
response = client.get(
Expand All @@ -300,6 +300,10 @@ def get_all_paginated(
if "data" not in response or "page" not in response:
raise Exception("Invalid list response")

# We only want to set num_pages once to avoid undefined behavior
# when the number of pages changes mid-aggregation
num_pages = num_pages or response["pages"]

result.extend(response["data"])

if num_results is not None and len(result) >= num_results:
Expand Down
124 changes: 12 additions & 112 deletions plugins/modules/event_list.py
Original file line number Diff line number Diff line change
@@ -1,132 +1,32 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""This module allows users to list Linode events."""
"""This file contains the implementation of the event_list module."""

from __future__ import absolute_import, division, print_function

from typing import Any, Dict, Optional

import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.event_list as docs
from ansible_collections.linode.cloud.plugins.module_utils.linode_common import (
LinodeModuleBase,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_docs import (
global_authors,
global_requirements,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_helper import (
construct_api_filter,
get_all_paginated,
from ansible_collections.linode.cloud.plugins.module_utils.linode_common_list import (
ListModule,
)
from ansible_specdoc.objects import (
FieldType,
SpecDocMeta,
SpecField,
SpecReturnValue,
)

spec_filter = {
"name": SpecField(
type=FieldType.string,
required=True,
description=[
"The name of the field to filter on.",
"Valid filterable attributes can be found here: "
"https://techdocs.akamai.com/linode-api/reference/get-events",
],
),
"values": SpecField(
type=FieldType.list,
element_type=FieldType.string,
required=True,
description=[
"A list of values to allow for this field.",
"Fields will pass this filter if at least one of these values matches.",
],
),
}

spec = {
# Disable the default values
"state": SpecField(type=FieldType.string, required=False, doc_hide=True),
"label": SpecField(type=FieldType.string, required=False, doc_hide=True),
"order": SpecField(
type=FieldType.string,
description=["The order to list events in."],
default="asc",
choices=["desc", "asc"],
),
"order_by": SpecField(
type=FieldType.string, description=["The attribute to order events by."]
),
"filters": SpecField(
type=FieldType.list,
element_type=FieldType.dict,
suboptions=spec_filter,
description=["A list of filters to apply to the resulting events."],
),
"count": SpecField(
type=FieldType.integer,
description=[
"The number of results to return.",
"If undefined, all results will be returned.",
],
),
}

SPECDOC_META = SpecDocMeta(
description=["List and filter on Linode events."],
requirements=global_requirements,
author=global_authors,
options=spec,
module = ListModule(
result_display_name="Events",
result_field_name="events",
endpoint_template="/account/events",
result_docs_url="https://techdocs.akamai.com/linode-api/reference/get-events",
examples=docs.specdoc_examples,
return_values={
"events": SpecReturnValue(
description="The returned events.",
docs_url="https://techdocs.akamai.com/linode-api/reference/get-events",
type=FieldType.list,
elements=FieldType.dict,
sample=docs.result_events_samples,
)
},
result_samples=docs.result_events_samples,
)

SPECDOC_META = module.spec

DOCUMENTATION = r"""
"""
EXAMPLES = r"""
"""
RETURN = r"""
"""


class Module(LinodeModuleBase):
"""Module for getting info about a Linode events"""

def __init__(self) -> None:
self.module_arg_spec = SPECDOC_META.ansible_spec
self.results: Dict[str, Any] = {"events": []}

super().__init__(module_arg_spec=self.module_arg_spec)

def exec_module(self, **kwargs: Any) -> Optional[dict]:
"""Entrypoint for event list module"""

filter_dict = construct_api_filter(self.module.params)

self.results["events"] = get_all_paginated(
self.client,
"/account/events",
filter_dict,
num_results=self.module.params["count"],
)
return self.results


def main() -> None:
"""Constructs and calls the module"""
Module()


if __name__ == "__main__":
main()
module.run()

0 comments on commit 4eca745

Please sign in to comment.