1 package org
.argeo
.cms
.internal
.kernel
;
3 import static org
.argeo
.node
.DataModelNamespace
.CMS_DATA_MODEL_NAMESPACE
;
6 import java
.io
.InputStreamReader
;
8 import java
.lang
.management
.ManagementFactory
;
10 import java
.util
.ArrayList
;
11 import java
.util
.HashSet
;
12 import java
.util
.Hashtable
;
13 import java
.util
.List
;
17 import javax
.jcr
.Repository
;
18 import javax
.jcr
.Session
;
19 import javax
.security
.auth
.callback
.CallbackHandler
;
20 import javax
.transaction
.UserTransaction
;
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
;
53 public class CmsDeployment
implements NodeDeployment
{
54 // private final static String LEGACY_JCR_REPOSITORY_ALIAS =
55 // "argeo.jcr.repository.alias";
57 private final Log log
= LogFactory
.getLog(getClass());
58 private final BundleContext bc
= FrameworkUtil
.getBundle(getClass()).getBundleContext();
60 private DataModels dataModels
;
61 private DeployConfig deployConfig
;
62 private HomeRepository homeRepository
;
64 private Long availableSince
;
66 private final boolean cleanState
;
68 private NodeHttp nodeHttp
;
71 private boolean nodeAvailable
= false;
72 private boolean userAdminAvailable
= false;
73 private boolean httpExpected
= false;
74 private boolean httpAvailable
= false;
76 public CmsDeployment() {
77 ServiceReference
<NodeState
> nodeStateSr
= bc
.getServiceReference(NodeState
.class);
78 if (nodeStateSr
== null)
79 throw new CmsException("No node state available");
81 NodeState nodeState
= bc
.getService(nodeStateSr
);
82 cleanState
= nodeState
.isClean();
84 nodeHttp
= new NodeHttp(cleanState
);
85 dataModels
= new DataModels(bc
);
89 private void initTrackers() {
90 ServiceTracker
<?
, ?
> httpSt
= new ServiceTracker
<NodeHttp
, NodeHttp
>(bc
, NodeHttp
.class, null) {
93 public NodeHttp
addingService(ServiceReference
<NodeHttp
> reference
) {
96 return super.addingService(reference
);
100 KernelUtils
.asyncOpen(httpSt
);
102 ServiceTracker
<?
, ?
> repoContextSt
= new RepositoryContextStc();
103 // repoContextSt.open();
104 KernelUtils
.asyncOpen(repoContextSt
);
106 ServiceTracker
<?
, ?
> userAdminSt
= new ServiceTracker
<UserAdmin
, UserAdmin
>(bc
, UserAdmin
.class, null) {
108 public UserAdmin
addingService(ServiceReference
<UserAdmin
> reference
) {
109 UserAdmin userAdmin
= super.addingService(reference
);
110 addStandardSystemRoles(userAdmin
);
111 userAdminAvailable
= true;
116 // userAdminSt.open();
117 KernelUtils
.asyncOpen(userAdminSt
);
119 ServiceTracker
<?
, ?
> confAdminSt
= new ServiceTracker
<ConfigurationAdmin
, ConfigurationAdmin
>(bc
,
120 ConfigurationAdmin
.class, null) {
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;
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);
135 Configuration
[] configs
= configurationAdmin
136 .listConfigurations("(service.factoryPid=" + NodeConstants
.NODE_USER_ADMIN_PID
+ ")");
138 boolean hasDomain
= false;
139 for (Configuration config
: configs
) {
140 Object realm
= config
.getProperties().get(UserAdminConf
.realm
.name());
142 log
.debug("Found realm: " + realm
);
147 loadIpaJaasConfiguration();
149 } catch (Exception e
) {
150 throw new CmsException("Cannot initialize config", e
);
152 return super.addingService(reference
);
155 // confAdminSt.open();
156 KernelUtils
.asyncOpen(confAdminSt
);
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));
163 userTransaction
.begin();
164 Role adminRole
= userAdmin
.getRole(NodeConstants
.ROLE_ADMIN
);
165 if (adminRole
== null) {
166 adminRole
= userAdmin
.createRole(NodeConstants
.ROLE_ADMIN
, Role
.GROUP
);
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
);
172 userTransaction
.commit();
173 } catch (Exception e
) {
175 userTransaction
.rollback();
176 } catch (Exception e1
) {
179 throw new CmsException("Cannot add standard system roles", e
);
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.");
192 public void shutdown() {
193 if (nodeHttp
!= null)
195 if (deployConfig
!= null) {
196 new Thread(() -> deployConfig
.save(), "Save Argeo Deploy Config").start();
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
);
211 log
.debug("## data: " + data
);
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
);
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();
228 } catch (InterruptedException e
) {
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)) + " %");
238 private void prepareNodeRepository(Repository deployedNodeRepository
) {
239 if (availableSince
!= null) {
240 throw new CmsException("Deployment is already available");
244 prepareDataModel(NodeConstants
.NODE
, KernelUtils
.openAdminSession(deployedNodeRepository
));
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);
253 bc
.registerService(Repository
.class, homeRepository
, regProps
);
255 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
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
;
270 /** Session is logged out. */
271 private void prepareDataModel(String cn
, Session adminSession
) {
273 Set
<String
> processed
= new HashSet
<String
>();
274 bundles
: for (Bundle bundle
: bc
.getBundles()) {
275 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
278 if (NodeConstants
.NODE
.equals(cn
))// process all data models
279 processWiring(cn
, adminSession
, wiring
, processed
);
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
);
290 JcrUtils
.logoutQuietly(adminSession
);
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
);
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
);
306 publishAsLocalRepo
.add((String
) capability
.getAttributes().get(DataModelNamespace
.NAME
));
308 // Publish all at once, so that bundles with multiple CNDs are consistent
309 for (String dataModelName
: publishAsLocalRepo
)
310 publishLocalRepo(dataModelName
, adminSession
.getRepository());
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");
324 String path
= (String
) attrs
.get(DataModelNamespace
.CND
);
326 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
327 if (!dataModel
.exists()) {
328 URL url
= capability
.getRevision().getBundle().getResource(path
);
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);
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
);
344 if (KernelUtils
.asBoolean((String
) attrs
.get(DataModelNamespace
.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;
354 publishLocalRepo
= false;
356 return publishLocalRepo
;
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
);
372 public Long
getAvailableSince() {
373 return availableSince
;
376 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
378 public RepositoryContextStc() {
379 super(bc
, RepositoryContext
.class, null);
383 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
384 RepositoryContext repoContext
= bc
.getService(reference
);
385 String cn
= (String
) reference
.getProperty(NodeConstants
.CN
);
387 if (cn
.equals(NodeConstants
.NODE
)) {
388 prepareNodeRepository(repoContext
.getRepository());
389 // TODO separate home repository
390 prepareHomeRepository(repoContext
.getRepository());
391 nodeAvailable
= true;
394 prepareDataModel(cn
, KernelUtils
.openAdminSession(repoContext
.getRepository()));
401 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
405 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {