Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions tableauserverclient/models/task_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ def _parse_element(cls, element, ns):
last_run_at = None
workbook_element = element.find(".//t:workbook", namespaces=ns)
datasource_element = element.find(".//t:datasource", namespaces=ns)
flow_element = element.find(".//t:flow", namespaces=ns)
last_run_at_element = element.find(".//t:lastRunAt", namespaces=ns)

schedule_item_list = ScheduleItem.from_element(element, ns)
Expand All @@ -105,6 +106,8 @@ def _parse_element(cls, element, ns):
if datasource_element is not None:
datasource_id = datasource_element.get("id", None)
target = Target(datasource_id, "datasource")
if flow_element is not None:
target = Target(flow_element.get("id", None), "flow")
if last_run_at_element is not None:
last_run_at = parse_datetime(last_run_at_element.text)

Expand Down
108 changes: 106 additions & 2 deletions tableauserverclient/server/endpoint/schedules_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@
from typing import TYPE_CHECKING, Any, Callable, Literal, overload

from .endpoint import Endpoint, api, parameter_added_in
from .exceptions import MissingRequiredFieldError
from .exceptions import MissingRequiredFieldError, ServerResponseError
from tableauserverclient.server import RequestFactory
from tableauserverclient.models import PaginationItem, ScheduleItem, TaskItem, ExtractItem
from tableauserverclient.server.exceptions import EndpointUnavailableError
from tableauserverclient.server.pager import Pager
from tableauserverclient.models import ExtractItem, PaginationItem, ScheduleItem, SubscriptionItem, TaskItem
from tableauserverclient.models.schedule_item import parse_batch_schedule_state

from tableauserverclient.helpers.logging import logger

AddResponse = namedtuple("AddResponse", ("result", "error", "warnings", "task_created"))
ScheduleTasks = namedtuple("ScheduleTasks", ("extracts", "subscriptions", "flow_tasks"))
OK = AddResponse(result=True, error=None, warnings=None, task_created=None)

if TYPE_CHECKING:
Expand Down Expand Up @@ -282,6 +285,107 @@ def get_extract_refresh_tasks(

return extract_items, pagination_item

@api(version="3.2")
def get_subscriptions_by_schedule(self, schedule_id: str) -> list[SubscriptionItem]:
"""
Return the Tableau Server subscriptions on this schedule.

The REST API has no ``/schedules/{id}/subscriptions`` method. This
lists the site's subscriptions and keeps those whose schedule id
matches. Tableau Cloud subscriptions use a frequency instead of a
server schedule id, so they are not included.

REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_subscriptions.htm#list_subscriptions

Parameters
----------
schedule_id : str
The schedule to match.

Returns
-------
list[SubscriptionItem]
"""
if not schedule_id:
raise ValueError("Schedule ID undefined")
matches = []
for subscription in Pager(self.parent_srv.subscriptions):
if subscription.schedule_id == schedule_id:
matches.append(subscription)
return matches

def get_flow_tasks_by_schedule(self, schedule_id: str) -> list[TaskItem]:
"""
Return flow run tasks on this server schedule.

Flow tasks are listed for the site and kept when their schedule id
matches. There is no version gate: ``tasks.get`` raises
``EndpointUnavailableError`` below REST API 2.6, and a server that
does not implement the method answers 404001. Both return an empty
list. Any other error is raised, including a 404 for a missing site.

REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_flow.htm#get_flow_run_tasks

Parameters
----------
schedule_id : str
The schedule to match.

Returns
-------
list[TaskItem]
"""
if not schedule_id:
raise ValueError("Schedule ID undefined")
try:
tasks = list(Pager(self.parent_srv.tasks.get, task_type=TaskItem.Type.RunFlow))
except EndpointUnavailableError:
logger.info("Flow tasks are not available before REST API 2.6")
return []
except ServerResponseError as error:
if error.code == "404001":
logger.info("Flow tasks are not available on this server: %s", error.code)
return []
raise
return [task for task in tasks if task.schedule_id == schedule_id]

@api(version="2.3")
def get_tasks(self, schedule_id: str) -> ScheduleTasks:
"""
List the extract refreshes, subscriptions, and flow tasks on a schedule.

Extract refreshes come from the schedule. Subscriptions are included
from REST API 3.2 and flow tasks from 3.3; on an older server those
parts are empty and are not requested. Tableau Cloud subscriptions,
which have no server schedule id, are left out.

REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_jobs_tasks_and_schedules.htm#list_extract_refresh_tasks
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_subscriptions.htm#list_subscriptions
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_flow.htm#get_flow_run_tasks

Parameters
----------
schedule_id : str
The schedule to list.

Returns
-------
ScheduleTasks
``extracts``, ``subscriptions``, and ``flow_tasks``.
"""
if not schedule_id:
raise ValueError("Schedule ID undefined")
extracts: list[ExtractItem] = list(
Pager(lambda options: self.get_extract_refresh_tasks(schedule_id, options)) # type: ignore[arg-type]
)
subscriptions = (
self.get_subscriptions_by_schedule(schedule_id) if self.parent_srv.check_at_least_version("3.2") else []
)
flow_tasks = (
self.get_flow_tasks_by_schedule(schedule_id) if self.parent_srv.check_at_least_version("3.3") else []
)
return ScheduleTasks(extracts, subscriptions, flow_tasks)

@overload
def batch_update_state(
self,
Expand Down
18 changes: 18 additions & 0 deletions test/assets/schedule_flow_tasks.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="http://tableau.com/api">
<pagination pageNumber="1" pageSize="100" totalAvailable="2"/>
<tasks>
<task>
<runFlow id="flow-task-1" type="RunFlowTask" priority="50">
<schedule id="sched-1" name="Nightly" type="Flow"/>
<flow id="flow-1"/>
</runFlow>
</task>
<task>
<runFlow id="flow-task-2" type="RunFlowTask" priority="40">
<schedule id="sched-other" name="Weekly" type="Flow"/>
<flow id="flow-2"/>
</runFlow>
</task>
</tasks>
</tsResponse>
7 changes: 7 additions & 0 deletions test/assets/schedule_flow_tasks_missing.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="http://tableau.com/api">
<error code="404001">
<summary>Resource Not Found</summary>
<detail>Method not found</detail>
</error>
</tsResponse>
7 changes: 7 additions & 0 deletions test/assets/schedule_flow_tasks_site_missing.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="http://tableau.com/api">
<error code="404000">
<summary>Site not found</summary>
<detail>The site ID in the URI doesn't correspond to an existing site.</detail>
</error>
</tsResponse>
16 changes: 16 additions & 0 deletions test/assets/schedule_subscriptions.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="http://tableau.com/api">
<pagination pageNumber="1" pageSize="100" totalAvailable="2"/>
<subscriptions>
<subscription id="sub-on-schedule" subject="On the schedule">
<content id="view-1" type="View"/>
<schedule id="sched-1" name="Nightly"/>
<user id="user-1" name="ada"/>
</subscription>
<subscription id="sub-cloud" subject="Cloud frequency">
<content id="view-2" type="View"/>
<schedule frequency="Weekly" nextRunAt="2023-06-08T17:05:00-0700"/>
<user id="user-1" name="ada"/>
</subscription>
</subscriptions>
</tsResponse>
83 changes: 83 additions & 0 deletions test/test_schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
ADD_DATASOURCE_TO_SCHEDULE = TEST_ASSET_DIR / "schedule_add_datasource.xml"
ADD_FLOW_TO_SCHEDULE = TEST_ASSET_DIR / "schedule_add_flow.xml"
GET_EXTRACT_TASKS_XML = TEST_ASSET_DIR / "schedule_get_extract_refresh_tasks.xml"
SUBSCRIPTIONS_XML = TEST_ASSET_DIR / "schedule_subscriptions.xml"
FLOW_TASKS_XML = TEST_ASSET_DIR / "schedule_flow_tasks.xml"
FLOW_MISSING_XML = TEST_ASSET_DIR / "schedule_flow_tasks_missing.xml"
FLOW_OTHER_404_XML = TEST_ASSET_DIR / "schedule_flow_tasks_site_missing.xml"
BATCH_UPDATE_STATE = TEST_ASSET_DIR / "schedule_batch_update_state.xml"

WORKBOOK_GET_BY_ID_XML = TEST_ASSET_DIR / "workbook_get_by_id.xml"
Expand Down Expand Up @@ -492,3 +496,82 @@ def test_batch_update_state_all(server: TSC.Server) -> None:
history = m.request_history[0]

assert history.text == "<tsRequest />"


def test_get_tasks_on_schedule(server: TSC.Server) -> None:
server.version = "3.10"
schedule_id = "sched-1"
with requests_mock.mock() as m:
m.get(f"{server.schedules.siteurl}/{schedule_id}/extracts", text=GET_EXTRACT_TASKS_XML.read_text())
m.get(f"{server.baseurl}/sites/{server.site_id}/subscriptions", text=SUBSCRIPTIONS_XML.read_text())
m.get(f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow", text=FLOW_TASKS_XML.read_text())
tasks = server.schedules.get_tasks(schedule_id)

assert [item.id for item in tasks.extracts] == ["task1", "task2"]
assert [item.id for item in tasks.subscriptions] == ["sub-on-schedule"]
assert [item.id for item in tasks.flow_tasks] == ["flow-task-1"]
assert tasks.flow_tasks[0].target.id == "flow-1"
assert tasks.flow_tasks[0].target.type == "flow"


def test_get_tasks_skips_methods_the_server_version_does_not_have(server: TSC.Server) -> None:
schedule_id = "sched-1"
extracts = f"{server.schedules.siteurl}/{schedule_id}/extracts"
subscriptions = f"{server.baseurl}/sites/{server.site_id}/subscriptions"
flows = f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow"

server.version = "2.4"
with requests_mock.mock() as m:
m.get(extracts, text=GET_EXTRACT_TASKS_XML.read_text())
m.get(subscriptions, text=SUBSCRIPTIONS_XML.read_text())
m.get(flows, text=FLOW_TASKS_XML.read_text())
tasks = server.schedules.get_tasks(schedule_id)
assert [item.id for item in tasks.extracts] == ["task1", "task2"]
assert tasks.subscriptions == []
assert tasks.flow_tasks == []
assert [call.path for call in m.request_history] == [
f"/api/2.4/sites/{server.site_id}/schedules/{schedule_id}/extracts"
]

server.version = "3.2"
extracts = f"{server.schedules.siteurl}/{schedule_id}/extracts"
subscriptions = f"{server.baseurl}/sites/{server.site_id}/subscriptions"
flows = f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow"
with requests_mock.mock() as m:
m.get(extracts, text=GET_EXTRACT_TASKS_XML.read_text())
m.get(subscriptions, text=SUBSCRIPTIONS_XML.read_text())
m.get(flows, text=FLOW_TASKS_XML.read_text())
tasks = server.schedules.get_tasks(schedule_id)
assert [item.id for item in tasks.subscriptions] == ["sub-on-schedule"]
assert tasks.flow_tasks == []
assert flows not in [call.url for call in m.request_history]


def test_flow_tasks_missing_on_older_server(server: TSC.Server) -> None:
server.version = "2.4"
with requests_mock.mock() as m:
m.get(f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow", text=FLOW_TASKS_XML.read_text())
assert server.schedules.get_flow_tasks_by_schedule("sched-1") == []
assert m.request_history == []

server.version = "3.10"
with requests_mock.mock() as m:
m.get(
f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow",
status_code=404,
text=FLOW_MISSING_XML.read_text(),
)
assert server.schedules.get_flow_tasks_by_schedule("sched-1") == []


def test_flow_tasks_other_404_is_raised(server: TSC.Server) -> None:
server.version = "3.10"
with requests_mock.mock() as m:
m.get(
f"{server.baseurl}/sites/{server.site_id}/tasks/runFlow",
status_code=404,
text=FLOW_OTHER_404_XML.read_text(),
)
with pytest.raises(TSC.ServerResponseError) as raised:
server.schedules.get_flow_tasks_by_schedule("sched-1")
assert raised.value.code == "404000"