]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/kernel/DeployConfig.java
Use Argeo TP Core v2.1.25 and Argeo TP Extras v2.1.13.
[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 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 save();
132
133 // Explicitly configure Jetty so that the default server is not started by the
134 // activator of the Equinox Jetty bundle.
135 Dictionary<String, Object> webServerConfig = InitUtils
136 .getHttpServerConfig(getProps(KernelConstants.JETTY_FACTORY_PID, NodeConstants.DEFAULT));
137 if (!webServerConfig.isEmpty()) {
138 webServerConfig.put("customizer.class", KernelConstants.CMS_JETTY_CUSTOMIZER_CLASS);
139 }
140 try {
141 JettyConfigurator.startServer(KernelConstants.DEFAULT_JETTY_SERVER, webServerConfig);
142 } catch (Exception e) {
143 log.error("Cannot start default Jetty server with config " + webServerConfig, e);
144 }
145
146 }
147
148 private void init(ConfigurationAdmin configurationAdmin, boolean isClean, boolean isFirstInit) throws IOException {
149
150 try (InputStream in = Files.newInputStream(deployConfigPath)) {
151 deployConfigs = new LdifParser().read(in);
152 }
153 if (isClean) {
154 setFromFrameworkProperties(isFirstInit);
155 for (LdapName dn : deployConfigs.keySet()) {
156 Rdn lastRdn = dn.getRdn(dn.size() - 1);
157 LdapName prefix = (LdapName) dn.getPrefix(dn.size() - 1);
158 if (prefix.toString().equals(NodeConstants.DEPLOY_BASEDN)) {
159 if (lastRdn.getType().equals(NodeConstants.CN)) {
160 // service
161 String pid = lastRdn.getValue().toString();
162 Configuration conf = configurationAdmin.getConfiguration(pid);
163 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
164 conf.update(dico);
165 } else {
166 // service factory definition
167 }
168 } else {
169 // service factory service
170 Rdn beforeLastRdn = dn.getRdn(dn.size() - 2);
171 assert beforeLastRdn.getType().equals(NodeConstants.OU);
172 String factoryPid = beforeLastRdn.getValue().toString();
173 Configuration conf = configurationAdmin.createFactoryConfiguration(factoryPid.toString(), null);
174 AttributesDictionary dico = new AttributesDictionary(deployConfigs.get(dn));
175 conf.update(dico);
176 }
177 }
178 }
179 // TODO check consistency if not clean
180 }
181
182 @Override
183 public void configurationEvent(ConfigurationEvent event) {
184 try {
185 if (ConfigurationEvent.CM_UPDATED == event.getType()) {
186 ConfigurationAdmin configurationAdmin = bc.getService(event.getReference());
187 Configuration conf = configurationAdmin.getConfiguration(event.getPid(), null);
188 LdapName serviceDn = null;
189 String factoryPid = conf.getFactoryPid();
190 if (factoryPid != null) {
191 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
192 if (deployConfigs.containsKey(serviceFactoryDn)) {
193 for (LdapName dn : deployConfigs.keySet()) {
194 if (dn.startsWith(serviceFactoryDn)) {
195 Rdn lastRdn = dn.getRdn(dn.size() - 1);
196 assert lastRdn.getType().equals(NodeConstants.CN);
197 Object value = conf.getProperties().get(lastRdn.getType());
198 assert value != null;
199 if (value.equals(lastRdn.getValue())) {
200 serviceDn = dn;
201 break;
202 }
203 }
204 }
205
206 Object cn = conf.getProperties().get(NodeConstants.CN);
207 if (cn == null)
208 throw new IllegalArgumentException("Properties must contain cn");
209 if (serviceDn == null) {
210 putFactoryDeployConfig(factoryPid, conf.getProperties());
211 } else {
212 Attributes attrs = deployConfigs.get(serviceDn);
213 assert attrs != null;
214 AttributesDictionary.copy(conf.getProperties(), attrs);
215 }
216 save();
217 if (log.isDebugEnabled())
218 log.debug("Updated deploy config " + serviceDn(factoryPid, cn.toString()));
219 } else {
220 // ignore non config-registered service factories
221 }
222 } else {
223 serviceDn = serviceDn(event.getPid());
224 if (deployConfigs.containsKey(serviceDn)) {
225 Attributes attrs = deployConfigs.get(serviceDn);
226 assert attrs != null;
227 AttributesDictionary.copy(conf.getProperties(), attrs);
228 save();
229 if (log.isDebugEnabled())
230 log.debug("Updated deploy config " + serviceDn);
231 } else {
232 // ignore non config-registered services
233 }
234 }
235 }
236 } catch (Exception e) {
237 log.error("Could not handle configuration event", e);
238 }
239 }
240
241 void putFactoryDeployConfig(String factoryPid, Dictionary<String, Object> props) {
242 Object cn = props.get(NodeConstants.CN);
243 if (cn == null)
244 throw new IllegalArgumentException("cn must be set in properties");
245 LdapName serviceFactoryDn = serviceFactoryDn(factoryPid);
246 if (!deployConfigs.containsKey(serviceFactoryDn))
247 deployConfigs.put(serviceFactoryDn, new BasicAttributes(NodeConstants.OU, factoryPid));
248 LdapName serviceDn = serviceDn(factoryPid, cn.toString());
249 Attributes attrs = new BasicAttributes();
250 AttributesDictionary.copy(props, attrs);
251 deployConfigs.put(serviceDn, attrs);
252 }
253
254 void putDeployConfig(String servicePid, Dictionary<String, Object> props) {
255 LdapName serviceDn = serviceDn(servicePid);
256 Attributes attrs = new BasicAttributes(NodeConstants.CN, servicePid);
257 AttributesDictionary.copy(props, attrs);
258 deployConfigs.put(serviceDn, attrs);
259 }
260
261 void save() {
262 try (Writer writer = Files.newBufferedWriter(deployConfigPath)) {
263 new LdifWriter(writer).write(deployConfigs);
264 } catch (IOException e) {
265 // throw new CmsException("Cannot save deploy configs", e);
266 log.error("Cannot save deploy configs", e);
267 }
268 }
269
270 boolean isStandalone(String dataModelName) {
271 return getProps(NodeConstants.NODE_REPOS_FACTORY_PID, dataModelName) != null;
272 }
273
274 /*
275 * UTILITIES
276 */
277 private LdapName serviceFactoryDn(String factoryPid) {
278 try {
279 return new LdapName(NodeConstants.OU + "=" + factoryPid + "," + NodeConstants.DEPLOY_BASEDN);
280 } catch (InvalidNameException e) {
281 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid, e);
282 }
283 }
284
285 private LdapName serviceDn(String servicePid) {
286 try {
287 return new LdapName(NodeConstants.CN + "=" + servicePid + "," + NodeConstants.DEPLOY_BASEDN);
288 } catch (InvalidNameException e) {
289 throw new IllegalArgumentException("Cannot generate DN from " + servicePid, e);
290 }
291 }
292
293 private LdapName serviceDn(String factoryPid, String cn) {
294 try {
295 return (LdapName) serviceFactoryDn(factoryPid).add(new Rdn(NodeConstants.CN, cn));
296 } catch (InvalidNameException e) {
297 throw new IllegalArgumentException("Cannot generate DN from " + factoryPid + " and " + cn, e);
298 }
299 }
300
301 Dictionary<String, Object> getProps(String factoryPid, String cn) {
302 Attributes attrs = deployConfigs.get(serviceDn(factoryPid, cn));
303 if (attrs != null)
304 return new AttributesDictionary(attrs);
305 else
306 return null;
307 }
308
309 static boolean isInitialized() {
310 return Files.exists(deployConfigPath);
311 }
312
313 }