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