test_processor_kfp.py 20 KB

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