Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 8b4b153

Browse files
authored
Add admin API to get some information about federation status (#11407)
1 parent 494ebd7 commit 8b4b153

File tree

7 files changed

+783
-0
lines changed

7 files changed

+783
-0
lines changed

changelog.d/11407.feature

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add admin API to get some information about federation status with remote servers.

docs/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
- [Statistics](admin_api/statistics.md)
6666
- [Users](admin_api/user_admin_api.md)
6767
- [Server Version](admin_api/version_api.md)
68+
- [Federation](usage/administration/admin_api/federation.md)
6869
- [Manhole](manhole.md)
6970
- [Monitoring](metrics-howto.md)
7071
- [Understanding Synapse Through Grafana Graphs](usage/administration/understanding_synapse_through_grafana_graphs.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Federation API
2+
3+
This API allows a server administrator to manage Synapse's federation with other homeservers.
4+
5+
Note: This API is new, experimental and "subject to change".
6+
7+
## List of destinations
8+
9+
This API gets the current destination retry timing info for all remote servers.
10+
11+
The list contains all the servers with which the server federates,
12+
regardless of whether an error occurred or not.
13+
If an error occurs, it may take up to 20 minutes for the error to be displayed here,
14+
as a complete retry must have failed.
15+
16+
The API is:
17+
18+
A standard request with no filtering:
19+
20+
```
21+
GET /_synapse/admin/v1/federation/destinations
22+
```
23+
24+
A response body like the following is returned:
25+
26+
```json
27+
{
28+
"destinations":[
29+
{
30+
"destination": "matrix.org",
31+
"retry_last_ts": 1557332397936,
32+
"retry_interval": 3000000,
33+
"failure_ts": 1557329397936,
34+
"last_successful_stream_ordering": null
35+
}
36+
],
37+
"total": 1
38+
}
39+
```
40+
41+
To paginate, check for `next_token` and if present, call the endpoint again
42+
with `from` set to the value of `next_token`. This will return a new page.
43+
44+
If the endpoint does not return a `next_token` then there are no more destinations
45+
to paginate through.
46+
47+
**Parameters**
48+
49+
The following query parameters are available:
50+
51+
- `from` - Offset in the returned list. Defaults to `0`.
52+
- `limit` - Maximum amount of destinations to return. Defaults to `100`.
53+
- `order_by` - The method in which to sort the returned list of destinations.
54+
Valid values are:
55+
- `destination` - Destinations are ordered alphabetically by remote server name.
56+
This is the default.
57+
- `retry_last_ts` - Destinations are ordered by time of last retry attempt in ms.
58+
- `retry_interval` - Destinations are ordered by how long until next retry in ms.
59+
- `failure_ts` - Destinations are ordered by when the server started failing in ms.
60+
- `last_successful_stream_ordering` - Destinations are ordered by the stream ordering
61+
of the most recent successfully-sent PDU.
62+
- `dir` - Direction of room order. Either `f` for forwards or `b` for backwards. Setting
63+
this value to `b` will reverse the above sort order. Defaults to `f`.
64+
65+
*Caution:* The database only has an index on the column `destination`.
66+
This means that if a different sort order is used,
67+
this can cause a large load on the database, especially for large environments.
68+
69+
**Response**
70+
71+
The following fields are returned in the JSON response body:
72+
73+
- `destinations` - An array of objects, each containing information about a destination.
74+
Destination objects contain the following fields:
75+
- `destination` - string - Name of the remote server to federate.
76+
- `retry_last_ts` - integer - The last time Synapse tried and failed to reach the
77+
remote server, in ms. This is `0` if the last attempt to communicate with the
78+
remote server was successful.
79+
- `retry_interval` - integer - How long since the last time Synapse tried to reach
80+
the remote server before trying again, in ms. This is `0` if no further retrying occuring.
81+
- `failure_ts` - nullable integer - The first time Synapse tried and failed to reach the
82+
remote server, in ms. This is `null` if communication with the remote server has never failed.
83+
- `last_successful_stream_ordering` - nullable integer - The stream ordering of the most
84+
recent successfully-sent [PDU](understanding_synapse_through_grafana_graphs.md#federation)
85+
to this destination, or `null` if this information has not been tracked yet.
86+
- `next_token`: string representing a positive integer - Indication for pagination. See above.
87+
- `total` - integer - Total number of destinations.
88+
89+
# Destination Details API
90+
91+
This API gets the retry timing info for a specific remote server.
92+
93+
The API is:
94+
95+
```
96+
GET /_synapse/admin/v1/federation/destinations/<destination>
97+
```
98+
99+
A response body like the following is returned:
100+
101+
```json
102+
{
103+
"destination": "matrix.org",
104+
"retry_last_ts": 1557332397936,
105+
"retry_interval": 3000000,
106+
"failure_ts": 1557329397936,
107+
"last_successful_stream_ordering": null
108+
}
109+
```
110+
111+
**Response**
112+
113+
The response fields are the same like in the `destinations` array in
114+
[List of destinations](#list-of-destinations) response.

synapse/rest/admin/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@
4040
EventReportDetailRestServlet,
4141
EventReportsRestServlet,
4242
)
43+
from synapse.rest.admin.federation import (
44+
DestinationsRestServlet,
45+
ListDestinationsRestServlet,
46+
)
4347
from synapse.rest.admin.groups import DeleteGroupAdminRestServlet
4448
from synapse.rest.admin.media import ListMediaInRoom, register_servlets_for_media_repo
4549
from synapse.rest.admin.registration_tokens import (
@@ -261,6 +265,8 @@ def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
261265
ListRegistrationTokensRestServlet(hs).register(http_server)
262266
NewRegistrationTokenRestServlet(hs).register(http_server)
263267
RegistrationTokenRestServlet(hs).register(http_server)
268+
DestinationsRestServlet(hs).register(http_server)
269+
ListDestinationsRestServlet(hs).register(http_server)
264270

265271
# Some servlets only get registered for the main process.
266272
if hs.config.worker.worker_app is None:

synapse/rest/admin/federation.py

+135
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Copyright 2021 The Matrix.org Foundation C.I.C.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import logging
15+
from http import HTTPStatus
16+
from typing import TYPE_CHECKING, Tuple
17+
18+
from synapse.api.errors import Codes, NotFoundError, SynapseError
19+
from synapse.http.servlet import RestServlet, parse_integer, parse_string
20+
from synapse.http.site import SynapseRequest
21+
from synapse.rest.admin._base import admin_patterns, assert_requester_is_admin
22+
from synapse.storage.databases.main.transactions import DestinationSortOrder
23+
from synapse.types import JsonDict
24+
25+
if TYPE_CHECKING:
26+
from synapse.server import HomeServer
27+
28+
logger = logging.getLogger(__name__)
29+
30+
31+
class ListDestinationsRestServlet(RestServlet):
32+
"""Get request to list all destinations.
33+
This needs user to have administrator access in Synapse.
34+
35+
GET /_synapse/admin/v1/federation/destinations?from=0&limit=10
36+
37+
returns:
38+
200 OK with list of destinations if success otherwise an error.
39+
40+
The parameters `from` and `limit` are required only for pagination.
41+
By default, a `limit` of 100 is used.
42+
The parameter `destination` can be used to filter by destination.
43+
The parameter `order_by` can be used to order the result.
44+
"""
45+
46+
PATTERNS = admin_patterns("/federation/destinations$")
47+
48+
def __init__(self, hs: "HomeServer"):
49+
self._auth = hs.get_auth()
50+
self._store = hs.get_datastore()
51+
52+
async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
53+
await assert_requester_is_admin(self._auth, request)
54+
55+
start = parse_integer(request, "from", default=0)
56+
limit = parse_integer(request, "limit", default=100)
57+
58+
if start < 0:
59+
raise SynapseError(
60+
HTTPStatus.BAD_REQUEST,
61+
"Query parameter from must be a string representing a positive integer.",
62+
errcode=Codes.INVALID_PARAM,
63+
)
64+
65+
if limit < 0:
66+
raise SynapseError(
67+
HTTPStatus.BAD_REQUEST,
68+
"Query parameter limit must be a string representing a positive integer.",
69+
errcode=Codes.INVALID_PARAM,
70+
)
71+
72+
destination = parse_string(request, "destination")
73+
74+
order_by = parse_string(
75+
request,
76+
"order_by",
77+
default=DestinationSortOrder.DESTINATION.value,
78+
allowed_values=[dest.value for dest in DestinationSortOrder],
79+
)
80+
81+
direction = parse_string(request, "dir", default="f", allowed_values=("f", "b"))
82+
83+
destinations, total = await self._store.get_destinations_paginate(
84+
start, limit, destination, order_by, direction
85+
)
86+
response = {"destinations": destinations, "total": total}
87+
if (start + limit) < total:
88+
response["next_token"] = str(start + len(destinations))
89+
90+
return HTTPStatus.OK, response
91+
92+
93+
class DestinationsRestServlet(RestServlet):
94+
"""Get details of a destination.
95+
This needs user to have administrator access in Synapse.
96+
97+
GET /_synapse/admin/v1/federation/destinations/<destination>
98+
99+
returns:
100+
200 OK with details of a destination if success otherwise an error.
101+
"""
102+
103+
PATTERNS = admin_patterns("/federation/destinations/(?P<destination>[^/]+)$")
104+
105+
def __init__(self, hs: "HomeServer"):
106+
self._auth = hs.get_auth()
107+
self._store = hs.get_datastore()
108+
109+
async def on_GET(
110+
self, request: SynapseRequest, destination: str
111+
) -> Tuple[int, JsonDict]:
112+
await assert_requester_is_admin(self._auth, request)
113+
114+
destination_retry_timings = await self._store.get_destination_retry_timings(
115+
destination
116+
)
117+
118+
if not destination_retry_timings:
119+
raise NotFoundError("Unknown destination")
120+
121+
last_successful_stream_ordering = (
122+
await self._store.get_destination_last_successful_stream_ordering(
123+
destination
124+
)
125+
)
126+
127+
response = {
128+
"destination": destination,
129+
"failure_ts": destination_retry_timings.failure_ts,
130+
"retry_last_ts": destination_retry_timings.retry_last_ts,
131+
"retry_interval": destination_retry_timings.retry_interval,
132+
"last_successful_stream_ordering": last_successful_stream_ordering,
133+
}
134+
135+
return HTTPStatus.OK, response

synapse/storage/databases/main/transactions.py

+70
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import logging
1616
from collections import namedtuple
17+
from enum import Enum
1718
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
1819

1920
import attr
@@ -44,6 +45,16 @@
4445
)
4546

4647

48+
class DestinationSortOrder(Enum):
49+
"""Enum to define the sorting method used when returning destinations."""
50+
51+
DESTINATION = "destination"
52+
RETRY_LAST_TS = "retry_last_ts"
53+
RETTRY_INTERVAL = "retry_interval"
54+
FAILURE_TS = "failure_ts"
55+
LAST_SUCCESSFUL_STREAM_ORDERING = "last_successful_stream_ordering"
56+
57+
4758
@attr.s(slots=True, frozen=True, auto_attribs=True)
4859
class DestinationRetryTimings:
4960
"""The current destination retry timing info for a remote server."""
@@ -480,3 +491,62 @@ def _get_catch_up_outstanding_destinations_txn(
480491

481492
destinations = [row[0] for row in txn]
482493
return destinations
494+
495+
async def get_destinations_paginate(
496+
self,
497+
start: int,
498+
limit: int,
499+
destination: Optional[str] = None,
500+
order_by: str = DestinationSortOrder.DESTINATION.value,
501+
direction: str = "f",
502+
) -> Tuple[List[JsonDict], int]:
503+
"""Function to retrieve a paginated list of destinations.
504+
This will return a json list of destinations and the
505+
total number of destinations matching the filter criteria.
506+
507+
Args:
508+
start: start number to begin the query from
509+
limit: number of rows to retrieve
510+
destination: search string in destination
511+
order_by: the sort order of the returned list
512+
direction: sort ascending or descending
513+
Returns:
514+
A tuple of a list of mappings from destination to information
515+
and a count of total destinations.
516+
"""
517+
518+
def get_destinations_paginate_txn(
519+
txn: LoggingTransaction,
520+
) -> Tuple[List[JsonDict], int]:
521+
order_by_column = DestinationSortOrder(order_by).value
522+
523+
if direction == "b":
524+
order = "DESC"
525+
else:
526+
order = "ASC"
527+
528+
args = []
529+
where_statement = ""
530+
if destination:
531+
args.extend(["%" + destination.lower() + "%"])
532+
where_statement = "WHERE LOWER(destination) LIKE ?"
533+
534+
sql_base = f"FROM destinations {where_statement} "
535+
sql = f"SELECT COUNT(*) as total_destinations {sql_base}"
536+
txn.execute(sql, args)
537+
count = txn.fetchone()[0]
538+
539+
sql = f"""
540+
SELECT destination, retry_last_ts, retry_interval, failure_ts,
541+
last_successful_stream_ordering
542+
{sql_base}
543+
ORDER BY {order_by_column} {order}, destination ASC
544+
LIMIT ? OFFSET ?
545+
"""
546+
txn.execute(sql, args + [limit, start])
547+
destinations = self.db_pool.cursor_to_dict(txn)
548+
return destinations, count
549+
550+
return await self.db_pool.runInteraction(
551+
"get_destinations_paginate_txn", get_destinations_paginate_txn
552+
)

0 commit comments

Comments
 (0)