001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019package org.apache.wiki.workflow; 020 021import org.apache.commons.collections4.queue.CircularFifoQueue; 022import org.apache.commons.lang3.time.StopWatch; 023import org.apache.logging.log4j.LogManager; 024import org.apache.logging.log4j.Logger; 025import org.apache.wiki.api.core.Context; 026import org.apache.wiki.api.core.Engine; 027import org.apache.wiki.api.core.Session; 028import org.apache.wiki.api.exceptions.WikiException; 029import org.apache.wiki.auth.AuthorizationManager; 030import org.apache.wiki.auth.acl.UnresolvedPrincipal; 031import org.apache.wiki.event.WikiEvent; 032import org.apache.wiki.event.WikiEventEmitter; 033import org.apache.wiki.event.WorkflowEvent; 034import org.apache.wiki.util.Synchronizer; 035import org.apache.wiki.util.TextUtil; 036 037import java.io.*; 038import java.nio.file.Files; 039import java.security.Principal; 040import java.util.*; 041import java.util.concurrent.ConcurrentHashMap; 042import java.util.concurrent.CopyOnWriteArrayList; 043import java.util.concurrent.locks.ReentrantLock; 044 045 046/** 047 * <p> 048 * Monitor class that tracks running Workflows. The WorkflowManager also keeps track of the names of 049 * users or groups expected to approve particular Workflows. 050 * </p> 051 */ 052public class DefaultWorkflowManager implements WorkflowManager, Serializable { 053 054 private static final Logger LOG = LogManager.getLogger( DefaultWorkflowManager.class ); 055 static final String SERIALIZATION_FILE = "wkflmgr.ser"; 056 057 /** We use this also a generic serialization id */ 058 private static final long serialVersionUID = 6L; 059 060 DecisionQueue m_queue; 061 Set< Workflow > m_workflows; 062 final Map< String, Principal > m_approvers; 063 Queue< Workflow > m_completed; 064 private Engine m_engine; 065 private int retainCompleted; 066 067 /** 068 * A lock used to ensure thread safety when accessing shared resources. 069 * This lock provides more flexibility and capabilities than the intrinsic locking mechanism, 070 * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread 071 * waiting to acquire a lock. 072 * 073 * @see java.util.concurrent.locks.ReentrantLock 074 */ 075 private final ReentrantLock lock = new ReentrantLock(); 076 077 /** 078 * Constructs a new WorkflowManager, with an empty workflow cache. 079 */ 080 public DefaultWorkflowManager() { 081 m_workflows = ConcurrentHashMap.newKeySet(); 082 m_approvers = new ConcurrentHashMap<>(); 083 m_queue = new DecisionQueue(); 084 WikiEventEmitter.register( this ); 085 } 086 087 /** 088 * {@inheritDoc} 089 */ 090 @Override 091 public Set< Workflow > getWorkflows() { 092 final Set< Workflow > workflows = ConcurrentHashMap.newKeySet(); 093 workflows.addAll( m_workflows ); 094 return workflows; 095 } 096 097 /** 098 * {@inheritDoc} 099 */ 100 @Override 101 public Map< Integer, Workflow > getWorkflowsAsMap() { 102 final Map< Integer, Workflow > workflows = new ConcurrentHashMap<>(); 103 m_workflows.forEach( w -> workflows.put( w.getId(), w ) ); 104 return workflows; 105 } 106 107 /** 108 * {@inheritDoc} 109 */ 110 @Override 111 public List< Workflow > getCompletedWorkflows() { 112 return new CopyOnWriteArrayList< >( m_completed ); 113 } 114 115 /** 116 * {@inheritDoc} 117 * 118 * Any properties that begin with {@link #PROPERTY_APPROVER_PREFIX} will be assumed to be Decisions that require approval. For a given 119 * property key, everything after the prefix denotes the Decision's message key. The property value indicates the Principal (Role, 120 * GroupPrincipal, WikiPrincipal) that must approve the Decision. For example, if the property key/value pair is 121 * {@code jspwiki.approver.workflow.saveWikiPage=Admin}, the Decision's message key is <code>workflow.saveWikiPage</code>. The Principal 122 * <code>Admin</code> will be resolved via {@link org.apache.wiki.auth.AuthorizationManager#resolvePrincipal(String)}. 123 */ 124 @Override 125 public void initialize( final Engine engine, final Properties props ) { 126 m_engine = engine; 127 retainCompleted = TextUtil.getIntegerProperty( engine.getWikiProperties(), "jspwiki.workflow.completed.retain", 2048 ); 128 m_completed = new CircularFifoQueue<>( retainCompleted ); 129 130 // Identify the workflows requiring approvals 131 for( final Object o : props.keySet() ) { 132 final String prop = ( String )o; 133 if( prop.startsWith( PROPERTY_APPROVER_PREFIX ) ) { 134 // For the key, everything after the prefix is the workflow name 135 final String key = prop.substring( PROPERTY_APPROVER_PREFIX.length() ); 136 if(!key.isEmpty()) { 137 // Only use non-null/non-blank approvers 138 final String approver = props.getProperty( prop ); 139 if( approver != null && !approver.isEmpty() ) { 140 m_approvers.put( key, new UnresolvedPrincipal( approver ) ); 141 } 142 } 143 } 144 } 145 146 unserializeFromDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) ); 147 } 148 149 /** 150 * Reads the serialized data from the disk back to memory. 151 * 152 * @return the date when the data was last written on disk or {@code 0} if there has been problems reading from disk. 153 */ 154 @SuppressWarnings( "unchecked" ) 155 long unserializeFromDisk( final File f ) { 156 return Synchronizer.synchronize(lock, () -> { 157 long saved = 0L; 158 final StopWatch sw = new StopWatch(); 159 sw.start(); 160 try( final ObjectInputStream in = new ObjectInputStream( new BufferedInputStream( Files.newInputStream( f.toPath() ) ) ) ) { 161 final long ver = in.readLong(); 162 if( ver != serialVersionUID ) { 163 LOG.warn( "File format has changed; Unable to recover workflows and decision queue from disk." ); 164 } else { 165 saved = in.readLong(); 166 m_workflows = ( Set< Workflow > )in.readObject(); 167 m_queue = ( DecisionQueue )in.readObject(); 168 m_completed = new CircularFifoQueue<>( retainCompleted ); 169 m_completed.addAll( ( Collection< Workflow > )in.readObject() ); 170 LOG.debug( "Read serialized data successfully in " + sw ); 171 } 172 } catch( final IOException | ClassNotFoundException e ) { 173 LOG.warn( "unable to recover from disk workflows and decision queue: " + e.getMessage() ); 174 } 175 sw.stop(); 176 177 return saved; 178 }); 179 } 180 181 /** 182 * Serializes workflows and decisionqueue to disk. The format is private, don't touch it. 183 */ 184 void serializeToDisk( final File f ) { 185 Synchronizer.synchronize(lock, () -> { 186 try( final ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( Files.newOutputStream( f.toPath() ) ) ) ) { 187 final StopWatch sw = new StopWatch(); 188 sw.start(); 189 190 out.writeLong( serialVersionUID ); 191 out.writeLong( System.currentTimeMillis() ); // Timestamp 192 out.writeObject( m_workflows ); 193 out.writeObject( m_queue ); 194 out.writeObject( m_completed ); 195 196 sw.stop(); 197 198 LOG.debug( "serialization done - took " + sw ); 199 } catch( final IOException ioe ) { 200 LOG.error( "Unable to serialize!", ioe ); 201 } 202 }); 203 } 204 205 /** 206 * {@inheritDoc} 207 */ 208 @Override 209 public boolean requiresApproval( final String messageKey ) { 210 return m_approvers.containsKey( messageKey ); 211 } 212 213 /** 214 * {@inheritDoc} 215 */ 216 @Override 217 public Principal getApprover( final String messageKey ) throws WikiException { 218 Principal approver = m_approvers.get( messageKey ); 219 if ( approver == null ) { 220 throw new WikiException( "Workflow '" + messageKey + "' does not require approval." ); 221 } 222 223 // Try to resolve UnresolvedPrincipals 224 if ( approver instanceof UnresolvedPrincipal ) { 225 final String name = approver.getName(); 226 approver = m_engine.getManager( AuthorizationManager.class ).resolvePrincipal( name ); 227 228 // If still unresolved, throw exception; otherwise, freshen our cache 229 if ( approver instanceof UnresolvedPrincipal ) { 230 throw new WikiException( "Workflow approver '" + name + "' cannot not be resolved." ); 231 } 232 233 m_approvers.put( messageKey, approver ); 234 } 235 return approver; 236 } 237 238 /** 239 * Protected helper method that returns the associated Engine 240 * 241 * @return the wiki engine 242 */ 243 protected Engine getEngine() { 244 if ( m_engine == null ) { 245 throw new IllegalStateException( "Engine cannot be null; please initialize WorkflowManager first." ); 246 } 247 return m_engine; 248 } 249 250 /** 251 * Returns the DecisionQueue associated with this WorkflowManager 252 * 253 * @return the decision queue 254 */ 255 @Override 256 public DecisionQueue getDecisionQueue() { 257 return m_queue; 258 } 259 260 /** 261 * {@inheritDoc} 262 */ 263 @Override 264 public List< Workflow > getOwnerWorkflows( final Session session ) { 265 final List< Workflow > workflows = new ArrayList<>(); 266 if ( session.isAuthenticated() ) { 267 final Principal[] sessionPrincipals = session.getPrincipals(); 268 for( final Workflow w : m_workflows ) { 269 final Principal owner = w.getOwner(); 270 if (Arrays.stream(sessionPrincipals).anyMatch(sessionPrincipal -> sessionPrincipal.equals(owner))) { 271 workflows.add(w); 272 } 273 } 274 } 275 return workflows; 276 } 277 278 /** 279 * Listens for {@link WorkflowEvent} objects emitted by Workflows. In particular, this method listens for {@link WorkflowEvent#CREATED}, 280 * {@link WorkflowEvent#ABORTED}, {@link WorkflowEvent#COMPLETED} and {@link WorkflowEvent#DQ_REMOVAL} events. If a workflow is created, 281 * it is automatically added to the cache. If one is aborted or completed, it is automatically removed. If a removal from decision queue 282 * is issued, the current step from workflow, which is assumed to be a {@link Decision}, is removed from the {@link DecisionQueue}. 283 * 284 * @param event the event passed to this listener 285 */ 286 @Override 287 public void actionPerformed( final WikiEvent event ) { 288 if( event instanceof WorkflowEvent && isOwnEvent( event ) ) { 289 if( event.getSrc() instanceof Workflow ) { 290 final Workflow workflow = event.getSrc(); 291 switch( event.getType() ) { 292 // Remove from manager 293 case WorkflowEvent.ABORTED : 294 case WorkflowEvent.COMPLETED : remove( workflow ); break; 295 // Add to manager 296 case WorkflowEvent.CREATED : add( workflow ); break; 297 default: break; 298 } 299 } else if( event.getSrc() instanceof Decision ) { 300 final Decision decision = event.getSrc(); 301 switch( event.getType() ) { 302 // Add to DecisionQueue 303 case WorkflowEvent.DQ_ADDITION : addToDecisionQueue( decision ); break; 304 // Remove from DecisionQueue 305 case WorkflowEvent.DQ_REMOVAL : removeFromDecisionQueue( decision, event.getArg( 0, Context.class ) ); break; 306 default: break; 307 } 308 } 309 serializeToDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) ); 310 } 311 } 312 313 /** 314 * Workflow events are broadcast to every manager in the JVM, so each one has to tell if the event is about a workflow it tracks. A 315 * newly created Workflow is not tracked yet, so it belongs to the manager of the engine it was bound to, or to every manager if it 316 * was not bound to any. 317 * 318 * @param event a workflow event 319 * @return {@code true} if the event concerns a workflow of this manager 320 */ 321 boolean isOwnEvent( final WikiEvent event ) { 322 if( event.getSrc() instanceof Workflow ) { 323 if( event.getType() == WorkflowEvent.CREATED ) { 324 final Engine engine = event.getArg( 0, Engine.class ); 325 return engine == null || engine == m_engine; 326 } 327 return m_workflows.contains( event.< Workflow >getSrc() ); 328 } 329 if( event.getSrc() instanceof Decision ) { 330 final int workflowId = event.< Decision >getSrc().getWorkflowId(); 331 return m_workflows.stream().anyMatch( w -> w.getId() == workflowId ); 332 } 333 return false; 334 } 335 336 /** 337 * Protected helper method that adds a newly created Workflow to the cache, and sets its {@code workflowManager} and 338 * {@code Id} properties if not set. 339 * 340 * @param workflow the workflow to add 341 */ 342 protected void add( final Workflow workflow ) { 343 m_workflows.add( workflow ); 344 } 345 346 /** 347 * Protected helper method that removes a specified Workflow from the cache, and moves it to the workflow history list. This method 348 * defensively checks to see if the workflow has not yet been removed. 349 * 350 * @param workflow the workflow to remove 351 */ 352 protected void remove( final Workflow workflow ) { 353 if( m_workflows.contains( workflow ) ) { 354 m_workflows.remove( workflow ); 355 m_completed.add( workflow ); 356 } 357 } 358 359 protected void removeFromDecisionQueue( final Decision decision, final Context context ) { 360 // If current workflow is waiting for input, restart it and remove Decision from DecisionQueue 361 final int workflowId = decision.getWorkflowId(); 362 final Optional< Workflow > optw = m_workflows.stream().filter( w -> w.getId() == workflowId ).findAny(); 363 if( optw.isPresent() ) { 364 final Workflow w = optw.get(); 365 if( w.getCurrentState() == Workflow.WAITING && decision.equals( w.getCurrentStep() ) ) { 366 getDecisionQueue().remove( decision ); 367 // Restart workflow 368 try { 369 w.restart( context ); 370 } catch( final WikiException e ) { 371 LOG.error( "restarting workflow #" + w.getId() + " caused " + e.getMessage(), e ); 372 } 373 } 374 } 375 } 376 377 protected void addToDecisionQueue( final Decision decision ) { 378 getDecisionQueue().add( decision ); 379 } 380 381}