b580b53cf95093a5ec79564f86420e8715106362
[ccsdk/features.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                      reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.ccsdk.features.sdnr.northbound.energysavings;
23
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Properties;
30 import java.util.concurrent.Future;
31 import javax.ws.rs.HttpMethod;
32 import javax.ws.rs.core.MediaType;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.EnergysavingsService;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadInputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadOutput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadOutputBuilder;
39 import org.opendaylight.yangtools.yang.common.RpcResult;
40 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
44 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
45 import com.google.common.base.Preconditions;
46 import com.google.common.util.concurrent.Futures;
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.ClientResponse;
49 import com.sun.jersey.api.client.WebResource;
50 import com.sun.jersey.api.client.config.ClientConfig;
51 import com.sun.jersey.api.client.config.DefaultClientConfig;
52 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
53
54 public class EnergysavingsProvider implements EnergysavingsService {
55
56     private static final Logger LOG = LoggerFactory.getLogger(EnergysavingsProvider.class);
57
58     private final String appName = "EnergySavings";
59
60     private final DataBroker dataBroker;
61     private final RpcProviderRegistry rpcProviderRegistry;
62     private RpcRegistration<EnergysavingsService> serviceRegistration;
63
64     // Locations and names of the configuration files
65     private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
66     private static final String PROPERTIES_FILE_NAME = "sdnr-energy-savings.properties";
67     private static final String PARSING_ERROR =
68             "Could not create the request message to send to the server; no message will be sent";
69
70     /*
71      * Use a flag veryFirstTime to ensure that some tasks are done only once. The value is set here and
72      * during initialization.
73      */
74     private Boolean veryFirstTime = true;
75
76     // Parameters for the REST calls
77
78     // to publish SDNR_TO_POLICY DMaaP topic
79     private WebResource dmaapSdnrToPolicyWebResource = null;
80
81     // to the Energy Savings server
82     private WebResource energySavingsWebResource = null;
83
84     public EnergysavingsProvider(final DataBroker dataBroker, RpcProviderRegistry rpcProviderRegistry) {
85         this.dataBroker = dataBroker;
86         this.rpcProviderRegistry = rpcProviderRegistry;
87     }
88
89     /**
90      * Method called when the blueprint container is created.
91      */
92     public void init() {
93         serviceRegistration = rpcProviderRegistry.addRpcImplementation(EnergysavingsService.class, this);
94
95         LOG.debug("Initializing provider for " + appName);
96
97         Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
98
99         // Set the initialization flag so some tasks will be done only once
100         veryFirstTime = true;
101
102         // Read parameters from the properties file in SDNC_CONFIG_DIR
103         String propDir = System.getenv(SDNC_CONFIG_DIR);
104         if (propDir == null) {
105             LOG.error("Environment variable SDNC_CONFIG_DIR is not set");
106             propDir = "/opt/onap/ccsdk/data/properties/";
107         } else if (!propDir.endsWith("/")) {
108             propDir = propDir + "/";
109         }
110
111         // Get the parameters for the REST calls
112         HashMap<String, String> dmaapPolicyHttpParams = new HashMap<String, String>();
113         HashMap<String, String> energySavingsServerHttpParams = new HashMap<String, String>();
114
115         try {
116             FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME);
117             Properties properties = new Properties();
118             properties.load(fileInput);
119             fileInput.close();
120
121             for (String param : new String[] {"url", "httpMethod", "authentication", "user", "password"}) {
122                 dmaapPolicyHttpParams.put(param, properties.getProperty("dmaapPolicy." + param));
123                 energySavingsServerHttpParams.put(param, properties.getProperty("energySavingsServer." + param));
124             }
125         } catch (FileNotFoundException e) {
126             e.printStackTrace();
127         } catch (IOException e) {
128             e.printStackTrace();
129         }
130
131         // Create a web resource for the Energy Savings server
132         ClientConfig esClientConfig = new DefaultClientConfig();
133         // 3 minute read time out
134         esClientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 180000);
135         // 1 minute connect time out
136         esClientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 60000);
137         Client esClient = Client.create(esClientConfig);
138
139         // Authentication for the Energy Savings server
140         String authenticationMethod = energySavingsServerHttpParams.get("authentication");
141
142         if (authenticationMethod.equals("basic")) {
143             esClient.addFilter(new HTTPBasicAuthFilter(energySavingsServerHttpParams.get("user"),
144                     energySavingsServerHttpParams.get("password")));
145             energySavingsWebResource = esClient.resource(energySavingsServerHttpParams.get("url"));
146         } else if (authenticationMethod.equals("none")) {
147             energySavingsWebResource = esClient.resource(energySavingsServerHttpParams.get("url"));
148         } else {
149             LOG.error("Unexpected value for energy savings server authentication: " + authenticationMethod);
150         }
151
152         // Create a web resource for the DMaaP SDNR_TO_POLICY topic
153         ClientConfig dmaapClientConfig = new DefaultClientConfig();
154         // 3 minute read time out
155         dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 180000);
156         // 1 minute connect time out
157         dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 60000);
158         Client dmaapClient = Client.create(dmaapClientConfig);
159
160         // Authentication for the DMaaP message router
161         authenticationMethod = dmaapPolicyHttpParams.get("authentication");
162
163         if (authenticationMethod.equals("basic")) {
164             dmaapClient.addFilter(
165                     new HTTPBasicAuthFilter(dmaapPolicyHttpParams.get("user"), dmaapPolicyHttpParams.get("password")));
166             dmaapSdnrToPolicyWebResource = dmaapClient.resource(dmaapPolicyHttpParams.get("url"));
167         } else if (authenticationMethod.equals("none")) {
168             dmaapSdnrToPolicyWebResource = dmaapClient.resource(dmaapPolicyHttpParams.get("url"));
169         } else {
170             LOG.error("Unexpected value for DMaaP message router authentication: " + authenticationMethod);
171         }
172
173         LOG.debug("energySavingsServerHttpParams: " + Collections.singletonList(energySavingsServerHttpParams));
174         LOG.debug("dmaapPolicyHttpParams: " + Collections.singletonList(dmaapPolicyHttpParams));
175         LOG.debug("Initialization complete for " + appName);
176     }
177
178     /**
179      * Method called when the blueprint container is destroyed.
180      */
181     public void close() {
182         LOG.debug("EnergysavingsProvider Closed");
183     }
184
185     public WebResource getDmaapSdnrToPolicyWebResource() {
186         return this.dmaapSdnrToPolicyWebResource;
187     }
188
189     public WebResource getEnergySavingsWebResource() {
190         return this.energySavingsWebResource;
191     }
192
193     @Override
194     public Future<RpcResult<PayloadOutput>> payload(PayloadInput input) {
195
196         /*
197          * Policy has published a POLICY_TO_SDNR DMaaP topic. Currently, this feature simply forwards the
198          * input to the Energy Savings server untouched.
199          */
200
201         // Assume success
202         Boolean requestSucceeded = true;
203
204         // Build the result now so error messages can be included in the response
205         PayloadOutputBuilder resultBuilder = new PayloadOutputBuilder();
206
207         if (input == null) {
208             LOG.error("Input is null");
209             resultBuilder.setResult("Input is null");
210             requestSucceeded = false;
211         } else {
212             try {
213                 PayloadInputBuilder inputBuilder = new PayloadInputBuilder(input);
214                 input = inputBuilder.build();
215                 LOG.debug("Received payload: " + input.getPayload());
216             } catch (Exception e) {
217                 LOG.error("Cannot build input");
218                 resultBuilder.setResult(e.toString() + " : " + e.getMessage());
219                 requestSucceeded = false;
220             }
221         }
222
223         /*
224          * See if the web resources were created during initialization. No use in proceeding if not.
225          */
226         if (energySavingsWebResource == null) {
227             LOG.error("energySavingsWebResouce is null");
228             resultBuilder.setResult("energySavingsWebResource is null");
229             requestSucceeded = false;
230         }
231
232         if (dmaapSdnrToPolicyWebResource == null) {
233             LOG.error("dmaapSdnrToPolicyWebResouce is null");
234             resultBuilder.setResult("dmaapSdnrToPolicyWebResource is null");
235             requestSucceeded = false;
236         }
237
238         /*
239          * Forward the POLICY_TO_SDNR message to the Energy Savings server
240          */
241
242         ClientResponse response = null;
243         if (requestSucceeded) {
244             try {
245                 LOG.debug("Sending message to controller: \n" + input.getPayload());
246                 response = energySavingsWebResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
247                         .method(HttpMethod.POST, ClientResponse.class, input.getPayload());
248                 LOG.debug("Received response from Energy Savings server: \n" + response.toString());
249             } catch (Exception e) {
250                 LOG.error("Error while posting POLICY_TO_SDNR input to server:", e);
251                 resultBuilder.setResult("Error while posting POLICY_TO_SDNR input to server\n" + e.toString());
252                 requestSucceeded = false;
253             }
254         }
255
256         /*
257          * Return the response from the server to Policy using the SDNR_TO_POLICY topic
258          */
259
260         if (requestSucceeded) {
261             String esServerResponse = response.getEntity(String.class);
262             try {
263                 LOG.debug("Sending SDNR_TO_POLICY topic: \n" + esServerResponse);
264                 response =
265                         dmaapSdnrToPolicyWebResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
266                                 .method(HttpMethod.POST, ClientResponse.class, esServerResponse);
267                 LOG.debug("Received response from DMaaP message router: \n" + response.toString());
268             } catch (Exception e) {
269                 LOG.error("Error while posting SDNR_TO_POLICY topic: ", e);
270                 resultBuilder.setResult("Error while posting SDNR_TO_POLICY topic:\n" + e.toString());
271                 requestSucceeded = false;
272             }
273         }
274
275         if (requestSucceeded) {
276             return Futures.immediateFuture(
277                     RpcResultBuilder.<PayloadOutput>success().withResult(resultBuilder.build()).build());
278         } else {
279             return Futures.immediateFuture(
280                     RpcResultBuilder.<PayloadOutput>failed().withResult(resultBuilder.build()).build());
281         }
282     }
283 }