| 1 |
Metadata-Version: 2.1 |
| 2 |
Name: taskcluster |
| 3 |
Version: 75.0.1 |
| 4 |
Summary: Python client for Taskcluster |
| 5 |
Home-page: https://github.com/taskcluster/taskcluster |
| 6 |
Author: Mozilla Taskcluster and Release Engineering |
| 7 |
Author-email: [email protected] |
| 8 |
Classifier: Programming Language :: Python :: 3.8 |
| 9 |
Classifier: Programming Language :: Python :: 3.9 |
| 10 |
Classifier: Programming Language :: Python :: 3.10 |
| 11 |
Classifier: Programming Language :: Python :: 3.11 |
| 12 |
Description-Content-Type: text/markdown |
| 13 |
License-File: LICENSE |
| 14 |
Requires-Dist: requests>=2.4.3 |
| 15 |
Requires-Dist: mohawk>=0.3.4 |
| 16 |
Requires-Dist: python-dateutil>=2.8.2 |
| 17 |
Requires-Dist: slugid>=2 |
| 18 |
Requires-Dist: taskcluster-urls>=12.1.0 |
| 19 |
Requires-Dist: aiohttp>=3.7.4 |
| 20 |
Requires-Dist: async_timeout>=2.0.0 |
| 21 |
Provides-Extra: test |
| 22 |
Requires-Dist: pytest; extra == "test" |
| 23 |
Requires-Dist: pytest-cov; extra == "test" |
| 24 |
Requires-Dist: pytest-mock; extra == "test" |
| 25 |
Requires-Dist: pytest-asyncio; extra == "test" |
| 26 |
Requires-Dist: httmock; extra == "test" |
| 27 |
Requires-Dist: mock; extra == "test" |
| 28 |
Requires-Dist: setuptools-lint; extra == "test" |
| 29 |
Requires-Dist: flake8; extra == "test" |
| 30 |
Requires-Dist: psutil; extra == "test" |
| 31 |
Requires-Dist: hypothesis; extra == "test" |
| 32 |
Requires-Dist: tox; extra == "test" |
| 33 |
Requires-Dist: coverage; extra == "test" |
| 34 |
Requires-Dist: aiofiles; extra == "test" |
| 35 |
Requires-Dist: httptest; extra == "test" |
| 36 |
|
| 37 |
# Taskcluster Client for Python |
| 38 |
|
| 39 |
[](https://pypi.python.org/pypi/taskcluster) |
| 40 |
[](http://mozilla.org/MPL/2.0) |
| 41 |
|
| 42 |
**A Taskcluster client library for Python.** |
| 43 |
|
| 44 |
This library is a complete interface to Taskcluster in Python. It provides |
| 45 |
both synchronous and asynchronous interfaces for all Taskcluster API methods. |
| 46 |
|
| 47 |
## Usage |
| 48 |
|
| 49 |
For a general guide to using Taskcluster clients, see [Calling Taskcluster APIs](https://docs.taskcluster.net/docs/manual/using/api). |
| 50 |
|
| 51 |
### Setup |
| 52 |
|
| 53 |
Before calling an API end-point, you'll need to create a client instance. |
| 54 |
There is a class for each service, e.g., `Queue` and `Auth`. Each takes the |
| 55 |
same options, described below. Note that only `rootUrl` is |
| 56 |
required, and it's unusual to configure any other options aside from |
| 57 |
`credentials`. |
| 58 |
|
| 59 |
For each service, there are sync and async variants. The classes under |
| 60 |
`taskcluster` (e.g., `taskcluster.Queue`) operate synchronously. The classes |
| 61 |
under `taskcluster.aio` (e.g., `taskcluster.aio.Queue`) are asynchronous. |
| 62 |
|
| 63 |
#### Authentication Options |
| 64 |
|
| 65 |
Here is a simple set-up of an Index client: |
| 66 |
|
| 67 |
```python |
| 68 |
import taskcluster |
| 69 |
index = taskcluster.Index({ |
| 70 |
'rootUrl': 'https://tc.example.com', |
| 71 |
'credentials': {'clientId': 'id', 'accessToken': 'accessToken'}, |
| 72 |
}) |
| 73 |
``` |
| 74 |
|
| 75 |
The `rootUrl` option is required as it gives the Taskcluster deployment to |
| 76 |
which API requests should be sent. Credentials are only required if the |
| 77 |
request is to be authenticated -- many Taskcluster API methods do not require |
| 78 |
authentication. |
| 79 |
|
| 80 |
In most cases, the root URL and Taskcluster credentials should be provided in [standard environment variables](https://docs.taskcluster.net/docs/manual/design/env-vars). Use `taskcluster.optionsFromEnvironment()` to read these variables automatically: |
| 81 |
|
| 82 |
```python |
| 83 |
auth = taskcluster.Auth(taskcluster.optionsFromEnvironment()) |
| 84 |
``` |
| 85 |
|
| 86 |
Note that this function does not respect `TASKCLUSTER_PROXY_URL`. To use the Taskcluster Proxy from within a task: |
| 87 |
|
| 88 |
```python |
| 89 |
auth = taskcluster.Auth({'rootUrl': os.environ['TASKCLUSTER_PROXY_URL']}) |
| 90 |
``` |
| 91 |
|
| 92 |
#### Authorized Scopes |
| 93 |
|
| 94 |
If you wish to perform requests on behalf of a third-party that has small set |
| 95 |
of scopes than you do. You can specify [which scopes your request should be |
| 96 |
allowed to |
| 97 |
use](https://docs.taskcluster.net/docs/manual/design/apis/hawk/authorized-scopes), |
| 98 |
in the `authorizedScopes` option. |
| 99 |
|
| 100 |
```python |
| 101 |
opts = taskcluster.optionsFromEnvironment() |
| 102 |
opts['authorizedScopes'] = ['queue:create-task:highest:my-provisioner/my-worker-type'] |
| 103 |
queue = taskcluster.Queue(opts) |
| 104 |
``` |
| 105 |
|
| 106 |
#### Other Options |
| 107 |
|
| 108 |
The following additional options are accepted when constructing a client object: |
| 109 |
|
| 110 |
* `signedUrlExpiration` - default value for the `expiration` argument to `buildSignedUrl` |
| 111 |
* `maxRetries` - maximum number of times to retry a failed request |
| 112 |
|
| 113 |
### Calling API Methods |
| 114 |
|
| 115 |
API methods are available as methods on the corresponding client object. For |
| 116 |
sync clients, these are sync methods, and for async clients they are async |
| 117 |
methods; the calling convention is the same in either case. |
| 118 |
|
| 119 |
There are four calling conventions for methods: |
| 120 |
|
| 121 |
```python |
| 122 |
client.method(v1, v1, payload) |
| 123 |
client.method(payload, k1=v1, k2=v2) |
| 124 |
client.method(payload=payload, query=query, params={k1: v1, k2: v2}) |
| 125 |
client.method(v1, v2, payload=payload, query=query) |
| 126 |
``` |
| 127 |
|
| 128 |
Here, `v1` and `v2` are URL parameters (named `k1` and `k2`), `payload` is the |
| 129 |
request payload, and `query` is a dictionary of query arguments. |
| 130 |
|
| 131 |
For example, in order to call an API method with query-string arguments: |
| 132 |
|
| 133 |
```python |
| 134 |
await queue.listTaskGroup('JzTGxwxhQ76_Tt1dxkaG5g', |
| 135 |
query={'continuationToken': previousResponse.get('continuationToken')}) |
| 136 |
``` |
| 137 |
|
| 138 |
|
| 139 |
### Generating URLs |
| 140 |
|
| 141 |
It is often necessary to generate the URL for an API method without actually calling the method. |
| 142 |
To do so, use `buildUrl` or, for an API method that requires authentication, `buildSignedUrl`. |
| 143 |
|
| 144 |
```python |
| 145 |
import taskcluster |
| 146 |
|
| 147 |
index = taskcluster.Index(taskcluster.optionsFromEnvironment()) |
| 148 |
print(index.buildUrl('findTask', 'builds.v1.latest')) |
| 149 |
secrets = taskcluster.Secrets(taskcluster.optionsFromEnvironment()) |
| 150 |
print(secret.buildSignedUrl('get', 'my-secret')) |
| 151 |
``` |
| 152 |
|
| 153 |
Note that signed URLs are time-limited; the expiration can be set with the `signedUrlExpiration` option to the client constructor, or with the `expiration` keyword arguement to `buildSignedUrl`, both given in seconds. |
| 154 |
|
| 155 |
### Generating Temporary Credentials |
| 156 |
|
| 157 |
If you have non-temporary taskcluster credentials you can generate a set of |
| 158 |
[temporary credentials](https://docs.taskcluster.net/docs/manual/design/apis/hawk/temporary-credentials) as follows. Notice that the credentials cannot last more |
| 159 |
than 31 days, and you can only revoke them by revoking the credentials that was |
| 160 |
used to issue them (this takes up to one hour). |
| 161 |
|
| 162 |
It is not the responsibility of the caller to apply any clock drift adjustment |
| 163 |
to the start or expiry time - this is handled by the auth service directly. |
| 164 |
|
| 165 |
```python |
| 166 |
import datetime |
| 167 |
|
| 168 |
start = datetime.datetime.now() |
| 169 |
expiry = start + datetime.timedelta(0,60) |
| 170 |
scopes = ['ScopeA', 'ScopeB'] |
| 171 |
name = 'foo' |
| 172 |
|
| 173 |
credentials = taskcluster.createTemporaryCredentials( |
| 174 |
# issuing clientId |
| 175 |
clientId, |
| 176 |
# issuing accessToken |
| 177 |
accessToken, |
| 178 |
# Validity of temporary credentials starts here, in timestamp |
| 179 |
start, |
| 180 |
# Expiration of temporary credentials, in timestamp |
| 181 |
expiry, |
| 182 |
# Scopes to grant the temporary credentials |
| 183 |
scopes, |
| 184 |
# credential name (optional) |
| 185 |
name |
| 186 |
) |
| 187 |
``` |
| 188 |
|
| 189 |
You cannot use temporary credentials to issue new temporary credentials. You |
| 190 |
must have `auth:create-client:<name>` to create a named temporary credential, |
| 191 |
but unnamed temporary credentials can be created regardless of your scopes. |
| 192 |
|
| 193 |
### Handling Timestamps |
| 194 |
Many taskcluster APIs require ISO 8601 time stamps offset into the future |
| 195 |
as way of providing expiration, deadlines, etc. These can be easily created |
| 196 |
using `datetime.datetime.isoformat()`, however, it can be rather error prone |
| 197 |
and tedious to offset `datetime.datetime` objects into the future. Therefore |
| 198 |
this library comes with two utility functions for this purposes. |
| 199 |
|
| 200 |
```python |
| 201 |
dateObject = taskcluster.fromNow("2 days 3 hours 1 minute") |
| 202 |
# -> datetime.datetime(2017, 1, 21, 17, 8, 1, 607929) |
| 203 |
dateString = taskcluster.fromNowJSON("2 days 3 hours 1 minute") |
| 204 |
# -> '2017-01-21T17:09:23.240178Z' |
| 205 |
``` |
| 206 |
|
| 207 |
By default it will offset the date time into the future, if the offset strings |
| 208 |
are prefixed minus (`-`) the date object will be offset into the past. This is |
| 209 |
useful in some corner cases. |
| 210 |
|
| 211 |
```python |
| 212 |
dateObject = taskcluster.fromNow("- 1 year 2 months 3 weeks 5 seconds"); |
| 213 |
# -> datetime.datetime(2015, 10, 30, 18, 16, 50, 931161) |
| 214 |
``` |
| 215 |
|
| 216 |
The offset string is ignorant of whitespace and case insensitive. It may also |
| 217 |
optionally be prefixed plus `+` (if not prefixed minus), any `+` prefix will be |
| 218 |
ignored. However, entries in the offset string must be given in order from |
| 219 |
high to low, ie. `2 years 1 day`. Additionally, various shorthands may be |
| 220 |
employed, as illustrated below. |
| 221 |
|
| 222 |
``` |
| 223 |
years, year, yr, y |
| 224 |
months, month, mo |
| 225 |
weeks, week, w |
| 226 |
days, day, d |
| 227 |
hours, hour, h |
| 228 |
minutes, minute, min |
| 229 |
seconds, second, sec, s |
| 230 |
``` |
| 231 |
|
| 232 |
The `fromNow` method may also be given a date to be relative to as a second |
| 233 |
argument. This is useful if offset the task expiration relative to the the task |
| 234 |
deadline or doing something similar. This argument can also be passed as the |
| 235 |
kwarg `dateObj` |
| 236 |
|
| 237 |
```python |
| 238 |
dateObject1 = taskcluster.fromNow("2 days 3 hours"); |
| 239 |
dateObject2 = taskcluster.fromNow("1 year", dateObject1); |
| 240 |
taskcluster.fromNow("1 year", dateObj=dateObject1); |
| 241 |
# -> datetime.datetime(2018, 1, 21, 17, 59, 0, 328934) |
| 242 |
``` |
| 243 |
### Generating SlugIDs |
| 244 |
|
| 245 |
To generate slugIds (Taskcluster's client-generated unique IDs), use |
| 246 |
`taskcluster.slugId()`, which will return a unique slugId on each call. |
| 247 |
|
| 248 |
In some cases it is useful to be able to create a mapping from names to |
| 249 |
slugIds, with the ability to generate the same slugId multiple times. |
| 250 |
The `taskcluster.stableSlugId()` function returns a callable that does |
| 251 |
just this. |
| 252 |
|
| 253 |
```python |
| 254 |
gen = taskcluster.stableSlugId() |
| 255 |
sometask = gen('sometask') |
| 256 |
assert gen('sometask') == sometask # same input generates same output |
| 257 |
assert gen('sometask') != gen('othertask') |
| 258 |
|
| 259 |
gen2 = taskcluster.stableSlugId() |
| 260 |
sometask2 = gen('sometask') |
| 261 |
assert sometask2 != sometask # but different slugId generators produce |
| 262 |
# different output |
| 263 |
``` |
| 264 |
|
| 265 |
### Scope Analysis |
| 266 |
|
| 267 |
The `scopeMatch(assumedScopes, requiredScopeSets)` function determines |
| 268 |
whether one or more of a set of required scopes are satisfied by the assumed |
| 269 |
scopes, taking *-expansion into account. This is useful for making local |
| 270 |
decisions on scope satisfaction, but note that `assumed_scopes` must be the |
| 271 |
*expanded* scopes, as this function cannot perform expansion. |
| 272 |
|
| 273 |
It takes a list of a assumed scopes, and a list of required scope sets on |
| 274 |
disjunctive normal form, and checks if any of the required scope sets are |
| 275 |
satisfied. |
| 276 |
|
| 277 |
Example: |
| 278 |
|
| 279 |
```python |
| 280 |
requiredScopeSets = [ |
| 281 |
["scopeA", "scopeB"], |
| 282 |
["scopeC:*"] |
| 283 |
] |
| 284 |
assert scopesMatch(['scopeA', 'scopeB'], requiredScopeSets) |
| 285 |
assert scopesMatch(['scopeC:xyz'], requiredScopeSets) |
| 286 |
assert not scopesMatch(['scopeA'], requiredScopeSets) |
| 287 |
assert not scopesMatch(['scopeC'], requiredScopeSets) |
| 288 |
``` |
| 289 |
|
| 290 |
### Pagination |
| 291 |
|
| 292 |
Many Taskcluster API methods are paginated. There are two ways to handle |
| 293 |
pagination easily with the python client. The first is to implement pagination |
| 294 |
in your code: |
| 295 |
|
| 296 |
```python |
| 297 |
import taskcluster |
| 298 |
queue = taskcluster.Queue({'rootUrl': 'https://tc.example.com'}) |
| 299 |
i = 0 |
| 300 |
tasks = 0 |
| 301 |
outcome = queue.listTaskGroup('JzTGxwxhQ76_Tt1dxkaG5g') |
| 302 |
while outcome.get('continuationToken'): |
| 303 |
print('Response %d gave us %d more tasks' % (i, len(outcome['tasks']))) |
| 304 |
if outcome.get('continuationToken'): |
| 305 |
outcome = queue.listTaskGroup('JzTGxwxhQ76_Tt1dxkaG5g', query={'continuationToken': outcome.get('continuationToken')}) |
| 306 |
i += 1 |
| 307 |
tasks += len(outcome.get('tasks', [])) |
| 308 |
print('Task Group %s has %d tasks' % (outcome['taskGroupId'], tasks)) |
| 309 |
``` |
| 310 |
|
| 311 |
There's also an experimental feature to support built in automatic pagination |
| 312 |
in the sync client. This feature allows passing a callback as the |
| 313 |
'paginationHandler' keyword-argument. This function will be passed the |
| 314 |
response body of the API method as its sole positional arugment. |
| 315 |
|
| 316 |
This example of the built in pagination shows how a list of tasks could be |
| 317 |
built and then counted: |
| 318 |
|
| 319 |
```python |
| 320 |
import taskcluster |
| 321 |
queue = taskcluster.Queue({'rootUrl': 'https://tc.example.com'}) |
| 322 |
|
| 323 |
responses = [] |
| 324 |
|
| 325 |
def handle_page(y): |
| 326 |
print("%d tasks fetched" % len(y.get('tasks', []))) |
| 327 |
responses.append(y) |
| 328 |
|
| 329 |
queue.listTaskGroup('JzTGxwxhQ76_Tt1dxkaG5g', paginationHandler=handle_page) |
| 330 |
|
| 331 |
tasks = 0 |
| 332 |
for response in responses: |
| 333 |
tasks += len(response.get('tasks', [])) |
| 334 |
|
| 335 |
print("%d requests fetch %d tasks" % (len(responses), tasks)) |
| 336 |
``` |
| 337 |
|
| 338 |
### Pulse Events |
| 339 |
|
| 340 |
This library can generate exchange patterns for Pulse messages based on the |
| 341 |
Exchanges definitions provded by each service. This is done by instantiating a |
| 342 |
`<service>Events` class and calling a method with the name of the vent. |
| 343 |
Options for the topic exchange methods can be in the form of either a single |
| 344 |
dictionary argument or keyword arguments. Only one form is allowed. |
| 345 |
|
| 346 |
```python |
| 347 |
from taskcluster import client |
| 348 |
qEvt = client.QueueEvents({rootUrl: 'https://tc.example.com'}) |
| 349 |
# The following calls are equivalent |
| 350 |
print(qEvt.taskCompleted({'taskId': 'atask'})) |
| 351 |
print(qEvt.taskCompleted(taskId='atask')) |
| 352 |
``` |
| 353 |
|
| 354 |
Note that the client library does *not* provide support for interfacing with a Pulse server. |
| 355 |
|
| 356 |
### Logging |
| 357 |
|
| 358 |
Logging is set up in `taskcluster/__init__.py`. If the special |
| 359 |
`DEBUG_TASKCLUSTER_CLIENT` environment variable is set, the `__init__.py` |
| 360 |
module will set the `logging` module's level for its logger to `logging.DEBUG` |
| 361 |
and if there are no existing handlers, add a `logging.StreamHandler()` |
| 362 |
instance. This is meant to assist those who do not wish to bother figuring out |
| 363 |
how to configure the python logging module but do want debug messages |
| 364 |
|
| 365 |
## Uploading and Downloading Objects |
| 366 |
|
| 367 |
The Object service provides an API for reliable uploads and downloads of large objects. |
| 368 |
This library provides convenience methods to implement the client portion of those APIs, providing well-tested, resilient upload and download functionality. |
| 369 |
These methods will negotiate the appropriate method with the object service and perform the required steps to transfer the data. |
| 370 |
|
| 371 |
All methods are available in both sync and async versions, with identical APIs except for the `async`/`await` keywords. |
| 372 |
|
| 373 |
In either case, you will need to provide a configured `Object` instance with appropriate credentials for the operation. |
| 374 |
|
| 375 |
NOTE: There is an helper function to upload `s3` artifacts, `taskcluster.helper.upload_artifact`, but it is deprecated as it only supports the `s3` artifact type. |
| 376 |
|
| 377 |
### Uploads |
| 378 |
|
| 379 |
To upload, use any of the following: |
| 380 |
|
| 381 |
* `await taskcluster.aio.upload.uploadFromBuf(projectId=.., name=.., contentType=.., contentLength=.., uploadId=.., expires=.., maxRetries=.., objectService=.., data=..)` - asynchronously upload data from a buffer full of bytes. |
| 382 |
* `await taskcluster.aio.upload.uploadFromFile(projectId=.., name=.., contentType=.., contentLength=.., uploadId=.., expires=.., maxRetries=.., objectService=.., file=..)` - asynchronously upload data from a standard Python file. |
| 383 |
Note that this is [probably what you want](https://github.com/python/asyncio/wiki/ThirdParty#filesystem), even in an async context. |
| 384 |
* `await taskcluster.aio.upload(projectId=.., name=.., contentType=.., contentLength=.., expires=.., uploadId=.., maxRetries=.., objectService=.., readerFactory=..)` - asynchronously upload data from an async reader factory. |
| 385 |
* `taskcluster.upload.uploadFromBuf(projectId=.., name=.., contentType=.., contentLength=.., expires=.., uploadId=.., maxRetries=.., objectService=.., data=..)` - upload data from a buffer full of bytes. |
| 386 |
* `taskcluster.upload.uploadFromFile(projectId=.., name=.., contentType=.., contentLength=.., expires=.., uploadId=.., maxRetries=.., objectService=.., file=..)` - upload data from a standard Python file. |
| 387 |
* `taskcluster.upload(projectId=.., name=.., contentType=.., contentLength=.., expires=.., uploadId=.., maxRetries=.., objectService=.., readerFactory=..)` - upload data from a sync reader factory. |
| 388 |
|
| 389 |
A "reader" is an object with a `read(max_size=-1)` method which reads and returns a chunk of 1 .. `max_size` bytes, or returns an empty string at EOF, async for the async functions and sync for the remainder. |
| 390 |
A "reader factory" is an async callable which returns a fresh reader, ready to read the first byte of the object. |
| 391 |
When uploads are retried, the reader factory may be called more than once. |
| 392 |
|
| 393 |
The `uploadId` parameter may be omitted, in which case a new slugId will be generated. |
| 394 |
|
| 395 |
### Downloads |
| 396 |
|
| 397 |
To download, use any of the following: |
| 398 |
|
| 399 |
* `await taskcluster.aio.download.downloadToBuf(name=.., maxRetries=.., objectService=..)` - asynchronously download an object to an in-memory buffer, returning a tuple (buffer, content-type). |
| 400 |
If the file is larger than available memory, this will crash. |
| 401 |
* `await taskcluster.aio.download.downloadToFile(name=.., maxRetries=.., objectService=.., file=..)` - asynchronously download an object to a standard Python file, returning the content type. |
| 402 |
* `await taskcluster.aio.download.download(name=.., maxRetries=.., objectService=.., writerFactory=..)` - asynchronously download an object to an async writer factory, returning the content type. |
| 403 |
* `taskcluster.download.downloadToBuf(name=.., maxRetries=.., objectService=..)` - download an object to an in-memory buffer, returning a tuple (buffer, content-type). |
| 404 |
If the file is larger than available memory, this will crash. |
| 405 |
* `taskcluster.download.downloadToFile(name=.., maxRetries=.., objectService=.., file=..)` - download an object to a standard Python file, returning the content type. |
| 406 |
* `taskcluster.download.download(name=.., maxRetries=.., objectService=.., writerFactory=..)` - download an object to a sync writer factory, returning the content type. |
| 407 |
|
| 408 |
A "writer" is an object with a `write(data)` method which writes the given data, async for the async functions and sync for the remainder. |
| 409 |
A "writer factory" is a callable (again either async or sync) which returns a fresh writer, ready to write the first byte of the object. |
| 410 |
When uploads are retried, the writer factory may be called more than once. |
| 411 |
|
| 412 |
### Artifact Downloads |
| 413 |
|
| 414 |
Artifacts can be downloaded from the queue service with similar functions to those above. |
| 415 |
These functions support all of the queue's storage types, raising an error for `error` artifacts. |
| 416 |
In each case, if `runId` is omitted then the most recent run will be used. |
| 417 |
|
| 418 |
* `await taskcluster.aio.download.downloadArtifactToBuf(taskId=.., runId=.., name=.., maxRetries=.., queueService=..)` - asynchronously download an object to an in-memory buffer, returning a tuple (buffer, content-type). |
| 419 |
If the file is larger than available memory, this will crash. |
| 420 |
* `await taskcluster.aio.download.downloadArtifactToFile(taskId=.., runId=.., name=.., maxRetries=.., queueService=.., file=..)` - asynchronously download an object to a standard Python file, returning the content type. |
| 421 |
* `await taskcluster.aio.download.downloadArtifact(taskId=.., runId=.., name=.., maxRetries=.., queueService=.., writerFactory=..)` - asynchronously download an object to an async writer factory, returning the content type. |
| 422 |
* `taskcluster.download.downloadArtifactToBuf(taskId=.., runId=.., name=.., maxRetries=.., queueService=..)` - download an object to an in-memory buffer, returning a tuple (buffer, content-type). |
| 423 |
If the file is larger than available memory, this will crash. |
| 424 |
* `taskcluster.download.downloadArtifactToFile(taskId=.., runId=.., name=.., maxRetries=.., queueService=.., file=..)` - download an object to a standard Python file, returning the content type. |
| 425 |
* `taskcluster.download.downloadArtifact(taskId=.., runId=.., name=.., maxRetries=.., queueService=.., writerFactory=..)` - download an object to a sync writer factory, returning the content type. |
| 426 |
|
| 427 |
## Integration Helpers |
| 428 |
|
| 429 |
The Python Taskcluster client has a module `taskcluster.helper` with utilities which allows you to easily share authentication options across multiple services in your project. |
| 430 |
|
| 431 |
Generally a project using this library will face different use cases and authentication options: |
| 432 |
|
| 433 |
* No authentication for a new contributor without Taskcluster access, |
| 434 |
* Specific client credentials through environment variables on a developer's computer, |
| 435 |
* Taskcluster Proxy when running inside a task. |
| 436 |
|
| 437 |
### Shared authentication |
| 438 |
|
| 439 |
The class `taskcluster.helper.TaskclusterConfig` is made to be instantiated once in your project, usually in a top level module. That singleton is then accessed by different parts of your projects, whenever a Taskcluster service is needed. |
| 440 |
|
| 441 |
Here is a sample usage: |
| 442 |
|
| 443 |
1. in `project/__init__.py`, no call to Taskcluster is made at that point: |
| 444 |
|
| 445 |
```python |
| 446 |
from taskcluster.helper import Taskcluster config |
| 447 |
|
| 448 |
tc = TaskclusterConfig('https://community-tc.services.mozilla.com') |
| 449 |
``` |
| 450 |
|
| 451 |
2. in `project/boot.py`, we authenticate on Taskcuster with provided credentials, or environment variables, or taskcluster proxy (in that order): |
| 452 |
|
| 453 |
```python |
| 454 |
from project import tc |
| 455 |
|
| 456 |
tc.auth(client_id='XXX', access_token='YYY') |
| 457 |
``` |
| 458 |
|
| 459 |
3. at that point, you can load any service using the authenticated wrapper from anywhere in your code: |
| 460 |
|
| 461 |
```python |
| 462 |
from project import tc |
| 463 |
|
| 464 |
def sync_usage(): |
| 465 |
queue = tc.get_service('queue') |
| 466 |
queue.ping() |
| 467 |
|
| 468 |
async def async_usage(): |
| 469 |
hooks = tc.get_service('hooks', use_async=True) # Asynchronous service class |
| 470 |
await hooks.ping() |
| 471 |
``` |
| 472 |
|
| 473 |
Supported environment variables are: |
| 474 |
- `TASKCLUSTER_ROOT_URL` to specify your Taskcluster instance base url. You can either use that variable or instanciate `TaskclusterConfig` with the base url. |
| 475 |
- `TASKCLUSTER_CLIENT_ID` & `TASKCLUSTER_ACCESS_TOKEN` to specify your client credentials instead of providing them to `TaskclusterConfig.auth` |
| 476 |
- `TASKCLUSTER_PROXY_URL` to specify the proxy address used to reach Taskcluster in a task. It defaults to `http://taskcluster` when not specified. |
| 477 |
|
| 478 |
For more details on Taskcluster environment variables, [here is the documentation](https://docs.taskcluster.net/docs/manual/design/env-vars). |
| 479 |
|
| 480 |
### Loading secrets across multiple authentications |
| 481 |
|
| 482 |
Another available utility is `taskcluster.helper.load_secrets` which allows you to retrieve a secret using an authenticated `taskcluster.Secrets` instance (using `TaskclusterConfig.get_service` or the synchronous class directly). |
| 483 |
|
| 484 |
This utility loads a secret, but allows you to: |
| 485 |
1. share a secret across multiple projects, by using key prefixes inside the secret, |
| 486 |
2. check that some required keys are present in the secret, |
| 487 |
3. provide some default values, |
| 488 |
4. provide a local secret source instead of using the Taskcluster service (useful for local development or sharing _secrets_ with contributors) |
| 489 |
|
| 490 |
Let's say you have a secret on a Taskcluster instance named `project/foo/prod-config`, which is needed by a backend and some tasks. Here is its content: |
| 491 |
|
| 492 |
```yaml |
| 493 |
common: |
| 494 |
environment: production |
| 495 |
remote_log: https://log.xx.com/payload |
| 496 |
|
| 497 |
backend: |
| 498 |
bugzilla_token: XXXX |
| 499 |
|
| 500 |
task: |
| 501 |
backend_url: https://backend.foo.mozilla.com |
| 502 |
``` |
| 503 |
|
| 504 |
In your backend, you would do: |
| 505 |
|
| 506 |
```python |
| 507 |
from taskcluster import Secrets |
| 508 |
from taskcluster.helper import load_secrets |
| 509 |
|
| 510 |
prod_config = load_secrets( |
| 511 |
Secrets({...}), |
| 512 |
'project/foo/prod-config', |
| 513 |
|
| 514 |
# We only need the common & backend parts |
| 515 |
prefixes=['common', 'backend'], |
| 516 |
|
| 517 |
# We absolutely need a bugzilla token to run |
| 518 |
required=['bugzilla_token'], |
| 519 |
|
| 520 |
# Let's provide some default value for the environment |
| 521 |
existing={ |
| 522 |
'environment': 'dev', |
| 523 |
} |
| 524 |
) |
| 525 |
# -> prod_config == { |
| 526 |
# "environment": "production" |
| 527 |
# "remote_log": "https://log.xx.com/payload", |
| 528 |
# "bugzilla_token": "XXXX", |
| 529 |
# } |
| 530 |
``` |
| 531 |
|
| 532 |
In your task, you could do the following using `TaskclusterConfig` mentionned above (the class has a shortcut to use an authenticated `Secrets` service automatically): |
| 533 |
|
| 534 |
```python |
| 535 |
from project import tc |
| 536 |
|
| 537 |
prod_config = tc.load_secrets( |
| 538 |
'project/foo/prod-config', |
| 539 |
|
| 540 |
# We only need the common & bot parts |
| 541 |
prefixes=['common', 'bot'], |
| 542 |
|
| 543 |
# Let's provide some default value for the environment and backend_url |
| 544 |
existing={ |
| 545 |
'environment': 'dev', |
| 546 |
'backend_url': 'http://localhost:8000', |
| 547 |
} |
| 548 |
) |
| 549 |
# -> prod_config == { |
| 550 |
# "environment": "production" |
| 551 |
# "remote_log": "https://log.xx.com/payload", |
| 552 |
# "backend_url": "https://backend.foo.mozilla.com", |
| 553 |
# } |
| 554 |
``` |
| 555 |
|
| 556 |
To provide local secrets value, you first need to load these values as a dictionary (usually by reading a local file in your format of choice : YAML, JSON, ...) and providing the dictionary to `load_secrets` by using the `local_secrets` parameter: |
| 557 |
|
| 558 |
```python |
| 559 |
import os |
| 560 |
import yaml |
| 561 |
|
| 562 |
from taskcluster import Secrets |
| 563 |
from taskcluster.helper import load_secrets |
| 564 |
|
| 565 |
local_path = 'path/to/file.yml' |
| 566 |
|
| 567 |
prod_config = load_secrets( |
| 568 |
Secrets({...}), |
| 569 |
'project/foo/prod-config', |
| 570 |
|
| 571 |
# We support an optional local file to provide some configuration without reaching Taskcluster |
| 572 |
local_secrets=yaml.safe_load(open(local_path)) if os.path.exists(local_path) else None, |
| 573 |
) |
| 574 |
``` |
| 575 |
|
| 576 |
## Compatibility |
| 577 |
|
| 578 |
This library is co-versioned with Taskcluster itself. |
| 579 |
That is, a client with version x.y.z contains API methods corresponding to Taskcluster version x.y.z. |
| 580 |
Taskcluster is careful to maintain API compatibility, and guarantees it within a major version. |
| 581 |
That means that any client with version x.* will work against any Taskcluster services at version x.*, and is very likely to work for many other major versions of the Taskcluster services. |
| 582 |
Any incompatibilities are noted in the [Changelog](https://github.com/taskcluster/taskcluster/blob/main/CHANGELOG.md). |