]> git.argeo.org Git - lgpl/argeo-commons.git/blob - internal/kernel/DeployConfig.java
Prepare next development cycle
[lgpl/argeo-commons.git] / internal / kernel / DeployConfig.java
1 package org.argeo.cms.internal.kernel;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.Writer;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.util.ArrayList;
9 import java.util.Dictionary;
10 import java.util.List;
11 import java.util.SortedMap;
12 import java.util.TreeMap;
13
14 import javax.naming.InvalidNameException;
15 import javax.naming.directory.Attributes;
16 import javax.naming.directory.BasicAttributes;
17 import javax.naming.ldap.LdapName;
18 import javax.naming.ldap.Rdn;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.argeo.cms.CmsException;
23 import org.argeo.naming.AttributesDictionary;
24 import org.argeo.naming.LdifParser;
25 import org.argeo.naming.LdifWriter;
26 import org.argeo.node.NodeConstants;
27 import org.argeo.osgi.useradmin.UserAdminConf;
28 import org.eclipse.equinox.http.jetty.JettyConfigurator;
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.FrameworkUtil;
31 import org.osgi.service.cm.Configuration;
32 import org.osgi.service.cm.ConfigurationAdmin;
33 import org.osgi.service.cm.ConfigurationEvent;
34 import org.osgi.service.cm.ConfigurationListener;
35
36 /** Manages the LDIF-based deployment configuration. */
37 class DeployConfig implements ConfigurationListener {
38 private final Log log = LogFactory.getLog(getClass());
39 private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
40
41 private static Path deployConfigPath = KernelUtils.getOsgiInstancePath(KernelConstants.DEPLOY_CONFIG_PATH);
42 private SortedMap<LdapName, Attributes> deployConfigs = new TreeMap<>();
43 private final DataModels dataModels;
44
45 public DeployConfig(ConfigurationAdmin configurationAdmin, DataModels dataModels, boolean isClean) {
46 this.dataModels = dataModels;
47 // ConfigurationAdmin configurationAdmin =
48 // bc.getService(bc.getServiceReference(ConfigurationAdmin.class));
49 try {
50 boolean isFirstInit = false;
51 if (!isInitialized()) { // first init
52 isFirstInit = true;
53 firstInit();
54 }
55 init(configurationAdmin, isClean, isFirstInit);
56 } catch (IOException e) {
57 throw new CmsException("Could not init deploy configs", e);
58 }
59 // FIXME check race conditions during initialization
60 // bc.registerService(ConfigurationListener.class, this, null);
61 }
62
63 private void firstInit() throws IOException {
64 log.info("## FIRST INIT ##");
65 Files.createDirectories(deployConfigPath.getParent());
66
67 // FirstInit firstInit = new FirstInit();
68 InitUtils.prepareFirstInitInstanceArea();
69
70 if (!Files.exists(deployConfigPath))
71 deployConfigs = new TreeMap<>();
72 else// config file could have juste been copied by preparation
73 try (InputStream in = Files.newInputStream(deployConfigPath)) {
74 deployConfigs = new LdifParser().read(in);
75 }
76 save();
77 }
78
79 private void setFromFrameworkProperties(boolean isFirstInit) {
80 // node repository
81 Dictionary<String, Object> nodeConfig = InitUtils
82 .getNodeRepositoryConfig(getProps(NodeConstants.NODE_REPOS_FACTORY_PID, NodeConstants.NODE));
83 // node repository is mandatory
84 putFactoryDeployConfig(NodeConstants.NODE_REPOS_FACTORY_PID, nodeConfig);
85
86 // additional repositories
87 dataModels: for (DataModels.DataModel dataModel : dataModels.getNonAbstractDataModels()) {
88 if (NodeConstants.NODE.equals(dataModel.getName()))
89 continue dataModels;
90 Dictionary<String, Object> config = InitUtils.getRepositoryConfig(dataModel.getName(),
91 getProps(NodeConstants.NODE_REPOS_FACTORY_PID, dataModel.getName()));
92 if (config.size() != 0)
93 putFactoryDeployConfig(NodeConstants.NODE_REPOS_FACTORY_PID, config);
94 }
95
96 // user admin
97 List<Dictionary<String, Object>> userDirectoryConfigs = InitUtils.getUserDirectoryConfigs();
98 if (userDirectoryConfigs.size() != 0) {
99 List<String> activeCns = new ArrayList<>();
100 for (int i = 0; i < userDirectoryConfigs.size(); i++) {
101 Dictionary<String, Object> userDirectoryConfig = userDirectoryConfigs.get(i);
102 String cn = UserAdminConf.baseDnHash(userDirectoryConfig);
103 activeCns.add(cn);
104 userDirectoryConfig.put(NodeConstants.CN, cn);
105 putFactoryDeployConfig(NodeConstants.NODE_USER_ADMIN_PID, userDirectoryConfig);
106 }
107 // disable others
108 LdapName userAdminFactoryName = serviceFactoryDn(NodeConstants.NODE_USER_ADMIN_PID);
109 for (LdapName name : deployConfigs.keySet()) {
110 if (name.startsWith(userAdminFactoryName) && !name.equals(userAdminFactoryName)) {
111 try {
112 Attributes attrs = deployConfigs.get(name);
113 String cn = name.getRdn(name.size() - 1).getValue().toString();
114 if (!activeCns.contains(cn)) {
115 attrs.put(UserAdminConf.disabled.name(), "true");
116 }
117 } catch (Exception e) {
118 throw new CmsException("Cannot disable user directory " + name, e);
119 }
120 }
121 }
122 }
123
124 // http server
125 // Dictionary<String, Object> webServerConfig = InitUtils
126 // .getHttpServerConfig(getProps(KernelConstants.JETTY_FACTORY_PID, NodeConstants.DEFAULT));
127 // if (!webServerConfig.isEmpty()) {
128 // // TODO check for other customizers
129 // webServerConfig.put("customizer.class", "org.argeo.equinox.jetty.CmsJettyCustomizer");
130 // putFactoryDeployConfig(KernelConstants.JETTY_FACTORY_PID, webServerConfig);
131 // }
132 LdapName defaultHttpServiceDn = serviceDn(KernelConstants.JETTY_FACTORY_PID, NodeConstants.DEFAULT);
133 if (deployConfigs.containsKey(defaultHttpServiceDn)) {
134 // remove old default configs since we have now to start Jetty servlet bridge
135 // indirectly
136 deployConfigs.remove(defaultHttpServiceDn);
137 }
138
139 // SAVE
140 save();
141 //
142
143 // Explicitly configures Jetty so that the default server is not started by the
144 // activator of the Equinox Jetty bundle.
145 Dictionary<String, Object> webServerConfig = InitUtils
146 .getHttpServerConfig(getProps(KernelConstants.JETTY_FACTORY_PID, NodeConstants.DEFAULT));
147 if (!webServerConfig.isEmpty()) {
148 webServerConfig.put("customizer.class", KernelConstants.CMS_JETTY_CUSTOMIZER_CLASS);
149 }
150
151 int tryCount = 60;
152 try {
153 tryGettyJetty: while (tryCount > 0) {
154 try {
155 JettyConfigurator.startServer(KernelConstants.DEFAULT_JETTY_SERVER, webServerConfig);
156 // Explicitly starts Jetty OSGi HTTP bundle, so that it gets triggered if OSGi
157 // configuration is not cleaned
158 FrameworkUtil.getBundle(JettyConfigurator.class).start();
159 break tryGettyJetty;
160 } catch (IllegalStateException e) {
161 // Jetty may not be ready
162 try {
163 Thread.sleep(1000);
164 } catch (Exception e1) {
165 // silent
166 }
167 }
168 }
169 } catch (Exception e) {
170 log.error("Cannot start default Jetty server with config " + webServerConfig, e);
171 }
172
173 }
174
175 private void init(ConfigurationAdmin configurationAdmin, boolean isClean, boolean isFirstInit) throws IOException {
176
177 try (InputStream in = Files.newInputStream(deployConfigPath)) {
178 deployConfigs = new LdifParser().read(in);
179 }
180 if (isClean) {
181 setFromFrameworkProperties(isFirstInit);
182 for (LdapName dn : deployConfigs.keySet()) {
183 Rdn lastRdn = dn.getRdn(dn.size() - 1);
184 LdapName prefix = (LdapName) dn.getPrefix(dn.size() - 1);
185 if (prefix.toString().equals(NodeConstants.DEPLOY_BASEDN)) {
186 if (lastRdn.getType().equals(NodeConstants.CN)) {
187 // service
188 String pid = lastRdn.getValue().toString();
189 Configuration conf = configurationAdmin.getConfiguration(pid);
190 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
191 conf.update(dico);
192 } else {
193 // service factory definition
194 }
195 } else {
196 // service factory service
197 Rdn beforeLastRdn = dn.getRdn(dn.size() - 2);
198 assert beforeLastRdn.getType().equals(NodeConstants.OU);
199 String factoryPid = beforeLastRdn.getValue().toString();
200 Configuration conf = configurationAdmin.createFactoryConfiguration(factoryPid.toString(), null);
201 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
202 conf.update(dico);
203 }
204 }
205 }
206 // TODO check consistency if not clean
207 }
208
209 @Override
210 public void configurationEvent(ConfigurationEvent event) {
211 try {
212 if (ConfigurationEvent.CM_UPDATED == event.getType()) {
213 ConfigurationAdmin configurationAdmin = bc.getService(event.getReference());
214 Configuration conf = configurationAdmin.getConfiguration(event.getPid(), null);
215 LdapName serviceDn = null;
216 String factoryPid = conf.getFactoryPid();
217 if (factoryPid != null) {
218 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
219 if (deployConfigs.containsKey(serviceFactoryDn)) {
220 for (LdapName dn : deployConfigs.keySet()) {
221 if (dn.startsWith(serviceFactoryDn)) {
222 Rdn lastRdn = dn.getRdn(dn.size() - 1);
223 assert lastRdn.getType().equals(NodeConstants.CN);
224 Object value = conf.getProperties().get(lastRdn.getType());
225 assert value != null;
226 if (value.equals(lastRdn.getValue())) {
227 serviceDn = dn;
228 break;
229 }
230 }
231 }
232
233 Object cn = conf.getProperties().get(NodeConstants.CN);
234 if (cn == null)
235 throw new IllegalArgumentException("Properties must contain cn");
236 if (serviceDn == null) {
237 putFactoryDeployConfig(factoryPid, conf.getProperties());
238 } else {
239 Attributes attrs = deployConfigs.get(serviceDn);
240 assert attrs != null;
241 AttributesDictionary.copy(conf.getProperties(), attrs);
242 }
243 save();
244 if (log.isDebugEnabled())
245 log.debug("Updated deploy config " + serviceDn(factoryPid, cn.toString()));
246 } else {
247 // ignore non config-registered service factories
248 }
249 } else {
250 serviceDn = serviceDn(event.getPid());
251 if (deployConfigs.containsKey(serviceDn)) {
252 Attributes attrs = deployConfigs.get(serviceDn);
253 assert attrs != null;
254 AttributesDictionary.copy(conf.getProperties(), attrs);
255 save();
256 if (log.isDebugEnabled())
257 log.debug("Updated deploy config " + serviceDn);
258 } else {
259 // ignore non config-registered services
260 }
261 }
262 }
263 } catch (Exception e) {
264 log.error("Could not handle configuration event", e);
265 }
266 }
267
268 void putFactoryDeployConfig(String factoryPid, Dictionary<String, Object> props) {
269 Object cn = props.get(NodeConstants.CN);
270 if (cn == null)
271 throw new IllegalArgumentException("cn must be set in properties");
272 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
273 if (!deployConfigs.containsKey(serviceFactoryDn))
274 deployConfigs.put(serviceFactoryDn, new BasicAttributes(NodeConstants.OU, factoryPid));
275 LdapName serviceDn = serviceDn(factoryPid, cn.toString());
276 Attributes attrs = new BasicAttributes();
277 AttributesDictionary.copy(props, attrs);
278 deployConfigs.put(serviceDn, attrs);
279 }
280
281 void putDeployConfig(String servicePid, Dictionary<String, Object> props) {
282 LdapName serviceDn = serviceDn(servicePid);
283 Attributes attrs = new BasicAttributes(NodeConstants.CN, servicePid);
284 AttributesDictionary.copy(props, attrs);
285 deployConfigs.put(serviceDn, attrs);
286 }
287
288 void save() {
289 try (Writer writer = Files.newBufferedWriter(deployConfigPath)) {
290 new LdifWriter(writer).write(deployConfigs);
291 } catch (IOException e) {
292 // throw new CmsException("Cannot save deploy configs", e);
293 log.error("Cannot save deploy configs", e);
294 }
295 }
296
297 boolean isStandalone(String dataModelName) {
298 return getProps(NodeConstants.NODE_REPOS_FACTORY_PID, dataModelName) != null;
299 }
300
301 /*
302 * UTILITIES
303 */
304 private LdapName serviceFactoryDn(String factoryPid) {
305 try {
306 return new LdapName(NodeConstants.OU + "=" + factoryPid + "," + NodeConstants.DEPLOY_BASEDN);
307 } catch (InvalidNameException e) {
308 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid, e);
309 }
310 }
311
312 private LdapName serviceDn(String servicePid) {
313 try {
314 return new LdapName(NodeConstants.CN + "=" + servicePid + "," + NodeConstants.DEPLOY_BASEDN);
315 } catch (InvalidNameException e) {
316 throw new IllegalArgumentException("Cannot generate DN from " + servicePid, e);
317 }
318 }
319
320 private LdapName serviceDn(String factoryPid, String cn) {
321 try {
322 return (LdapName) serviceFactoryDn(factoryPid).add(new Rdn(NodeConstants.CN, cn));
323 } catch (InvalidNameException e) {
324 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid + " and " + cn, e);
325 }
326 }
327
328 Dictionary<String, Object> getProps(String factoryPid, String cn) {
329 Attributes attrs = deployConfigs.get(serviceDn(factoryPid, cn));
330 if (attrs != null)
331 return new AttributesDictionary(attrs);
332 else
333 return null;
334 }
335
336 static boolean isInitialized() {
337 return Files.exists(deployConfigPath);
338 }
339
340 }