aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java
blob: 8e3f254def506b00144d195bc4edb8bcb37f764d (plain)
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
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.mso.bpmn.core.plugins;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener;
import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener;
import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl;
import org.camunda.bpm.engine.impl.pvm.process.TransitionImpl;
import org.camunda.bpm.engine.impl.util.xml.Element;
import org.camunda.bpm.engine.impl.variable.VariableDeclaration;

import org.openecomp.mso.bpmn.core.BPMNLogger;
import org.openecomp.mso.bpmn.core.PropertyConfiguration;
import org.openecomp.mso.bpmn.core.mybatis.CustomMyBatisSessionFactory;
import org.openecomp.mso.bpmn.core.mybatis.URNMapping;
import org.openecomp.mso.logger.MessageEnum;
import org.openecomp.mso.logger.MsoLogger;

/**
 * Plugin for MSO logging and URN mapping.
 */
public class LoggingAndURNMappingPlugin extends AbstractProcessEnginePlugin {
	private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
	private static final String FSPROPKEY = "URNMapping.FileSystemLoading.Enabled";

	@Override
	public void preInit(
			ProcessEngineConfigurationImpl processEngineConfiguration) {
		List<BpmnParseListener> preParseListeners = processEngineConfiguration
				.getCustomPreBPMNParseListeners();
		if (preParseListeners == null) {
			preParseListeners = new ArrayList<BpmnParseListener>();
			processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
		}
		preParseListeners.add(new LoggingParseListener());
	}
	
	/**
	 * Called when a process flow is parsed so we can inject listeners.
	 */
	public static class LoggingParseListener extends AbstractBpmnParseListener {
		private void injectLogExecutionListener(ActivityImpl activity) {
			activity.addListener(
					ExecutionListener.EVENTNAME_END,
					new LoggingExecutionListener("END"));

			activity.addListener(
					ExecutionListener.EVENTNAME_START,
					new LoggingExecutionListener("START"));

			activity.addListener(
					ExecutionListener.EVENTNAME_TAKE,
					new LoggingExecutionListener("TAKE"));
		}

		public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
		}

		public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl startEventActivity) {
			// Inject these listeners only on the main start event for the flow, not on any embedded subflow start events
			if (scope instanceof ProcessDefinitionEntity) {
				startEventActivity.addListener(ExecutionListener.EVENTNAME_START, new URNMappingInitializerListener("START"));
				startEventActivity.addListener(ExecutionListener.EVENTNAME_START, new LoggingInitializerListener("START"));
			}

			injectLogExecutionListener(startEventActivity);
		}

		public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseExclusiveGateway(Element exclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseInclusiveGateway(Element inclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseParallelGateway(Element parallelGwElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseScriptTask(Element scriptTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseManualTask(Element manualTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseBoundaryTimerEventDefinition(Element timerEventDefinition, boolean interrupting, ActivityImpl timerActivity) {
			injectLogExecutionListener(timerActivity);
		}

		public void parseBoundaryErrorEventDefinition(Element errorEventDefinition, boolean interrupting, ActivityImpl activity, ActivityImpl nestedErrorEventActivity) {
			injectLogExecutionListener(activity);
		}

		public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseProperty(Element propertyElement, VariableDeclaration variableDeclaration, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseSequenceFlow(Element sequenceFlowElement, ScopeImpl scopeElement, TransitionImpl transition) {
			//injectLogExecutionListener(activity);
		}

		public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) {
			injectLogExecutionListener(timerActivity);
		}

		public void parseRootElement(Element rootElement, List<ProcessDefinitionEntity> processDefinitions) {
			//injectLogExecutionListener(activity);
		}

		public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) {
			injectLogExecutionListener(signalActivity);
		}

		public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) {
			injectLogExecutionListener(signalActivity);
		}

		public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) {
			injectLogExecutionListener(compensationActivity);
		}

		public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
			injectLogExecutionListener(activity);
		}

		public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl nestedActivity) {
			injectLogExecutionListener(nestedActivity);
		}

		public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
			injectLogExecutionListener(nestedActivity);
		}

		public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
			injectLogExecutionListener(messageActivity);
		}
	}

	/**
	 * Initializes URN mapping variables on process entry.
	 */
	public static class URNMappingInitializerListener implements ExecutionListener {
		private String event;

		public URNMappingInitializerListener(String eventData) {
			this.event = eventData;
		}

		public String getEvent() {
			return event;
		}

		public void notify(DelegateExecution execution) throws Exception {
			ProcessEngineConfigurationImpl processEngineConfiguration =
				Context.getProcessEngineConfiguration();
			loadURNProperties(execution, processEngineConfiguration);
		}

		private void loadURNProperties(DelegateExecution execution,
				ProcessEngineConfigurationImpl processEngineConfiguration) {
			Map<String,String> bpmnProps = PropertyConfiguration.getInstance().getProperties("mso.bpmn.properties");
			if (bpmnProps == null) {
				LOGGER.debug("Unable to load mso.bpmn.properties; loading URN Mapping from DB");
				
				LOGGER.error (MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 
					"Unable to load mso.bpmn.properties; loading URN Mapping from DB");
				
				loadFromDB(execution, processEngineConfiguration);
			} else {
				String fsEnabled = bpmnProps.get(FSPROPKEY);
				if (fsEnabled != null) {
					if (Boolean.parseBoolean(fsEnabled)) {
						LOGGER.debug("File system loading is enabled; loading URN properties from File system");
						LOGGER.info(MessageEnum.BPMN_GENERAL_INFO,  "BPMN",  "File system loading is enabled; loading URN properties from File System");
						loadFromFileSystem(execution);
					} else {
						LOGGER.debug("File system loading is disabled; loading URN properties from DB");
						LOGGER.info (MessageEnum.BPMN_GENERAL_INFO, "BPMN", "File system loading is disabled; loading URN properties from DB");
						
						loadFromDB(execution, processEngineConfiguration);
					}
				} else {
					
					LOGGER.error (MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 
						"Unable to retrieve URNMapping.FileSystemLoading.Enabled from mso.bpmn.properties; loading URN Mapping from DB");
					
					loadFromDB(execution, processEngineConfiguration);
				}
			}
		}

		private void loadFromFileSystem(DelegateExecution execution) {
			PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance();
			Map<String,String> props = propertyConfiguration.getProperties("mso.bpmn.urn.properties");
			for (String key : props.keySet()) {
				String varName = URNMapping.createIdentifierFromURN(key);
				String varValue = props.get(key);
				execution.setVariable(varName, varValue);
			}
		}

		private void loadFromDB(DelegateExecution execution, ProcessEngineConfigurationImpl processEngineConfiguration) {
			Command<List<URNMapping>> command = new Command<List<URNMapping>>() {
				@SuppressWarnings("unchecked")
				public List<URNMapping> execute(CommandContext commandContext) {
					return (List<URNMapping>) commandContext.getDbSqlSession().selectList(
						"mso.urnMapping.selectAll", null);
				}
			};

			CustomMyBatisSessionFactory sessionFactory = new CustomMyBatisSessionFactory();
			sessionFactory.initFromProcessEngineConfiguration(processEngineConfiguration,
				"customMyBatisConfiguration.xml");

			List<URNMapping> mappings = sessionFactory.getCommandExecutorTxRequired().execute(command);

			if (mappings != null && mappings.size() > 0) {
				for (URNMapping mapping : mappings) {
					String varName = URNMapping.createIdentifierFromURN(mapping.getName());
					String varValue = mapping.getValue();

					LOGGER.debug("URN Mapping = '" + mapping.getName()
						+ "', setting variable '" + varName + "' to '" + varValue + "'");

					execution.setVariable(varName, varValue);
				}
			}
		}
	}

	/**
	 * Sets the isDebugLogEnabled variable on process entry.
	 */
	public static class LoggingInitializerListener implements ExecutionListener {
		private String event;

		public LoggingInitializerListener(String eventData) {
			this.event = eventData;
		}

		public String getEvent() {
			return event;
		}

		public void notify(DelegateExecution execution) throws Exception {
			String processKey = execution.getProcessEngineServices().getRepositoryService()
				.getProcessDefinition(execution.getProcessDefinitionId()).getKey();

			// If a "true" value is already injected, e.g. from a top-level flow, it SHOULD NOT be
			// overridden by the value in the URN mapping. This allows a top-level flow and all
			// invoked subflows to be debugged by turning on the debug flag for just the top-level
			// flow, assuming the isDebugEnabled flag variable is passed from the top-level flow to
			// its subflows.

			// If a "false" value is already injected, e.g. from a top-level flow, it SHOULD be
			// overridden by the value in the URN mapping.  This allows a subflow to be debugged
			// without turning on the the debug flag for the top-level flow.

			String injectedValue = (String) execution.getVariable("isDebugLogEnabled");
			String urnValue = "true".equals(execution.getVariable("URN_log_debug_" + processKey)) ? "true" : "false";

			if ("true".equals(injectedValue)) {
				LOGGER.debug("Setting isDebugLogEnabled to \"" + injectedValue + "\" for process: " + processKey + " (injected value)");
				execution.setVariable("isDebugLogEnabled", injectedValue);
			} else {
				LOGGER.debug("Setting isDebugLogEnabled to \"" + urnValue + "\" for process: " + processKey + " (from URN mapping)");
				execution.setVariable("isDebugLogEnabled", urnValue);
			}
		}
	}
	
	/**
	 * Logs details about the current activity.
	 */
	public static class LoggingExecutionListener implements ExecutionListener {
		private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
		private static ConcurrentHashMap<String, Long> startTimes = new ConcurrentHashMap<String, Long>();

		private String event;

		public LoggingExecutionListener(String event) {
			this.event = event;
		}

		public String getEvent() {
			return event;
		}

		public void notify(DelegateExecution execution) throws Exception {
			BPMNLogger.debug(
				(String) execution.getVariable("isDebugLogEnabled"),
				"Logging for activity---------------:" + event + ":"
						+ execution.getCurrentActivityName()
						+ ", processDefinitionId="
						+ execution.getProcessDefinitionId() + ", activtyId="
						+ execution.getCurrentActivityId() + ", activtyName='"
						+ execution.getCurrentActivityName() + "'"
						+ ", processInstanceId="
						+ execution.getProcessInstanceId() + ", businessKey="
						+ execution.getProcessBusinessKey() + ", executionId="
						+ execution.getId());

			if (!isBlank(execution.getCurrentActivityName())) {
				try {
					String id = execution.getId();
					if ("START".equals(event) && id != null ) {
						startTimes.put(id, (Long)System.currentTimeMillis());
					} else if ("END".equals(event) && id != null) {
						String prefix = (String) execution.getVariable("prefix");

						if (prefix != null ) {
							MsoLogger.setServiceName("MSO." + prefix.substring(0,prefix.length()-1));
						}

						String requestId = (String) execution.getVariable("att-mso-request-id");
						String svcid = (String) execution.getVariable("att-mso-service-instance-id");
						MsoLogger.setLogContext(requestId, svcid);
						long startTime = startTimes.remove(id);

						if (startTime != 0) {
							
							LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
									event + ": " + execution.getCurrentActivityName(), "BPMN", execution.getCurrentActivityName(), null);
							
						}
					}
				} catch(Exception e) {
					// Do nothing
				}
			}
		}

		private boolean isBlank(Object object) {
			return object == null || object.toString().trim().equals("");
		}
	}
}