]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/kernel/CmsDeployment.java
Introduce Argeo Sync
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / 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 new Thread(() -> deployConfig.save(), "Save Argeo Deploy Config").start();
197 }
198 }
199
200 private void checkReadiness() {
201 if (nodeAvailable && userAdminAvailable && (httpExpected ? httpAvailable : true)) {
202 String data = KernelUtils.getFrameworkProp(KernelUtils.OSGI_INSTANCE_AREA);
203 String state = KernelUtils.getFrameworkProp(KernelUtils.OSGI_CONFIGURATION_AREA);
204 availableSince = System.currentTimeMillis();
205 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
206 String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
207 log.info("## ARGEO NODE AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
208 if (log.isDebugEnabled()) {
209 log.debug("## state: " + state);
210 if (data != null)
211 log.debug("## data: " + data);
212 }
213 long begin = bc.getService(bc.getServiceReference(NodeState.class)).getAvailableSince();
214 long initDuration = System.currentTimeMillis() - begin;
215 if (log.isTraceEnabled())
216 log.trace("Kernel initialization took " + initDuration + "ms");
217 tributeToFreeSoftware(initDuration);
218 }
219 }
220
221 final private void tributeToFreeSoftware(long initDuration) {
222 if (log.isTraceEnabled()) {
223 long ms = initDuration / 100;
224 log.trace("Spend " + ms + "ms" + " reflecting on the progress brought to mankind" + " by Free Software...");
225 long beginNano = System.nanoTime();
226 try {
227 Thread.sleep(ms, 0);
228 } catch (InterruptedException e) {
229 // silent
230 }
231 long durationNano = System.nanoTime() - beginNano;
232 final double M = 1000d * 1000d;
233 double sleepAccuracy = ((double) durationNano) / (ms * M);
234 log.trace("Sleep accuracy: " + String.format("%.2f", 100 - (sleepAccuracy * 100 - 100)) + " %");
235 }
236 }
237
238 private void prepareNodeRepository(Repository deployedNodeRepository) {
239 if (availableSince != null) {
240 throw new CmsException("Deployment is already available");
241 }
242
243 // home
244 prepareDataModel(NodeConstants.NODE, KernelUtils.openAdminSession(deployedNodeRepository));
245 }
246
247 private void prepareHomeRepository(RepositoryImpl deployedRepository) {
248 Hashtable<String, String> regProps = new Hashtable<String, String>();
249 regProps.put(NodeConstants.CN, NodeConstants.HOME);
250 // regProps.put(LEGACY_JCR_REPOSITORY_ALIAS, NodeConstants.HOME);
251 homeRepository = new HomeRepository(deployedRepository, false);
252 // register
253 bc.registerService(Repository.class, homeRepository, regProps);
254
255 new ServiceTracker<CallbackHandler, CallbackHandler>(bc, CallbackHandler.class, null) {
256
257 @Override
258 public CallbackHandler addingService(ServiceReference<CallbackHandler> reference) {
259 NodeKeyRing nodeKeyring = new NodeKeyRing(homeRepository);
260 CallbackHandler callbackHandler = bc.getService(reference);
261 nodeKeyring.setDefaultCallbackHandler(callbackHandler);
262 bc.registerService(LangUtils.names(Keyring.class, CryptoKeyring.class, ManagedService.class),
263 nodeKeyring, LangUtils.dico(Constants.SERVICE_PID, NodeConstants.NODE_KEYRING_PID));
264 return callbackHandler;
265 }
266
267 }.open();
268 }
269
270 /** Session is logged out. */
271 private void prepareDataModel(String cn, Session adminSession) {
272 try {
273 Set<String> processed = new HashSet<String>();
274 bundles: for (Bundle bundle : bc.getBundles()) {
275 BundleWiring wiring = bundle.adapt(BundleWiring.class);
276 if (wiring == null)
277 continue bundles;
278 if (NodeConstants.NODE.equals(cn))// process all data models
279 processWiring(cn, adminSession, wiring, processed);
280 else {
281 List<BundleCapability> capabilities = wiring.getCapabilities(CMS_DATA_MODEL_NAMESPACE);
282 for (BundleCapability capability : capabilities) {
283 String dataModelName = (String) capability.getAttributes().get(DataModelNamespace.NAME);
284 if (dataModelName.equals(cn))// process only own data model
285 processWiring(cn, adminSession, wiring, processed);
286 }
287 }
288 }
289 } finally {
290 JcrUtils.logoutQuietly(adminSession);
291 }
292 }
293
294 private void processWiring(String cn, Session adminSession, BundleWiring wiring, Set<String> processed) {
295 // recursively process requirements first
296 List<BundleWire> requiredWires = wiring.getRequiredWires(CMS_DATA_MODEL_NAMESPACE);
297 for (BundleWire wire : requiredWires) {
298 processWiring(cn, adminSession, wire.getProviderWiring(), processed);
299 }
300
301 List<String> publishAsLocalRepo = new ArrayList<>();
302 List<BundleCapability> capabilities = wiring.getCapabilities(CMS_DATA_MODEL_NAMESPACE);
303 for (BundleCapability capability : capabilities) {
304 boolean publish = registerDataModelCapability(cn, adminSession, capability, processed);
305 if (publish)
306 publishAsLocalRepo.add((String) capability.getAttributes().get(DataModelNamespace.NAME));
307 }
308 // Publish all at once, so that bundles with multiple CNDs are consistent
309 for (String dataModelName : publishAsLocalRepo)
310 publishLocalRepo(dataModelName, adminSession.getRepository());
311 }
312
313 private boolean registerDataModelCapability(String cn, Session adminSession, BundleCapability capability,
314 Set<String> processed) {
315 Map<String, Object> attrs = capability.getAttributes();
316 String name = (String) attrs.get(DataModelNamespace.NAME);
317 if (processed.contains(name)) {
318 if (log.isTraceEnabled())
319 log.trace("Data model " + name + " has already been processed");
320 return false;
321 }
322
323 // CND
324 String path = (String) attrs.get(DataModelNamespace.CND);
325 if (path != null) {
326 File dataModel = bc.getBundle().getDataFile("dataModels/" + path);
327 if (!dataModel.exists()) {
328 URL url = capability.getRevision().getBundle().getResource(path);
329 if (url == null)
330 throw new CmsException("No data model '" + name + "' found under path " + path);
331 try (Reader reader = new InputStreamReader(url.openStream())) {
332 CndImporter.registerNodeTypes(reader, adminSession, true);
333 processed.add(name);
334 dataModel.getParentFile().mkdirs();
335 dataModel.createNewFile();
336 if (log.isDebugEnabled())
337 log.debug("Registered CND " + url);
338 } catch (Exception e) {
339 throw new CmsException("Cannot import CND " + url, e);
340 }
341 }
342 }
343
344 if (KernelUtils.asBoolean((String) attrs.get(DataModelNamespace.ABSTRACT)))
345 return false;
346 // Non abstract
347 boolean isStandalone = deployConfig.isStandalone(name);
348 boolean publishLocalRepo;
349 if (isStandalone && name.equals(cn))// includes the node itself
350 publishLocalRepo = true;
351 else if (!isStandalone && cn.equals(NodeConstants.NODE))
352 publishLocalRepo = true;
353 else
354 publishLocalRepo = false;
355
356 return publishLocalRepo;
357 }
358
359 private void publishLocalRepo(String dataModelName, Repository repository) {
360 Hashtable<String, Object> properties = new Hashtable<>();
361 // properties.put(LEGACY_JCR_REPOSITORY_ALIAS, name);
362 properties.put(NodeConstants.CN, dataModelName);
363 if (dataModelName.equals(NodeConstants.NODE))
364 properties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
365 LocalRepository localRepository = new LocalRepository(repository, dataModelName);
366 bc.registerService(Repository.class, localRepository, properties);
367 if (log.isDebugEnabled())
368 log.debug("Published data model " + dataModelName);
369 }
370
371 @Override
372 public Long getAvailableSince() {
373 return availableSince;
374 }
375
376 private class RepositoryContextStc extends ServiceTracker<RepositoryContext, RepositoryContext> {
377
378 public RepositoryContextStc() {
379 super(bc, RepositoryContext.class, null);
380 }
381
382 @Override
383 public RepositoryContext addingService(ServiceReference<RepositoryContext> reference) {
384 RepositoryContext repoContext = bc.getService(reference);
385 String cn = (String) reference.getProperty(NodeConstants.CN);
386 if (cn != null) {
387 if (cn.equals(NodeConstants.NODE)) {
388 prepareNodeRepository(repoContext.getRepository());
389 // TODO separate home repository
390 prepareHomeRepository(repoContext.getRepository());
391 nodeAvailable = true;
392 checkReadiness();
393 } else {
394 prepareDataModel(cn, KernelUtils.openAdminSession(repoContext.getRepository()));
395 }
396 }
397 return repoContext;
398 }
399
400 @Override
401 public void modifiedService(ServiceReference<RepositoryContext> reference, RepositoryContext service) {
402 }
403
404 @Override
405 public void removedService(ServiceReference<RepositoryContext> reference, RepositoryContext service) {
406 }
407
408 }
409
410 }