Skip to content

Entity and methods

Run

Bases: UnversionedEntity

A class representing a run.

Source code in digitalhub_core/entities/run/entity.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class Run(UnversionedEntity):
    """
    A class representing a run.
    """

    ENTITY_TYPE = EntityTypes.RUN.value

    def __init__(
        self,
        project: str,
        uuid: str,
        kind: str,
        metadata: Metadata,
        spec: RunSpec,
        status: RunStatus,
        user: str | None = None,
    ) -> None:
        super().__init__(project, uuid, kind, metadata, spec, status, user)

        self.spec: RunSpec
        self.status: RunStatus

    ##############################
    #  Run Methods
    ##############################

    def build(self) -> None:
        """
        Build run.

        Returns
        -------
        None
        """
        runtime = self._get_runtime()
        executable = self._get_executable(runtime)
        task = self._get_task(runtime)
        new_spec = runtime.build(executable, task, self.to_dict())
        self.spec = build_spec(
            self.kind,
            **new_spec,
        )
        self._set_state(State.BUILT.value)
        self.save()

    def run(self) -> Run:
        """
        Run run.

        Returns
        -------
        Run
            Run object.
        """
        self.refresh()
        if self.spec.local_execution:
            if not self._is_built():
                raise EntityError("Run is not in built state. Build it again.")
            self._set_state(State.RUNNING.value)
            self.save(update=True)

        # Try to get inputs if they exist
        try:
            self.spec.inputs = self.inputs(as_dict=True)
        except EntityError:
            pass

        try:
            status = self._get_runtime().run(self.to_dict())
        except Exception as e:
            self.refresh()
            if self.spec.local_execution:
                self._set_state(State.ERROR.value)
            self._set_message(str(e))
            self.save(update=True)
            raise e

        self.refresh()
        if not self.spec.local_execution:
            status.pop("state", None)
        new_status = {**self.status.to_dict(), **status}
        self._set_status(new_status)
        self.save(update=True)
        return self

    def wait(self, log_info: bool = True) -> Run:
        """
        Wait for run to finish.

        Parameters
        ----------
        log_info : bool
            If True, log information.

        Returns
        -------
        Run
            Run object.
        """
        start = time.time()
        while True:
            if log_info:
                LOGGER.info(f"Waiting for run {self.id} to finish...")
            self.refresh()
            time.sleep(5)
            if self.status.state in [
                State.STOPPED.value,
                State.ERROR.value,
                State.COMPLETED.value,
            ]:
                if log_info:
                    current = time.time() - start
                    LOGGER.info(f"Run {self.id} finished in {current:.2f} seconds.")
                return self

    def inputs(self, as_dict: bool = False) -> list[dict]:
        """
        Get inputs passed in spec as objects or as dictionaries.

        Parameters
        ----------
        as_dict : bool
            If True, return inputs as dictionaries.

        Returns
        -------
        list[dict]
            List of input objects.
        """
        try:
            return self.spec.get_inputs(as_dict=as_dict)
        except AttributeError:
            msg = f"Run of type {self.kind} has no inputs."
            raise EntityError(msg)

    def results(self) -> dict:
        """
        Get results from runtime execution.

        Returns
        -------
        dict
            Results.
        """
        try:
            return self.status.get_results()
        except AttributeError:
            msg = f"Run of type {self.kind} has no results."
            raise EntityError(msg)

    def result(self, key: str) -> Any:
        """
        Get result from runtime execution by key.

        Parameters
        ----------
        key : str
            Key of the result.

        Returns
        -------
        Any
            Result.
        """
        return self.results().get(key)

    def outputs(self, as_key: bool = False, as_dict: bool = False) -> dict:
        """
        Get run objects results.

        Parameters
        ----------
        as_key : bool
            If True, return results as keys.
        as_dict : bool
            If True, return results as dictionaries.

        Returns
        -------
        dict
            List of output objects.
        """
        try:
            return self.status.get_outputs(as_key=as_key, as_dict=as_dict)
        except AttributeError:
            msg = f"Run of type {self.kind} has no outputs."
            raise EntityError(msg)

    def output(self, key: str, as_key: bool = False, as_dict: bool = False) -> MaterialEntity | dict | str | None:
        """
        Get run object result by key.

        Parameters
        ----------
        key : str
            Key of the result.
        as_key : bool
            If True, return result as key.
        as_dict : bool
            If True, return result as dictionary.

        Returns
        -------
        Entity | dict | str | None
            Result.
        """
        return self.outputs(as_key=as_key, as_dict=as_dict).get(key)

    def values(self) -> dict:
        """
        Get values from runtime execution.

        Returns
        -------
        dict
            Values from backend.
        """
        try:
            value_list = getattr(self.spec, "values", [])
            value_list = value_list if value_list is not None else []
            return self.status.get_values(value_list)
        except AttributeError:
            msg = f"Run of type {self.kind} has no values."
            raise EntityError(msg)

    def logs(self) -> dict:
        """
        Get object from backend.
        Returns empty dictionary if context is local.

        Returns
        -------
        dict
            Logs from backend.
        """
        if self._context().local:
            return {}
        return logs_api(self.project, self.ENTITY_TYPE, self.id)

    def stop(self) -> None:
        """
        Stop run.

        Returns
        -------
        None
        """
        if not self._context().local and not self.spec.local_execution:
            return stop_api(self.project, self.ENTITY_TYPE, self.id)
        try:
            self.status.stop()
        except AttributeError:
            return

    def invoke(self, **kwargs) -> requests.Response:
        """
        Invoke run.

        Parameters
        ----------
        kwargs
            Keyword arguments to pass to the request.

        Returns
        -------
        requests.Response
            Response from service.
        """
        try:
            if not self._context().local and not self.spec.local_execution:
                local = False
            else:
                local = True
            if kwargs is None:
                kwargs = {}
            return self.status.invoke(local, **kwargs)
        except AttributeError:
            msg = f"Run of type {self.kind} has no invoke operation."
            raise EntityError(msg)

    ##############################
    #  Helpers
    ##############################

    def _is_built(self) -> bool:
        """
        Check if run is in built state.

        Returns
        -------
        bool
            True if run is in built state, False otherwise.
        """
        return self.status.state == State.BUILT.value

    def _set_status(self, status: dict) -> None:
        """
        Set run status.

        Parameters
        ----------
        status : dict
            Status to set.

        Returns
        -------
        None
        """
        self.status: RunStatus = build_status(self.kind, **status)

    def _set_state(self, state: str) -> None:
        """
        Update run state.

        Parameters
        ----------
        state : str
            State to set.

        Returns
        -------
        None
        """
        self.status.state = state

    def _set_message(self, message: str) -> None:
        """
        Update run message.

        Parameters
        ----------
        message : str
            Message to set.

        Returns
        -------
        None
        """
        self.status.message = message

    def _get_runtime(self) -> Runtime:
        """
        Build runtime to build run or execute it.

        Returns
        -------
        Runtime
            Runtime object.
        """
        return build_runtime(self.kind, self.project)

    def _get_executable(self, runtime: Runtime) -> dict:
        """
        Get object from backend. Reimplemented to avoid circular imports.

        Parameters
        ----------
        runtime : Runtime
            Runtime object.

        Returns
        -------
        dict
            Executable (function or workflow) from backend.
        """
        exec_kind = runtime.get_executable_kind()
        entity_type = registry.get_entity_type(exec_kind)
        splitted = self.spec.task.split("/")
        exec_name = splitted[-1].split(":")[0]
        exec_id = splitted[-1].split(":")[1]
        return read_entity_api_ctx(
            exec_name,
            entity_type=entity_type,
            project=self.project,
            entity_id=exec_id,
        )

    def _get_task(self, runtime: Runtime) -> dict:
        """
        Get object from backend. Reimplemented to avoid circular imports.

        Parameters
        ----------
        runtime : Runtime
            Runtime object.

        Returns
        -------
        dict
            Task from backend.
        """
        executable_kind = runtime.get_executable_kind()
        exec_string = f"{executable_kind}://{self.spec.task.split('://')[1]}"

        # Local backend
        if self._context().local:
            tasks = list_entity_api_base(self._context().client, EntityTypes.TASK.value)
            for i in tasks:
                if i.get("spec").get("function") == exec_string:
                    return i
            raise EntityError("Task not found.")

        # Remote backend
        task_kind = self.spec.task.split("://")[0]
        params = {"function": exec_string, "kind": task_kind}
        return list_entity_api_ctx(self.project, EntityTypes.TASK.value, params=params)[0]

build()

Build run.

Returns:

Type Description
None
Source code in digitalhub_core/entities/run/entity.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def build(self) -> None:
    """
    Build run.

    Returns
    -------
    None
    """
    runtime = self._get_runtime()
    executable = self._get_executable(runtime)
    task = self._get_task(runtime)
    new_spec = runtime.build(executable, task, self.to_dict())
    self.spec = build_spec(
        self.kind,
        **new_spec,
    )
    self._set_state(State.BUILT.value)
    self.save()

inputs(as_dict=False)

Get inputs passed in spec as objects or as dictionaries.

Parameters:

Name Type Description Default
as_dict bool

If True, return inputs as dictionaries.

False

Returns:

Type Description
list[dict]

List of input objects.

Source code in digitalhub_core/entities/run/entity.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def inputs(self, as_dict: bool = False) -> list[dict]:
    """
    Get inputs passed in spec as objects or as dictionaries.

    Parameters
    ----------
    as_dict : bool
        If True, return inputs as dictionaries.

    Returns
    -------
    list[dict]
        List of input objects.
    """
    try:
        return self.spec.get_inputs(as_dict=as_dict)
    except AttributeError:
        msg = f"Run of type {self.kind} has no inputs."
        raise EntityError(msg)

invoke(**kwargs)

Invoke run.

Parameters:

Name Type Description Default
kwargs

Keyword arguments to pass to the request.

{}

Returns:

Type Description
Response

Response from service.

Source code in digitalhub_core/entities/run/entity.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def invoke(self, **kwargs) -> requests.Response:
    """
    Invoke run.

    Parameters
    ----------
    kwargs
        Keyword arguments to pass to the request.

    Returns
    -------
    requests.Response
        Response from service.
    """
    try:
        if not self._context().local and not self.spec.local_execution:
            local = False
        else:
            local = True
        if kwargs is None:
            kwargs = {}
        return self.status.invoke(local, **kwargs)
    except AttributeError:
        msg = f"Run of type {self.kind} has no invoke operation."
        raise EntityError(msg)

logs()

Get object from backend. Returns empty dictionary if context is local.

Returns:

Type Description
dict

Logs from backend.

Source code in digitalhub_core/entities/run/entity.py
258
259
260
261
262
263
264
265
266
267
268
269
270
def logs(self) -> dict:
    """
    Get object from backend.
    Returns empty dictionary if context is local.

    Returns
    -------
    dict
        Logs from backend.
    """
    if self._context().local:
        return {}
    return logs_api(self.project, self.ENTITY_TYPE, self.id)

output(key, as_key=False, as_dict=False)

Get run object result by key.

Parameters:

Name Type Description Default
key str

Key of the result.

required
as_key bool

If True, return result as key.

False
as_dict bool

If True, return result as dictionary.

False

Returns:

Type Description
Entity | dict | str | None

Result.

Source code in digitalhub_core/entities/run/entity.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def output(self, key: str, as_key: bool = False, as_dict: bool = False) -> MaterialEntity | dict | str | None:
    """
    Get run object result by key.

    Parameters
    ----------
    key : str
        Key of the result.
    as_key : bool
        If True, return result as key.
    as_dict : bool
        If True, return result as dictionary.

    Returns
    -------
    Entity | dict | str | None
        Result.
    """
    return self.outputs(as_key=as_key, as_dict=as_dict).get(key)

outputs(as_key=False, as_dict=False)

Get run objects results.

Parameters:

Name Type Description Default
as_key bool

If True, return results as keys.

False
as_dict bool

If True, return results as dictionaries.

False

Returns:

Type Description
dict

List of output objects.

Source code in digitalhub_core/entities/run/entity.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def outputs(self, as_key: bool = False, as_dict: bool = False) -> dict:
    """
    Get run objects results.

    Parameters
    ----------
    as_key : bool
        If True, return results as keys.
    as_dict : bool
        If True, return results as dictionaries.

    Returns
    -------
    dict
        List of output objects.
    """
    try:
        return self.status.get_outputs(as_key=as_key, as_dict=as_dict)
    except AttributeError:
        msg = f"Run of type {self.kind} has no outputs."
        raise EntityError(msg)

result(key)

Get result from runtime execution by key.

Parameters:

Name Type Description Default
key str

Key of the result.

required

Returns:

Type Description
Any

Result.

Source code in digitalhub_core/entities/run/entity.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def result(self, key: str) -> Any:
    """
    Get result from runtime execution by key.

    Parameters
    ----------
    key : str
        Key of the result.

    Returns
    -------
    Any
        Result.
    """
    return self.results().get(key)

results()

Get results from runtime execution.

Returns:

Type Description
dict

Results.

Source code in digitalhub_core/entities/run/entity.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def results(self) -> dict:
    """
    Get results from runtime execution.

    Returns
    -------
    dict
        Results.
    """
    try:
        return self.status.get_results()
    except AttributeError:
        msg = f"Run of type {self.kind} has no results."
        raise EntityError(msg)

run()

Run run.

Returns:

Type Description
Run

Run object.

Source code in digitalhub_core/entities/run/entity.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def run(self) -> Run:
    """
    Run run.

    Returns
    -------
    Run
        Run object.
    """
    self.refresh()
    if self.spec.local_execution:
        if not self._is_built():
            raise EntityError("Run is not in built state. Build it again.")
        self._set_state(State.RUNNING.value)
        self.save(update=True)

    # Try to get inputs if they exist
    try:
        self.spec.inputs = self.inputs(as_dict=True)
    except EntityError:
        pass

    try:
        status = self._get_runtime().run(self.to_dict())
    except Exception as e:
        self.refresh()
        if self.spec.local_execution:
            self._set_state(State.ERROR.value)
        self._set_message(str(e))
        self.save(update=True)
        raise e

    self.refresh()
    if not self.spec.local_execution:
        status.pop("state", None)
    new_status = {**self.status.to_dict(), **status}
    self._set_status(new_status)
    self.save(update=True)
    return self

stop()

Stop run.

Returns:

Type Description
None
Source code in digitalhub_core/entities/run/entity.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def stop(self) -> None:
    """
    Stop run.

    Returns
    -------
    None
    """
    if not self._context().local and not self.spec.local_execution:
        return stop_api(self.project, self.ENTITY_TYPE, self.id)
    try:
        self.status.stop()
    except AttributeError:
        return

values()

Get values from runtime execution.

Returns:

Type Description
dict

Values from backend.

Source code in digitalhub_core/entities/run/entity.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def values(self) -> dict:
    """
    Get values from runtime execution.

    Returns
    -------
    dict
        Values from backend.
    """
    try:
        value_list = getattr(self.spec, "values", [])
        value_list = value_list if value_list is not None else []
        return self.status.get_values(value_list)
    except AttributeError:
        msg = f"Run of type {self.kind} has no values."
        raise EntityError(msg)

wait(log_info=True)

Wait for run to finish.

Parameters:

Name Type Description Default
log_info bool

If True, log information.

True

Returns:

Type Description
Run

Run object.

Source code in digitalhub_core/entities/run/entity.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def wait(self, log_info: bool = True) -> Run:
    """
    Wait for run to finish.

    Parameters
    ----------
    log_info : bool
        If True, log information.

    Returns
    -------
    Run
        Run object.
    """
    start = time.time()
    while True:
        if log_info:
            LOGGER.info(f"Waiting for run {self.id} to finish...")
        self.refresh()
        time.sleep(5)
        if self.status.state in [
            State.STOPPED.value,
            State.ERROR.value,
            State.COMPLETED.value,
        ]:
            if log_info:
                current = time.time() - start
                LOGGER.info(f"Run {self.id} finished in {current:.2f} seconds.")
            return self