test_processor_kfp.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. #
  2. # Copyright 2018-2022 Elyra Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import os
  17. from pathlib import Path
  18. import tarfile
  19. from unittest import mock
  20. from kfp import compiler as kfp_argo_compiler
  21. import pytest
  22. import yaml
  23. from elyra.metadata.metadata import Metadata
  24. from elyra.pipeline.catalog_connector import FilesystemComponentCatalogConnector
  25. from elyra.pipeline.catalog_connector import UrlComponentCatalogConnector
  26. from elyra.pipeline.component import Component
  27. from elyra.pipeline.kfp.processor_kfp import KfpPipelineProcessor
  28. from elyra.pipeline.parser import PipelineParser
  29. from elyra.pipeline.pipeline import GenericOperation
  30. from elyra.pipeline.pipeline import Operation
  31. from elyra.pipeline.pipeline import Pipeline
  32. from elyra.tests.pipeline.test_pipeline_parser import _read_pipeline_resource
  33. ARCHIVE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "resources", "archive")
  34. @pytest.fixture
  35. def processor(setup_factory_data):
  36. processor = KfpPipelineProcessor(root_dir=os.getcwd())
  37. return processor
  38. @pytest.fixture
  39. def pipeline():
  40. pipeline_resource = _read_pipeline_resource("resources/sample_pipelines/pipeline_3_node_sample.json")
  41. return PipelineParser.parse(pipeline_resource)
  42. @pytest.fixture
  43. def sample_metadata():
  44. return {
  45. "api_endpoint": "http://examples.com:31737",
  46. "cos_endpoint": "http://examples.com:31671",
  47. "cos_username": "example",
  48. "cos_password": "example123",
  49. "cos_bucket": "test",
  50. "engine": "Argo",
  51. "tags": [],
  52. }
  53. def test_fail_get_metadata_configuration_invalid_namespace(processor):
  54. with pytest.raises(RuntimeError):
  55. processor._get_metadata_configuration(schemaspace="non_existent_namespace", name="non_existent_metadata")
  56. def test_generate_dependency_archive(processor):
  57. pipelines_test_file = os.path.join(ARCHIVE_DIR, "test.ipynb")
  58. pipeline_dependencies = ["airflow.json"]
  59. correct_filelist = ["test.ipynb", "airflow.json"]
  60. component_parameters = {
  61. "filename": pipelines_test_file,
  62. "dependencies": pipeline_dependencies,
  63. "runtime_image": "tensorflow/tensorflow:latest",
  64. }
  65. test_operation = GenericOperation(
  66. id="123e4567-e89b-12d3-a456-426614174000",
  67. type="execution-node",
  68. classifier="execute-notebook-node",
  69. name="test",
  70. component_params=component_parameters,
  71. )
  72. archive_location = processor._generate_dependency_archive(test_operation)
  73. tar_content = []
  74. with tarfile.open(archive_location, "r:gz") as tar:
  75. for tarinfo in tar:
  76. if tarinfo.isreg():
  77. print(tarinfo.name)
  78. tar_content.append(tarinfo.name)
  79. assert sorted(correct_filelist) == sorted(tar_content)
  80. def test_fail_generate_dependency_archive(processor):
  81. pipelines_test_file = "this/is/a/rel/path/test.ipynb"
  82. pipeline_dependencies = ["non_existent_file.json"]
  83. component_parameters = {
  84. "filename": pipelines_test_file,
  85. "dependencies": pipeline_dependencies,
  86. "runtime_image": "tensorflow/tensorflow:latest",
  87. }
  88. test_operation = GenericOperation(
  89. id="123e4567-e89b-12d3-a456-426614174000",
  90. type="execution-node",
  91. classifier="execute-notebook-node",
  92. name="test",
  93. component_params=component_parameters,
  94. )
  95. with pytest.raises(Exception):
  96. processor._generate_dependency_archive(test_operation)
  97. def test_get_dependency_source_dir(processor):
  98. pipelines_test_file = "this/is/a/rel/path/test.ipynb"
  99. processor.root_dir = "/this/is/an/abs/path/"
  100. correct_filepath = "/this/is/an/abs/path/this/is/a/rel/path"
  101. component_parameters = {"filename": pipelines_test_file, "runtime_image": "tensorflow/tensorflow:latest"}
  102. test_operation = GenericOperation(
  103. id="123e4567-e89b-12d3-a456-426614174000",
  104. type="execution-node",
  105. classifier="execute-notebook-node",
  106. name="test",
  107. component_params=component_parameters,
  108. )
  109. filepath = processor._get_dependency_source_dir(test_operation)
  110. assert filepath == correct_filepath
  111. def test_get_dependency_archive_name(processor):
  112. pipelines_test_file = "this/is/a/rel/path/test.ipynb"
  113. correct_filename = "test-this-is-a-test-id.tar.gz"
  114. component_parameters = {"filename": pipelines_test_file, "runtime_image": "tensorflow/tensorflow:latest"}
  115. test_operation = GenericOperation(
  116. id="this-is-a-test-id",
  117. type="execution-node",
  118. classifier="execute-notebook-node",
  119. name="test",
  120. component_params=component_parameters,
  121. )
  122. filename = processor._get_dependency_archive_name(test_operation)
  123. assert filename == correct_filename
  124. def test_collect_envs(processor):
  125. pipelines_test_file = "this/is/a/rel/path/test.ipynb"
  126. # add system-owned envs with bogus values to ensure they get set to system-derived values,
  127. # and include some user-provided edge cases
  128. operation_envs = [
  129. 'ELYRA_RUNTIME_ENV="bogus_runtime"',
  130. 'ELYRA_ENABLE_PIPELINE_INFO="bogus_pipeline"',
  131. "ELYRA_WRITABLE_CONTAINER_DIR=", # simulate operation reference in pipeline
  132. 'AWS_ACCESS_KEY_ID="bogus_key"',
  133. 'AWS_SECRET_ACCESS_KEY="bogus_secret"',
  134. "USER_EMPTY_VALUE= ",
  135. "USER_TWO_EQUALS=KEY=value",
  136. "USER_NO_VALUE=",
  137. ]
  138. component_parameters = {
  139. "filename": pipelines_test_file,
  140. "env_vars": operation_envs,
  141. "runtime_image": "tensorflow/tensorflow:latest",
  142. }
  143. test_operation = GenericOperation(
  144. id="this-is-a-test-id",
  145. type="execution-node",
  146. classifier="execute-notebook-node",
  147. name="test",
  148. component_params=component_parameters,
  149. )
  150. envs = processor._collect_envs(test_operation, cos_secret=None, cos_username="Alice", cos_password="secret")
  151. assert envs["ELYRA_RUNTIME_ENV"] == "kfp"
  152. assert envs["AWS_ACCESS_KEY_ID"] == "Alice"
  153. assert envs["AWS_SECRET_ACCESS_KEY"] == "secret"
  154. assert envs["ELYRA_ENABLE_PIPELINE_INFO"] == "True"
  155. assert envs["ELYRA_WRITABLE_CONTAINER_DIR"] == "/tmp"
  156. assert "USER_EMPTY_VALUE" not in envs
  157. assert envs["USER_TWO_EQUALS"] == "KEY=value"
  158. assert "USER_NO_VALUE" not in envs
  159. # Repeat with non-None secret - ensure user and password envs are not present, but others are
  160. envs = processor._collect_envs(test_operation, cos_secret="secret", cos_username="Alice", cos_password="secret")
  161. assert envs["ELYRA_RUNTIME_ENV"] == "kfp"
  162. assert "AWS_ACCESS_KEY_ID" not in envs
  163. assert "AWS_SECRET_ACCESS_KEY" not in envs
  164. assert envs["ELYRA_ENABLE_PIPELINE_INFO"] == "True"
  165. assert envs["ELYRA_WRITABLE_CONTAINER_DIR"] == "/tmp"
  166. assert "USER_EMPTY_VALUE" not in envs
  167. assert envs["USER_TWO_EQUALS"] == "KEY=value"
  168. assert "USER_NO_VALUE" not in envs
  169. def test_process_list_value_function(processor):
  170. # Test values that will be successfully converted to list
  171. assert processor._process_list_value("") == []
  172. assert processor._process_list_value(None) == []
  173. assert processor._process_list_value("[]") == []
  174. assert processor._process_list_value("None") == []
  175. assert processor._process_list_value("['elem1']") == ["elem1"]
  176. assert processor._process_list_value("['elem1', 'elem2', 'elem3']") == ["elem1", "elem2", "elem3"]
  177. assert processor._process_list_value(" ['elem1', 'elem2' , 'elem3'] ") == ["elem1", "elem2", "elem3"]
  178. assert processor._process_list_value("[1, 2]") == [1, 2]
  179. assert processor._process_list_value("[True, False, True]") == [True, False, True]
  180. assert processor._process_list_value("[{'obj': 'val', 'obj2': 'val2'}, {}]") == [{"obj": "val", "obj2": "val2"}, {}]
  181. # Test values that will not be successfully converted to list
  182. assert processor._process_list_value("[[]") == "[[]"
  183. assert processor._process_list_value("[elem1, elem2]") == "[elem1, elem2]"
  184. assert processor._process_list_value("elem1, elem2") == "elem1, elem2"
  185. assert processor._process_list_value(" elem1, elem2 ") == "elem1, elem2"
  186. assert processor._process_list_value("'elem1', 'elem2'") == "'elem1', 'elem2'"
  187. def test_process_dictionary_value_function(processor):
  188. # Test values that will be successfully converted to dictionary
  189. assert processor._process_dictionary_value("") == {}
  190. assert processor._process_dictionary_value(None) == {}
  191. assert processor._process_dictionary_value("{}") == {}
  192. assert processor._process_dictionary_value("None") == {}
  193. assert processor._process_dictionary_value("{'key': 'value'}") == {"key": "value"}
  194. dict_as_str = "{'key1': 'value', 'key2': 'value'}"
  195. assert processor._process_dictionary_value(dict_as_str) == {"key1": "value", "key2": "value"}
  196. dict_as_str = " { 'key1': 'value' , 'key2' : 'value'} "
  197. assert processor._process_dictionary_value(dict_as_str) == {"key1": "value", "key2": "value"}
  198. dict_as_str = "{'key1': [1, 2, 3], 'key2': ['elem1', 'elem2']}"
  199. assert processor._process_dictionary_value(dict_as_str) == {"key1": [1, 2, 3], "key2": ["elem1", "elem2"]}
  200. dict_as_str = "{'key1': 2, 'key2': 'value', 'key3': True, 'key4': None, 'key5': [1, 2, 3]}"
  201. expected_value = {"key1": 2, "key2": "value", "key3": True, "key4": None, "key5": [1, 2, 3]}
  202. assert processor._process_dictionary_value(dict_as_str) == expected_value
  203. dict_as_str = "{'key1': {'key2': 2, 'key3': 3, 'key4': 4}, 'key5': {}}"
  204. expected_value = {
  205. "key1": {
  206. "key2": 2,
  207. "key3": 3,
  208. "key4": 4,
  209. },
  210. "key5": {},
  211. }
  212. assert processor._process_dictionary_value(dict_as_str) == expected_value
  213. # Test values that will not be successfully converted to dictionary
  214. assert processor._process_dictionary_value("{{}") == "{{}"
  215. assert processor._process_dictionary_value("{key1: value, key2: value}") == "{key1: value, key2: value}"
  216. assert processor._process_dictionary_value(" { key1: value, key2: value } ") == "{ key1: value, key2: value }"
  217. assert processor._process_dictionary_value("key1: value, key2: value") == "key1: value, key2: value"
  218. assert processor._process_dictionary_value("{'key1': true}") == "{'key1': true}"
  219. assert processor._process_dictionary_value("{'key': null}") == "{'key': null}"
  220. dict_as_str = "{'key1': [elem1, elem2, elem3], 'key2': ['elem1', 'elem2']}"
  221. assert processor._process_dictionary_value(dict_as_str) == dict_as_str
  222. dict_as_str = "{'key1': {key2: 2}, 'key3': ['elem1', 'elem2']}"
  223. assert processor._process_dictionary_value(dict_as_str) == dict_as_str
  224. dict_as_str = "{'key1': {key2: 2}, 'key3': ['elem1', 'elem2']}"
  225. assert processor._process_dictionary_value(dict_as_str) == dict_as_str
  226. def test_processing_url_runtime_specific_component(monkeypatch, processor, component_cache, sample_metadata, tmpdir):
  227. # Define the appropriate reader for a URL-type component definition
  228. kfp_supported_file_types = [".yaml"]
  229. reader = UrlComponentCatalogConnector(kfp_supported_file_types)
  230. # Assign test resource location
  231. url = (
  232. "https://raw.githubusercontent.com/elyra-ai/elyra/main/"
  233. "elyra/tests/pipeline/resources/components/filter_text.yaml"
  234. )
  235. # Read contents of given path -- read_component_definition() returns a
  236. # a dictionary of component definition content indexed by path
  237. entry_data = reader.get_entry_data({"url": url}, {})
  238. component_definition = entry_data.definition
  239. # Instantiate a url-based component
  240. component_id = "test_component"
  241. component = Component(
  242. id=component_id,
  243. name="Filter text",
  244. description="",
  245. op="filter-text",
  246. catalog_type="url-catalog",
  247. component_reference={"url": url},
  248. definition=component_definition,
  249. categories=[],
  250. properties=[],
  251. )
  252. # Fabricate the component cache to include single filename-based component for testing
  253. component_cache._component_cache[processor._type.name] = {
  254. "spoofed_catalog": {"components": {component_id: component}}
  255. }
  256. # Construct hypothetical operation for component
  257. operation_name = "Filter text test"
  258. operation_params = {"text": "path/to/text.txt", "pattern": "hello"}
  259. operation = Operation(
  260. id="filter-text-id",
  261. type="execution_node",
  262. classifier=component_id,
  263. name=operation_name,
  264. parent_operation_ids=[],
  265. component_params=operation_params,
  266. )
  267. # Build a mock runtime config for use in _cc_pipeline
  268. mocked_runtime = Metadata(name="test-metadata", display_name="test", schema_name="kfp", metadata=sample_metadata)
  269. mocked_func = mock.Mock(return_value="default", side_effect=[mocked_runtime, sample_metadata])
  270. monkeypatch.setattr(processor, "_get_metadata_configuration", mocked_func)
  271. # Construct single-operation pipeline
  272. pipeline = Pipeline(
  273. id="pipeline-id", name="kfp_test", runtime="kfp", runtime_config="test", source="filter_text.pipeline"
  274. )
  275. pipeline.operations[operation.id] = operation
  276. # Establish path and function to construct pipeline
  277. pipeline_path = os.path.join(tmpdir, "kfp_test.yaml")
  278. constructed_pipeline_function = lambda: processor._cc_pipeline(pipeline=pipeline, pipeline_name="test_pipeline")
  279. # TODO Check against both argo and tekton compilations
  280. # Compile pipeline and save into pipeline_path
  281. kfp_argo_compiler.Compiler().compile(constructed_pipeline_function, pipeline_path)
  282. # Read contents of pipeline YAML
  283. with open(pipeline_path) as f:
  284. pipeline_yaml = yaml.safe_load(f.read())
  285. # Check the pipeline file contents for correctness
  286. pipeline_template = pipeline_yaml["spec"]["templates"][0]
  287. assert pipeline_template["metadata"]["annotations"]["pipelines.kubeflow.org/task_display_name"] == operation_name
  288. assert pipeline_template["inputs"]["artifacts"][0]["raw"]["data"] == operation_params["text"]
  289. def test_processing_filename_runtime_specific_component(
  290. monkeypatch, processor, component_cache, sample_metadata, tmpdir
  291. ):
  292. # Define the appropriate reader for a filesystem-type component definition
  293. kfp_supported_file_types = [".yaml"]
  294. reader = FilesystemComponentCatalogConnector(kfp_supported_file_types)
  295. # Assign test resource location
  296. absolute_path = os.path.abspath(
  297. os.path.join(os.path.dirname(__file__), "..", "resources", "components", "download_data.yaml")
  298. )
  299. # Read contents of given path -- read_component_definition() returns a
  300. # a dictionary of component definition content indexed by path
  301. entry_data = reader.get_entry_data({"path": absolute_path}, {})
  302. component_definition = entry_data.definition
  303. # Instantiate a file-based component
  304. component_id = "test-component"
  305. component = Component(
  306. id=component_id,
  307. name="Download data",
  308. description="",
  309. op="download-data",
  310. catalog_type="elyra-kfp-examples-catalog",
  311. component_reference={"path": absolute_path},
  312. definition=component_definition,
  313. properties=[],
  314. categories=[],
  315. )
  316. # Fabricate the component cache to include single filename-based component for testing
  317. component_cache._component_cache[processor._type.name] = {
  318. "spoofed_catalog": {"components": {component_id: component}}
  319. }
  320. # Construct hypothetical operation for component
  321. operation_name = "Download data test"
  322. operation_params = {
  323. "url": "https://raw.githubusercontent.com/elyra-ai/elyra/main/tests/assets/helloworld.ipynb",
  324. "curl_options": "--location",
  325. }
  326. operation = Operation(
  327. id="download-data-id",
  328. type="execution_node",
  329. classifier=component_id,
  330. name=operation_name,
  331. parent_operation_ids=[],
  332. component_params=operation_params,
  333. )
  334. # Build a mock runtime config for use in _cc_pipeline
  335. mocked_runtime = Metadata(name="test-metadata", display_name="test", schema_name="kfp", metadata=sample_metadata)
  336. mocked_func = mock.Mock(return_value="default", side_effect=[mocked_runtime, sample_metadata])
  337. monkeypatch.setattr(processor, "_get_metadata_configuration", mocked_func)
  338. # Construct single-operation pipeline
  339. pipeline = Pipeline(
  340. id="pipeline-id", name="kfp_test", runtime="kfp", runtime_config="test", source="download_data.pipeline"
  341. )
  342. pipeline.operations[operation.id] = operation
  343. # Establish path and function to construct pipeline
  344. pipeline_path = os.path.join(tmpdir, "kfp_test.yaml")
  345. constructed_pipeline_function = lambda: processor._cc_pipeline(pipeline=pipeline, pipeline_name="test_pipeline")
  346. # TODO Check against both argo and tekton compilations
  347. # Compile pipeline and save into pipeline_path
  348. kfp_argo_compiler.Compiler().compile(constructed_pipeline_function, pipeline_path)
  349. # Read contents of pipeline YAML
  350. with open(pipeline_path) as f:
  351. pipeline_yaml = yaml.safe_load(f.read())
  352. # Check the pipeline file contents for correctness
  353. pipeline_template = pipeline_yaml["spec"]["templates"][0]
  354. assert pipeline_template["metadata"]["annotations"]["pipelines.kubeflow.org/task_display_name"] == operation_name
  355. assert pipeline_template["container"]["command"][3] == operation_params["url"]
  356. def test_cc_pipeline_component_no_input(monkeypatch, processor, component_cache, sample_metadata, tmpdir):
  357. """
  358. Verifies that cc_pipeline can handle KFP component definitions that don't
  359. include any inputs
  360. """
  361. # Define the appropriate reader for a filesystem-type component definition
  362. kfp_supported_file_types = [".yaml"]
  363. reader = FilesystemComponentCatalogConnector(kfp_supported_file_types)
  364. # Assign test resource location
  365. cpath = (Path(__file__).parent / ".." / "resources" / "components" / "kfp_test_operator_no_inputs.yaml").resolve()
  366. assert cpath.is_file()
  367. cpath = str(cpath)
  368. # Read contents of given path -- read_component_definition() returns a
  369. # a dictionary of component definition content indexed by path
  370. entry_data = reader.get_entry_data({"path": cpath}, {})
  371. component_definition = entry_data.definition
  372. # Instantiate a file-based component
  373. component_id = "test-component"
  374. component = Component(
  375. id=component_id,
  376. name="No input data",
  377. description="",
  378. op="no-input-data",
  379. catalog_type="elyra-kfp-examples-catalog",
  380. component_reference={"path": cpath},
  381. definition=component_definition,
  382. properties=[],
  383. categories=[],
  384. )
  385. # Fabricate the component cache to include single filename-based component for testing
  386. component_cache._component_cache[processor._type.name] = {
  387. "spoofed_catalog": {"components": {component_id: component}}
  388. }
  389. # Construct hypothetical operation for component
  390. operation_name = "no-input-test"
  391. operation_params = {}
  392. operation = Operation(
  393. id="no-input-id",
  394. type="execution_node",
  395. classifier=component_id,
  396. name=operation_name,
  397. parent_operation_ids=[],
  398. component_params=operation_params,
  399. )
  400. # Build a mock runtime config for use in _cc_pipeline
  401. mocked_runtime = Metadata(name="test-metadata", display_name="test", schema_name="kfp", metadata=sample_metadata)
  402. mocked_func = mock.Mock(return_value="default", side_effect=[mocked_runtime, sample_metadata])
  403. monkeypatch.setattr(processor, "_get_metadata_configuration", mocked_func)
  404. # Construct single-operation pipeline
  405. pipeline = Pipeline(
  406. id="pipeline-id", name="kfp_test", runtime="kfp", runtime_config="test", source="no_input.pipeline"
  407. )
  408. pipeline.operations[operation.id] = operation
  409. constructed_pipeline_function = lambda: processor._cc_pipeline(pipeline=pipeline, pipeline_name="test_pipeline")
  410. pipeline_path = str(Path(tmpdir) / "no_inputs_test.yaml")
  411. # Compile pipeline and save into pipeline_path
  412. kfp_argo_compiler.Compiler().compile(constructed_pipeline_function, pipeline_path)