Coverage for pyTooling/GitLab/Tracing.py: 97%

198 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 03:23 +0000

1# ==================================================================================================================== # 

2# _____ _ _ ____ _ _ _ _ # 

3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___(_) |_| | __ _| |__ # 

4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | _| | __| | / _` | '_ \ # 

5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |_| | | |_| |__| (_| | |_) | # 

6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_|\__|_____\__,_|_.__/ # 

7# |_| |___/ |___/ # 

8# ==================================================================================================================== # 

9# Authors: # 

10# Patrick Lehmann # 

11# # 

12# License: # 

13# ==================================================================================================================== # 

14# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # 

15# # 

16# Licensed under the Apache License, Version 2.0 (the "License"); # 

17# you may not use this file except in compliance with the License. # 

18# You may obtain a copy of the License at # 

19# # 

20# http://www.apache.org/licenses/LICENSE-2.0 # 

21# # 

22# Unless required by applicable law or agreed to in writing, software # 

23# distributed under the License is distributed on an "AS IS" BASIS, # 

24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

25# See the License for the specific language governing permissions and # 

26# limitations under the License. # 

27# # 

28# SPDX-License-Identifier: Apache-2.0 # 

29# ==================================================================================================================== # 

30# 

31""" 

32Read the timing of a GitLab CI/CD pipeline into a software execution trace. 

33 

34A pipeline becomes a :class:`~pyTooling.Tracing.Trace`, and each job a :class:`~pyTooling.Tracing.Span`. The time a job 

35waited for a runner is a separate timespan in front of the job. The instances of a matrix are grouped below a timespan 

36named like the job, and the jobs of a child pipeline below a timespan named like the trigger job. 

37 

38.. code-block:: python 

39 

40 from os import getenv 

41 from pyTooling.GitLab.Tracing import PipelineReader 

42 

43 reader = PipelineReader("gitlab-org/gitlab-development-kit", token=getenv("GITLAB_TOKEN")) 

44 trace = reader.ReadPipeline(2954836704) 

45 print("\\n".join(trace.Format())) 

46 

47.. hint:: 

48 

49 See :ref:`high-level help <VIS/PipelineTrace>` for explanations and usage examples. 

50""" 

51from datetime import datetime, timedelta 

52from typing import Any, ClassVar, Iterable, Mapping, Optional as Nullable, Self, Union 

53 

54from pyTooling.CI import Base, JobGroup, Matrix 

55from pyTooling.Common import getFullyQualifiedName 

56from pyTooling.Decorators import export 

57from pyTooling.GitLab import DownstreamPipeline, GitLabError, Job, MatrixJob, Pipeline, ProjectClient, Status 

58from pyTooling.MetaClasses import ExtendedType 

59from pyTooling.REST import JSONObject, RESTError 

60from pyTooling.Tracing import Span 

61from pyTooling.Tracing.CI import OTLP, Result, JobSpan as CIJobSpan, MatrixSpan as CIMatrixSpan, \ 

62 PipelineTrace as CIPipelineTrace, QueuedSpan as CIQueuedSpan, \ 

63 WorkflowSpan as CIWorkflowSpan 

64 

65 

66@export 

67class GitLab(metaclass=ExtendedType, slots=True): 

68 """ 

69 Attribute keys naming what only GitLab CI/CD reports, beside the keys of :class:`~pyTooling.Tracing.CI.OTLP`. 

70 

71 The nesting mirrors the key itself, as it does there: :attr:`GitLab.Runner.Tags` spells ``'gitlab.runner.tags'``. 

72 """ 

73 

74 Status: ClassVar[str] = "gitlab.status" #: GitLab's own status, next to the result it maps to. 

75 

76 class Pipeline(metaclass=ExtendedType, slots=True): 

77 """Attribute keys naming a pipeline.""" 

78 

79 IID: ClassVar[str] = "gitlab.pipeline.iid" #: The pipeline's number within its project. 

80 Source: ClassVar[str] = "gitlab.pipeline.source" #: What started the pipeline, e.g. ``'push'``. 

81 

82 class Project(metaclass=ExtendedType, slots=True): 

83 """Attribute keys naming a project.""" 

84 

85 ID: ClassVar[str] = "gitlab.project.id" #: GitLab's identifier of the project. 

86 

87 class Job(metaclass=ExtendedType, slots=True): 

88 """Attribute keys naming a job.""" 

89 

90 Stage: ClassVar[str] = "gitlab.job.stage" #: The stage the job is listed in. 

91 AllowFailure: ClassVar[str] = "gitlab.job.allow_failure" #: Whether the job may fail, its pipeline not. 

92 FailureReason: ClassVar[str] = "gitlab.job.failure_reason" #: Why the job failed, e.g. ``'script_failure'``. 

93 

94 class Matrix(metaclass=ExtendedType, slots=True): 

95 """Attribute keys naming a matrix.""" 

96 

97 Dimensions: ClassVar[str] = "gitlab.matrix.dimensions" #: One instance's values, e.g. ``['3.14', 'linux']``. 

98 

99 class Runner(metaclass=ExtendedType, slots=True): 

100 """Attribute keys naming the runner a job ran on.""" 

101 

102 ID: ClassVar[str] = "gitlab.runner.id" #: GitLab's identifier of the runner. 

103 Tags: ClassVar[str] = "gitlab.runner.tags" #: The tags the job asked for, e.g. ``['saas-linux-small-amd64']``. 

104 

105 class Downstream(metaclass=ExtendedType, slots=True): 

106 """Attribute keys naming a downstream pipeline.""" 

107 

108 ID: ClassVar[str] = "gitlab.downstream.id" #: GitLab's identifier of the downstream pipeline. 

109 ProjectID: ClassVar[str] = "gitlab.downstream.project_id" #: GitLab's identifier of its project. 

110 

111 class Trigger(metaclass=ExtendedType, slots=True): 

112 """Attribute keys naming the trigger job, which started a downstream pipeline.""" 

113 

114 ID: ClassVar[str] = "gitlab.trigger.id" #: GitLab's identifier of the trigger job. 

115 Status: ClassVar[str] = "gitlab.trigger.status" #: The trigger job's status. 

116 URL: ClassVar[str] = "gitlab.trigger.url" #: The trigger job's address. 

117 

118 

119@export 

120def runnerCategory(span: Span) -> str: 

121 """ 

122 Span category naming the runner a timespan ran on, for :class:`~pyTooling.Tracing.Render.GanttLayout`. 

123 

124 The runner is the first tag of the timespan or its nearest ancestor, e.g. ``saas-linux-large-amd64``; a job without 

125 tags is categorized by the runner's description, :data:`OTLP.CICD.Worker.Name <pyTooling.Tracing.CI.OTLP>`. 

126 

127 :param span: The timespan. 

128 :returns: The category, or the empty string if neither the timespan nor an ancestor names its runner. 

129 """ 

130 current: Nullable[Span] = span 

131 while current is not None: 

132 if GitLab.Runner.Tags in current and len(tags := current[GitLab.Runner.Tags]) > 0: 

133 return str(tags[0]) 

134 elif OTLP.CICD.Worker.Name in current: 

135 return str(current[OTLP.CICD.Worker.Name]) 

136 

137 current = current.Parent 

138 

139 return "" 

140 

141 

142@export 

143class GitLabTimespanMixin(metaclass=ExtendedType, mixin=True): 

144 """ 

145 Mixin-class for a timespan built from :mod:`pyTooling.GitLab`'s model of a pipeline. 

146 

147 It holds what every flavour needs to read that model: the result an element's outcome is, and the span a group's 

148 contents have. Everything else the model answers itself - the order its elements are in, and the times of a 

149 downstream pipeline, which contain the jobs of its child pipeline. 

150 """ 

151 

152 @staticmethod 

153 def _Result(element: Base) -> Nullable[Result]: 

154 """ 

155 Return the CI/CD result of an element of the model. 

156 

157 The result is the member of the same value as the element's :attr:`~pyTooling.CI.Base.Outcome`. A GitLab 

158 status is mapped onto an outcome by :meth:`Status.ToOutcome <pyTooling.GitLab.Status.ToOutcome>`. 

159 

160 :param element: The pipeline, job or downstream pipeline. 

161 :returns: The CI/CD result, or ``None`` while the element hasn't ended. 

162 """ 

163 if element.Outcome is None: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true

164 return None 

165 

166 return Result(element.Outcome.value) 

167 

168 @staticmethod 

169 def _NotBefore(end: Nullable[datetime], begin: datetime) -> Nullable[datetime]: 

170 """ 

171 Clamp an end time so it doesn't precede a begin time. 

172 

173 :param end: Optional, the end time. Default: ``None``. 

174 :param begin: The begin time. 

175 :returns: The end time, but not before the begin time. 

176 """ 

177 return None if end is None else max(end, begin) 

178 

179 @staticmethod 

180 def _Value(status: Nullable[Status]) -> Nullable[str]: 

181 """ 

182 Return the value of a status, as GitLab reports it. 

183 

184 :param status: Optional, the status. Default: ``None``. 

185 :returns: The status' value, or ``None`` if there is none. 

186 """ 

187 return None if status is None else status.value 

188 

189 @staticmethod 

190 def _NotBeforeParent(begin: datetime, parent: Span) -> datetime: 

191 """ 

192 Clamp a begin time so it doesn't precede the begin of the parent timespan. 

193 

194 :mod:`pyTooling.Tracing` requires a timespan to lie within its parent. GitLab reports a job's times in 

195 milliseconds, but the time it was queued as a duration, so a waiting timespan may reach a moment before the 

196 timespan holding it. 

197 

198 :param begin: The begin time. 

199 :param parent: The parent timespan. 

200 :returns: The begin time, but not before the parent's. 

201 """ 

202 if parent.StartTime is None or begin >= parent.StartTime: 202 ↛ 205line 202 didn't jump to line 205 because the condition on line 202 was always true

203 return begin 

204 

205 return parent.StartTime 

206 

207 @staticmethod 

208 def _Earliest(times: Iterable[datetime]) -> Nullable[datetime]: 

209 """ 

210 Return the earliest of some times. 

211 

212 :param times: The times. 

213 :returns: The earliest time, or ``None`` if there is none. 

214 """ 

215 return min(times, default=None) 

216 

217 @staticmethod 

218 def _QueueBegin(job: Job) -> Nullable[datetime]: 

219 """ 

220 Return when a job started waiting for a runner, by the time GitLab reports it was queued. 

221 

222 :param job: The job. 

223 :returns: The time, or ``None`` if the job hasn't started, was skipped, or wasn't queued. 

224 """ 

225 if job.StartedAt is None or job.QueuedDuration is None or job.QueuedDuration <= 0.0 or job.Status is Status.Skipped: 

226 return None 

227 

228 return job.StartedAt - timedelta(seconds=job.QueuedDuration) 

229 

230 @classmethod 

231 def _GroupTimespan(cls, group: JobGroup) -> tuple[Nullable[datetime], Nullable[datetime]]: 

232 """ 

233 Return the timespan of a group, which holds the time its jobs were queued too. 

234 

235 A group begins when it or its first element started, or earlier, when a job was queued for a runner before. A group 

236 reporting no start - a downstream pipeline whose payload wasn't read - begins at its creation. A group nothing of 

237 which started - e.g. a matrix of jobs waiting to be started by hand - has nothing to place on a timeline. 

238 

239 :param group: The group - a pipeline, a downstream pipeline or a matrix. 

240 :returns: When the timespan begins and ends, each ``None`` if there is nothing to place on a timeline 

241 respectively while it is still running. 

242 """ 

243 begins = [queueBegin for job in group.IterateJobs() if (queueBegin := cls._QueueBegin(job)) is not None] 

244 for started in (group.StartedAt, group.ContentsStartedAt): 

245 if started is not None: 

246 begins.append(started) 

247 

248 if len(begins) == 0: 

249 if not group.IsReported or group.CreatedAt is None: 

250 return None, None 

251 

252 begins.append(group.CreatedAt) 

253 

254 begin = min(begins) 

255 

256 return begin, cls._NotBefore(group.CompletedAt, begin) 

257 

258 @classmethod 

259 def _AddContents(cls, group: JobGroup, parent: Span) -> None: 

260 """ 

261 Add the jobs, matrices and downstream pipelines of a group to a timespan, in the order they were created. 

262 

263 :param group: The group - a pipeline, a downstream pipeline or a matrix. 

264 :param parent: The timespan the group's contents are added to. 

265 """ 

266 for item in group.IterateElements(): 

267 if isinstance(item, Job): 

268 JobSpan.FromJob(item, parent) 

269 elif isinstance(item, Matrix): 

270 MatrixSpan.FromGroup(item, parent) 

271 else: 

272 DownstreamSpan.FromDownstreamPipeline(item, parent) 

273 

274 

275@export 

276class QueuedSpan(CIQueuedSpan, GitLabTimespanMixin): 

277 """The timespan a GitLab job waited for a runner, in front of the job's own timespan.""" 

278 

279 @classmethod 

280 def FromJob(cls, job: Job, begin: datetime, started: Nullable[datetime], parent: Span) -> Self: 

281 """ 

282 Build the timespan a job waited for a runner. 

283 

284 :param job: The job that waited. 

285 :param begin: When the job started waiting for a runner. 

286 :param started: Optional, when the job started, or ``None`` while it is still waiting. 

287 :param parent: The timespan of the trace, matrix or downstream pipeline containing the job. 

288 :returns: The waiting timespan. 

289 """ 

290 begin = cls._NotBeforeParent(begin, parent) 

291 

292 return cls( 

293 f"{job!s} (queued)", 

294 begin, 

295 cls._NotBefore(started, begin), 

296 parent=parent, 

297 taskName=job.QualifiedName, 

298 attributes={GitLab.Runner.Tags: list(job.Tags)} 

299 ) 

300 

301 

302@export 

303class JobSpan(CIJobSpan, GitLabTimespanMixin): 

304 """The timespan of a GitLab job, from the moment it started on a runner until it completed.""" 

305 

306 @classmethod 

307 def FromJob(cls, job: Job, parent: Span) -> Nullable[Self]: 

308 """ 

309 Build the timespans of a job: the time it waited for a runner, and the job itself. 

310 

311 GitLab creates every job of a pipeline when the pipeline is created, so the time between a job's creation and 

312 its start is mostly the time it waited for the jobs it depends on. The waiting timespan is therefore the time 

313 GitLab reports the job was queued for a runner - :attr:`~pyTooling.GitLab.JobMixin.QueuedDuration` - right in 

314 front of its start. A job not yet started has no timespan. 

315 

316 :param job: The job. 

317 :param parent: The timespan of the trace, matrix or downstream pipeline containing the job. 

318 :returns: The job's timespan, or ``None`` if the job hasn't started. 

319 """ 

320 started = job.StartedAt 

321 completed = job.CompletedAt 

322 

323 if job.Status is Status.Skipped: 

324 # A skipped job neither waited for a runner nor ran on one: it is placed at the moment it was skipped. 

325 if (skippedAt := started if started is not None else completed) is None: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true

326 return None 

327 

328 begin = cls._NotBeforeParent(skippedAt, parent) 

329 end = begin 

330 elif started is None: 

331 return None 

332 else: 

333 if (queueBegin := cls._QueueBegin(job)) is not None: 

334 QueuedSpan.FromJob(job, queueBegin, started, parent) 

335 

336 begin = cls._NotBeforeParent(started, parent) 

337 end = cls._NotBefore(completed, begin) 

338 

339 attributes: dict[str, Any] = { 

340 GitLab.Status: cls._Value(job.Status), 

341 GitLab.Job.Stage: job.Stage, 

342 GitLab.Job.AllowFailure: job.AllowFailure, 

343 GitLab.Job.FailureReason: job.FailureReason, 

344 GitLab.Runner.ID: job.RunnerID, 

345 GitLab.Runner.Tags: list(job.Tags) 

346 } 

347 if isinstance(job, MatrixJob): 

348 attributes[GitLab.Matrix.Dimensions] = [str(value) for value in job.Dimensions.values()] 

349 

350 return cls( 

351 str(job), 

352 begin, 

353 end, 

354 parent=parent, 

355 taskName=job.QualifiedName, 

356 runID=None if job.ID is None else str(job.ID), 

357 runURL=None if job.URL is None else str(job.URL), 

358 result=cls._Result(job), 

359 workerName=job.RunnerDescription, 

360 attributes=attributes 

361 ) 

362 

363 

364@export 

365class MatrixSpan(CIMatrixSpan, GitLabTimespanMixin): 

366 """The instances a matrix produced, grouped into one timespan.""" 

367 

368 @classmethod 

369 def FromGroup(cls, group: Matrix, parent: Span) -> Nullable[Self]: 

370 """ 

371 Build the timespan of a matrix and everything below it. 

372 

373 :param group: The matrix. 

374 :param parent: The timespan containing the matrix. 

375 :returns: The matrix' timespan, or ``None`` if no instance of it started. 

376 """ 

377 begin, end = cls._GroupTimespan(group) 

378 if begin is None: 

379 return None 

380 

381 begin = cls._NotBeforeParent(begin, parent) 

382 span = cls(str(group), begin, cls._NotBefore(end, begin), parent=parent, taskName=group.QualifiedName) 

383 cls._AddContents(group, span) 

384 

385 return span 

386 

387 

388@export 

389class DownstreamSpan(CIWorkflowSpan, GitLabTimespanMixin): 

390 """The jobs of a downstream pipeline, grouped into one timespan named like its trigger job.""" 

391 

392 @classmethod 

393 def FromDownstreamPipeline(cls, pipeline: DownstreamPipeline, parent: Span) -> Nullable[Self]: 

394 """ 

395 Build the timespan of a downstream pipeline and everything below it. 

396 

397 :param pipeline: The downstream pipeline. 

398 :param parent: The timespan containing the trigger job. 

399 :returns: The downstream pipeline's timespan, or ``None`` if it hasn't been created, or nothing of it 

400 started. 

401 """ 

402 begin, end = cls._GroupTimespan(pipeline) 

403 if begin is None: 

404 return None 

405 

406 begin = cls._NotBeforeParent(begin, parent) 

407 span = cls( 

408 str(pipeline), 

409 begin, 

410 cls._NotBefore(end, begin), 

411 parent=parent, 

412 taskName=pipeline.QualifiedName, 

413 attributes={ 

414 OTLP.CICD.Pipeline.Task.Run.ID: None if pipeline.DownstreamID is None else str(pipeline.DownstreamID), 

415 OTLP.CICD.Pipeline.Task.Run.URL.Full: None if pipeline.URL is None else str(pipeline.URL), 

416 OTLP.CICD.Pipeline.Task.Run.Result: cls._Result(pipeline), 

417 GitLab.Status: cls._Value(pipeline.Status), 

418 GitLab.Job.Stage: pipeline.Stage, 

419 GitLab.Downstream.ID: pipeline.DownstreamID, 

420 GitLab.Downstream.ProjectID: pipeline.DownstreamProjectID, 

421 GitLab.Trigger.ID: pipeline.ID, 

422 GitLab.Trigger.Status: cls._Value(pipeline.TriggerStatus), 

423 GitLab.Trigger.URL: None if pipeline.TriggerURL is None else str(pipeline.TriggerURL) 

424 } 

425 ) 

426 cls._AddContents(pipeline, span) 

427 

428 return span 

429 

430 

431@export 

432class PipelineTrace(CIPipelineTrace, GitLabTimespanMixin): 

433 """A GitLab CI/CD pipeline as a trace.""" 

434 

435 @classmethod 

436 def Parse( 

437 cls, 

438 pipeline: JSONObject, 

439 jobs: Nullable[Iterable[JSONObject]] = None, 

440 bridges: Nullable[Iterable[JSONObject]] = None, 

441 downstream: Nullable[Mapping[Union[int, str], JSONObject]] = None 

442 ) -> Self: 

443 """ 

444 Build the trace of a pipeline from the payloads the GitLab REST API answers with. 

445 

446 The payloads are read into a :class:`~pyTooling.GitLab.Pipeline` first, so the tree - the matrices, the jobs 

447 and the downstream pipelines - is reconstructed by the model rather than here, and :meth:`FromPipeline` turns it 

448 into timespans. 

449 

450 :param pipeline: The pipeline, as returned by ``GET /projects/{id}/pipelines/{pipeline_id}``. 

451 :param jobs: Optional, the pipeline's jobs, as listed by ``GET .../pipelines/{pipeline_id}/jobs``. 

452 :param bridges: Optional, the pipeline's trigger jobs, as listed by 

453 ``GET .../pipelines/{pipeline_id}/bridges``. 

454 :param downstream: Optional, the downstream pipelines' payloads, by the downstream pipeline's identifier, as 

455 for :meth:`Pipeline.Parse <pyTooling.GitLab.Pipeline.Parse>`. Default: ``None``. 

456 :returns: The pipeline as a trace. 

457 :raises TypeError: If parameter 'pipeline' is not of type :class:`dict`. 

458 :raises GitLabError: If a mandatory field is missing, or a field holds a value GitLab doesn't document. 

459 """ 

460 return cls.FromPipeline(Pipeline.Parse(pipeline, jobs, bridges, downstream)) 

461 

462 @classmethod 

463 def FromPipeline(cls, pipeline: Pipeline) -> Self: 

464 """ 

465 Build the trace of a pipeline, as :mod:`pyTooling.GitLab` models it. 

466 

467 * The pipeline becomes the trace, widened where a job started earlier or completed later than the pipeline 

468 reports. 

469 * A matrix and a downstream pipeline become a timespan holding the jobs below them. 

470 * A job becomes a timespan from its start to its completion, preceded by ``<job> (queued)`` for the time GitLab 

471 reports it was queued for a runner. A job that hasn't started has no timespan; a skipped job no waiting 

472 timespan. 

473 * Every timespan is classified by :attr:`CI.Span.Kind <pyTooling.Tracing.CI.CI>` and carries the OpenTelemetry 

474 CI/CD attributes, GitLab's status (:class:`GitLab`), and for jobs the stage, the runner and its tags. 

475 

476 :param pipeline: The pipeline. 

477 :returns: The pipeline as a trace. 

478 :raises TypeError: If parameter 'pipeline' is not of type :class:`~pyTooling.GitLab.Pipeline`. 

479 """ 

480 if not isinstance(pipeline, Pipeline): 

481 ex = TypeError("Parameter 'pipeline' is not of type 'Pipeline'.") 

482 ex.add_note(f"Got type '{getFullyQualifiedName(pipeline)}'.") 

483 raise ex 

484 

485 beginTime = pipeline.StartedAt if pipeline.StartedAt is not None else pipeline.CreatedAt 

486 endTime = cls._NotBefore(pipeline.CompletedAt, beginTime) if beginTime is not None else pipeline.CompletedAt 

487 

488 # a job's queue may begin before the pipeline reports itself started, and a job may complete after it finished 

489 jobsBegin = cls._Earliest( 

490 queueBegin for job in pipeline.IterateJobs() if (queueBegin := cls._QueueBegin(job)) is not None 

491 ) 

492 jobsEnd = pipeline.ContentsCompletedAt 

493 if (contentsBegin := pipeline.ContentsStartedAt) is not None: 

494 jobsBegin = contentsBegin if jobsBegin is None else min(jobsBegin, contentsBegin) 

495 

496 if jobsBegin is not None: 

497 beginTime = jobsBegin if beginTime is None else min(beginTime, jobsBegin) 

498 

499 if endTime is not None and jobsEnd is not None: 

500 endTime = max(endTime, jobsEnd) 

501 

502 trace = cls( 

503 pipeline.Name, 

504 beginTime, 

505 endTime, 

506 runID=None if pipeline.ID is None else str(pipeline.ID), 

507 runURL=None if pipeline.URL is None else str(pipeline.URL), 

508 result=cls._Result(pipeline), 

509 reference=pipeline.GitReference, 

510 revision=pipeline.SHA, 

511 attributes={ 

512 GitLab.Status: cls._Value(pipeline.Status), 

513 GitLab.Pipeline.IID: pipeline.IID, 

514 GitLab.Pipeline.Source: None if pipeline.Source is None else pipeline.Source.value, 

515 GitLab.Project.ID: pipeline.ProjectID 

516 } 

517 ) 

518 cls._AddContents(pipeline, trace) 

519 

520 return trace 

521 

522 

523@export 

524class PipelineReader(ProjectClient): 

525 """ 

526 Reads pipelines of a GitLab project through the GitLab REST API and converts them into traces. 

527 

528 A token is needed for a private project - inside a pipeline, ``CI_JOB_TOKEN`` doesn't suffice, a token with the 

529 ``read_api`` scope does. A public project's pipelines are read without one. 

530 """ 

531 

532 def ReadPayloads(self, pipelineID: int, downstream: bool = True) -> JSONObject: 

533 """ 

534 Read a pipeline's payloads: the pipeline, its jobs, its trigger jobs, and those of its child pipelines. 

535 

536 The result has the shape of :meth:`Pipeline.Parse <pyTooling.GitLab.Pipeline.Parse>`'s parameters, so it is read 

537 with :pycode:`Pipeline.Parse(**payloads)`. A child pipeline - a downstream pipeline of the same project - is read 

538 with its own child pipelines; a multi-project pipeline isn't, as it belongs to a project this reader wasn't 

539 made for. 

540 

541 :param pipelineID: The pipeline's identifier. 

542 :param downstream: Optional, ``True``, if the child pipelines are read too. Default: ``True``. 

543 :returns: The payloads - ``pipeline``, ``jobs``, ``bridges`` and ``downstream``. 

544 :raises ValueError: If parameter 'pipelineID' is ``None``. 

545 :raises TypeError: If parameter 'pipelineID' is not of type :class:`int`. 

546 :raises ValueError: If parameter 'pipelineID' isn't positive. 

547 :raises TypeError: If parameter 'downstream' is not of type :class:`bool`. 

548 :raises RESTError: If a request fails, or GitLab's answer isn't JSON of the expected shape. 

549 :raises GitLabError: If GitLab's answer lacks a mandatory field. 

550 """ 

551 if pipelineID is None: 

552 raise ValueError("Parameter 'pipelineID' is None.") 

553 elif isinstance(pipelineID, bool) or not isinstance(pipelineID, int): 

554 ex = TypeError("Parameter 'pipelineID' is not of type 'int'.") 

555 ex.add_note(f"Got type '{getFullyQualifiedName(pipelineID)}'.") 

556 raise ex 

557 elif pipelineID <= 0: 

558 ex = ValueError("Parameter 'pipelineID' isn't positive.") 

559 ex.add_note(f"Got value '{pipelineID}'.") 

560 raise ex 

561 

562 if not isinstance(downstream, bool): 

563 ex = TypeError("Parameter 'downstream' is not of type 'bool'.") 

564 ex.add_note(f"Got type '{getFullyQualifiedName(downstream)}'.") 

565 raise ex 

566 

567 pipelinePath = f"{self.ProjectResourcePath}/pipelines/{pipelineID}" 

568 pipeline, _ = self.GetJSONObject(pipelinePath) 

569 if not isinstance(pipeline, dict) or (projectID := pipeline.get("project_id", None)) is None: 

570 raise GitLabError(f"Field 'project_id' is missing in the answer of '{pipelinePath}'.") 

571 

572 jobs = self.GetJSONArray(f"{pipelinePath}/jobs") 

573 bridges = self.GetJSONArray(f"{pipelinePath}/bridges") 

574 

575 children: dict[str, JSONObject] = {} 

576 if downstream: 

577 for bridge in bridges: 

578 child = bridge.get("downstream_pipeline", None) 

579 if isinstance(child, dict) and child.get("project_id", None) == projectID and child.get("id", None) is not None: 

580 children[str(child["id"])] = self.ReadPayloads(child["id"]) 

581 

582 return {"pipeline": pipeline, "jobs": jobs, "bridges": bridges, "downstream": children} 

583 

584 def ReadPipeline(self, pipelineID: int, downstream: bool = True) -> PipelineTrace: 

585 """ 

586 Read a pipeline, its jobs and its child pipelines, and convert them into a trace. 

587 

588 :param pipelineID: The pipeline's identifier. 

589 :param downstream: Optional, ``True``, if the child pipelines are read too. Default: ``True``. 

590 :returns: The pipeline as a trace (see :meth:`PipelineTrace.Parse`). 

591 :raises ValueError: If parameter 'pipelineID' is ``None``. 

592 :raises TypeError: If parameter 'pipelineID' is not of type :class:`int`. 

593 :raises ValueError: If parameter 'pipelineID' isn't positive. 

594 :raises TypeError: If parameter 'downstream' is not of type :class:`bool`. 

595 :raises RESTError: If a request fails, or GitLab's answer isn't JSON of the expected shape. 

596 :raises GitLabError: If GitLab's answer lacks a mandatory field, or a field holds a value GitLab doesn't document. 

597 """ 

598 return PipelineTrace.Parse(**self.ReadPayloads(pipelineID, downstream)) 

599 

600 def _AddErrorNotes(self, error: RESTError, status: int) -> None: 

601 """ 

602 Add a note saying what a failing status means for the GitLab REST API. 

603 

604 :param error: The error the note is added to. 

605 :param status: The HTTP status the request failed with. 

606 """ 

607 if status in (401, 403, 404): 607 ↛ exitline 607 didn't return from function '_AddErrorNotes' because the condition on line 607 was always true

608 error.add_note("Check the project's path or identifier, and that the token may read the project's pipelines.")