Skip to content

confluence ¤

admin ¤

client ¤

ConfluenceClient ¤

ConfluenceClient(base_url: str, username: str, api_key: str)

Bases: HttpClient

Helper methods for Confluence API.

Should not be used directly, be used by firefighter.confluence.service.ConfluenceService.

Source code in src/firefighter/confluence/client.py
def __init__(self, base_url: str, username: str, api_key: str):
    super().__init__(client_kwargs={"auth": (username, api_key)})
    self.base_url_api = base_url
    """Confluence API base URL. (with `/wiki/rest/api`)"""
    self.base_url = self.base_url_api.removesuffix("/rest/api")
    """Confluence base URL. (with `/wiki`, without `/rest/api`)"""

base_url instance-attribute ¤

base_url = self.base_url_api.removesuffix('/rest/api')

Confluence base URL. (with /wiki, without /rest/api)

base_url_api instance-attribute ¤

base_url_api: str = base_url

Confluence API base URL. (with /wiki/rest/api)

management ¤

commands ¤

sort_postmortems ¤

sort_runbooks ¤

sync_postmortems ¤

sync_runbooks ¤

models ¤

ConfluencePage ¤

Bases: Model

Represents a Confluence page.

PostMortem ¤

Bases: ConfluencePage

Represents a Confluence PostMortem page.

RunbookFilterSet ¤

Bases: FilterSet

Set of filters for Runbooks.

RunbookManager ¤

Bases: Manager['Runbook']

search staticmethod ¤

search(queryset: QuerySet[Runbook] | None, search_term: str) -> tuple[QuerySet[Runbook], bool]

Parameters:

  • queryset (QuerySet[Runbook] | None) –

    Queryset to search in. If None, search in all incidents. The Queryset allows to search on a subset of Runbooks (already filtered).

  • search_term (str) –

    Search term.

Returns:

  • tuple[QuerySet[Runbook], bool]

    tuple[QuerySet[Runbook], bool]: Queryset of Runbooks matching the search term, and a boolean indicating if the search may contain duplicates objects.

Source code in src/firefighter/confluence/models.py
@staticmethod
def search(
    queryset: QuerySet[Runbook] | None, search_term: str
) -> tuple[QuerySet[Runbook], bool]:
    """Args:
        queryset (QuerySet[Runbook] | None): Queryset to search in. If None, search in all incidents. The Queryset allows to search on a subset of Runbooks (already filtered).
        search_term (str): Search term.

    Returns:
        tuple[QuerySet[Runbook], bool]: Queryset of Runbooks matching the search term, and a boolean indicating if the search may contain duplicates objects.
    """
    if queryset is None:
        queryset = Runbook.objects.all()

    # If not search, return the original queryset
    if search_term is None or search_term.strip() == "":
        return queryset, False

    # XXX Improve search performance and relevance
    vector = (
        SearchVector("name", config="english", weight="A")
        + SearchVector("service_name", config="english", weight="B")
        + SearchVector("body_storage", config="english", weight="C")
    )
    query = SearchQuery(search_term, config="english", search_type="websearch")
    queryset = (
        queryset.annotate(rank=SearchRank(vector, query))
        .filter(rank__gte=0.05)
        .order_by("-rank")
    )

    return queryset, False

service ¤

ConfluenceService ¤

ConfluenceService()

Provide methods to interact with Confluence, without regards to the underlying library or HTTP client used.

TODO: The service should provide Pythonic errors and return types, and should not leak the underlying library or Confluence errors. It is not a priority for now, as the Confluence API is not used in critical paths.

Source code in src/firefighter/confluence/service.py
def __init__(self) -> None:
    self._client = None

base_url class-attribute instance-attribute ¤

base_url: str = settings.CONFLUENCE_URL.removesuffix('/rest/api')

Confluence base URL. (with /wiki, without /rest/api)

create_page ¤

create_page(title: str, parent_id: ConfluencePageId, body: str, space: str | None = None) -> ConfluencePage

TODO: Errors.

Parameters:

  • title (str) –

    Title of the page to create.

  • parent_id (ConfluencePageId) –

    Where to create the page. Will be a child of this page.

  • body (str) –

    Body of the page.

  • space (str | None, default: None ) –

    Space to create the page in. If None, defaults to theService's default space. Defaults to None.

Returns:

  • ConfluencePage ( ConfluencePage ) –

    The newly created page.

Source code in src/firefighter/confluence/service.py
def create_page(
    self,
    title: str,
    parent_id: ConfluencePageId,
    body: str,
    space: str | None = None,
) -> ConfluencePage:
    """TODO: Errors.

    Args:
        title (str): Title of the page to create.
        parent_id (ConfluencePageId): Where to create the page. Will be a child of this page.
        body (str): Body of the page.
        space (str | None, optional): Space to create the page in. If None, defaults to theService's default space. Defaults to None.

    Returns:
        ConfluencePage: The newly created page.
    """
    if not space:
        space = self.DEFAULT_SPACE
    return self.client.create_page(title, parent_id, space, body).json()

create_postmortem ¤

create_postmortem(title: str) -> None | ConfluencePage

Create a PostMortem page.

Parameters:

  • title (str) –

    Title of the PostMortem page.

Returns:

  • None | ConfluencePage

    None | ConfluencePage: The newly created page, or None if it failed.

Source code in src/firefighter/confluence/service.py
def create_postmortem(self, title: str) -> None | ConfluencePage:
    """Create a PostMortem page.

    Args:
        title (str): Title of the PostMortem page.

    Returns:
        None | ConfluencePage: The newly created page, or None if it failed.
    """
    # Get the body from the template page
    postmortem_template = (
        self.client.get_page(self.POSTMORTEM_TEMPLATE_PAGE_ID)
    ).json()
    body = get_in(postmortem_template, "body.storage.value")
    logger.debug(body)

    # Create the postmortem with the template body
    page_created: ConfluencePage = self.create_page(
        title, self.POSTMORTEM_FOLDER_ID, body
    )

    logger.debug("Postmortem page id: %s ", page_created.get("id"))
    if "statusCode" in page_created:
        logger.error(
            f"Can't create postmortem page with title {title}: {page_created}"
        )
        return None
    logger.debug(page_created)
    return page_created

get_page ¤

get_page(page_id: ConfluencePageId) -> ConfluencePage

TODO: Errors.

Parameters:

Returns:

  • ConfluencePage ( ConfluencePage ) –

    The page.

Source code in src/firefighter/confluence/service.py
def get_page(self, page_id: ConfluencePageId) -> ConfluencePage:
    """TODO: Errors.

    Args:
        page_id (ConfluencePageId): ID of the page to get.

    Returns:
        ConfluencePage: The page.
    """
    return self.client.get_page(page_id).json()

get_page_children_pages ¤

get_page_children_pages(page_id: ConfluencePageId, *args: Any, **kwargs: Any) -> list[ConfluencePage]

Get all children pages of a given page. TODO: testing.

Parameters:

  • page_id (ConfluencePageId) –

    ID of the page to get children pages from.

  • *args (Any, default: () ) –

    Arguments to pass to Confluence.

  • **kwargs (Any, default: {} ) –

    Keyword arguments to pass to Confluence.

Returns:

  • list[ConfluencePage]

    list[ConfluencePage]: list of children pages.

Source code in src/firefighter/confluence/service.py
def get_page_children_pages(
    self, page_id: ConfluencePageId, *args: Any, **kwargs: Any
) -> list[ConfluencePage]:
    """Get all children pages of a given page.
    TODO: testing.

    Args:
        page_id (ConfluencePageId): ID of the page to get children pages from.
        *args: Arguments to pass to Confluence.
        **kwargs: Keyword arguments to pass to Confluence.

    Returns:
        list[ConfluencePage]: list of children pages.
    """
    return list(self.client.get_page_children_pages(page_id, *args, **kwargs))

get_page_descendant_pages ¤

get_page_descendant_pages(page_id: ConfluencePageId, *args: Any, **kwargs: Any) -> list[ConfluencePage]

Get all descendant (nested children) pages of a given page. TODO: Pagination support and testing.

Parameters:

  • page_id (ConfluencePageId) –

    ID of the page to get children pages from.

  • *args (Any, default: () ) –

    Arguments to pass to Confluence.

  • **kwargs (Any, default: {} ) –

    Keyword arguments to pass to Confluence.

Returns:

  • list[ConfluencePage]

    list[ConfluencePage]: list of children pages.

Source code in src/firefighter/confluence/service.py
def get_page_descendant_pages(
    self, page_id: ConfluencePageId, *args: Any, **kwargs: Any
) -> list[ConfluencePage]:
    """Get all descendant (nested children) pages of a given page.
    TODO: Pagination support and testing.

    Args:
        page_id (ConfluencePageId): ID of the page to get children pages from.
        *args: Arguments to pass to Confluence.
        **kwargs: Keyword arguments to pass to Confluence.

    Returns:
        list[ConfluencePage]: list of children pages.
    """
    return self.client.get_page_descendant_pages(page_id, *args, **kwargs).json()[
        "results"
    ]

move_page ¤

move_page(
    page_id: ConfluencePageId,
    target_page_id: ConfluencePageId,
    position: Literal["before", "after", "append"] = "append",
    *,
    dry_run: bool = False
) -> None | ConfluencePage

Parameters:

  • page_id (ConfluencePageId) –

    ID of the page to move.

  • target_page_id (ConfluencePageId) –

    ID of the parent page to move the page in relation to.

  • position (Literal['before', 'after', 'append'], default: 'append' ) –

    Where should the page be moved, in relation to the target page. Defaults to "append".

  • dry_run (bool, default: False ) –

    If True, will log instead of moving. Defaults to False.

Returns:

  • None | ConfluencePage

    None | ConfluencePage: The moved page, or None if it failed.

Source code in src/firefighter/confluence/service.py
def move_page(
    self,
    page_id: ConfluencePageId,
    target_page_id: ConfluencePageId,
    position: Literal["before", "after", "append"] = "append",
    *,
    dry_run: bool = False,
) -> None | ConfluencePage:
    """Args:
        page_id (ConfluencePageId): ID of the page to move.
        target_page_id (ConfluencePageId): ID of the parent page to move the page in relation to.
        position (Literal["before", "after", "append"], optional): Where should the page be moved, in relation to the target page. Defaults to "append".
        dry_run (bool, optional): If True, will log instead of moving. Defaults to False.

    Returns:
        None | ConfluencePage: The moved page, or None if it failed.
    """
    if dry_run:
        logger.info(
            f"Would have moved {page_id} {'into' if position == 'append' else position} {target_page_id} if not dry run"
        )
        return None

    res = self.client.move_page(page_id, target_page_id, position)
    logger.info(
        f"Moved {page_id} {'into' if position == 'append' else position} {target_page_id}"
    )
    if res.status_code == 200:
        return res.json()
    logger.error(f"Error moving page {page_id} {res.status_code} {res.text}")
    return None

parse_confluence_page ¤

parse_confluence_page(pm: dict[str, Any] | ConfluencePage) -> PageInfo

Helper to parse a Confluence page into a PageInfo object.

Parameters:

  • pm (dict[str, Any] | ConfluencePage) –

    ConfluencePage from the API, or a dict with the same structure.

Returns:

Raises:

  • TypeError

    If one of page_id, page_title, page_url or page_edit_url are not strings.

Source code in src/firefighter/confluence/service.py
def parse_confluence_page(self, pm: dict[str, Any] | ConfluencePage) -> PageInfo:
    """Helper to parse a Confluence page into a PageInfo object.

    Args:
        pm (dict[str, Any] | ConfluencePage): ConfluencePage from the API, or a dict with the same structure.

    Returns:
        PageInfo: The parsed page details that are present on [firefighter.confluence.models.ConfluencePage][].

    Raises:
        TypeError: If one of page_id, page_title, page_url or page_edit_url are not strings.
    """
    page_url = f'{self.base_url}{get_in(pm, "_links.webui")}'
    page_edit_url = f'{self.base_url}{get_in(pm, "_links.editui")}'

    page_id = str(pm.get("id"))
    page_title = pm.get("title")
    if not isinstance(page_id, str):
        raise TypeError("page_id is not a string")
    if not isinstance(page_title, str):
        raise TypeError("page_title is not a string")
    if not isinstance(page_url, str):
        raise TypeError("page_url is not a string")
    if not isinstance(page_edit_url, str):
        raise TypeError("page_edit_url is not a string")
    return {
        "name": page_title,
        "page_id": page_id,
        "page_url": page_url,
        "page_edit_url": page_edit_url,
    }

sort_pages ¤

sort_pages(page_ids: list[tuple[ConfluencePageId, ConfluencePage]], *, dry_run: bool = False) -> None

Sort pages according to the list order.

Be careful: - this will move pages around, and will not check if the pages are already in the right order. - this will not check that the pages are in the same parent. - this will perform n moves, where n is the number of pages in the list.

Parameters:

  • page_ids (list[tuple[ConfluencePageId, ConfluencePage]]) –

    Sorted list of (PageId, Page) tuples.

  • dry_run (bool, default: False ) –

    If True, will log instead of sorting. Defaults to False.

Source code in src/firefighter/confluence/service.py
def sort_pages(
    self,
    page_ids: list[tuple[ConfluencePageId, ConfluencePage]],
    *,
    dry_run: bool = False,
) -> None:
    """Sort pages according to the list order.

    **Be careful**:
    - this will move pages around, and will not check if the pages are already in the right order.
    - this will not check that the pages are in the same parent.
    - this will perform n moves, where n is the number of pages in the list.

    Args:
        page_ids (list[tuple[ConfluencePageId, ConfluencePage]]): Sorted list of (PageId, Page) tuples.
        dry_run (bool, optional): If True, will log instead of sorting. Defaults to False.
    """
    for index, page in enumerate(page_ids):
        if index == 0:
            continue

        target_id = page_ids[index - 1][0]
        page_id = page[0]
        self.move_page(
            page_id,
            target_id,
            position="after",
            dry_run=dry_run,
        )

update_oncall_page ¤

update_oncall_page(users: dict[str, User]) -> bool

Update the Confluence list of On-Call users, if the page needs to be updated. Users should have a SlackUser AND a PagerDutyUser associated.

Parameters:

  • users (list[User]) –

    list of Users to update the page with.

Returns:

  • bool ( bool ) –

    has the page been updated?

Source code in src/firefighter/confluence/service.py
def update_oncall_page(self, users: dict[str, User]) -> bool:
    """Update the Confluence list of On-Call users, if the page needs to be updated.
    Users should have a SlackUser AND a PagerDutyUser associated.

    Args:
        users (list[User]): list of Users to update the page with.

    Returns:
        bool: has the page been updated?
    """
    if not settings.CONFLUENCE_ON_CALL_PAGE_ID:
        logger.info("No Confluence OnCall page ID, skipping.")
        return False

    content = (self.client.get_page(settings.CONFLUENCE_ON_CALL_PAGE_ID)).json()

    page_version = get_in(content, "version.number")
    if not page_version:
        logger.error("No page version in Confluence page! %s", content)
        return False
    page_version += 1
    page_body = self._build_page_from_django_template(
        "oncall_team.xml",
        context={
            "users": users.items(),
            "oncall_page_link": urljoin(
                settings.BASE_URL, reverse("pagerduty:oncall-list")
            ),
        },
    )
    logger.debug("Confluence OnCall page body: %s", page_body)
    if get_in(content, "body.storage.value") != page_body:
        res = self.client.update_page(
            content.get("id"),
            content.get("type"),
            content.get("title"),
            page_body,
            page_version,
        )
        if res.status_code != 200:
            logger.error("Can't update OnCall page: %s", res.json())
            return False
        return True

    logger.info("Confluence OnCall page is up to date, and was not updated.")
    return False

signals ¤

incident_updated ¤

tasks ¤

archive_postmortems ¤

archive_and_sort_postmortems ¤

archive_and_sort_postmortems(*, dry_run: bool = True) -> None

Archive postmortems that are older than 2 weeks, for incidents that are closed.

Parameters:

  • dry_run (bool, default: True ) –

    Should actions be performed? If True, Confluence will be accessed in read-only mode. Defaults to False.

Source code in src/firefighter/confluence/tasks/archive_postmortems.py
@shared_task(
    name="confluence.archive_and_sort_postmortems",
    soft_time_limit=60 * 5,
    time_limit=60 * 7,
)
def archive_and_sort_postmortems(*, dry_run: bool = True) -> None:
    """Archive postmortems that are older than 2 weeks, for incidents that are closed.

    Args:
        dry_run (bool, optional): Should actions be performed? If True, Confluence will be accessed in read-only mode. Defaults to False.
    """
    logger.info(f"Running in {'dry run' if dry_run else 'real'} mode")

    # 1. Get top level pages
    pm_to_sort, quarter_bins = _get_top_level_pages(
        confluence_service.POSTMORTEM_FOLDER_ID
    )

    # 2. Create current quarter folder if it does not exist
    create_current_bin_if_needed(quarter_bins, dry_run=dry_run)

    # 3. Archive postmortems in root into their quarter folder (if appropriate)
    _archive_postmortems(pm_to_sort, quarter_bins, dry_run=dry_run)

    # 4. Move archived postmortems in the right quarter folder if there is any error
    # Not needed atm

    # 5. Sort postmortems in each quarter folder
    sort_postmortems_in_bins(quarter_bins, dry_run=dry_run)

sort_postmortems_in_bins ¤

sort_postmortems_in_bins(quarter_bins: dict[str, int], *, dry_run: bool = False) -> None

Sort postmortems in each quarter archive folder.

Parameters:

  • quarter_bins (dict[str, int]) –

    description

  • dry_run (bool, default: False ) –

    description. Defaults to False.

Source code in src/firefighter/confluence/tasks/archive_postmortems.py
def sort_postmortems_in_bins(
    quarter_bins: dict[str, int], *, dry_run: bool = False
) -> None:
    """Sort postmortems in each quarter archive folder.

    Args:
        quarter_bins (dict[str, int]): _description_
        dry_run (bool, optional): _description_. Defaults to False.
    """
    for quarter, quarter_page_id in quarter_bins.items():
        # Get children per archive page
        children: list[ConfluencePage] = confluence_service.get_page_children_pages(
            quarter_page_id, expand=""
        )
        logger.info(f"Found {len(children)} postmortems in {quarter}")
        quarter_children: list[tuple[int, datetime, ConfluencePage]] = []

        for page in children:
            title: str = page["title"]
            page_id: int = int(page["id"])

            date_, fmt = parse_postmortem_title(title)
            if date_ and fmt:
                quarter_children.append((page_id, date_, page))

        sorted_children = sorted(quarter_children, key=lambda x: x[1], reverse=True)
        # Check if already sorted
        if sorted_children == quarter_children:
            logger.debug(f"Quarter {quarter} is already sorted. Skipping")
            continue

        logger.info(f"Quarter {quarter} is not sorted. Sorting")

        clean_sorted: list[tuple[ConfluencePageId, ConfluencePage]] = [
            (x[0], x[2]) for x in sorted_children
        ]

        confluence_service.sort_pages(clean_sorted, dry_run=dry_run)

        logger.info(f"Fetched {len(quarter_children)} postmortems")

sort_runbooks ¤

sort_runbooks ¤

sort_runbooks(*, dry_run: bool = False) -> None

Sort runbooks in Confluence.

Parameters:

  • dry_run (bool, default: False ) –

    Should actions be performed? If True, Confluence will be accessed in read-only mode. Defaults to False.

Source code in src/firefighter/confluence/tasks/sort_runbooks.py
@shared_task(name="confluence.sort_runbooks", soft_time_limit=60 * 5, time_limit=60 * 7)
def sort_runbooks(*, dry_run: bool = False) -> None:
    """Sort runbooks in Confluence.

    Args:
        dry_run (bool, optional): Should actions be performed? If True, Confluence will be accessed in read-only mode. Defaults to False.
    """
    logger.info(f"Running in {'dry run' if dry_run else 'real'} mode")

    # 1. Get top level pages
    folders = _get_top_level_pages(confluence_service.RUNBOOKS_FOLDER_ID)

    # 2. Sort runbooks in each folder
    sort_runbooks_in_folders(folders, dry_run=dry_run)

sort_runbooks_in_folders ¤

sort_runbooks_in_folders(folders: list[ConfluencePageId], *, dry_run: bool = False) -> None

Sort runbooks in each folder.

Parameters:

  • folders (list[ConfluencePageId]) –

    List of folders to sort runbooks in.

  • dry_run (bool, default: False ) –

    Do not perform the sort. Defaults to False.

Source code in src/firefighter/confluence/tasks/sort_runbooks.py
def sort_runbooks_in_folders(
    folders: list[ConfluencePageId], *, dry_run: bool = False
) -> None:
    """Sort runbooks in each folder.

    Args:
        folders (list[ConfluencePageId]): List of folders to sort runbooks in.
        dry_run (bool, optional): Do not perform the sort. Defaults to False.
    """
    for folder_page_id in folders:
        # Get children per archive page
        children: list[ConfluencePage] = confluence_service.get_page_children_pages(
            folder_page_id, expand=""
        )

        folder_children: list[tuple[ConfluencePageId, str, ConfluencePage]] = []

        for page in children:
            title: str = page["title"]
            page_id: ConfluencePageId = page["id"]

            runbook_name_clean = parse_runbook_title(title)
            if runbook_name_clean:
                folder_children.append((page_id, runbook_name_clean, page))

        sorted_children = sorted(folder_children, key=lambda x: x[1].lower())
        # Check if already sorted
        if sorted_children == folder_children:
            logger.debug(f"Folder {folder_page_id} is already sorted. Skipping")
            continue
        clean_sorted_children: list[tuple[ConfluencePageId, ConfluencePage]] = [
            (x[0], x[2]) for x in sorted_children
        ]
        logger.info(f"Folder {folder_page_id} is not sorted. Sorting")
        confluence_service.sort_pages(clean_sorted_children, dry_run=dry_run)

sync_pages_content ¤

sync_postmortems ¤

sync_runbooks ¤

urls ¤

utils ¤

ConfluencePageId module-attribute ¤

ConfluencePageId: TypeAlias = int | str

Alias of int | str

PageInfo ¤

Bases: TypedDict

Dict mapped to mandatory fields for a firefighter.confluence.models.ConfluencePage.

parse_postmortem_title ¤

parse_postmortem_title(title: str) -> tuple[datetime, str] | tuple[None, None]

Parse postmortem title and return the date and quarter associated to this date, in the format YYYYQX.

Parameters:

  • title (str) –

    Title of the postmortem, in the format #YYYYMMDD-- (SEV/P) </p> </div> </li> </ul> <p>Returns:</p> <ul> <li class="field-body"> <code><a class="autorefs autorefs-external" href="https://docs.python.org/3.11/library/stdtypes.html#tuple">tuple</a>[<span title="django.utils.timezone.datetime">datetime</span>, <a class="autorefs autorefs-external" href="https://docs.python.org/3.11/library/stdtypes.html#str">str</a>] | <a class="autorefs autorefs-external" href="https://docs.python.org/3.11/library/stdtypes.html#tuple">tuple</a>[None, None]</code> – <div class="doc-md-description"> <p>tuple[datetime, str] | tuple[None, None]: Date and quarter associated to this date.</p> </div> </li> </ul> <details class="quote"> <summary>Source code in <code>src/firefighter/confluence/utils.py</code></summary> <div class="highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal"><a href="#__codelineno-0-59">59</a></span> <span class="normal"><a href="#__codelineno-0-60">60</a></span> <span class="normal"><a href="#__codelineno-0-61">61</a></span> <span class="normal"><a href="#__codelineno-0-62">62</a></span> <span class="normal"><a href="#__codelineno-0-63">63</a></span> <span class="normal"><a href="#__codelineno-0-64">64</a></span> <span class="normal"><a href="#__codelineno-0-65">65</a></span> <span class="normal"><a href="#__codelineno-0-66">66</a></span> <span class="normal"><a href="#__codelineno-0-67">67</a></span> <span class="normal"><a href="#__codelineno-0-68">68</a></span> <span class="normal"><a href="#__codelineno-0-69">69</a></span> <span class="normal"><a href="#__codelineno-0-70">70</a></span> <span class="normal"><a href="#__codelineno-0-71">71</a></span> <span class="normal"><a href="#__codelineno-0-72">72</a></span> <span class="normal"><a href="#__codelineno-0-73">73</a></span> <span class="normal"><a href="#__codelineno-0-74">74</a></span> <span class="normal"><a href="#__codelineno-0-75">75</a></span> <span class="normal"><a href="#__codelineno-0-76">76</a></span> <span class="normal"><a href="#__codelineno-0-77">77</a></span> <span class="normal"><a href="#__codelineno-0-78">78</a></span> <span class="normal"><a href="#__codelineno-0-79">79</a></span> <span class="normal"><a href="#__codelineno-0-80">80</a></span></pre></div></td><td class="code"><div><pre><span></span><code><a id="__codelineno-0-59" name="__codelineno-0-59"></a><span class="k">def</span> <span class="nf">parse_postmortem_title</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">tuple</span><span class="p">[</span><span class="n">datetime</span><span class="p">,</span> <span class="nb">str</span><span class="p">]</span> <span class="o">|</span> <span class="nb">tuple</span><span class="p">[</span><span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">]:</span> <a id="__codelineno-0-60" name="__codelineno-0-60"></a><span class="w"> </span><span class="sd">"""Parse postmortem title and return the date and quarter associated to this date, in the format YYYYQX.</span> <a id="__codelineno-0-61" name="__codelineno-0-61"></a> <a id="__codelineno-0-62" name="__codelineno-0-62"></a><span class="sd"> Args:</span> <a id="__codelineno-0-63" name="__codelineno-0-63"></a><span class="sd"> title (str): Title of the postmortem, in the format #YYYYMMDD-<id>-<component> (SEV/P<N>) <title></span> <a id="__codelineno-0-64" name="__codelineno-0-64"></a> <a id="__codelineno-0-65" name="__codelineno-0-65"></a><span class="sd"> Returns:</span> <a id="__codelineno-0-66" name="__codelineno-0-66"></a><span class="sd"> tuple[datetime, str] | tuple[None, None]: Date and quarter associated to this date.</span> <a id="__codelineno-0-67" name="__codelineno-0-67"></a><span class="sd"> """</span> <a id="__codelineno-0-68" name="__codelineno-0-68"></a> <span class="n">match</span> <span class="o">=</span> <span class="n">CONFLUENCE_PM_TITLE_REGEX</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">title</span><span class="p">)</span> <a id="__codelineno-0-69" name="__codelineno-0-69"></a> <span class="k">if</span> <span class="ow">not</span> <span class="n">match</span><span class="p">:</span> <a id="__codelineno-0-70" name="__codelineno-0-70"></a> <span class="k">return</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span> <a id="__codelineno-0-71" name="__codelineno-0-71"></a> <a id="__codelineno-0-72" name="__codelineno-0-72"></a> <span class="n">res</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span> <a id="__codelineno-0-73" name="__codelineno-0-73"></a> <span class="n">grp</span> <span class="o">=</span> <span class="n">res</span><span class="p">[</span><span class="s2">"date"</span><span class="p">]</span> <a id="__codelineno-0-74" name="__codelineno-0-74"></a> <span class="n">grp</span> <span class="o">=</span> <span class="n">grp</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"-inc"</span><span class="p">,</span> <span class="s2">""</span><span class="p">)</span> <a id="__codelineno-0-75" name="__codelineno-0-75"></a> <a id="__codelineno-0-76" name="__codelineno-0-76"></a> <span class="n">date_</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="n">grp</span><span class="p">,</span> <span class="s2">"%Y%m</span><span class="si">%d</span><span class="s2">"</span><span class="p">)</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="n">get_current_timezone</span><span class="p">())</span> <a id="__codelineno-0-77" name="__codelineno-0-77"></a> <span class="n">quarter</span> <span class="o">=</span> <span class="n">get_quarter_from_week</span><span class="p">(</span><span class="n">date_</span><span class="o">.</span><span class="n">isocalendar</span><span class="p">()[</span><span class="mi">1</span><span class="p">])</span> <a id="__codelineno-0-78" name="__codelineno-0-78"></a> <span class="n">year</span> <span class="o">=</span> <span class="n">date_</span><span class="o">.</span><span class="n">isocalendar</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <a id="__codelineno-0-79" name="__codelineno-0-79"></a> <span class="n">fmt</span> <span class="o">=</span> <span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">year</span><span class="si">}</span><span class="s2">Q</span><span class="si">{</span><span class="n">quarter</span><span class="si">}</span><span class="s2">"</span> <a id="__codelineno-0-80" name="__codelineno-0-80"></a> <span class="k">return</span> <span class="n">date_</span><span class="p">,</span> <span class="n">fmt</span> </code></pre></div></td></tr></table></div> </details> </div> </div> <div class="doc doc-object doc-function"> <h3 id="firefighter.confluence.utils.parse_runbook_title" class="doc doc-heading"> <span class="doc doc-object-name doc-function-name">parse_runbook_title</span> <a href="#firefighter.confluence.utils.parse_runbook_title" class="headerlink" title="Permanent link">¤</a></h3> <div class="doc-signature highlight"><pre><span></span><code><a id="__codelineno-0-1" name="__codelineno-0-1" href="#__codelineno-0-1"></a><span class="n">parse_runbook_title</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span> <span class="o">|</span> <span class="kc">None</span> </code></pre></div> <div class="doc doc-contents "> <p>Parse runbooks title and return the service name, or None if the title is not valid.</p> <p>Useful to remove prefixes like [WIP] or [ARCHIVED] from the title, to sort runbooks.</p> <p>Parameters:</p> <ul> <li class="field-body"> <b><code>title</code></b> (<code><a class="autorefs autorefs-external" href="https://docs.python.org/3.11/library/stdtypes.html#str">str</a></code>) – <div class="doc-md-description"> <p>Title of the runbook</p> </div> </li> </ul> <p>Returns:</p> <ul> <li class="field-body"> <code><a class="autorefs autorefs-external" href="https://docs.python.org/3.11/library/stdtypes.html#str">str</a> | None</code> – <div class="doc-md-description"> <p>str | None: Service name or None if the title is not valid.</p> </div> </li> </ul> <details class="quote"> <summary>Source code in <code>src/firefighter/confluence/utils.py</code></summary> <div class="highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal"><a href="#__codelineno-0-87"> 87</a></span> <span class="normal"><a href="#__codelineno-0-88"> 88</a></span> <span class="normal"><a href="#__codelineno-0-89"> 89</a></span> <span class="normal"><a href="#__codelineno-0-90"> 90</a></span> <span class="normal"><a href="#__codelineno-0-91"> 91</a></span> <span class="normal"><a href="#__codelineno-0-92"> 92</a></span> <span class="normal"><a href="#__codelineno-0-93"> 93</a></span> <span class="normal"><a href="#__codelineno-0-94"> 94</a></span> <span class="normal"><a href="#__codelineno-0-95"> 95</a></span> <span class="normal"><a href="#__codelineno-0-96"> 96</a></span> <span class="normal"><a href="#__codelineno-0-97"> 97</a></span> <span class="normal"><a href="#__codelineno-0-98"> 98</a></span> <span class="normal"><a href="#__codelineno-0-99"> 99</a></span> <span class="normal"><a href="#__codelineno-0-100">100</a></span> <span class="normal"><a href="#__codelineno-0-101">101</a></span> <span class="normal"><a href="#__codelineno-0-102">102</a></span> <span class="normal"><a href="#__codelineno-0-103">103</a></span></pre></div></td><td class="code"><div><pre><span></span><code><a id="__codelineno-0-87" name="__codelineno-0-87"></a><span class="k">def</span> <span class="nf">parse_runbook_title</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span> <span class="o">|</span> <span class="kc">None</span><span class="p">:</span> <a id="__codelineno-0-88" name="__codelineno-0-88"></a><span class="w"> </span><span class="sd">"""Parse runbooks title and return the service name, or None if the title is not valid.</span> <a id="__codelineno-0-89" name="__codelineno-0-89"></a> <a id="__codelineno-0-90" name="__codelineno-0-90"></a><span class="sd"> Useful to remove prefixes like [WIP] or [ARCHIVED] from the title, to sort runbooks.</span> <a id="__codelineno-0-91" name="__codelineno-0-91"></a> <a id="__codelineno-0-92" name="__codelineno-0-92"></a><span class="sd"> Args:</span> <a id="__codelineno-0-93" name="__codelineno-0-93"></a><span class="sd"> title (str): Title of the runbook</span> <a id="__codelineno-0-94" name="__codelineno-0-94"></a> <a id="__codelineno-0-95" name="__codelineno-0-95"></a><span class="sd"> Returns:</span> <a id="__codelineno-0-96" name="__codelineno-0-96"></a><span class="sd"> str | None: Service name or None if the title is not valid.</span> <a id="__codelineno-0-97" name="__codelineno-0-97"></a><span class="sd"> """</span> <a id="__codelineno-0-98" name="__codelineno-0-98"></a> <span class="k">if</span> <span class="s2">"[RUNBOOK]"</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">title</span> <span class="ow">or</span> <span class="s2">"[TEMPLATE]"</span> <span class="ow">in</span> <span class="n">title</span><span class="o">.</span><span class="n">upper</span><span class="p">():</span> <a id="__codelineno-0-99" name="__codelineno-0-99"></a> <span class="k">return</span> <span class="kc">None</span> <a id="__codelineno-0-100" name="__codelineno-0-100"></a> <a id="__codelineno-0-101" name="__codelineno-0-101"></a> <span class="c1"># Remove leading text in brackets</span> <a id="__codelineno-0-102" name="__codelineno-0-102"></a> <span class="n">title</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">"^\[.*\] "</span><span class="p">,</span> <span class="s2">""</span><span class="p">,</span> <span class="n">title</span><span class="p">)</span> <a id="__codelineno-0-103" name="__codelineno-0-103"></a> <span class="k">return</span> <span class="n">title</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> </code></pre></div></td></tr></table></div> </details> </div> </div> </div> </div> </div> <div class="doc doc-object doc-module"> <h2 id="firefighter.confluence.views" class="doc doc-heading"> <span class="doc doc-object-name doc-module-name">views</span> <a href="#firefighter.confluence.views" class="headerlink" title="Permanent link">¤</a></h2> <div class="doc doc-contents "> <div class="doc doc-children"> <div class="doc doc-object doc-module"> <h3 id="firefighter.confluence.views.runbook" class="doc doc-heading"> <span class="doc doc-object-name doc-module-name">runbook</span> <a href="#firefighter.confluence.views.runbook" class="headerlink" title="Permanent link">¤</a></h3> <div class="doc doc-contents "> <div class="doc doc-children"> <div class="doc doc-object doc-module"> <h4 id="firefighter.confluence.views.runbook.runbook_list" class="doc doc-heading"> <span class="doc doc-object-name doc-module-name">runbook_list</span> <a href="#firefighter.confluence.views.runbook.runbook_list" class="headerlink" title="Permanent link">¤</a></h4> <div class="doc doc-contents "> <div class="doc doc-children"> <div class="doc doc-object doc-class"> <h5 id="firefighter.confluence.views.runbook.runbook_list.RunbooksViewList" class="doc doc-heading"> <span class="doc doc-object-name doc-class-name">RunbooksViewList</span> <a href="#firefighter.confluence.views.runbook.runbook_list.RunbooksViewList" class="headerlink" title="Permanent link">¤</a></h5> <div class="doc doc-contents "> <p class="doc doc-class-bases"> Bases: <code><span title="django_tables2.views.SingleTableMixin">SingleTableMixin</span></code>, <code><span title="django_filters.views.FilterView">FilterView</span></code></p> <div class="doc doc-children"> <div class="doc doc-object doc-function"> <h6 id="firefighter.confluence.views.runbook.runbook_list.RunbooksViewList.get_context_data" class="doc doc-heading"> <span class="doc doc-object-name doc-function-name">get_context_data</span> <a href="#firefighter.confluence.views.runbook.runbook_list.RunbooksViewList.get_context_data" class="headerlink" title="Permanent link">¤</a></h6> <div class="doc-signature highlight"><pre><span></span><code><a id="__codelineno-0-1" name="__codelineno-0-1" href="#__codelineno-0-1"></a><span class="n">get_context_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Any</span><span class="p">]</span> </code></pre></div> <div class="doc doc-contents "> <p>No *args to pass.</p> <details class="quote"> <summary>Source code in <code>src/firefighter/confluence/views/runbook/runbook_list.py</code></summary> <div class="highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal"><a href="#__codelineno-0-38">38</a></span> <span class="normal"><a href="#__codelineno-0-39">39</a></span> <span class="normal"><a href="#__codelineno-0-40">40</a></span> <span class="normal"><a href="#__codelineno-0-41">41</a></span> <span class="normal"><a href="#__codelineno-0-42">42</a></span> <span class="normal"><a href="#__codelineno-0-43">43</a></span> <span class="normal"><a href="#__codelineno-0-44">44</a></span> <span class="normal"><a href="#__codelineno-0-45">45</a></span> <span class="normal"><a href="#__codelineno-0-46">46</a></span></pre></div></td><td class="code"><div><pre><span></span><code><a id="__codelineno-0-38" name="__codelineno-0-38"></a><span class="k">def</span> <span class="nf">get_context_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Any</span><span class="p">]:</span> <a id="__codelineno-0-39" name="__codelineno-0-39"></a><span class="w"> </span><span class="sd">"""No *args to pass."""</span> <a id="__codelineno-0-40" name="__codelineno-0-40"></a> <span class="n">context</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">get_context_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <a id="__codelineno-0-41" name="__codelineno-0-41"></a> <span class="n">context</span><span class="p">[</span><span class="s2">"filter_order"</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span> <a id="__codelineno-0-42" name="__codelineno-0-42"></a> <span class="s2">"search"</span><span class="p">,</span> <a id="__codelineno-0-43" name="__codelineno-0-43"></a> <span class="s2">"service_type"</span><span class="p">,</span> <a id="__codelineno-0-44" name="__codelineno-0-44"></a> <span class="p">]</span> <a id="__codelineno-0-45" name="__codelineno-0-45"></a> <span class="n">context</span><span class="p">[</span><span class="s2">"page_title"</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Runbooks List"</span> <a id="__codelineno-0-46" name="__codelineno-0-46"></a> <span class="k">return</span> <span class="n">context</span> </code></pre></div></td></tr></table></div> </details> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var tab,labels=set.querySelector(".tabbed-labels");for(tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type="button" class="md-top md-icon" data-md-component="top" hidden> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8v12Z"/></svg> Back to top </button> </main> <footer class="md-footer"> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-copyright"> <div class="md-copyright__highlight"> Copyright © 2021-2024 Colibri SAS </div> </div> <div class="md-social"> <a href="https://github.com/ManoManoTech/firefighter-incident" target="_blank" rel="noopener" title="github.com" class="md-social__link"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc.--><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg> </a> </div> </div> </div> </footer> </div> <div class="md-dialog" data-md-component="dialog"> <div class="md-dialog__inner md-typeset"></div> </div> <div class="md-progress" data-md-component="progress" role="progressbar"></div> <script id="__config" type="application/json">{"base": "../..", "features": ["content.action.edit", "content.action.view", "content.code.annotate", "content.tabs.link", "navigation.expand", "navigation.instant", "navigation.instant.progress", "navigation.tracking", "navigation.tabs", "navigation.tabs.sticky", "navigation.top", "search.highlight", "search.share", "search.suggest"], "search": "../../assets/javascripts/workers/search.c011b7c0.min.js", "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}, "version": {"provider": "mike"}}</script> <script src="../../assets/javascripts/bundle.7389ff0e.min.js"></script> <script src="../../assets/_markdown_exec_pyodide.js"></script> </body> </html>