aboutsummaryrefslogtreecommitdiffstats
path: root/feature-mdc-filters/src/main/java/org/onap/policy/drools/mdc/filters/MdcFilterFeature.java
blob: fecdbe91d724fe6287b73c72fe45a5801ca7b02a (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
/*
 * ============LICENSE_START=======================================================
 * feature-mdc-filters
 * ================================================================================
 * Copyright (C) 2019 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.onap.policy.drools.mdc.filters;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.onap.policy.common.endpoints.event.comm.Topic;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.features.NetLoggerFeatureApi;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
import org.onap.policy.drools.features.PolicyControllerFeatureApi;
import org.onap.policy.drools.persistence.SystemPersistence;
import org.onap.policy.drools.system.PolicyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class MdcFilterFeature implements NetLoggerFeatureApi, PolicyControllerFeatureApi {

    /**
     * Logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(MdcFilterFeature.class);

    /**
     * Feature properties.
     */
    public static final String FEATURE_NAME = "feature-mdc-filters";
    public static final String SOURCE = "source";
    public static final String SINK = "sink";
    public static final String MDC_FILTERS = ".mdcFilters";

    /**
     * Mapping of 'protocol:type:topic' key to a 'MdcTopicFilter' object.
     */
    private Map<String, MdcTopicFilter> topicFilters = new HashMap<>();

    /**
     * Feature properties map obtained from the feature properties file.
     */
    private Properties featureProps = null;

    /**
     * Constructor.
     */
    public MdcFilterFeature() {
        super();
        featureProps = getFeatureProps();
    }

    /**
     * Gets the feature properties.
     *
     * @return the properties for this feature.
     */
    protected Properties getFeatureProps() {
        return SystemPersistence.manager.getProperties(FEATURE_NAME);
    }

    /**
     * Sequence number to be used for order of feature implementer execution.
     */
    @Override
    public int getSequenceNumber() {
        return 1;
    }

    /**
     * Loops through all source and sink topics to find which topics have mdc filters and
     * inserts an MdcTopicFilter in to the topicFilters map.
     */
    @Override
    public boolean afterCreate(PolicyController controller) {
        createSourceTopicFilters(controller);
        createSinkTopicFilters(controller);
        return false;
    }

    /**
     * Extracts the fields in a JSON string that are to be logged in an abbreviated
     * message. The event delivery infrastructure details are put in the MDC as well using
     * the keys networkEventType (IN/OUT), networkProtocol (UEB/DMAAP/NOOP/REST), and
     * networkTopic.
     */
    @Override
    public boolean beforeLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,
                    String message) {

        String filterKey = null;
        if (type == EventType.IN) {
            filterKey = getTopicKey(protocol.name().toLowerCase(), SOURCE, topic);
        } else {
            filterKey = getTopicKey(protocol.name().toLowerCase(), SINK, topic);
        }

        MDC.put("networkEventType", type.name());
        MDC.put("networkProtocol", protocol.name());
        MDC.put("networkTopic", topic);

        MdcTopicFilter filter = topicFilters.get(filterKey);
        if (filter != null) {
            for (Map.Entry<String, List<String>> entry : filter.find(message).entrySet()) {
                String mdcKey = entry.getKey();
                List<String> results = entry.getValue();
                if (results.isEmpty()) {
                    logger.debug("No results found for key {}", mdcKey);
                } else if (results.size() > 1) {
                    logger.debug("Multple results found for key {}, returning list as a string", mdcKey);
                    MDC.put(mdcKey, results.toString());
                } else {
                    MDC.put(mdcKey, results.get(0));
                }
            }
        } else {
            logger.debug("No mdc topic filters exist for key {}", filterKey);
        }

        return false;
    }

    /**
     * Clears the MDC mapping after a message is logged.
     */
    @Override
    public boolean afterLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,
                    String message) {
        MDC.clear();
        return false;
    }

    /**
     * Creates a key using the protocol, type, and topic name.
     *
     * @param protocol defined as ueb, dmaap, noop
     * @param type defined as source or sink
     * @param topic name of the topic
     * @return a key that is the concatenation of the protocol, type, and topic name
     */
    private String getTopicKey(String protocol, String type, String topic) {
        return protocol + ":" + type + ":" + topic;
    }

    /**
     * Creates MdcTopicFilters for a source/sink topic based on the type.
     *
     * @param topic the topic name
     * @param type 'source' or 'sink'
     */
    private void createTopicFilter(Topic topic, String type) {
        String protocol = topic.getTopicCommInfrastructure().name().toLowerCase();
        String topicName = topic.getTopic();

        String propertyKey = protocol + "." + type + ".topics." + topicName + MDC_FILTERS;
        String propertyValue = featureProps.getProperty(propertyKey);
        if (propertyValue != null) {
            String topicKey = getTopicKey(protocol, type, topicName);
            if (!topicFilters.containsKey(topicKey)) {
                logger.debug("MdcTopicFilter created for {} {} topic {}", protocol, type, topicName);
                topicFilters.put(topicKey, new MdcTopicFilter(propertyValue));
            } else {
                logger.debug("An MdcTopicFilter already exists for key {}", topicKey);
            }
        } else {
            logger.debug("No MDC filters defined for {} {} topic {}", protocol, type, topicName);
        }
    }

    /**
     * Creates MdcTopicFilters for the controller's source topics.
     */
    private void createSourceTopicFilters(PolicyController controller) {
        controller.getTopicSources().forEach(sourceTopic -> createTopicFilter(sourceTopic, SOURCE));
    }

    /**
     * Creates MdcTopicFilters for the controller's sink topics.
     */
    private void createSinkTopicFilters(PolicyController controller) {
        controller.getTopicSinks().forEach(sinkTopic -> createTopicFilter(sinkTopic, SINK));
    }
}