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)
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
);
210 log
.debug("## data: " + data
);
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
);
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();
227 } catch (InterruptedException e
) {
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)) + " %");
237 private void prepareNodeRepository(Repository deployedNodeRepository
) {
238 if (availableSince
!= null) {
239 throw new CmsException("Deployment is already available");
243 prepareDataModel(NodeConstants
.NODE
, KernelUtils
.openAdminSession(deployedNodeRepository
));
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);
252 bc
.registerService(Repository
.class, homeRepository
, regProps
);
254 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
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
;
269 /** Session is logged out. */
270 private void prepareDataModel(String cn
, Session adminSession
) {
272 Set
<String
> processed
= new HashSet
<String
>();
273 bundles
: for (Bundle bundle
: bc
.getBundles()) {
274 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
277 if (NodeConstants
.NODE
.equals(cn
))// process all data models
278 processWiring(cn
, adminSession
, wiring
, processed
);
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
);
289 JcrUtils
.logoutQuietly(adminSession
);
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
);
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
);
305 publishAsLocalRepo
.add((String
) capability
.getAttributes().get(DataModelNamespace
.NAME
));
307 // Publish all at once, so that bundles with multiple CNDs are consistent
308 for (String dataModelName
: publishAsLocalRepo
)
309 publishLocalRepo(dataModelName
, adminSession
.getRepository());
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");
323 String path
= (String
) attrs
.get(DataModelNamespace
.CND
);
325 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
326 if (!dataModel
.exists()) {
327 URL url
= capability
.getRevision().getBundle().getResource(path
);
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);
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
);
343 if (KernelUtils
.asBoolean((String
) attrs
.get(DataModelNamespace
.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;
353 publishLocalRepo
= false;
355 return publishLocalRepo
;
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
);
371 public Long
getAvailableSince() {
372 return availableSince
;
375 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
377 public RepositoryContextStc() {
378 super(bc
, RepositoryContext
.class, null);
382 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
383 RepositoryContext repoContext
= bc
.getService(reference
);
384 String cn
= (String
) reference
.getProperty(NodeConstants
.CN
);
386 if (cn
.equals(NodeConstants
.NODE
)) {
387 prepareNodeRepository(repoContext
.getRepository());
388 // TODO separate home repository
389 prepareHomeRepository(repoContext
.getRepository());
390 nodeAvailable
= true;
393 prepareDataModel(cn
, KernelUtils
.openAdminSession(repoContext
.getRepository()));
400 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
404 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {