Repository navigation
Expand file tree
/
Copy pathhdctl
More file actions
executable file
·1930 lines (1656 loc) · 67.8 KB
/
Copy pathhdctl
File metadata and controls
executable file
·1930 lines (1656 loc) · 67.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
###############################################################################
# #
# hdctl #
# #
# Manage maintenance / devops tasks around hetida designer installations #
# #
# #
###############################################################################
#
# LICENSE
# Copyright © 2024 fuseki GmbH
#
# MIT License
# see https://github.com/hetida/hetida-designer/blob/release/LICENSE
#
# INTRODUCTION
# hdctl is a bash command line tool for managing typical maintenance /
# devops tasks around hetida designer installations.
#
# hdctl can export/import components and workflows from/to the backend api
# while taking care of authentication. A typical use case is syncing
# components / workflows from dev instances to test or prod instances.
#
# Another use case is running maintenance operations, e.g. as described in
# https://github.com/hetida/hetida-designer/blob/release/docs/cleanup.md
# from the command line only, i.e. without needing docker.
#
# hdctl is based on bash/coreutils + curl with the additional requirement
# of awk and jq for some tasks that involve json wrangling. This enables
# managing hetida designer instances from locations where no docker or
# python installation is available or installing arbitrary dependencies
# and software is difficult due to administrative / security restrictions.
#
# INSTALLATION
# Just copy this bash script to the environment where you want to run it
# from. There you need
# * modern/recent bash (version >4)
# * GNU coreutils
# * curl (ideally >= 7.87.0)
# * optionally awk and jq (https://stedolan.github.io/jq/) for some
# subcommands that involve json unpacking
#
# Notes:
# * hdctl should run under Git Bash on Windows. Recent versions of Git
# for Windows include curl >= 7.87.0 and gawk. jq must be installed
# separately. If you experience problems please open an issue.
# * Using nix, you can start an environment with all dependencies by
# running
# nix-shell \
# -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-unstable.tar.gz \
# -p bashInteractive jq gawk coreutils curl
# At least with the following fixed nixpkgs commit it should
# definitely work:
# nix-shell \
# -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/28319deb5ab05458d9cd5c7d99e1a24ec2e8fc4b.tar.gz \
# -p bashInteractive jq gawk coreutils curl
#
#
# USAGE
# Run
# hdctl usage
# to see detailed usage instructions and descriptions of all subcommands
# and arguments.
set -e
######################## Initialize mutable Global variables ##################
ACCESS_TOKEN=""
EXPIRATION_EPOCH=0
_JQ_AVAILABLE=true
###############################################################################
# #
# Logging functions #
# #
###############################################################################
_info() {
if [[ $SILENT = false ]]; then
echo "${@}" >&2
fi
}
_debug() {
if [[ $VERBOSITY == "debug" ]]; then
echo "${@}" >&2
fi
}
_log_error() {
echo "${@}" >&2
}
###############################################################################
# #
# System environment detection helper functions #
# #
###############################################################################
_detect_jq() {
if ! command -v jq 1>/dev/null; then
_info "WARNING: jq not available. Some parameters/options cannot be used."
_JQ_AVAILABLE=false
else
_info "Successfully detected jq in PATH."
fi
}
JQ_ENSURED=false
_ensure_jq() {
if ! command -v jq 1>/dev/null; then
_log_error "Called command needs jq command line tool, which was not found. Aborting."
exit 127
fi
JQ_ENSURED=true
}
_ensure_jq_once() {
if ! "$JQ_ENSURED"; then
_ensure_jq
fi
}
# outputs a certain value from env file
value_from_env_file() {
local var_name="$1"
local env_file_path="$2"
local env_file_entry
env_file_entry="$(grep -m 1 '^'"$var_name"= "$env_file_path")"
local str_after_equal="${env_file_entry#*=}" # may contain " or so
local actual_str
eval actual_str="$str_after_equal" # to get rid of enclosing ""
printf '%s' "$actual_str"
}
# shellcheck disable=SC2046
PYTEST_INI_CONTENT=$(
cat <<'END_HEREDOC'
[pytest]
python_files = *.py
addopts = --doctest-modules
END_HEREDOC
)
# shellcheck disable=SC2046
HDUTILS_PY_CONTENT=$(
cat <<'END_HEREDOC'
import datetime
import io
import json
import logging
from collections.abc import Generator
from enum import StrEnum
from types import UnionType
from typing import Any, Literal, TypedDict
from uuid import UUID
import numpy as np
import pandas as pd
import pytz
from plotly.graph_objects import Figure
from plotly.utils import PlotlyJSONEncoder
from pydantic import BaseConfig, BaseModel, Field, ValidationError, create_model
logger = logging.getLogger(__name__)
MULTITSFRAME_COLUMN_NAMES = ["timestamp", "metric", "value"]
class ComponentException(Exception):
"""Exception to re-raise exceptions with error code raised in the component code."""
__is_hetida_designer_exception__ = True
def __init__(
self,
*args: Any,
error_code: int | str = "",
extra_information: dict | None = None,
**kwargs: Any,
) -> None:
if not isinstance(error_code, int | str):
raise ValueError("The ComponentException.error_code must be int or string!")
self.error_code = error_code
self.extra_information = extra_information
super().__init__(*args, **kwargs)
class ComponentInputValidationException(ComponentException):
"""In code input validation failures"""
def __init__(
self,
*args: Any,
invalid_component_inputs: list[str],
error_code: int | str = "",
**kwargs: Any,
) -> None:
super().__init__(
*args,
error_code=error_code,
extra_information={"invalid_component_inputs": invalid_component_inputs},
**kwargs,
)
class WrappedModelWithCustomObjects(BaseModel):
model: Any
custom_objects: dict[str, Any]
class MetaDataWrapped(BaseModel):
"""Allows to wrap pandas object data with metadata"""
hd_wrapped_data_object__: Literal["SERIES", "DATAFRAME"] = Field(
..., alias="__hd_wrapped_data_object__"
)
metadata__: dict[str, Any] = Field(
...,
alias="__metadata__",
description="Json serializable dictionary of metadata. Will be written"
"to the resulting pandas object's attrs attribute.",
)
data__: dict | list = Field(
...,
alias="__data__",
description="The actual data which constitutes the pandas object.",
)
data_parsing_options__: dict = Field(
{},
alias="__data_parsing_options__",
description=(
"Additional options for parsing the provided data."
" For example, setting orient to one of the allowed values for the respective"
" Pandas type allows to use different json representations for the actual data."
),
)
def try_parse_wrapped(
data: str | dict | list,
hd_wrapped_data_object: Literal["SERIES", "DATAFRAME"],
) -> MetaDataWrapped:
if isinstance(data, str):
wrapped_data = MetaDataWrapped.parse_raw(data) # model_validate_json in pydantic 2.0
if wrapped_data.hd_wrapped_data_object__ != hd_wrapped_data_object:
msg = (
f"Unexpected hd model type: {wrapped_data.hd_wrapped_data_object__}."
f" Expected {hd_wrapped_data_object}"
)
logger.warning(msg)
raise TypeError(msg)
else:
wrapped_data = MetaDataWrapped.parse_obj(data) # model_validate in pydantic 2.0
return wrapped_data
def parse_wrapped_content(
v: str | dict | list,
wrapped_data_objec: Literal["SERIES", "DATAFRAME"],
) -> tuple[str | dict | list, None | dict[str, Any], dict[str, Any]]:
data_content: str | dict | list
try:
wrapped_object = try_parse_wrapped(v, wrapped_data_objec)
parsed_metadata = wrapped_object.metadata__
data_content = wrapped_object.data__
parsing_options = wrapped_object.data_parsing_options__
except (ValidationError, TypeError) as e:
logger.debug("Data object is not wrapped: %s", str(e))
data_content = v
parsed_metadata = None
parsing_options = {}
return data_content, parsed_metadata, parsing_options
def wrap_metadata_as_attrs(
data_object: pd.Series | pd.DataFrame, metadata: None | dict[str, Any]
) -> pd.Series | pd.DataFrame: # TODO: make generic: input type = output type
if metadata is not None:
data_object.attrs = metadata
else:
data_object.attrs = {}
return data_object
def parse_pandas_data_content(
data_content: str | dict | list, typ: Literal["series", "frame"], parsing_options: dict
) -> pd.DataFrame | pd.Series:
try:
if isinstance(data_content, str):
parsed_pandas_object = pd.read_json(
io.StringIO(data_content), typ=typ, **parsing_options
)
else:
parsed_pandas_object = pd.read_json(data_content, typ=typ, **parsing_options)
except Exception: # noqa: BLE001
try:
parsed_pandas_object = pd.read_json(
io.StringIO(json.dumps(data_content)), typ=typ, **parsing_options
)
except Exception as read_json_exception: # noqa: BLE001
raise ValueError(
"Could not parse provided input as Pandas "
+ ("Series" if type == "series" else "DataFrame")
) from read_json_exception
return parsed_pandas_object
class DataType(StrEnum):
"""hetida designer data types
These are the types available for component/workflow inputs/outputs.
"""
Integer = "INT"
Float = "FLOAT"
String = "STRING"
DataFrame = "DATAFRAME"
Series = "SERIES"
MultiTSFrame = "MULTITSFRAME"
Boolean = "BOOLEAN"
Any = "ANY"
PlotlyJson = "PLOTLYJSON"
class PydanticPandasSeries:
"""Custom pydantic Data Type for parsing Pandas Series
Parses either a json string according to pandas.read_json
with typ="series" and default arguments otherwise or
a Python dict-like data structure using the constructor
of the pandas.Series class with default arguments.
Also allows a wrapped variant where metadata can be provided.
Examples of valid input:
'{"0":1.0,"1":2.1,"2":3.2}'
{"0":1.0,"1":2.1,"2":3.2}
[1.2, 3.5, 2.9]
'[1.2, 3.5, 2.9]'
"""
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate
@classmethod
def validate( # noqa: PLR0911,PLR0912
cls, v: pd.Series | str | dict | list
) -> pd.Series:
if isinstance(v, pd.Series):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing Series: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "SERIES")
return wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "series", parsing_options), metadata
)
class PydanticPandasDataFrame:
"""Custom pydantic Data Type for parsing Pandas DataFrames
Parses either a json string according to pandas.read_json
with typ="frame" and default arguments otherwise or
a Python dict-like data structure using the constructor
of the pandas.DataFrame class with default arguments.
Additionally a MetaDataWrapped variant of these can be parsed
and then is equipped with the provided metadata in the `attrs`
attribute (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.attrs.html
"""
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate
@classmethod
def validate(cls, v: pd.DataFrame | str | dict | list) -> pd.DataFrame:
if isinstance(v, pd.DataFrame):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing DataFrame: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "DATAFRAME")
return wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "frame", parsing_options), metadata
)
class PydanticMultiTimeseriesPandasDataFrame:
"""Custom pydantic Data Type for parsing Multi Timeseries Pandas DataFrames
Parses data as a dataframe similarly to PydanticPandasDataFrame but
additionally checks the column layout and types to match the conventions
for a multitsframe.
"""
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate_df
yield cls.validate_multits_properties
@classmethod
def validate_df(cls, v: pd.DataFrame | str | dict | list) -> pd.DataFrame:
if isinstance(v, pd.DataFrame):
return v
if not isinstance(
v, str | dict | list
): # need to check at runtime since we get objects from user code
msg = f"Got unexpected type at runtime when parsing MultiTsFrame: {str(type(v))}"
logger.error(msg)
raise ValueError(msg)
data_content, metadata, parsing_options = parse_wrapped_content(v, "DATAFRAME")
return wrap_metadata_as_attrs(
parse_pandas_data_content(data_content, "frame", parsing_options), metadata
)
@classmethod
def validate_multits_properties( # noqa:PLR0912
cls, df: pd.DataFrame
) -> pd.DataFrame:
if len(df.columns) == 0:
df = pd.DataFrame(columns=MULTITSFRAME_COLUMN_NAMES)
if len(df.columns) < 3:
raise ValueError(
"MultiTSFrame requires at least 3 columns: metric, timestamp"
f" and at least one additional columns. Only found {str(df.columns)}"
)
if not ({"metric", "timestamp"}.issubset(set(df.columns))):
column_names_string = ", ".join(df.columns)
raise ValueError(
f"The column names {column_names_string} don't contain required columns"
' "timestamp" and "metric" for a MultiTSFrame.'
)
if df["metric"].isna().any():
raise ValueError(
"No null values are allowed for the column 'metric' of a MulitTSFrame."
)
df["metric"] = df["metric"].astype("string")
if df["timestamp"].isna().any():
raise ValueError(
"No null values are allowed for the column 'timestamp' of a MulitTSFrame."
)
if len(df.index) == 0:
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
if not isinstance(df["timestamp"].dtype, pd.DatetimeTZDtype):
raise ValueError(
"Column 'timestamp' of MultiTSFrame does not have DatetimeTZDtype dtype. "
f'Got {str(df["timestamp"].dtype)} index dtype instead.'
)
if not df["timestamp"].dt.tz in (pytz.UTC, datetime.timezone.utc):
raise ValueError(
"Column 'timestamp' of MultiTSFrame does not have UTC timezone. "
f'Got {str(df["timestamp"].dt.tz)} timezone instead.'
)
return df.sort_values("timestamp")
class ParsedAny:
"""Tries to parse Any objects somehow intelligently
Reason is that an object may be provided by the backend either as a proper json-object directly
in some cases (dict-like objects) or as json-encoded string (happens for example for lists).
Sometimes, if the frontend is involved, json strings get even double-string-encoded! This is a
known bug of frontend-backend-runtime interaction.
Sometimes adapter implementations deliver ANY-data directly as json objects and othertimes
string-encoded.
As a workaround for all these cases this class tries to json-parse a string if it receives one
and only if that does not work it yields the actual string value. If it works and the result is
itself a string again it tries to json-decode a second time and returns the result if that
works. Otherwise it returns the result string of the first parsing.
This workaround is justified by the argument that the user should really use a STRING input if
a string is expected and not an ANY input. Likewise, adapters should offer string data as STRING
data sources and not as ANY data sources.
"""
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> Any:
if isinstance(v, str):
# try to parse string as json
try:
parsed_json_object = json.loads(v)
except json.decoder.JSONDecodeError:
logger.info(
"Could not JSON-parse string %s in Any input."
" Therefore treating it as actual string value",
v[:30] + "..." if len(v) > 10 else v,
)
return v
if isinstance(
parsed_json_object, str
): # sometimes it even gets double-encoded for some reasons
try:
parsed_json_object = json.loads(parsed_json_object)
except json.decoder.JSONDecodeError:
logger.info(
"Could not JSON-parse string %s in Any input. "
" Therefore treating it as actual string value",
parsed_json_object[:30] + "..." if len(v) > 10 else v,
)
return parsed_json_object
return parsed_json_object
return v
data_type_map: dict[DataType, type] = {
DataType.Integer: int,
DataType.Float: float,
DataType.String: str,
DataType.Series: PydanticPandasSeries,
DataType.MultiTSFrame: PydanticMultiTimeseriesPandasDataFrame,
DataType.DataFrame: PydanticPandasDataFrame,
DataType.Boolean: bool,
# Any as Type is the correct way to tell pydantic how to parse an arbitrary object:
DataType.Any: ParsedAny,
DataType.PlotlyJson: dict,
}
optional_data_type_map: dict[DataType, UnionType] = {
DataType.Integer: int | None,
DataType.Float: float | None,
DataType.String: str | None,
DataType.Series: PydanticPandasSeries | None,
DataType.MultiTSFrame: PydanticMultiTimeseriesPandasDataFrame | None,
DataType.DataFrame: PydanticPandasDataFrame | None,
DataType.Boolean: bool | None,
# Any as Type is the correct way to tell pydantic how to parse an arbitrary object:
DataType.Any: ParsedAny | None,
DataType.PlotlyJson: dict | None,
}
class AdvancedTypesOutputSerializationConfig(BaseConfig):
"""Enable Pydantic Models to serialize Pandas obejcts with this config class"""
# Unfortunately there is no good way to get None for NaN or NaT:
json_encoders = {
pd.Series: lambda v: {
"__hd_wrapped_data_object__": "SERIES",
"__metadata__": v.attrs,
"__data__": json.loads(
# double serialization7deserialization in order to serialize both NaN and NaT
# to null
v.to_json(
date_format="iso",
orient="split",
# orient="split" serialization is the only way pandas keeps duplicate index
# (with possibly different values) entries for Series objects!
)
),
"__data_parsing_options__": {"orient": "split"},
},
pd.DataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso") # in order to serialize both NaN and NaT to null
),
},
PydanticPandasSeries: lambda v: {
"__hd_wrapped_data_object__": "SERIES",
"__metadata__": v.attrs,
"__data__": v.to_dict(),
},
PydanticPandasDataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso") # in order to serialize both NaN and NaT to null
),
},
PydanticMultiTimeseriesPandasDataFrame: lambda v: {
"__hd_wrapped_data_object__": "DATAFRAME",
"__metadata__": v.attrs,
"__data__": json.loads(
v.to_json(date_format="iso")
), # in order to serialize both NaN and NaT to null
},
np.ndarray: lambda v: v.tolist(),
datetime.datetime: lambda v: v.isoformat(),
UUID: lambda v: str(v), # alternatively: v.hex
Figure: lambda v: json.loads(json.dumps(v.to_plotly_json(), cls=PlotlyJSONEncoder)),
}
class NamedDataTypedValue(TypedDict):
name: str
type: DataType # noqa: A003
value: Any
def parse_via_pydantic(
entries: list[NamedDataTypedValue],
type_map: dict[DataType, type] | dict[DataType, UnionType] | None = None,
) -> BaseModel:
"""Parse data dynamically into a pydantic object
Optionally a type_map can be specified which differs from the default data_type_map
Returns an instantiated pydantic object if no parsing exception is thrown.
May raise the typical exceptions of pydantic parsing.
"""
type_dict: dict[str, tuple[type | UnionType, "ellipsis"]] = { # noqa: F821
entry["name"]: (
type_map[entry["type"]]
if type_map is not None
else data_type_map[entry["type"]], # default to data_type_map
...,
)
for entry in entries
}
DynamicModel = create_model("DynamicyModel", **type_dict) # type: ignore
return DynamicModel(**{entry["name"]: entry["value"] for entry in entries}) # type: ignore
def parse_dynamically_from_datatypes(
entries: list[NamedDataTypedValue], nullable: bool = False
) -> BaseModel:
return parse_via_pydantic(
entries, type_map=data_type_map if nullable is False else optional_data_type_map
)
def parse_single_value_dynamically(
name: str, value: Any, data_type: DataType, nullable: bool
) -> Any:
return parse_dynamically_from_datatypes(
[{"name": name, "type": data_type, "value": value}], nullable
).dict()[name]
def parse_value(value: Any, data_type_str: str, nullable: bool) -> Any:
return parse_single_value_dynamically("some_value", value, DataType(data_type_str), nullable)
def parse_default_value(component_info: dict, input_name: str) -> Any:
"""Parse default value from COMPONENT_INFO dict
Used in component main function header to parse a default
value from the COMPONENT_INFO dict for an input.
"""
inp = component_info["inputs"][input_name]
return parse_value(inp["default_value"], inp["data_type"], True)
def plotly_fig_to_json_dict(fig: Figure) -> Any:
"""Turn Plotly figure into a Python dict-like object
This function can be used in visualization components to obtain the
correct plotly json-like object from a Plotly Figure object.
See visualization components from the accompanying base components for
examples on usage.
"""
# possibly quite inefficient (multiple serialisation / deserialization) but
# guarantees that the PlotlyJSONEncoder is used and so the resulting Json
# should be definitely compatible with the plotly javascript library:
return json.loads(json.dumps(fig.to_plotly_json(), cls=PlotlyJSONEncoder))
END_HEREDOC
)
###############################################################################
# #
# Usage / help #
# #
###############################################################################
usage() {
if [ -n "${1-}" ]; then
_log_error "--> ERROR: $1"
fi
echo "BASIC USAGE: Run"
echo " $0 SUBCOMMAND <parameters>"
echo " $0 sync SYNCCOMMAND INSTANCE"
echo
echo "EXAMPLES"
echo
echo " SYNC:"
echo " Init a new hetida designer instance against which you want to sync"
echo
echo " $0 sync init my-hd-instance"
echo
echo " After following the instructions and setting configuration options"
echo " and credentials in the generated files:"
echo
echo " $0 sync pull my-hd-instance # sync to local dir"
echo " $0 sync push my-hd-instance # push local dir to hd instance"
echo
echo " Sync of the local file content of my-hd-instance to/from another configured"
echo " instance named my-other-hd-instance can be done via"
echo
echo " $0 sync push my-other-hd-instance from my-hd-instance"
echo " $0 sync pull my-other-hd-instance to my-hd-instance"
echo
echo " It is recommended to use git for versioning of local files and you"
echo " should commit before and after each sync operation."
echo
echo " FETCHING:"
echo " Write json list of all components from Physics category to stdout"
echo
echo " $0 "'fetch --url-append "?category=Physics&type=COMPONENT"'
echo
echo " Notes: * In these examples configuration like backend api url, auth etc is assumed to"
echo " come from ./hdctl.env file or HDCTL_* environment variables."
echo " * available query parameters of the backend api are documented in the openapi"
echo " documentation of the /api/transformations GET / PUT endpoints and the"
echo " /api/maintenance/* endpoints"
echo " * --url-append does not urlencode automatically."
echo
echo " With recent curl (>= 7.87.0, from 2023 or later) you can also propagate query params"
echo " via --url-query which automatically url encodes them as follows (note the space char"
echo " in category):"
echo
echo " $0 "'fetch -- --url-query "category=Anomaly Detection" --url-query "type=COMPONENT"'
echo
echo " Export json list of transformation revisions of category Physics into single file,"
echo " pretty printing the json by piping it through jq:"
echo
echo " $0 fetch -- -d "'"category=Physics"'" | jq > physics_trafos.json"
echo
echo " Export all non-deprecated workflows into directory structure at ./exported_trafos including"
echo " their dependencies. The directory and subdirectories for type and catgeory will be created"
echo " if necessary (This command needs awk and jq!)"
echo
echo " $0 "'fetch --export-directory ./exported_trafos -- \'
echo ' --url-query "type=WORKFLOW"\'
echo ' --url-query "include_dependencies=true"\'
echo ' --url-query "include_deprecated=false"'
echo
echo " PUSHING:"
echo ' Import from export directory only the workflows with name "Combine two Series'
echo ' into DataFrame" which are released (there may be drafts or deprecated revisions)'
echo " together with their dependencies. Overwrite released trafo revs if necessary:"
echo
echo " $0 "'push --export-trafos ./exported_trafos --\'
echo ' --url-query "name=Combine two Series into DataFrame"\'
echo ' --url-query "include_dependencies=true"\'
echo ' --url-query "allow_overwrite_released=true"\'
echo ' --url-query "state=RELEASED"'
echo
echo " The response shows which trafo revs actually where imported and which where ignored."
echo " You may want to pipe it through jq for pretty printing."
echo
echo " Import released components from json file containing list of trafo revs allowing overwriting"
echo " of released components:"
echo
echo " $0 "'push physics_trafos.json --url-append "?type=COMPONENT&state=RELEASED&allow_overwrite_released=true"'
echo
echo " MAINTENANCE:"
echo
echo " Redeploy base trafos on a remote instance hddev, e.g. after upgrading:"
echo
echo " $0 "'deploy_base_trafos -i hddev --url-query "allow_overwrite_released=true"'
echo
echo " Following examples assume that the maintenance secret is set either in hdctl.env"
echo " file (MAINTENANCE_SECRET) or as environment variable HDCTL_MAINTENANCE_SECRET."
echo
echo " Deprecate all but the latest released (i.e. by release date, disregarding version tag!)"
echo " revision of every transformation revision group:"
echo
echo " $0 deprecate_all_but_latest_per_group"
echo
echo " Purge your installation: Delete everything and afterwards redeploy base trafos from"
echo " running backend (WARNING: irreversible data loss!):"
echo
echo " $0 purge"
echo
echo "GENERAL HINTS"
echo "Parameters can be supplied with increasing priority as follows:"
echo " * On startup a .env file is sourced if available, by default ./hdctl.env."
echo " You can configure its path via HDCTL_ENV_FILE environment variable. It should"
echo " define variables corresponding to settings of form NAME_IN_UPPER_CASE. In case"
echo " of using the sync subcommands instance and credential files are used instead."
echo " * Environment variables prefixed with HDCTL_ (HDCTL_NAME_IN_UPPER_CASE) are interpreted"
echo " and may override NAME_IN_UPPER_CASE from the env file."
echo " * explicit command line parameters override all these settings"
echo
echo "On the command line values to parameters are separated with space inbetween like"
echo " --backend-api-url http://localhost:8080/api"
echo "or"
echo " -b http://localhost:8080/api"
echo "(i.e. not --backend-api-url=http://localhost:8080/api )"
echo
echo "Most parameters are general and can be set independantly of subcommands. Whether they"
echo "are used depends on the actual subcommand invoked."
echo
echo "Arguments after -- are gathered. If the subcommand invokes curl, they are appended to "
echo "the curl command at the end. This allows for example to usq the --url-query curl argument"
echo "to control filters when fetching / pushing, as you can see in the examples above."
echo
echo "In the following we reference settings by naming them by the variable as it"
echo "would occur in the .env file (i.e. NAME_IN_UPPER_CASE). Recall that the corresponding"
echo "environment variable then is HDCTL_NAME_IN_UPPER_CASE."
echo
echo "Subcommands typically make http requests to a hd backend api configured via"
echo "HD_BACKEND_API_URL pointing to the /api resource of the backend service, e.g."
echo " http://localhost:8080/api"
echo
echo "Authentication is handled as follows:"
echo " * if DIRECT_ACCESS_TOKEN is set, it is passed as Bearer token."
echo " * if DIRECT_ACCESS_TOKEN is not set / empty string:"
echo " * if AUTH_URL is set (e.g. http://localhost/auth)"
echo " * if USERNAME is set / non-zero, an access token is tried to be obtained"
echo " with PASSWORD from the auth provider at AUTH_URL via openidconnect standard"
echo " using password grant credential flow."
echo " * if USERNAME is not set, CLIENT_ID and CLIENT_SECRET are used to obtain"
echo " an access token from the auth provider at AUTH_URL via openidconnect standard"
echo " using client credential grant flow."
echo " * if AUTH_URL is not set / empty string the backend is expected to be reachable"
echo " without authentication."
echo
echo "PARAMETERS"
echo " Mandatory arguments to long options are mandatory for short options too. Name of"
echo " corresponding environment variable with HDCTL_ prefix in parantheses."
echo
echo " -e | --env-file PATH (HDCTL_ENV_FILE)"
echo " path to env file that will be sourced at startup. Defaults to ./hdctl.env."
echo " If set to non-default value it must exist."
echo
echo " -i | --instance INSTANCE_NAME"
echo " Use config from instance files (see sync commands) instead of env file"
echo
echo " -b | --backend-api-url URL (HDCTL_HD_BACKEND_API_URL)"
echo " URL of the backend api resource, e.g. http://localhost:8080/api"
echo
echo " --insecure-backend (HDCTL_VERIFY_BACKEND_API_URL)"
echo " do not verify https when communicating with the backend."
echo
echo " --add (HDCTL_SYNC_CLEAR_DIRECTORY)"
echo " For sync pull commands: If set the target export directory will not be cleared."
echo " Trafos will be overwritten / added instead. Note that the environment"
echo " variable is true by default and setting --add sets it to false."
echo
echo " -d | --export-directory PATH (HDCTL_EXPORT_DIRECTORY)"
echo " PATH to a directory where data should be exported to (fetch) or loaded from (push)."
echo " fetch will create the directory and distribute downloaded trafo revs into json files"
echo " at pathes like, using jq and awk"
echo " PATH/{workflows,components}/<CATEGORY>/<NAME>_<VERSION_TAG>_<ID>.json"
echo " If this is not set, fetch will instead output a json list of all downloaded trafo revs"
echo " to stdout."
echo " push will use the directory as source if this is set. If not, push expects a path"
echo " to a single json file containing an array of trafo revs as first argument instead."
echo
echo " -a | --auth-url AUTH_URL (HDCTL_AUTH_URL)"
echo " Openidconnect auth provider auth endpoint, e.g. https://localhost/auth"
echo
echo " --insecure-auth (HDCTL_VERIFY_AUTH_URL)"
echo " do not verify https when communicating with auth provider"
echo
echo " -t | --access-token TOKEN (HDCTL_DIRECT_ACCESS_TOKEN)"
echo " If this is provided, it will be used as Bearer access token and no communication"
echo " with auth provider will happen. Make sure that TOKEN is not expired."
echo
echo " -r | --realm REALM (HDCTL_REALM)"
echo " openidconnect realm name that should be used."
echo
echo " -c | --client-id CLIENT_ID (HDCTL_CLIENT_ID)"
echo " The client id. Necessary for both password grant and client credential grant auth flow."
echo
echo " -s | --client-secret CLIENT_SECRET (HDCTL_CLIENT_SECRET)"
echo " The client secret when using client credential secret auth flow"
echo
echo " -m | --maintenance-secret SECRET (HDCTL_MAINTENANCE_SECRET)"
echo " Maintenance actions require a maintenance secret to be configured in the backend"
echo " and provided whith each maintenance endpoint request."
echo
echo " -p | --url-append PARAMSTRING (HDCTL_QUERY_URL_APPEND)"
echo " PARAMSTRING will be appended as-is to the url in curl invocations. Can be used"
echo ' to provide query parameters, for example --url-append "?type=COMPONENT&state=RELEASED"'
echo
echo " -q | --quiet (HDCTL_SILENT)"
echo " suppress some output"
echo
echo " -v | --verbose (HDCTL_VERBOSITY)"
echo ' The default is "info". Setting it will switch to "debug" and send some additional debug'
echo " output to stderr"
echo
echo " --"
echo " All command line arguments following -- will be gathered and for curl-invoking"
echo " subcommands they will be appended to the curl call."
echo
echo "AVAILABLE CUBCOMMANDS BY TOPIC"
echo " SYNC PULL / SYNC PUSH / SYNC INIT"
echo " Sync is the easiest way for bidirectional transfer of selections of workflows and"
echo " components between a local directory and a hetida designer instance. Under the hood"
echo " it uses the fetch and push commands described below, but allows configuration and"
echo " credentials to reside in local files. In combination with version control, e.g. git,"
echo " this enables:"
echo " * external version control"
echo " * editing locally / hybrid working and frequent switching between local work"
echo " and work in the hetida designer user interface"
echo " * scripting CD/CI and GitOps"
echo
echo " The configuration and credential files for a remote hetida designer instance"
echo ' you want to name "my-hd-instance" can be pregenerated via'
echo
echo " $0 sync init my-hd-instance"
echo
echo " Make sure you follow the instructions this command prints out! After that"
echo " you should have at least a my-hd-instance.hd-instance file and a "
echo " my-hd-instance.hd-creds file which are used as configuration for syncing."
echo " Additionally a my-hd-instance.hd-creds.stub file is present that can be checked into"
echo " version control together with the .hd-instance file. You should of course never"
echo " put the my-hd-instance.hd-creds into version control which you have provided"
echo " with actual passwords and secrets. Put *.hd-creds into your .gitignore instead!"
echo
echo " You can now transfer transformations from/to the configured local directory via"
echo
echo " $0 sync pull my-hd-instance"
echo " $0 sync push my-hd-instance"
echo
echo " Note that pulling overwrites the local directory completely. It is strongly"
echo " recommended to use version control and commit before and after puling and"
echo " pushing."
echo
echo " Note that what is pulled and pushed depends on the settings in your .hd-instance"
echo " file. The query url parameters of the /api/transformations GET and PUT endpoints"
echo " allow for fine-granular filtering and updating / expanding the exported"
echo " component code with documentation and a wiring."
echo
echo " Sync of the local file content of my-hd-instance to/from another configured"
echo " instance named my-other-hd-instance can be done via"
echo
echo " $0 sync push my-other-hd-instance from my-hd-instance"
echo " $0 sync pull my-other-hd-instance to my-hd-instance"
echo
echo " This pushes / pulls with the settings of my-other-hd-instance but uses the"
echo " export directory configured for my-hd-instance as source / target."
echo
echo " Finally you can explicitely override the directory to use, e.g.:"
echo
echo " $0 sync push my-prod-instance -d /mounted/volume/dir"
echo
echo " FETCH / EXPORT / DOWNLOAD"
echo " The fetch subcommand downloads / exports transformation revisions from the hetida"
echo " designer backends using curl, handling auth if necessary. If an export directory"
echo " is set it will use jq and awk to distribute the transformation revisions as single"
echo " json file each into a directory structure, separating by type and category"
echo
echo " $0 fetch -d EXPORT_DIRECTORY"
echo
echo " Otherwise it will output a json array to stdout"
echo
echo " $0 fetch"
echo
echo " Piping its output to a file creates a single json file containing all fetched"
echo " transformation revisions. See -d parameter for details."
echo