803d99adcbd9f2af329bfd23ec9dfab235034b73
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.context.distribution.infinispan;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.InputStream;
26
27 import org.infinispan.manager.DefaultCacheManager;
28 import org.infinispan.manager.EmbeddedCacheManager;
29 import org.onap.policy.apex.context.ContextException;
30 import org.onap.policy.apex.model.utilities.ResourceUtils;
31 import org.slf4j.ext.XLogger;
32 import org.slf4j.ext.XLoggerFactory;
33
34 /**
35  * The Class InfinispanManager holds the Infinispan cache manager for a JVM.
36  */
37 public class InfinispanManager {
38     // Logger for this class
39     private static final XLogger LOGGER = XLoggerFactory.getXLogger(InfinispanManager.class);
40
41     // The Infinispan Cache Manager
42     private EmbeddedCacheManager cacheManager;
43
44     /**
45      * Constructor, set up an Infinispan cache manager.
46      *
47      * @param infinispanDistributorParameters the infinispan distributor parameters
48      * @throws ContextException On errors connecting to Infinispan
49      */
50     public InfinispanManager(final InfinispanDistributorParameters infinispanDistributorParameters)
51             throws ContextException {
52         LOGGER.entry("Creating Infinispan Manager: " + infinispanDistributorParameters);
53
54         setSystemProperties(infinispanDistributorParameters);
55
56         // First, try and open a local input stream for Infinispan configuration
57         InputStream infinispanConfigStream =
58                 getLocalInfinispanConfigurationStream(infinispanDistributorParameters.getConfigFile());
59
60         // Check if a local file was found, if not then go to the class path
61         if (infinispanConfigStream == null) {
62             // If a local file is not specified, then check for an infinispan configuration file on
63             // the class path
64             infinispanConfigStream =
65                     getClasspathInfinispanConfigurationStream(infinispanDistributorParameters.getConfigFile());
66         }
67
68         // Check if we found configuration for Infinispan
69         if (infinispanConfigStream == null) {
70             final String errorMessage =
71                     "failed to start infinispan cache manager, no infinispan configuration found on local file system or in classpath, "
72                             + "try setting Infinspan \"configFile\" parameter";
73             LOGGER.error(errorMessage);
74             throw new ContextException(errorMessage);
75         }
76
77         try {
78             LOGGER.debug("starting infinispan cache manager using specified configuration . . .");
79             cacheManager = new DefaultCacheManager(infinispanConfigStream);
80             LOGGER.debug("started infinispan cache manager using specified configuration");
81         } catch (final Exception e) {
82             LOGGER.error("failed to start infinispan cache manager using specified configuration", e);
83             throw new ContextException("failed to start infinispan cache manager using specified configuration", e);
84         }
85
86         // Start the cache manager
87         cacheManager.start();
88
89         Runtime.getRuntime().addShutdownHook(new InfinspanManagerShutdownHook());
90
91         LOGGER.exit("Created Infinispan Manager: " + infinispanDistributorParameters);
92     }
93
94     /**
95      * Shutdown the manager.
96      */
97     public void shutdown() {
98         if (cacheManager == null) {
99             return;
100         }
101
102         cacheManager.stop();
103         cacheManager = null;
104     }
105
106     /**
107      * Get the cache manager.
108      *
109      * @return the infinispan cache manager
110      */
111     public EmbeddedCacheManager getCacheManager() {
112         return cacheManager;
113     }
114
115     /**
116      * Set system properties used by Infinispan.
117      *
118      * @param infinispanDistributorParameters The parameter values to set are passed as properties
119      */
120     private void setSystemProperties(final InfinispanDistributorParameters infinispanDistributorParameters) {
121         System.setProperty("java.net.preferIPv4Stack",
122                 Boolean.toString(infinispanDistributorParameters.preferIPv4Stack()));
123         System.setProperty("jgroups.bind_addr", infinispanDistributorParameters.getjGroupsBindAddress());
124     }
125
126     /**
127      * Get an Infinispan configuration stream from the local file system.
128      *
129      * @param infinispanConfigFileName The file name to open
130      * @return The file opened as a stream
131      * @throws ContextException If the local file could not be found or is invalid
132      */
133     private InputStream getLocalInfinispanConfigurationStream(final String infinispanConfigFileName)
134             throws ContextException {
135         LOGGER.debug("checking infinispan configuration file exists at \"" + infinispanConfigFileName + "\". . .");
136
137         // Check if the file exists
138         final File infinispanConfigFile = new File(infinispanConfigFileName);
139         if (!infinispanConfigFile.exists()) {
140             return null;
141         }
142
143         // Check the file
144         if (!infinispanConfigFile.isFile() || !infinispanConfigFile.canRead()) {
145             LOGGER.error("infinispan configuration file at \"" + infinispanConfigFileName
146                     + "\" does not exist or is invalid");
147             throw new ContextException("infinispan configuration file at \"" + infinispanConfigFileName
148                     + "\" does not exist or is invalid");
149         }
150
151         try {
152             final InputStream infinispanConfigStream = new FileInputStream(infinispanConfigFile);
153             LOGGER.debug("infinispan configuration file exists at \"" + infinispanConfigFileName + "\"");
154             return infinispanConfigStream;
155         } catch (final Exception e) {
156             LOGGER.error("infinispan configuration file at \"" + infinispanConfigFileName
157                     + "\" does not exist or is invalid", e);
158             throw new ContextException("infinispan configuration file at \"" + infinispanConfigFileName
159                     + "\" does not exist or is invalid", e);
160         }
161     }
162
163     /**
164      * Get an Infinispan configuration stream from the class path.
165      *
166      * @param apexInfinispanConfigFile the apex infinispan config file
167      * @return The file opened as a stream
168      */
169     private InputStream getClasspathInfinispanConfigurationStream(final String apexInfinispanConfigFile) {
170         LOGGER.debug(
171                 "checking infinispan configuration file exists at resource \"" + apexInfinispanConfigFile + "\". . .");
172         final InputStream infinispanConfigStream = ResourceUtils.getResourceAsStream(apexInfinispanConfigFile);
173
174         if (infinispanConfigStream != null) {
175             LOGGER.debug("infinispan configuration file exists at resource \"" + apexInfinispanConfigFile + "\"");
176         } else {
177             LOGGER.debug("infinispan configuration file at resource \"" + apexInfinispanConfigFile + "\" not found");
178         }
179         return infinispanConfigStream;
180     }
181
182     /**
183      * Private class to implement the shutdown hook for this infinispan manager.
184      */
185     public class InfinspanManagerShutdownHook extends Thread {
186         /*
187          * (non-Javadoc)
188          *
189          * @see java.lang.Thread#run()
190          */
191         @Override
192         public void run() {
193             shutdown();
194         }
195     }
196 }