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
.HashSet
;
11 import java
.util
.Hashtable
;
12 import java
.util
.List
;
16 import javax
.jcr
.Repository
;
17 import javax
.jcr
.Session
;
18 import javax
.security
.auth
.callback
.CallbackHandler
;
20 import org
.apache
.commons
.logging
.Log
;
21 import org
.apache
.commons
.logging
.LogFactory
;
22 import org
.apache
.jackrabbit
.commons
.cnd
.CndImporter
;
23 import org
.apache
.jackrabbit
.core
.RepositoryContext
;
24 import org
.argeo
.cms
.CmsException
;
25 import org
.argeo
.jcr
.JcrUtils
;
26 import org
.argeo
.node
.DataModelNamespace
;
27 import org
.argeo
.node
.NodeConstants
;
28 import org
.argeo
.node
.NodeDeployment
;
29 import org
.argeo
.node
.NodeState
;
30 import org
.argeo
.node
.security
.CryptoKeyring
;
31 import org
.argeo
.osgi
.useradmin
.UserAdminConf
;
32 import org
.argeo
.util
.LangUtils
;
33 import org
.osgi
.framework
.Bundle
;
34 import org
.osgi
.framework
.BundleContext
;
35 import org
.osgi
.framework
.Constants
;
36 import org
.osgi
.framework
.FrameworkUtil
;
37 import org
.osgi
.framework
.ServiceReference
;
38 import org
.osgi
.framework
.wiring
.BundleCapability
;
39 import org
.osgi
.framework
.wiring
.BundleWire
;
40 import org
.osgi
.framework
.wiring
.BundleWiring
;
41 import org
.osgi
.service
.cm
.Configuration
;
42 import org
.osgi
.service
.cm
.ConfigurationAdmin
;
43 import org
.osgi
.service
.cm
.ManagedService
;
44 import org
.osgi
.service
.useradmin
.UserAdmin
;
45 import org
.osgi
.util
.tracker
.ServiceTracker
;
47 public class CmsDeployment
implements NodeDeployment
{
48 private final static String LEGACY_JCR_REPOSITORY_ALIAS
= "argeo.jcr.repository.alias";
50 private final Log log
= LogFactory
.getLog(getClass());
51 private final BundleContext bc
= FrameworkUtil
.getBundle(getClass()).getBundleContext();
53 private DeployConfig deployConfig
;
54 private HomeRepository homeRepository
;
56 private Long availableSince
;
58 private final boolean cleanState
;
60 private NodeHttp nodeHttp
;
63 private boolean nodeAvailable
= false;
64 private boolean userAdminAvailable
= false;
65 private boolean httpExpected
= false;
66 private boolean httpAvailable
= false;
68 public CmsDeployment() {
69 ServiceReference
<NodeState
> nodeStateSr
= bc
.getServiceReference(NodeState
.class);
70 if (nodeStateSr
== null)
71 throw new CmsException("No node state available");
73 NodeState nodeState
= bc
.getService(nodeStateSr
);
74 cleanState
= nodeState
.isClean();
76 nodeHttp
= new NodeHttp();
80 private void initTrackers() {
81 ServiceTracker
<?
, ?
> httpSt
= new ServiceTracker
<NodeHttp
, NodeHttp
>(bc
, NodeHttp
.class, null) {
84 public NodeHttp
addingService(ServiceReference
<NodeHttp
> reference
) {
87 return super.addingService(reference
);
91 KernelUtils
.asyncOpen(httpSt
);
93 ServiceTracker
<?
, ?
> repoContextSt
= new RepositoryContextStc();
94 // repoContextSt.open();
95 KernelUtils
.asyncOpen(repoContextSt
);
97 ServiceTracker
<?
, ?
> userAdminSt
= new ServiceTracker
<UserAdmin
, UserAdmin
>(bc
, UserAdmin
.class, null) {
99 public UserAdmin
addingService(ServiceReference
<UserAdmin
> reference
) {
100 userAdminAvailable
= true;
102 return super.addingService(reference
);
105 // userAdminSt.open();
106 KernelUtils
.asyncOpen(userAdminSt
);
108 ServiceTracker
<?
, ?
> confAdminSt
= new ServiceTracker
<ConfigurationAdmin
, ConfigurationAdmin
>(bc
,
109 ConfigurationAdmin
.class, null) {
111 public ConfigurationAdmin
addingService(ServiceReference
<ConfigurationAdmin
> reference
) {
112 ConfigurationAdmin configurationAdmin
= bc
.getService(reference
);
113 deployConfig
= new DeployConfig(configurationAdmin
, cleanState
);
114 httpExpected
= deployConfig
.getProps(KernelConstants
.JETTY_FACTORY_PID
, "default") != null;
116 // Configuration[] configs = configurationAdmin
117 // .listConfigurations("(service.factoryPid=" +
118 // NodeConstants.NODE_REPOS_FACTORY_PID + ")");
119 // for (Configuration config : configs) {
120 // Object cn = config.getProperties().get(NodeConstants.CN);
121 // if (log.isDebugEnabled())
122 // log.debug("Standalone repo cn: " + cn);
124 Configuration
[] configs
= configurationAdmin
125 .listConfigurations("(service.factoryPid=" + NodeConstants
.NODE_USER_ADMIN_PID
+ ")");
127 boolean hasDomain
= false;
128 for (Configuration config
: configs
) {
129 Object realm
= config
.getProperties().get(UserAdminConf
.realm
.name());
131 log
.debug("Found realm: " + realm
);
136 loadIpaJaasConfiguration();
138 } catch (Exception e
) {
139 throw new CmsException("Cannot initialize config", e
);
141 return super.addingService(reference
);
144 // confAdminSt.open();
145 KernelUtils
.asyncOpen(confAdminSt
);
148 private void loadIpaJaasConfiguration() {
149 if (System
.getProperty(KernelConstants
.JAAS_CONFIG_PROP
) == null) {
150 String jaasConfig
= KernelConstants
.JAAS_CONFIG_IPA
;
151 URL url
= getClass().getClassLoader().getResource(jaasConfig
);
152 KernelUtils
.setJaasConfiguration(url
);
153 log
.debug("Set IPA JAAS configuration.");
157 public void shutdown() {
158 if (nodeHttp
!= null)
160 if (deployConfig
!= null)
164 private void checkReadiness() {
165 if (nodeAvailable
&& userAdminAvailable
&& (httpExpected ? httpAvailable
: true)) {
166 String data
= KernelUtils
.getFrameworkProp(KernelUtils
.OSGI_INSTANCE_AREA
);
167 String state
= KernelUtils
.getFrameworkProp(KernelUtils
.OSGI_CONFIGURATION_AREA
);
168 availableSince
= System
.currentTimeMillis();
169 long jvmUptime
= ManagementFactory
.getRuntimeMXBean().getUptime();
170 String jvmUptimeStr
= " in " + (jvmUptime
/ 1000) + "." + (jvmUptime
% 1000) + "s";
171 log
.info("## ARGEO NODE AVAILABLE" + (log
.isDebugEnabled() ? jvmUptimeStr
: "") + " ##");
172 if (log
.isDebugEnabled()) {
173 log
.debug("## state: " + state
);
175 log
.debug("## data: " + data
);
177 long begin
= bc
.getService(bc
.getServiceReference(NodeState
.class)).getAvailableSince();
178 long initDuration
= System
.currentTimeMillis() - begin
;
179 if (log
.isTraceEnabled())
180 log
.trace("Kernel initialization took " + initDuration
+ "ms");
181 tributeToFreeSoftware(initDuration
);
185 final private void tributeToFreeSoftware(long initDuration
) {
186 if (log
.isTraceEnabled()) {
187 long ms
= initDuration
/ 100;
188 log
.trace("Spend " + ms
+ "ms" + " reflecting on the progress brought to mankind" + " by Free Software...");
189 long beginNano
= System
.nanoTime();
192 } catch (InterruptedException e
) {
195 long durationNano
= System
.nanoTime() - beginNano
;
196 final double M
= 1000d
* 1000d
;
197 double sleepAccuracy
= ((double) durationNano
) / (ms
* M
);
198 log
.trace("Sleep accuracy: " + String
.format("%.2f", 100 - (sleepAccuracy
* 100 - 100)) + " %");
202 private void prepareNodeRepository(Repository deployedNodeRepository
) {
203 if (availableSince
!= null) {
204 throw new CmsException("Deployment is already available");
208 prepareDataModel(KernelUtils
.openAdminSession(deployedNodeRepository
));
211 private void prepareHomeRepository(Repository deployedRepository
) {
212 Hashtable
<String
, String
> regProps
= new Hashtable
<String
, String
>();
213 regProps
.put(NodeConstants
.CN
, NodeConstants
.HOME
);
214 regProps
.put(LEGACY_JCR_REPOSITORY_ALIAS
, NodeConstants
.HOME
);
215 homeRepository
= new HomeRepository(deployedRepository
);
217 bc
.registerService(Repository
.class, homeRepository
, regProps
);
219 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
222 public CallbackHandler
addingService(ServiceReference
<CallbackHandler
> reference
) {
223 NodeKeyRing nodeKeyring
= new NodeKeyRing(homeRepository
);
224 CallbackHandler callbackHandler
= bc
.getService(reference
);
225 nodeKeyring
.setDefaultCallbackHandler(callbackHandler
);
226 bc
.registerService(LangUtils
.names(CryptoKeyring
.class, ManagedService
.class), nodeKeyring
,
227 LangUtils
.dico(Constants
.SERVICE_PID
, NodeConstants
.NODE_KEYRING_PID
));
228 return callbackHandler
;
234 /** Session is logged out. */
235 private void prepareDataModel(Session adminSession
) {
237 Set
<String
> processed
= new HashSet
<String
>();
238 bundles
: for (Bundle bundle
: bc
.getBundles()) {
239 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
242 processWiring(adminSession
, wiring
, processed
);
245 JcrUtils
.logoutQuietly(adminSession
);
249 private void processWiring(Session adminSession
, BundleWiring wiring
, Set
<String
> processed
) {
250 // recursively process requirements first
251 List
<BundleWire
> requiredWires
= wiring
.getRequiredWires(CMS_DATA_MODEL_NAMESPACE
);
252 for (BundleWire wire
: requiredWires
) {
253 processWiring(adminSession
, wire
.getProviderWiring(), processed
);
254 // registerCnd(adminSession, wire.getCapability(), processed);
256 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
257 for (BundleCapability capability
: capabilities
) {
258 registerDataModelCapability(adminSession
, capability
, processed
);
262 private void registerDataModelCapability(Session adminSession
, BundleCapability capability
, Set
<String
> processed
) {
263 Map
<String
, Object
> attrs
= capability
.getAttributes();
264 String name
= (String
) attrs
.get(DataModelNamespace
.CAPABILITY_NAME_ATTRIBUTE
);
265 if (processed
.contains(name
)) {
266 if (log
.isTraceEnabled())
267 log
.trace("Data model " + name
+ " has already been processed");
272 String path
= (String
) attrs
.get(DataModelNamespace
.CAPABILITY_CND_ATTRIBUTE
);
274 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
275 if (!dataModel
.exists()) {
276 URL url
= capability
.getRevision().getBundle().getResource(path
);
278 throw new CmsException("No data model '" + name
+ "' found under path " + path
);
279 try (Reader reader
= new InputStreamReader(url
.openStream())) {
280 CndImporter
.registerNodeTypes(reader
, adminSession
, true);
282 dataModel
.getParentFile().mkdirs();
283 dataModel
.createNewFile();
284 if (log
.isDebugEnabled())
285 log
.debug("Registered CND " + url
);
286 } catch (Exception e
) {
287 throw new CmsException("Cannot import CND " + url
, e
);
292 if (!asBoolean((String
) attrs
.get(DataModelNamespace
.CAPABILITY_ABSTRACT_ATTRIBUTE
))) {
293 Hashtable
<String
, Object
> properties
= new Hashtable
<>();
294 properties
.put(LEGACY_JCR_REPOSITORY_ALIAS
, name
);
295 properties
.put(NodeConstants
.CN
, name
);
296 if (name
.equals(NodeConstants
.NODE
))
297 properties
.put(Constants
.SERVICE_RANKING
, Integer
.MAX_VALUE
);
298 LocalRepository localRepository
= new LocalRepository(adminSession
.getRepository(), capability
);
299 bc
.registerService(Repository
.class, localRepository
, properties
);
300 if (log
.isDebugEnabled())
301 log
.debug("Published data model " + name
);
305 private boolean asBoolean(String value
) {
314 throw new CmsException("Unsupported value for attribute " + DataModelNamespace
.CAPABILITY_ABSTRACT_ATTRIBUTE
320 public Long
getAvailableSince() {
321 return availableSince
;
324 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
326 public RepositoryContextStc() {
327 super(bc
, RepositoryContext
.class, null);
331 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
332 RepositoryContext nodeRepo
= bc
.getService(reference
);
333 Object cn
= reference
.getProperty(NodeConstants
.CN
);
335 if (cn
.equals(NodeConstants
.NODE
)) {
336 prepareNodeRepository(nodeRepo
.getRepository());
337 prepareHomeRepository(nodeRepo
.getRepository());
338 nodeAvailable
= true;
348 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
352 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {