DataWorks provides built-in checks, such as code reviews before task deployment and validations from the Data Governance Center. You can also integrate custom validation logic to enforce process controls in DataWorks. This topic demonstrates how to use an extension to prohibit specific functions in a workspace by using an example that checks for the MAX_PT function during submission or deployment.
Scenario
This best practice provides an example of how to check for the MAX_PT function in code that is submitted and deployed. The following table describes the validation process:
|
Step |
Core process |
Key feature |
|
1 |
Open Event sends file submission and deployment messages (such as submitting and deploying nodes) from a workspace to EventBridge. EventBridge then filters the event messages and sends them to your service. |
When you enable message subscription, use an event rule to subscribe to specific event types, such as file submission (dataworks:FileChange:CommitFile) and file deployment (dataworks:FileChange:DeployFile). For configuration details, see Best practice: (advanced feature) Prohibit the MAX_PT function. |
|
2 |
A local or online service receives the messages. The extension is configured to handle events as follows:
|
For configuration details, see Best practice: (advanced feature) Prohibit the MAX_PT function. |
Prerequisites
-
EventBridge is activated. For more information, see Activate EventBridge.
-
DataWorks is activated. For more information, see Activate DataWorks.
-
A DataWorks workspace is created. For more information, see Create a workspace.
Procedure
Step 1: Configure a custom event bus
-
Log on to the EventBridge console. In the left-side navigation pane, click Event Bus to go to the event bus page.
-
Click the
button to Create Custom Event Bus.-
In the Bus section, configure the Custom Event Bus Name, and then click Next step to proceed to the event source configuration.
-
Click Skip to skip the configuration of Event Source, Rule, and Target Module. Enter a Description.
-
-
In the left-side navigation pane, click Event Bus to go to the event bus page. Find the event bus that you created and click its name to go to the overview page.
-
In the left-side navigation pane, click Event Rules to go to the event rules page, and then click Create Rule to create an event rule.
-
In this example, the custom EventBridge bus is configured to receive file commit and file deployment event messages from DataWorks. The following section describes the configuration demo and key parameters.
-
Configure Basic Information: Customize the rule name.
-
Pattern Content.
-
Event Source Type: Select custom event source.
-
Event Source: Leave this field empty.
-
Pattern Content: Write in JSON format. The configuration is as follows.
{ "source": [ "acs.dataworks" ], "type": [ "dataworks:FileChange:CommitFile", "dataworks:FileChange:DeployFile" ] }-
source: Defines the product name identifier acs.dataworks.
-
type: Defines the event type identifiers under the product. Set this to dataworks:FileChange:CommitFile and dataworks:FileChange:DeployFile.
-
-
Event Pattern Debugging: Fill in and modify the source and type values, and then perform an event test. After the test succeeds, click Next. Click Test to verify that the custom event matches the pattern. If the test passes, the page displays Match passed, event can be triggered normally.
-
-
Configure Event Target.
-
Service Type: Select HTTPS or HTTP. For more service types, see Event targets.
-
URL: Enter the URL that receives messages pushed by the custom bus, such as
https://server-address:port/extensions/consumer. -
Body: Select Complete Event.
-
Network Type: Select Public Network.
-
-
-
Step 2: Configure an event distribution channel
Log on to the DataWorks console. In the target region, click in the left-side navigation pane. Click Go to Open Platform to open the Developer Backend page.
-
On the Developer Backend page, click OpenEvent in the left-side navigation pane. On the page that appears, click Add Event Distribution Channel and configure the settings in the dialog.
-
Workspace for Event Distribution: Select a workspace that you have created.
-
Custom Bus in Eventbridge for Distribution: Select the event bus created in Step 1.
-
-
After you save the event distribution channel, in the Operation column of the channel, click Enable to enable the new event distribution channel.
Step 3: Register and configure an extension
Log on to the DataWorks console. In the target region, click in the left-side navigation pane. Click Go to Open Platform to open the Developer Backend page.
-
On the Developer Backend page, click Extension in the left-side navigation pane. On the page that appears, click Register Extension and configure the settings in the dialog.
-
Deployment method: Select Deploy via self-built service.
-
Register the extension
-
Extension Name: Enter a custom name.
-
Extension Point Event: Select Before File Commit and Before File Deploy.
-
Workspace for Testing: After you configure this setting, you can test the extension in the specified workspace before submitting it.
-
Parameter Configurations for Extension
You can use this parameter to control the scope of the extension. In the specified workspace:
-
Submitting a node (Before File Commit) does not trigger extension validation or block the submit process.
-
Deploying a node (Before File Deploy) triggers extension validation. If validation fails, the deployment process is blocked.
Set this to
extension.project.commit-file.disabled=YourProjectId, where YourProjectId is the workspace ID in which the extension point event does not take effect. -
-
Options for Extension: Used to define response methods when validation fails. In this example, the specified response methods include alert and block.
{ "type":"object", "properties":{ "checkStatus":{ "type":"number", "title":"MAX-PT function check method", "x-decorator":"FormItem", "x-component":"Radio.Group", "x-decorator-props":{ "tooltip":"Description file" }, "x-component-props":{ "dataSource":[ { "value":"WARN", "label":"Warning" }, { "value":"FAIL", "label":"Disabled" } ], "mode":"multiple" } } } }The fields in the options configuration are described as follows:
-
checkStatus: A custom field name (component name, must be unique) defined by the extension developer in the options configuration. The extension server reads the value configured by the workspace administrator for the workspace through this field name. -
title: The title of the option. For values, see the parameter parsing and configuration examples in Advanced feature: Extension options configuration. In this example, the title is MAX-PT Function Check Method. -
x-component: The form component used by the option. In this example, a radio button component (Radio.Group) is used. -
dataSource: The selectable options for the radio button component, wherelabelis the text displayed on the UI andvalueis the corresponding identifier. This example provides two values: Alert (WARN) and Block (FAIL), which allow the workspace administrator to select the response method when the MAX_PT function is detected during extension enablement.
Combined with the sample code in this topic, you can understand the value flow of
checkStatus: When the workspace administrator enables the extension, they select either Alert or Block from MAX-PT Function Check Method. The extension server reads this configuration throughGetOptionValueForProject, retrieves the administrator's selection throughjsonObject.getString("checkStatus"), and returns the result to DataWorks throughsetCheckResultas a callback, which either alerts or blocks the deployment process of the node.NotecheckStatusis only one configuration example that uses the radio button component. The options configuration currently supports seven component types: text, single-line input, multi-line input, single-select dropdown, multi-select dropdown, checkbox, and radio button. For complete component types and configuration methods, see Advanced: Configure extension options. -
-
-
-
After you complete the configuration, click Determine to save and register the extension.
-
In the Operation column of the created extension, click Submit to submit the extension for review.
Note-
The extension review is performed by the DataWorks platform. The review typically takes T+3 business days to complete.
-
To test the created extension, configure Workspace for Testing.
-
-
After the review is approved, click Deploy in the Operation column to bring the extension online.
-
Click Manage Extensions to go to the page. Select the extension you created, enable it in the Enable column, and click Settings to configure the control level for MAX_PT function usage in the workspace.
Develop and configure the extension
EventBridge receives DataWorks event messages in JSON format through HTTP requests, parses the messages, and pushes them to the target service. After the service processes the events, it returns results to DataWorks.
Sample code
This code sample calls the UpdateIDEEventResult API to return the callback result. It uses the messageId parameter in the API to obtain the event details, performs logic to determine whether restricted functions are used, and returns the result to DataWorks through the UpdateIDEEventResult API. For more information, see Develop an extension.
Environment setup: Java 8, Maven build tool.
package com.aliyun.dataworks.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dataworks.config.Constants;
import com.aliyun.dataworks.config.EventCheckEnum;
import com.aliyun.dataworks.config.ExtensionParamProperties;
import com.aliyun.dataworks.services.DataWorksOpenApiClient;
import com.aliyun.dataworks_public20200518.Client;
import com.aliyun.dataworks_public20200518.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author dataworks demo
*/
@RestController
@RequestMapping("/extensions")
public class ExtensionsController {
@Autowired(required = false)
private DataWorksOpenApiClient dataWorksOpenApiClient;
@Autowired
private ExtensionParamProperties extensionParamProperties;
/**
* Receive messages pushed by EventBridge
*
* @param jsonParam
*/
@PostMapping("/consumer")
public void consumerEventBridge(@RequestBody String jsonParam) {
JSONObject jsonObj = JSON.parseObject(jsonParam);
String eventCode = jsonObj.getString(Constants.EVENT_CODE_FILED);
if (Constants.COMMIT_FILE_EVENT_CODE.equals(eventCode) || Constants.DEPLOY_FILE_EVENT_CODE.equals(eventCode)) {
//Initialize client
Client client = dataWorksOpenApiClient.createClient();
try {
//Current event parameter information
String messageId = jsonObj.getString("id");
JSONObject data = jsonObj.getObject("data", JSONObject.class);
Long projectId = data.getLong("projectId");
//Initialize event callback
UpdateIDEEventResultRequest updateIDEEventResultRequest = new UpdateIDEEventResultRequest();
updateIDEEventResultRequest.setMessageId(messageId);
updateIDEEventResultRequest.setExtensionCode(extensionParamProperties.getExtensionCode());
//Query the extension point data snapshot when the extension point event was triggered
GetIDEEventDetailRequest getIDEEventDetailRequest = new GetIDEEventDetailRequest();
getIDEEventDetailRequest.setMessageId(messageId);
getIDEEventDetailRequest.setProjectId(projectId);
GetIDEEventDetailResponse getIDEEventDetailResponse = client.getIDEEventDetail(getIDEEventDetailRequest);
String content = getIDEEventDetailResponse.getBody().getEventDetail().getCommittedFile().getContent();
//Check whether the code contains restricted functions
if (content.contains(Constants.CHECK_CODE)) {
//Get the extension option configuration for the workspace
GetOptionValueForProjectRequest getOptionValueForProjectRequest = new GetOptionValueForProjectRequest();
getOptionValueForProjectRequest.setProjectId(String.valueOf(projectId));
getOptionValueForProjectRequest.setExtensionCode(extensionParamProperties.getExtensionCode());
GetOptionValueForProjectResponse getOptionValueForProjectResponse = client.getOptionValueForProject(getOptionValueForProjectRequest);
JSONObject jsonObject = JSON.parseObject(getOptionValueForProjectResponse.getBody().getOptionValue());
//Note: fill in according to the actual format configured in DataWorks
String checkStatus = jsonObject.getString("checkStatus");
updateIDEEventResultRequest.setCheckResult(checkStatus);
updateIDEEventResultRequest.setCheckResultTip("Restricted functions found in code");
} else {//Success callback
updateIDEEventResultRequest.setCheckResult(EventCheckEnum.OK.getCode());
updateIDEEventResultRequest.setCheckResultTip(EventCheckEnum.OK.getName());
}
//Callback to DataWorks
UpdateIDEEventResultResponse response = client.updateIDEEventResult(updateIDEEventResultRequest);
//Unique request ID for subsequent troubleshooting
System.out.println("response:" + response.getBody().getRequestId());
} catch (Exception e) {
//Error description
System.out.println("ErrMsg:" + e.getMessage());
}
} else {
System.out.println("Failed to filter other events, please check the configuration steps");
}
}
}
Deploy the sample project
-
Prepare the environment and project
-
Required environment: Java 8 or later, Maven build tool.
-
Project download link: extensions-demo-maxpt.zip (219 KB).
-
-
Deployment methods
-
Local deployment: Package the project as a JAR file, and then run the
java -jar yourapp.jarcommand on a local server with Java 8 and Maven installed to start the service. -
Cloud deployment: Package the project as a JAR file, and then upload it to the appropriate runtime environment, such as a Docker container or cloud server, for deployment.
NoteThe deployed service must be accessible by EventBridge over the Internet.
-
-
After you download the project, navigate to the root directory and run the packaging command to build the JAR file.
mvn clean package -Dmaven.test.skip=true spring-boot:repackage -
Run the JAR file:
java -jar target/extensions-demo-maxpt-1.0.jarThe project starts successfully.
/\ / /'---'. __ __ ____ /'\'\\ ( ( )\'---'| '--'| '--'\/'--'| '\ \\\\ \/ /__) | |__| | | |__(___| | ) ) ) ) ' '__| | |__| |'| |___| | / / / / =========|_|===============|__/=/=/_/ :: Spring Boot :: (v2.7.2) 2022-08-22 11:17:35.261 INFO 28648 --- [ main] com.aliyun.dataworks.DemoStarter : Starting DemoStarter v1.0 using Java 1.8.0_151 on xxx.local with PID 28648 (/Users/xxx/ts/extensions-demo-maxpt) ns-demo-maxpt/target/extensions-demo-maxpt-1.0.jar started by guangzhen.zk in /Users/xxx/ts/extensions-demo-maxpt) 2022-08-22 11:17:35.264 INFO 28648 --- [ main] com.aliyun.dataworks.DemoStarter : No active profile set, falling back to 1 default profile: "default" 2022-08-22 11:17:35.276 INFO 28648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-08-22 11:17:36.291 INFO 28648 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-08-22 11:17:36.291 INFO 28648 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65] 2022-08-22 11:17:36.419 INFO 28648 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-08-22 11:17:36.419 INFO 28648 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1099 ms 2022-08-22 11:17:36.851 INFO 28648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-08-22 11:17:36.860 INFO 28648 --- [ main] com.aliyun.dataworks.DemoStarter : Started DemoStarter in 1.98 seconds (JVM running for 2.449)Enter
http://localhost:8080/indexin a browser. If you receive"hello world!", the application is deployed successfully. After you establish network connectivity, you can subscribe to EventBridge messages.
Result verification
After you complete the code deployment and establish network connectivity with EventBridge, you can verify the configuration in the workspace where the extension is enabled.
Verification steps
-
On the Data Studio page, create a node, write the prohibited
MAX_PTfunction in the node, save and submit the node. -
Click the Deploy button to go to the create deployment package page and deploy the node. This triggers extension validation.
NoteBased on the extension configuration, the extension does not take effect for file submit events in the specified workspace. Therefore, submitting a node that contains the
MAX_PTfunction does not trigger extension validation. The extension is triggered only when you deploy a node that contains theMAX_PTfunction.