]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/kernel/DeployConfig.java
Prepare release.
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / 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 break tryGettyJetty;
157 } catch (IllegalStateException e) {
158 // Jetty may not be ready
159 try {
160 Thread.sleep(1000);
161 } catch (Exception e1) {
162 // silent
163 }
164 }
165 }
166 } catch (Exception e) {
167 log.error("Cannot start default Jetty server with config " + webServerConfig, e);
168 }
169
170 }
171
172 private void init(ConfigurationAdmin configurationAdmin, boolean isClean, boolean isFirstInit) throws IOException {
173
174 try (InputStream in = Files.newInputStream(deployConfigPath)) {
175 deployConfigs = new LdifParser().read(in);
176 }
177 if (isClean) {
178 setFromFrameworkProperties(isFirstInit);
179 for (LdapName dn : deployConfigs.keySet()) {
180 Rdn lastRdn = dn.getRdn(dn.size() - 1);
181 LdapName prefix = (LdapName) dn.getPrefix(dn.size() - 1);
182 if (prefix.toString().equals(NodeConstants.DEPLOY_BASEDN)) {
183 if (lastRdn.getType().equals(NodeConstants.CN)) {
184 // service
185 String pid = lastRdn.getValue().toString();
186 Configuration conf = configurationAdmin.getConfiguration(pid);
187 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
188 conf.update(dico);
189 } else {
190 // service factory definition
191 }
192 } else {
193 // service factory service
194 Rdn beforeLastRdn = dn.getRdn(dn.size() - 2);
195 assert beforeLastRdn.getType().equals(NodeConstants.OU);
196 String factoryPid = beforeLastRdn.getValue().toString();
197 Configuration conf = configurationAdmin.createFactoryConfiguration(factoryPid.toString(), null);
198 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
199 conf.update(dico);
200 }
201 }
202 }
203 // TODO check consistency if not clean
204 }
205
206 @Override
207 public void configurationEvent(ConfigurationEvent event) {
208 try {
209 if (ConfigurationEvent.CM_UPDATED == event.getType()) {
210 ConfigurationAdmin configurationAdmin = bc.getService(event.getReference());
211 Configuration conf = configurationAdmin.getConfiguration(event.getPid(), null);
212 LdapName serviceDn = null;
213 String factoryPid = conf.getFactoryPid();
214 if (factoryPid != null) {
215 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
216 if (deployConfigs.containsKey(serviceFactoryDn)) {
217 for (LdapName dn : deployConfigs.keySet()) {
218 if (dn.startsWith(serviceFactoryDn)) {
219 Rdn lastRdn = dn.getRdn(dn.size() - 1);
220 assert lastRdn.getType().equals(NodeConstants.CN);
221 Object value = conf.getProperties().get(lastRdn.getType());
222 assert value != null;
223 if (value.equals(lastRdn.getValue())) {
224 serviceDn = dn;
225 break;
226 }
227 }
228 }
229
230 Object cn = conf.getProperties().get(NodeConstants.CN);
231 if (cn == null)
232 throw new IllegalArgumentException("Properties must contain cn");
233 if (serviceDn == null) {
234 putFactoryDeployConfig(factoryPid, conf.getProperties());
235 } else {
236 Attributes attrs = deployConfigs.get(serviceDn);
237 assert attrs != null;
238 AttributesDictionary.copy(conf.getProperties(), attrs);
239 }
240 save();
241 if (log.isDebugEnabled())
242 log.debug("Updated deploy config " + serviceDn(factoryPid, cn.toString()));
243 } else {
244 // ignore non config-registered service factories
245 }
246 } else {
247 serviceDn = serviceDn(event.getPid());
248 if (deployConfigs.containsKey(serviceDn)) {
249 Attributes attrs = deployConfigs.get(serviceDn);
250 assert attrs != null;
251 AttributesDictionary.copy(conf.getProperties(), attrs);
252 save();
253 if (log.isDebugEnabled())
254 log.debug("Updated deploy config " + serviceDn);
255 } else {
256 // ignore non config-registered services
257 }
258 }
259 }
260 } catch (Exception e) {
261 log.error("Could not handle configuration event", e);
262 }
263 }
264
265 void putFactoryDeployConfig(String factoryPid, Dictionary<String, Object> props) {
266 Object cn = props.get(NodeConstants.CN);
267 if (cn == null)
268 throw new IllegalArgumentException("cn must be set in properties");
269 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
270 if (!deployConfigs.containsKey(serviceFactoryDn))
271 deployConfigs.put(serviceFactoryDn, new BasicAttributes(NodeConstants.OU, factoryPid));
272 LdapName serviceDn = serviceDn(factoryPid, cn.toString());
273 Attributes attrs = new BasicAttributes();
274 AttributesDictionary.copy(props, attrs);
275 deployConfigs.put(serviceDn, attrs);
276 }
277
278 void putDeployConfig(String servicePid, Dictionary<String, Object> props) {
279 LdapName serviceDn = serviceDn(servicePid);
280 Attributes attrs = new BasicAttributes(NodeConstants.CN, servicePid);
281 AttributesDictionary.copy(props, attrs);
282 deployConfigs.put(serviceDn, attrs);
283 }
284
285 void save() {
286 try (Writer writer = Files.newBufferedWriter(deployConfigPath)) {
287 new LdifWriter(writer).write(deployConfigs);
288 } catch (IOException e) {
289 // throw new CmsException("Cannot save deploy configs", e);
290 log.error("Cannot save deploy configs", e);
291 }
292 }
293
294 boolean isStandalone(String dataModelName) {
295 return getProps(NodeConstants.NODE_REPOS_FACTORY_PID, dataModelName) != null;
296 }
297
298 /*
299 * UTILITIES
300 */
301 private LdapName serviceFactoryDn(String factoryPid) {
302 try {
303 return new LdapName(NodeConstants.OU + "=" + factoryPid + "," + NodeConstants.DEPLOY_BASEDN);
304 } catch (InvalidNameException e) {
305 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid, e);
306 }
307 }
308
309 private LdapName serviceDn(String servicePid) {
310 try {
311 return new LdapName(NodeConstants.CN + "=" + servicePid + "," + NodeConstants.DEPLOY_BASEDN);
312 } catch (InvalidNameException e) {
313 throw new IllegalArgumentException("Cannot generate DN from " + servicePid, e);
314 }
315 }
316
317 private LdapName serviceDn(String factoryPid, String cn) {
318 try {
319 return (LdapName) serviceFactoryDn(factoryPid).add(new Rdn(NodeConstants.CN, cn));
320 } catch (InvalidNameException e) {
321 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid + " and " + cn, e);
322 }
323 }
324
325 Dictionary<String, Object> getProps(String factoryPid, String cn) {
326 Attributes attrs = deployConfigs.get(serviceDn(factoryPid, cn));
327 if (attrs != null)
328 return new AttributesDictionary(attrs);
329 else
330 return null;
331 }
332
333 static boolean isInitialized() {
334 return Files.exists(deployConfigPath);
335 }
336
337 }