]> git.argeo.org Git - lgpl/argeo-commons.git/blob - kernel/CmsDeployment.java
Prepare next development cycle
[lgpl/argeo-commons.git] / kernel / CmsDeployment.java
1 package org.argeo.cms.internal.kernel;
2
3 import static org.argeo.node.DataModelNamespace.CMS_DATA_MODEL_NAMESPACE;
4
5 import java.io.File;
6 import java.io.InputStreamReader;
7 import java.io.Reader;
8 import java.lang.management.ManagementFactory;
9 import java.net.URL;
10 import java.util.ArrayList;
11 import java.util.HashSet;
12 import java.util.Hashtable;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16
17 import javax.jcr.Repository;
18 import javax.jcr.Session;
19 import javax.security.auth.callback.CallbackHandler;
20 import javax.transaction.UserTransaction;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.jackrabbit.commons.cnd.CndImporter;
25 import org.apache.jackrabbit.core.RepositoryContext;
26 import org.apache.jackrabbit.core.RepositoryImpl;
27 import org.argeo.cms.CmsException;
28 import org.argeo.jcr.JcrUtils;
29 import org.argeo.node.DataModelNamespace;
30 import org.argeo.node.NodeConstants;
31 import org.argeo.node.NodeDeployment;
32 import org.argeo.node.NodeState;
33 import org.argeo.node.security.CryptoKeyring;
34 import org.argeo.node.security.Keyring;
35 import org.argeo.osgi.useradmin.UserAdminConf;
36 import org.argeo.util.LangUtils;
37 import org.osgi.framework.Bundle;
38 import org.osgi.framework.BundleContext;
39 import org.osgi.framework.Constants;
40 import org.osgi.framework.FrameworkUtil;
41 import org.osgi.framework.ServiceReference;
42 import org.osgi.framework.wiring.BundleCapability;
43 import org.osgi.framework.wiring.BundleWire;
44 import org.osgi.framework.wiring.BundleWiring;
45 import org.osgi.service.cm.Configuration;
46 import org.osgi.service.cm.ConfigurationAdmin;
47 import org.osgi.service.cm.ManagedService;
48 import org.osgi.service.useradmin.Group;
49 import org.osgi.service.useradmin.Role;
50 import org.osgi.service.useradmin.UserAdmin;
51 import org.osgi.util.tracker.ServiceTracker;
52
53 public class CmsDeployment implements NodeDeployment {
54 // private final static String LEGACY_JCR_REPOSITORY_ALIAS =
55 // "argeo.jcr.repository.alias";
56
57 private final Log log = LogFactory.getLog(getClass());
58 private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
59
60 private DataModels dataModels;
61 private DeployConfig deployConfig;
62 private HomeRepository homeRepository;
63
64 private Long availableSince;
65
66 private final boolean cleanState;
67
68 private NodeHttp nodeHttp;
69
70 // Readiness
71 private boolean nodeAvailable = false;
72 private boolean userAdminAvailable = false;
73 private boolean httpExpected = false;
74 private boolean httpAvailable = false;
75
76 public CmsDeployment() {
77 ServiceReference<NodeState> nodeStateSr = bc.getServiceReference(NodeState.class);
78 if (nodeStateSr == null)
79 throw new CmsException("No node state available");
80
81 NodeState nodeState = bc.getService(nodeStateSr);
82 cleanState = nodeState.isClean();
83
84 nodeHttp = new NodeHttp(cleanState);
85 dataModels = new DataModels(bc);
86 initTrackers();
87 }
88
89 private void initTrackers() {
90 ServiceTracker<?, ?> httpSt = new ServiceTracker<NodeHttp, NodeHttp>(bc, NodeHttp.class, null) {
91
92 @Override
93 public NodeHttp addingService(ServiceReference<NodeHttp> reference) {
94 httpAvailable = true;
95 checkReadiness();
96 return super.addingService(reference);
97 }
98 };
99 // httpSt.open();
100 KernelUtils.asyncOpen(httpSt);
101
102 ServiceTracker<?, ?> repoContextSt = new RepositoryContextStc();
103 // repoContextSt.open();
104 KernelUtils.asyncOpen(repoContextSt);
105
106 ServiceTracker<?, ?> userAdminSt = new ServiceTracker<UserAdmin, UserAdmin>(bc, UserAdmin.class, null) {
107 @Override
108 public UserAdmin addingService(ServiceReference<UserAdmin> reference) {
109 UserAdmin userAdmin = super.addingService(reference);
110 addStandardSystemRoles(userAdmin);
111 userAdminAvailable = true;
112 checkReadiness();
113 return userAdmin;
114 }
115 };
116 // userAdminSt.open();
117 KernelUtils.asyncOpen(userAdminSt);
118
119 ServiceTracker<?, ?> confAdminSt = new ServiceTracker<ConfigurationAdmin, ConfigurationAdmin>(bc,
120 ConfigurationAdmin.class, null) {
121 @Override
122 public ConfigurationAdmin addingService(ServiceReference<ConfigurationAdmin> reference) {
123 ConfigurationAdmin configurationAdmin = bc.getService(reference);
124 deployConfig = new DeployConfig(configurationAdmin, dataModels, cleanState);
125 httpExpected = deployConfig.getProps(KernelConstants.JETTY_FACTORY_PID, "default") != null;
126 try {
127 // Configuration[] configs = configurationAdmin
128 // .listConfigurations("(service.factoryPid=" +
129 // NodeConstants.NODE_REPOS_FACTORY_PID + ")");
130 // for (Configuration config : configs) {
131 // Object cn = config.getProperties().get(NodeConstants.CN);
132 // if (log.isDebugEnabled())
133 // log.debug("Standalone repo cn: " + cn);
134 // }
135 Configuration[] configs = configurationAdmin
136 .listConfigurations("(service.factoryPid=" + NodeConstants.NODE_USER_ADMIN_PID + ")");
137
138 boolean hasDomain = false;
139 for (Configuration config : configs) {
140 Object realm = config.getProperties().get(UserAdminConf.realm.name());
141 if (realm != null) {
142 log.debug("Found realm: " + realm);
143 hasDomain = true;
144 }
145 }
146 if (hasDomain) {
147 loadIpaJaasConfiguration();
148 }
149 } catch (Exception e) {
150 throw new CmsException("Cannot initialize config", e);
151 }
152 return super.addingService(reference);
153 }
154 };
155 // confAdminSt.open();
156 KernelUtils.asyncOpen(confAdminSt);
157 }
158
159 private void addStandardSystemRoles(UserAdmin userAdmin) {
160 // we assume UserTransaction is already available (TODO make it more robust)
161 UserTransaction userTransaction = bc.getService(bc.getServiceReference(UserTransaction.class));
162 try {
163 userTransaction.begin();
164 Role adminRole = userAdmin.getRole(NodeConstants.ROLE_ADMIN);
165 if (adminRole == null) {
166 adminRole = userAdmin.createRole(NodeConstants.ROLE_ADMIN, Role.GROUP);
167 }
168 if (userAdmin.getRole(NodeConstants.ROLE_USER_ADMIN) == null) {
169 Group userAdminRole = (Group) userAdmin.createRole(NodeConstants.ROLE_USER_ADMIN, Role.GROUP);
170 userAdminRole.addMember(adminRole);
171 }
172 userTransaction.commit();
173 } catch (Exception e) {
174 try {
175 userTransaction.rollback();
176 } catch (Exception e1) {
177 // silent
178 }
179 throw new CmsException("Cannot add standard system roles", e);
180 }
181 }
182
183 private void loadIpaJaasConfiguration() {
184 if (System.getProperty(KernelConstants.JAAS_CONFIG_PROP) == null) {
185 String jaasConfig = KernelConstants.JAAS_CONFIG_IPA;
186 URL url = getClass().getClassLoader().getResource(jaasConfig);
187 KernelUtils.setJaasConfiguration(url);
188 log.debug("Set IPA JAAS configuration.");
189 }
190 }
191
192 public void shutdown() {
193 if (nodeHttp != null)
194 nodeHttp.destroy();
195 if (deployConfig != null)
196 deployConfig.save();
197 }
198
199 private void checkReadiness() {
200 if (nodeAvailable && userAdminAvailable && (httpExpected ? httpAvailable : true)) {
201 String data = KernelUtils.getFrameworkProp(KernelUtils.OSGI_INSTANCE_AREA);
202 String state = KernelUtils.getFrameworkProp(KernelUtils.OSGI_CONFIGURATION_AREA);
203 availableSince = System.currentTimeMillis();
204 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
205 String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
206 log.info("## ARGEO NODE AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
207 if (log.isDebugEnabled()) {
208 log.debug("## state: " + state);
209 if (data != null)
210 log.debug("## data: " + data);
211 }
212 long begin = bc.getService(bc.getServiceReference(NodeState.class)).getAvailableSince();
213 long initDuration = System.currentTimeMillis() - begin;
214 if (log.isTraceEnabled())
215 log.trace("Kernel initialization took " + initDuration + "ms");
216 tributeToFreeSoftware(initDuration);
217 }
218 }
219
220 final private void tributeToFreeSoftware(long initDuration) {
221 if (log.isTraceEnabled()) {
222 long ms = initDuration / 100;
223 log.trace("Spend " + ms + "ms" + " reflecting on the progress brought to mankind" + " by Free Software...");
224 long beginNano = System.nanoTime();
225 try {
226 Thread.sleep(ms, 0);
227 } catch (InterruptedException e) {
228 // silent
229 }
230 long durationNano = System.nanoTime() - beginNano;
231 final double M = 1000d * 1000d;
232 double sleepAccuracy = ((double) durationNano) / (ms * M);
233 log.trace("Sleep accuracy: " + String.format("%.2f", 100 - (sleepAccuracy * 100 - 100)) + " %");
234 }
235 }
236
237 private void prepareNodeRepository(Repository deployedNodeRepository) {
238 if (availableSince != null) {
239 throw new CmsException("Deployment is already available");
240 }
241
242 // home
243 prepareDataModel(NodeConstants.NODE, KernelUtils.openAdminSession(deployedNodeRepository));
244 }
245
246 private void prepareHomeRepository(RepositoryImpl deployedRepository) {
247 Hashtable<String, String> regProps = new Hashtable<String, String>();
248 regProps.put(NodeConstants.CN, NodeConstants.HOME);
249 // regProps.put(LEGACY_JCR_REPOSITORY_ALIAS, NodeConstants.HOME);
250 homeRepository = new HomeRepository(deployedRepository, false);
251 // register
252 bc.registerService(Repository.class, homeRepository, regProps);
253
254 new ServiceTracker<CallbackHandler, CallbackHandler>(bc, CallbackHandler.class, null) {
255
256 @Override
257 public CallbackHandler addingService(ServiceReference<CallbackHandler> reference) {
258 NodeKeyRing nodeKeyring = new NodeKeyRing(homeRepository);
259 CallbackHandler callbackHandler = bc.getService(reference);
260 nodeKeyring.setDefaultCallbackHandler(callbackHandler);
261 bc.registerService(LangUtils.names(Keyring.class, CryptoKeyring.class, ManagedService.class),
262 nodeKeyring, LangUtils.dico(Constants.SERVICE_PID, NodeConstants.NODE_KEYRING_PID));
263 return callbackHandler;
264 }
265
266 }.open();
267 }
268
269 /** Session is logged out. */
270 private void prepareDataModel(String cn, Session adminSession) {
271 try {
272 Set<String> processed = new HashSet<String>();
273 bundles: for (Bundle bundle : bc.getBundles()) {
274 BundleWiring wiring = bundle.adapt(BundleWiring.class);
275 if (wiring == null)
276 continue bundles;
277 if (NodeConstants.NODE.equals(cn))// process all data models
278 processWiring(cn, adminSession, wiring, processed);
279 else {
280 List<BundleCapability> capabilities = wiring.getCapabilities(CMS_DATA_MODEL_NAMESPACE);
281 for (BundleCapability capability : capabilities) {
282 String dataModelName = (String) capability.getAttributes().get(DataModelNamespace.NAME);
283 if (dataModelName.equals(cn))// process only own data model
284 processWiring(cn, adminSession, wiring, processed);
285 }
286 }
287 }
288 } finally {
289 JcrUtils.logoutQuietly(adminSession);
290 }
291 }
292
293 private void processWiring(String cn, Session adminSession, BundleWiring wiring, Set<String> processed) {
294 // recursively process requirements first
295 List<BundleWire> requiredWires = wiring.getRequiredWires(CMS_DATA_MODEL_NAMESPACE);
296 for (BundleWire wire : requiredWires) {
297 processWiring(cn, adminSession, wire.getProviderWiring(), processed);
298 }
299
300 List<String> publishAsLocalRepo = new ArrayList<>();
301 List<BundleCapability> capabilities = wiring.getCapabilities(CMS_DATA_MODEL_NAMESPACE);
302 for (BundleCapability capability : capabilities) {
303 boolean publish = registerDataModelCapability(cn, adminSession, capability, processed);
304 if (publish)
305 publishAsLocalRepo.add((String) capability.getAttributes().get(DataModelNamespace.NAME));
306 }
307 // Publish all at once, so that bundles with multiple CNDs are consistent
308 for (String dataModelName : publishAsLocalRepo)
309 publishLocalRepo(dataModelName, adminSession.getRepository());
310 }
311
312 private boolean registerDataModelCapability(String cn, Session adminSession, BundleCapability capability,
313 Set<String> processed) {
314 Map<String, Object> attrs = capability.getAttributes();
315 String name = (String) attrs.get(DataModelNamespace.NAME);
316 if (processed.contains(name)) {
317 if (log.isTraceEnabled())
318 log.trace("Data model " + name + " has already been processed");
319 return false;
320 }
321
322 // CND
323 String path = (String) attrs.get(DataModelNamespace.CND);
324 if (path != null) {
325 File dataModel = bc.getBundle().getDataFile("dataModels/" + path);
326 if (!dataModel.exists()) {
327 URL url = capability.getRevision().getBundle().getResource(path);
328 if (url == null)
329 throw new CmsException("No data model '" + name + "' found under path " + path);
330 try (Reader reader = new InputStreamReader(url.openStream())) {
331 CndImporter.registerNodeTypes(reader, adminSession, true);
332 processed.add(name);
333 dataModel.getParentFile().mkdirs();
334 dataModel.createNewFile();
335 if (log.isDebugEnabled())
336 log.debug("Registered CND " + url);
337 } catch (Exception e) {
338 throw new CmsException("Cannot import CND " + url, e);
339 }
340 }
341 }
342
343 if (KernelUtils.asBoolean((String) attrs.get(DataModelNamespace.ABSTRACT)))
344 return false;
345 // Non abstract
346 boolean isStandalone = deployConfig.isStandalone(name);
347 boolean publishLocalRepo;
348 if (isStandalone && name.equals(cn))// includes the node itself
349 publishLocalRepo = true;
350 else if (!isStandalone && cn.equals(NodeConstants.NODE))
351 publishLocalRepo = true;
352 else
353 publishLocalRepo = false;
354
355 return publishLocalRepo;
356 }
357
358 private void publishLocalRepo(String dataModelName, Repository repository) {
359 Hashtable<String, Object> properties = new Hashtable<>();
360 // properties.put(LEGACY_JCR_REPOSITORY_ALIAS, name);
361 properties.put(NodeConstants.CN, dataModelName);
362 if (dataModelName.equals(NodeConstants.NODE))
363 properties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
364 LocalRepository localRepository = new LocalRepository(repository, dataModelName);
365 bc.registerService(Repository.class, localRepository, properties);
366 if (log.isDebugEnabled())
367 log.debug("Published data model " + dataModelName);
368 }
369
370 @Override
371 public Long getAvailableSince() {
372 return availableSince;
373 }
374
375 private class RepositoryContextStc extends ServiceTracker<RepositoryContext, RepositoryContext> {
376
377 public RepositoryContextStc() {
378 super(bc, RepositoryContext.class, null);
379 }
380
381 @Override
382 public RepositoryContext addingService(ServiceReference<RepositoryContext> reference) {
383 RepositoryContext repoContext = bc.getService(reference);
384 String cn = (String) reference.getProperty(NodeConstants.CN);
385 if (cn != null) {
386 if (cn.equals(NodeConstants.NODE)) {
387 prepareNodeRepository(repoContext.getRepository());
388 // TODO separate home repository
389 prepareHomeRepository(repoContext.getRepository());
390 nodeAvailable = true;
391 checkReadiness();
392 } else {
393 prepareDataModel(cn, KernelUtils.openAdminSession(repoContext.getRepository()));
394 }
395 }
396 return repoContext;
397 }
398
399 @Override
400 public void modifiedService(ServiceReference<RepositoryContext> reference, RepositoryContext service) {
401 }
402
403 @Override
404 public void removedService(ServiceReference<RepositoryContext> reference, RepositoryContext service) {
405 }
406
407 }
408
409 }