Showing posts with label Tar Compaction. Show all posts
Showing posts with label Tar Compaction. Show all posts

January 4, 2021
Estimated Post Reading Time ~

AEM TAR Offline Compaction

Step-01: Oak-run
Download Oak-run JAR form here

Step-02: Create a file logback-compaction.xml (on the server)



Step-03: AEM OAK offline Compaction on Linux, Unix, and macOS systems

[code lang=bash highlight=1,14]

# Linux, Unix

sudo -u crx nohup java -Dtar.memoryMapped=true
-Doak.compaction.eagerFlush=true -server -Xmx30g
-Dcompaction-progress-log=5000000
-Dlogback.configurationFile=logback-compaction.xml
-Dcompress-interval=150000000
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/path/to/dumps
-jar oak-run-1.6.1.jar
compact /path/to/segmentstore >> oak-tar-compact.log
2>>oak-tar-error.log

# Windows Machines

java -server -Xmx3g “-Dsun.arch.data.model=32
-Doak.compaction.eagerFlush=true
-Dcompaction-progress-log=5000000
-Dupdate.limit=2500000
-Dlogback.configurationFile=C:\logback-compaction.xml
-Dcompress-interval=150000000”
-jar C:\compaction\oak-run-1.6.1.jar
compact C:\crx-quickstart\repository\segmentstore
>> C:\compaction\oak-tar-compact.log

[/code]



By aem4beginner

AEM OAK Offline Compaction on Remote Windows Server

Tools Needed:
Download Oak-run JAR form here

Step-01: Create a Freestyle Job on Jenkins


Step-02: Setup a parameterized build job, create a string parameter for remote Host


Step-03: Setup a string parameter for remote User


Step-04: Setup a String parameter for Remote User Password


Step-05: Create a Powershell script to run oak offline compaction on AEM

[code lang=powershell]

# stopping the job if it encounters an error
$ErrorActionPreference = ‘Stop’
$WarningPreference = ‘SilentlyContinue’

# Credentials are stored in env and dynamic variables
$SecurePassword = $env:Password | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $env:User, $SecurePassword

# Invoke a command on the remote machine.
Invoke-Command -ComputerName $env:Computer -Credential $cred -ScriptBlock {

$ServiceName = ‘AEM6A’
$arrService = Get-Service -Name $ServiceName
$compactionPATH = ‘C:\Users\SKYDEVOPS\Desktop\AEM\compaction’
$compactionARGS = ‘-Dsun.arch.data.model=32 -Doak.compaction.eagerFlush=true -Dcompaction-progress-log=5000000 -Dupdate.limit=2500000 -Dcompress-interval=150000000’
$compArgsLogBoook = “${compactionARGS} -Dlogback.configurationFile=${compactionPATH}\logback-compaction.xml”
$segmentstorePATH = ‘C:\Users\SKYDEVOPS\Desktop\AEM\author\crx-quickstart\repository\segmentstore’
$TIMESTAMP=$(get-date -f yyyy_MM_dd_hhmmss)
$BACKUP_PATH=”C:\Users\SKYDEVOPS\Desktop\backups”
$ARCHIVEPATH=”${BACKUP_PATH}archive_$TIMESTAMP”;
function Get-Size
{
param([string]$pth)
“{0:n2}” -f ((gci -path $pth -recurse | measure-object -property length -sum).sum /1mb) + ” MB”
}

if ($arrService.status -eq ‘Running’) {
write-host $ServiceName is currently $arrService.status
write-host “Stopping $ServiceName”
Stop-Service $ServiceName -warningaction SilentlyContinue
Start-Sleep -seconds 30
$arrService.Refresh()
if ($arrService.status -eq ‘STOPPED’) {
write-host $ServiceName is STOPPED
$sizeBefore = Get-Size $segmentstorePATH
write-host “Size of the segmentstore before Compation: $sizeBefore”
write-host “Backing up segmentstore”
compress-archive -Path $segmentstorePATH -CompressionLevel optimal -DestinationPath “${BACKUP_PATH}\segmentstore_archive_$TIMESTAMP.zip”
write-host “Backup Complete”
write-host “Starting Compaction”
java -server -Xmx3g ${compArgsLogBoook} -jar ${compactionPATH}\oak-run-1.6.1.jar compact ${segmentstorePATH} >> “${BACKUP_PATH}\oak-tar-compact-$TIMESTAMP.log”
write-host Compation Completed
$sizeAfter = Get-Size $segmentstorePATH
write-host “Size of the segmentstore after Compation: $sizeAfter”
write-host Starting $ServiceName
Start-Service $ServiceName
if ($arrService.status -eq ‘Running’) {
write-host $ServiceName Started
}
}
}
elseif ($arrService.status -eq ‘STOPPED’) {
write-host $ServiceName is STOPPED
$sizeBefore = Get-Size $segmentstorePATH
write-host “Size of the segmentstore before Compation: $sizeBefore”
write-host “Backing up segmentstore”
compress-archive -Path $segmentstorePATH -CompressionLevel optimal -DestinationPath “${BACKUP_PATH}\segmentstore_archive_$TIMESTAMP.zip”
write-host “Backup Complete”
write-host “Starting Compaction”
java -server -Xmx3g ${compArgsLogBoook} -jar ${compactionPATH}\oak-run-1.6.1.jar compact ${segmentstorePATH} >> “${BACKUP_PATH}\oak-tar-compact-$TIMESTAMP.log”
write-host Compation Completed
$sizeAfter = Get-Size $segmentstorePATH
write-host “Size of the segmentstore after Compation: $sizeAfter”
write-host Starting $ServiceName
Start-Service $ServiceName
if ($arrService.status -eq ‘Running’) {
write-host $ServiceName Started
}
}
}

[/code]
Step-06: logbook-compaction.xml





By aem4beginner

AEM — Offline Compaction by LINUX

SYNOPSIS
AEM Offline TAR Compaction script, using a custom logback configuration file with custom encoder for better logging.

For Windows
If you wish to execute on windows environment use the THIS script

Guide
#!/bin/bash

##############    AEM Offline TAR Compaction  ####################################
#                                          #
# ███████╗██╗  ██╗██╗   ██╗██████╗ ███████╗██╗   ██╗ ██████╗ ██████╗ ███████╗    #   
# ██╔════╝██║ ██╔╝╚██╗ ██╔╝██╔══██╗██╔════╝██║   ██║██╔═══██╗██╔══██╗██╔════╝    # 
# ███████╗█████╔╝  ╚████╔╝ ██║  ██║█████╗  ██║   ██║██║   ██║██████╔╝███████╗    # 
# ╚════██║██╔═██╗   ╚██╔╝  ██║  ██║██╔══╝  ╚██╗ ██╔╝██║   ██║██╔═══╝ ╚════██║    #
# ███████║██║  ██╗   ██║   ██████╔╝███████╗ ╚████╔╝ ╚██████╔╝██║     ███████║    #
# ╚══════╝╚═╝  ╚═╝   ╚═╝   ╚═════╝ ╚══════╝  ╚═══╝   ╚═════╝ ╚═╝     ╚══════╝    #
#                                        #
#                                        #
# SCRIPT: AEM Offline TAR Compaction                       #
# AUTHOR: Shashi Yebbare                             #
# DATE:   FEB, 09, 2019                                #
# REV:    1.3.P                                  #
#         (For Alpha, Beta, Dev, Test and Production)                  #
#                                        #
# PLATFORM: AIX, HP-UX, Linux, Solaris                       #
#                                        #
# PURPOSE:  To perform offline AEM compaction on Segmentstore          #
#           and reduce the size of the AEM repository, Script            #
#       uses a custom log-back XML configuration to log                #
#     additional compaction information.                   #
#                                          # 
# REVISED LIST:                                  #
#        DATE: FEB, 17 2019                            #
#        BY: Shashi Yebbare                            #
#        MODIFICATION: Added custom log back XML configuration           #
#                                        #
#                                        #
# set -n   # Uncomment to check your syntax, without execution.          #
#          # NOTE: Do not forget to put the comment back in or           #
#          #       the shell script will not execute!              #
#                                        #
##################################################################################

# ####################### BEGIN -- Parameter declaration ##########################

Date=$(date +%m-%d-%Y) # Get Current Date
Time=$(date +%T) # Get Current Time date +"%T"
Type="Author"
Port="4502"
Base="/opt/aem/${Type}/crx-quickstart"
Segmentstore="${Base}/repository/segmentstore"
OAK_JAR="/opt/aem/${Type}/support/oak-run.jar"
SUPPORTDIR="/opt/aem/${Type}/support"
CRXLOGS="${Base}/logs"
LOGFILE="TarComapction_${Date}_${Time}.log"
COUNT=0
DUMPSPATH="${SUPPORTDIR}/compactiondumps"
COMPACTARGS="-Dtar.memoryMapped=true  -Doak.compaction.eagerFlush=true -Dcompaction-progress-log=5000000 -Dcompress-interval=150000000 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DUMPSPATH}"
LOGBACKCONF="${SUPPORTDIR}/logback-compaction.xml"
SDMEMORY="8g"

# ####################### END -- Parameter declaration ############################

# ############# ############# #############
# ##       TIME TO RUN THE SCRIPT        ##
# ##                                     ##
# ## You shouldn't need to edit anything ##
# ## beneath this line                   ##
# ##                                     ##
# ############# ############# #############

# BEGIN -- Function checks the storagae size of segmentstore
function SDRepositorySize {
  echo ">>>> Repository Size: "
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  du -h $Segmentstore  | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
} # END -- Function checks the storagae size of segmentstore

# BEGIN -- Function to bring AEM instance offline
function SDStopAEM {
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  echo ">>>> Stopping AEM ${Type} Instance"  | tee -a "$CRXLOGS/$LOGFILE"
  Command="bash $Base/bin/stop"
  eval $Command | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  echo "Waiting 10 seconds" | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  sleep 10s
  PID=$(cat $Base/conf/cq.pid 2>/dev/null)
  if [ "$PID" ]; then
     echo " " | tee -a "$CRXLOGS/$LOGFILE"
     echo "AEM PID $PID" | tee -a "$CRXLOGS/$LOGFILE"
     echo " " | tee -a "$CRXLOGS/$LOGFILE"
     if ps -p $PID > /dev/null 2>&1; then
      eval $Command | tee -a "$CRXLOGS/$LOGFILE"
      sleep 30s
      while ps -p $PID > /dev/null 2>&1 && (($COUNT < $MAXCOUNT)); do
       sleep 10s
       let COUNT=COUNT+1
      done
     else
      echo "AEM was already stopped" | tee -a "$CRXLOGS/$LOGFILE"
      echo " " | tee -a "$CRXLOGS/$LOGFILE"
     fi
  else
      echo "cq.pid was not found" | tee -a "$CRXLOGS/$LOGFILE"
      echo "AEM ${Type} is already stopped" | tee -a "$CRXLOGS/$LOGFILE"
  fi
  if ps -p $PID > /dev/null 2>&1; then
      echo "The AEM application is still running after maxcount" | tee -a "$CRXLOGS/$LOGFILE"
      WAIT_SECONDS=600
    echo "Waiting additional $WAIT_SECONDS for kill process to complete" | tee -a "$CRXLOGS/$LOGFILE"
    count=0

    while kill $PID > /dev/null
    do
      sleep 1
      ((count++))

      if ! ps -p $PID > /dev/null ; then
        break
      fi

      if [ $count -gt $WAIT_SECONDS ]; then
        kill -9 $PID
        break
      fi
    done
    echo "Process has been killed after $count seconds" | tee -a "$CRXLOGS/$LOGFILE"
    echo " " | tee -a "$CRXLOGS/$LOGFILE"
  fi
  echo "AEM ${Type} Successfully stopped" | tee -a "$CRXLOGS/$LOGFILE"
} # END -- Function to bring AEM instance offline

# BEGIN -- Offline Tar Comapction
function SDOfflineCompaction {
  echo ">>>> Starting Offline Tar Compaction Process" | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  
  echo ">>>> Verifying Checkpoints"  | tee -a "$CRXLOGS/$LOGFILE"
  Command="java -server -Xmx${SDMEMORY} ${COMPACTARGS} -Dlogback.configurationFile=${LOGBACKCONF} -jar ${OAK_JAR} checkpoints $Segmentstore"
  eval $Command  | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  
  echo ">>>> Removing UnReferenced Checpoints"  | tee -a "$CRXLOGS/$LOGFILE"
  Command="java -server -Xmx${SDMEMORY} ${COMPACTARGS} -Dlogback.configurationFile=${LOGBACKCONF} -jar ${OAK_JAR} checkpoints $Segmentstore rm-unreferenced"
  eval $Command | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  
  echo ">>>> Compacting Segmentstore" | tee -a "$CRXLOGS/$LOGFILE"
  Command="java -server -Xmx${SDMEMORY} ${COMPACTARGS} -Dlogback.configurationFile=${LOGBACKCONF} -jar ${OAK_JAR} compact $Segmentstore"
  eval $Command | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  
  echo "Waiting 10 seconds"  | tee -a "$CRXLOGS/$LOGFILE"
  echo " " | tee -a "$CRXLOGS/$LOGFILE"
  sleep 10
  echo ">>>> Compaction Process Successfully Completed" | tee -a "$CRXLOGS/$LOGFILE"
} # END -- Offline Tar Comapction

# BEGIN -- Start AEM Instance
function SDStartAEM {
  echo "Starting AEM ${Type} Instance"  | tee -a "$CRXLOGS/$LOGFILE"
  Command="cd $Base/bin && ./start"
  eval $Command | tee -a "$CRXLOGS/$LOGFILE"
  sleep 10
  #Get the process id from AEM
  PID=$(cat $Base/conf/cq.pid 2>/dev/null)
  ps -p $PID
} # END -- Start AEM Instance

# ############################## Actual Script Execution ##############################
# Executing the function accordingly to get repository size before compaction       # 
# and execute comapction and check size of the repository after comapction        #
#######################################################################################

echo " "
echo "
##############    AEM Offline TAR Compaction  ####################################
#                                          #
# ███████╗██╗  ██╗██╗   ██╗██████╗ ███████╗██╗   ██╗ ██████╗ ██████╗ ███████╗    #   
# ██╔════╝██║ ██╔╝╚██╗ ██╔╝██╔══██╗██╔════╝██║   ██║██╔═══██╗██╔══██╗██╔════╝    # 
# ███████╗█████╔╝  ╚████╔╝ ██║  ██║█████╗  ██║   ██║██║   ██║██████╔╝███████╗    # 
# ╚════██║██╔═██╗   ╚██╔╝  ██║  ██║██╔══╝  ╚██╗ ██╔╝██║   ██║██╔═══╝ ╚════██║    #
# ███████║██║  ██╗   ██║   ██████╔╝███████╗ ╚████╔╝ ╚██████╔╝██║     ███████║    #
# ╚══════╝╚═╝  ╚═╝   ╚═╝   ╚═════╝ ╚══════╝  ╚═══╝   ╚═════╝ ╚═╝     ╚══════╝    #
#                                        #
#                                        #
# SCRIPT: AEM Offline TAR Compaction                       #
# AUTHOR: Shashi Yebbare                             #
# DATE:   FEB, 09, 2019                                #
# REV:    1.3.P                                  #
#         (For Alpha, Beta, Dev, Test and Production)                  #
#                                        #
# PLATFORM: AIX, HP-UX, Linux, Solaris                       #
#                                        #
# PURPOSE:  To perform offline AEM compaction on Segmentstore          #
#           and reduce the size of the AEM repository, Script            #
#       uses a custom log-back XML configuration to log                #
#     additional compaction information.                   #
#                                          # 
# REVISED LIST:                                  #
#        DATE: FEB, 17 2019                            #
#        BY: Shashi Yebbare                            #
#        MODIFICATION: Added custom log back XML configuration           #
#                                        #
#                                        #
# set -n   # Uncomment to check your syntax, without execution.          #
#          # NOTE: Do not forget to put the comment back in or           #
#          #       the shell script will not execute!              #
#                                        #
##################################################################################

" | tee -a "$CRXLOGS/$LOGFILE"

Date=$(date +%m-%d-%Y) # Get Current Date
OutTime=$(date +%r) # Get Current Time
echo " " | tee -a "$CRXLOGS/$LOGFILE"
echo "Compaction Script -- Start Time: $Date @ $OutTime" | tee -a "$CRXLOGS/$LOGFILE"

echo " " | tee -a "$CRXLOGS/$LOGFILE"
SDStopAEM;
echo " " | tee -a "$CRXLOGS/$LOGFILE"
echo ">>>> Checking Repository size BEFORE Compaction" | tee -a "$CRXLOGS/$LOGFILE"
SDRepositorySize;
echo " " | tee -a "$CRXLOGS/$LOGFILE"
SDOfflineCompaction;
echo " " | tee -a "$CRXLOGS/$LOGFILE"
echo ">>>> Checking Repository size AFTER Compaction" | tee -a "$CRXLOGS/$LOGFILE"
SDRepositorySize;
echo " " | tee -a "$CRXLOGS/$LOGFILE"
SDStartAEM;

# Concluding the Compaction Process
Date=$(date +%m-%d-%Y) # Get Current Date
OutTime=$(date +%r) # Get Current Time
echo " " | tee -a "$CRXLOGS/$LOGFILE"
echo "Compaction Script -- End Time: $Date @ $OutTime" | tee -a "$CRXLOGS/$LOGFILE"

LOGBACK File
<?xml version="1.0" encoding="UTF-8"?>
<!-- 
##############    AEM Offline TAR Compaction  ####################################
#                                          #
# ███████╗██╗  ██╗██╗   ██╗██████╗ ███████╗██╗   ██╗ ██████╗ ██████╗ ███████╗    #   
# ██╔════╝██║ ██╔╝╚██╗ ██╔╝██╔══██╗██╔════╝██║   ██║██╔═══██╗██╔══██╗██╔════╝    # 
# ███████╗█████╔╝  ╚████╔╝ ██║  ██║█████╗  ██║   ██║██║   ██║██████╔╝███████╗    # 
# ╚════██║██╔═██╗   ╚██╔╝  ██║  ██║██╔══╝  ╚██╗ ██╔╝██║   ██║██╔═══╝ ╚════██║    #
# ███████║██║  ██╗   ██║   ██████╔╝███████╗ ╚████╔╝ ╚██████╔╝██║     ███████║    #
# ╚══════╝╚═╝  ╚═╝   ╚═╝   ╚═════╝ ╚══════╝  ╚═══╝   ╚═════╝ ╚═╝     ╚══════╝    #
#                                                                                #
#                                                                                #
# SCRIPT: AEM Offline TAR Compaction - logback-compaction configuration          #
# AUTHOR: Shashi Yebbare                                                         #
# DATE:   FEB, 09, 2019                                                          #
# REV:    1.3.P                                                                  #
#         (For Alpha, Beta, Dev, Test and Production)                            #
#                                                                                #
# PLATFORM: AIX, HP-UX, Linux, Solaris                                           #
#                                                                                #
# PURPOSE:  Script to custom log additional compaction information.              #
#                                                                                # 
# REVISED LIST:                                                                  #
#        DATE: FEB, 17 2019                                                      #
#        BY: Shashi Yebbare                                                      #
#        MODIFICATION: Added custom encoder pattern                              #
#                                                                                #
#                                                                                #
# set -n   # Uncomment to check your syntax, without execution.                  #
#          # NOTE: Do not forget to put the comment back in or                   #
#          #       the shell script will not execute!                            #
#                                                                                #
##################################################################################
 -->
<configuration debug="true">
  <appender name="STDERR" class="ch.qos.logback.core.FileAppender">
    <file>"/Users/shashi/Sites/author/support/SD_Compaction.log"</file>
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <logger name="org.apache.jackrabbit.oak.plugins.segment.Compactor" level="DEBUG"/>
  <root level="warn">
    <appender-ref ref="STDERR" />
  </root>
</configuration>


By aem4beginner

January 2, 2021
Estimated Post Reading Time ~

AEM Tar Compaction - Revision Cleanup (for AEM 6.4 and 6.5)

This is an updated Tar Compaction and Garbage Collection process based on AEM 6.4. This maintenance functionality is now called Revision Cleanup.

The AEM platform is based on Apache Jackrabbit Oak. Oak is an effort to implement a scalable and performant hierarchical content repository for use as the foundation of modern world-class web sites and other demanding content applications. It uses TarMK, a fast, small, and simple embedded hierarchical database engine serving as a persistence backend for the Java Content Repository (JCR). 

It implements multi-version concurrency control (MVCC) and stores all data in tar files in an append-only way. And because of this MVCC persistence of only appending, it is critical to perform scheduled maintenance activities in keeping a performant and efficient AEM system. The lack of these maintenance tasks causes instability, performance, and disk space issues and outages.

To reclaim disk space, improve performance, and to avoid uncontrolled repository growth, old revisions need to be cleaned up to free disk resources. This maintenance functionality is called Revision Cleanup and has been available as an offline routine since AEM 6.0 which was called Tar Compaction. With AEM 6.4 (and above) an online version of this functionality called Online Revision Cleanup was introduced. 

Compared to Offline Revision Cleanup where the AEM instance has to be shut down, Online Revision Cleanup can be run while the AEM instance is online. Online Revision Cleanup is turned on by default and it is the recommended way of performing revision cleanup.

The revision cleanup process consists of three phases:
  • Estimation - determines whether to run the next phase (compaction) or not based on how much garbage might be collected.
  • Compaction - segments and tar files are rewritten leaving out any unused content.
  • Clean up - removes the old segments including any garbage they may contain.
AEM 6.4 introduces two new modes for the compaction phase of the Online Revision Cleanup process:
  • The full compaction mode rewrites all the segments and tar files in the whole repository. The subsequent cleanup phase can thus remove the maximum amount of garbage across the repository. Since full compaction affects the whole repository it requires a considerable amount of system resources and time to complete.
  • The tail compaction mode rewrites only the most recent segments and tar files in the repository. The most recent segments and tar files are those that have been added since the last time either full or tail compaction ran. The subsequent cleanup phase can thus only remove the garbage contained in the recent past of the repository. Since tail compaction only affects a part of the repository it requires considerably less system resources and time to complete than full compaction.
Technical Steps:
Online Revision Cleanup is configured by default to automatically run once a day on both AEM Author and Publish instances. All that is required is to define the maintenance window on when to run the maintenance task. This is usually during a period with the least user activity.

1. In AEM, go to Tools - Operations - Maintenance (/libs/granite/operations/content/maintenance.html)


2. Click on the Configure Icon of the Daily Maintenance Window



3. Validate the configuration values (recurrence, start and end time) and click Save. Between 2am and 5am are the recommended times for Tail Compaction (Mon. to Saturday) and Full Compaction on Sunday from Adobe.

The default configuration runs tail compaction on weekdays and full compaction on Sundays.

Tail Compaction schedule configuration:


Full Compaction schedule configuration:


Monitoring:
  • To check if the Online Revision Cleanup has completed successfully by checking the logs:
For example, "TarMK GC #{}: compaction completed in {} ({} ms), after {} cycles" means the compaction step completed successfully unless preceded by the message "TarMK GC #{}: compaction gave up compacting concurrent commits after {} cycles", which means there was too much concurrent load. Correspondingly there is a message "TarMK GC #{}: cleanup completed in {} ({} ms" for the successful completion of the cleanup step.
  • By monitoring the Maintenance Task RevisionCleanupTask MBean JMX Object


By aem4beginner

Scripts to Make AEM Compaction Easy

When provisioning a new AEM 6.0-6.2 environment, one of the first things you should configure is a TarMK compaction process. This process will remove deleted content from the underlying data store and compress the size of the AEM repository on the disk. This is especially important in the lower environments upfront as they will be heavily utilized for development and testing activities which can generate a lot of content churn.

A recent project I was on had a catastrophic issue in a lower environment because compaction was not enabled and the server simply ran out of disk. Don’t let this happen to you!

Compacting Servers
AEM requires offline compaction for these versions, so this will require downtime. I’ve found the easiest way to do this is to schedule an automatic job to run off-hours to stop AEM, run the compaction and then restart AEM when complete.

To do this, I created a script, compact.sh which will automatically stop the AEM server, perform the compaction, and restarting AEM. This script is based on others I’ve seen online, however, the advantage here is that this one will stop the AEM server and fully wait until it is stopped before starting the compaction. In order to use the script, you should:
  • Create a folder help as a sibling to crx-quickstart
  • Download the appropriate oak-run.jar into the help folder
  • Download the compact.sh into the help folder
  • Add a cron trigger to run the script periodically, here we do it at 5:00 AM on Saturdays:
0 5 * * 5 aem /opt/aem/help/compact.sh

Check out compact.sh on GitHub

Compacting a Whole Environment
So how do you run compaction across an entire environment without causing downtime? To do this, I created a script that will sequentially stop the instances in an environment and the associated dispatchers, ensuring the load balancer will direct traffic to the alternate instance during the compaction process.

This script is set up to run in a 2-publish, single-author environment, but you could adapt it to more significant buildouts. To use the script, deploy the compaction script to all of the servers, then replace the relevant server information in the ssh commands below for your particular environment.
#!/bin/bash
cat << EOF
WARNING!!!
-------
This script will run compaction on the Prod environment.
During the course of this operation, the Author and Publish AEM Instances will not be available.
Please ensure before starting appropriate backups have been taken!
EOF
read -p "Do you want to continue? (y/n) " CONT
if [ $CONT = "y" ]; then
    echo "Starting compaction of Prod environment..."
    echo "Stopping Author Dispatcher..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-author.prod.client.com 'sudo service httpd stop'
    echo "Running compaction script in Author..."
    ssh -i ~/.ssh/client-prod.pem -t user@aem-author.prod.client.com 'sudo su - aem /opt/aem/help/compact.sh'
    echo "Stopping Publish Dispatcher 1..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-publish-01.client.com 'sudo service httpd stop'
    echo "Running compaction script in Publish 1..."
    ssh -i ~/.ssh/client-prod.pem -t user@aem-publish-01.client.com 'sudo su - aem /opt/aem/help/compact.sh'
    echo "Starting Publish Dispatcher 1..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-publish-01.client.com 'sudo service httpd start'
    echo "Waiting for ELB resumption..."
    sleep 5m
    echo "Stopping Apache 2..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-publish-02.client.com 'sudo service httpd stop'
    echo "Running compaction script in Publish 2..."
    ssh -i ~/.ssh/client-prod.pem -t user@aem-publish-02.client.com 'sudo su - aem /opt/aem/help/compact.sh'
    echo "Starting Apache 2..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-publish-02.client.com 'sudo service httpd start'
    echo "Starting Author Dispatcher..."
    ssh -i ~/.ssh/client-prod.pem -t user@dispatcher-author.prod.client.com 'sudo service httpd start'
    echo "Prod Compacted!"
fi
Compacting a Local Instance
I also updated the aem-mgr.sh script I described in

Managing Multiple AEM Instances to add a new compaction option.

This script will not stop and start AEM but will run compaction on your local author and publish instances. In order to enable compaction, update every local

the instance you would want to compact with the following:
Looking forward to AEM 6.3
With the upcoming release of AEM 6.3, we anticipate support for online compaction. This will significantly ease the maintenance of AEM by eliminating the need for offline compaction. In the meantime, I hope this article is helpful for anyone using AEM 6.0, 6.1 or 6.2.


By aem4beginner

May 15, 2020
Estimated Post Reading Time ~

Is Your Repository Growing Rapidly in AEM 6?

Growth of repositories in CQ, and now AEM, have always been a pain point for most operations teams, and it is sometimes not clear where the problem stems from.

It's possible that wrong filters may have been applied, too many nodes were created, or huge renditions were also produced. Other times, it may even be a bug. In any case, Adobe has released the offline compaction method last year which is working great, and they also introduced the online compaction method. Online compaction allows you to trigger a repository compaction from within a running AEM instance via the brand new Operations & Maintenance Dashboard. It also lets you easily schedule it to ensure you have no performance hits during peak usage. Actions in the Dashboard can also be triggered via other means besides the web browser so automation of various processes is a goal that can now be achieved.

Online compaction
Before running any compactions make sure you have a consistent backup you can easily restore to in case its needed. These features are hot off the press!

1. First, get the latest hotfix of Oak which provides you this functionality from the package share for AEM 6.0 (Oak 1.0.22), with AEM 6.1 (Oak 1.2.7) it is built in!

2. Install it (there is a restart of AEM required afterwards) don't restart just stop after it is finished (make sure you tail the logs!)

3. ssh into your machine and use the oak-run.jar matching your oak version to clean up old checkpoints
-> http://mvnrepository.com/artifact/org.apache.jackrabbit/oak-run

4. To clean up the checkpoints follow the steps below

java -jar oak-run.jar checkpoints install-folder/crx-quickstart/repository/segmentstore

java -jar oak-run.jar checkpoints install-folder/crx-quickstart/repository/segmentstore rm-all

5. Now start your AEM again and go to the system console -> JMX -> search for "CompactionStrategy"

6. Make sure the PausedCompaction is set to false as well as CloneBinaries

7. Go to the maintenance dashboard -> http://localhost:4502/libs/granite/operations/content/maintenance/window.html/mnt/overlay/granite/operations/config/maintenance/_granite_daily

8. On there trigger the revision cleanup and tail to logs for progress

9. The log's will tell you how much it cleaned up but you can allways check with -> du -h --max-depth=1 and compare before and after results of your repository folder

If your curious about more functionality (backup etc.) of the oak-run.jar have a look on the jackrabbit github -> https://github.com/apache/jackrabbit-oak/tree/trunk/oak-run

Offline compaction
Offline compaction can be used any time the AEM instance is stopped. This is also a prerequisite to running online compaction if you haven't removed old checkpoints previously.

To see the full effect of the online compaction later, just remove the checkpoints and don't actually run the offline compaction.

Stop your AEM instance
Use the oak-run.jar tool to find any old checkpoints -> download -> http://mvnrepository.com/artifact/org.apache.jackrabbit/oak-run

java -jar oak-run.jar checkpoints your-install-folder/crx-quickstart/repository/segmentstore
Next, delete the unreferenced checkpoints

java -jar oak-run.jar checkpoints your-install-folder/crx-quickstart/repository/segmentstore rm-all
The final step is to run the compaction and wait for it to complete (tail the logs!)

java -jar oak-run.jar compact your-install-folder/crx-quickstart/repository/segmentstore

Closing words of wisdom
Make sure you keep track of repository growth as it can easily impact performance or cause a possible outage of the instance due to the system running out of storage space.

With AEM 6, Service Pack 1 and Service Pack 2 are a necessity and should be installed. The later hotfix mentioned applies the latest Oak Fixes and raises it to a version of 1.0.11 of the Oak Core.

Note that some Service Packs and Hotfixes, such as the one for Oak, require a restart! Ensure it gets thoroughly tested beforehand, and plan it into your continuous release cycle for the next deployment to stay up to date.

UPDATE 16.03.2015:
1. If interested in details of the hotfixes have a look on Adobes Hotfix Page
2. A new Hotfix 5916 was released which addresses some possible issues with the Oak garbage collection



By aem4beginner

April 27, 2020
Estimated Post Reading Time ~

How to disable the online compaction - AEM/Adobe CQ5

Adobe Experience Manager 6.1 will have a daily job scheduled and that will perform the online compaction.

Some times this may cause performance issues when the online compaction takes more time to complete due to load or authoring.

As a solution the online compaction job can be disabled and offline compaction can be used whenever required based on the maintenance window.

Steps to disable online compaction:
Go to CRXDE path - /libs/granite/operations/config/maintenance/granite:daily/granite:RevisionGC


Changed run mode from crx3 to crx3-disabled

Save


By aem4beginner

April 26, 2020
Estimated Post Reading Time ~

Offline Compaction - AEM Repository Size Growing Rapidly

Sometimes we observe AEM repository size increase rapidly. This post helps you in decreasing the respository size

AEM Repository Offline Compaction
Create new folder compact and place oak-run-1.2.2.jar and below .bat file.
Create a .bat file containing below code
java -jar oak-run-1.2.2.jar compact C:\Users\Kishore\AEM\crx-quickstart\repository\segmentstore

Download oak-run-1.2.2.jar


By aem4beginner

April 22, 2020
Estimated Post Reading Time ~

How to automate the Offline compaction process in AEM 6.2

Statement: Automate the offline compaction process.

Solution:
  • Offline compaction is still applicable for AEM 6.2 but AEM 6.3 is not required because it supports online compaction.
  • Below is the steps involved in the automation and script which is used automates entire process.
Steps involved in the Offline compaction Automation:
  • Shutdown AEM Server
  • Use Matching Oak jar version to find Old Checkpoints
  • Use Matching Oak jar version to Remove Unreferenced Checkpoints
  • Use Matching Oak jar version to Compact Oak
  • Restart AEM
SCRIPT:
#!/bin/bash
todayDate="$(date +'%d-%m-%Y')"
logfile="compact-$ todayDate.log"
installfolder="/data/aem"
aemfolder="$installfolder/crx-quickstart"
oakrun="$installfolder/help/oak-run-1.6.1.jar"

## Shutdown AEM
printf "Shutting down AEM.\n"
$aemfolder/bin/stop
todayDate ="$(date)"
echo "AEM Shutdown at: $ todayDate " >> $installfolder/help/logs/$logfile

## Find old checkpoints
printf "Finding old checkpoints.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Delete unreferenced checkpoints
printf "Deleting unreferenced checkpoints.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore rm-unreferenced >> $installfolder/help/logs/$logfile

## Run compaction
printf "Running compaction. This may take a while.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun compact $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Report Completed
printf "Compaction complete. Please check the log at:\n"
printf "$installfolder/help/logs/$logfile\n"

## Start AEM back up
todayDate ="$(date)"
printf "Starting up AEM.\n"
$aemfolder/bin/start
echo "AEM Startup at: $ todayDate " >> $installfolder/help/logs/$logfile


Reference: https://jackrabbit.apache.org/oak/docs/command_line.html


By aem4beginner

April 20, 2020
Estimated Post Reading Time ~

AEM Offline Compaction

Use case: When AEM repository size is growing rapidly
Solution:
  1. Create compact folder under under \crx-quickstart\repository\segemnetstore
  2. download the oak-run-1.2.2.jar file and place under compact folder created in step1
  3. create offcompact.bat file with the below code
java -jar oak-run-1.2.2.jar compact \crx-quickstart\repository\segemnetstore
place this. Bat file under compact folder created in step1.


By aem4beginner

April 16, 2020
Estimated Post Reading Time ~

Run Online and Offline Tar Compaction in AEM

After the release of AEM 6 and introduction of TarMK, operation teams has faced rapid growth in the size of repository due to a know oak bug for which adobe has already provided a hotfix Oak-core 1.0.25. But after installing this hotfix also it is becoming difficult to maintain or pause the rapid growth of repository. So, adobe come up with two housekeeping activities online and offline tar compaction to control the size of aem repository. Adobe strongly suggest not to use online tar compaction as it takes very long time for compacting repository and affect the performance of site.

Is your repository size increasing very rapidly ? Looking for step by step guide on how to run online and offline tar compaction in aem ? Then this tutorial is for you.

There are two ways to run tar compaction in aem Online Tar Compaction and 

Offline Tar Compaction. Below topics are covered in this tutorial:
  • Steps to Run Online Compaction in AEM
  • Steps to Run Offline Compaction in AEM
  • Increase Performance of offline tar compaction
  • Frequently Asked Questions

Note: Before running any type of compaction make sure you have taken backup of your existing repository.

Steps to Run Online Tar Compaction in AEM:
Running online tar compaction is not recommended by adobe, and from aem 6.2 it is triggered under restrictive use. Follow below steps to run online tar compaction:-

Note: In online compaction, checkpoints are not removed, so we have to manually run the script to clear the old checkpoints.
Download correct version of oakrun.jar (Refer faq below on how to find correct version of oakrun.jar). For Example AEM 6.0 (Oak 1.0.22), with AEM 6.1 (Oak 1.2.7), with AEM 6.1 SP1 (Oak 1.2.11)
Shutdown your AEM instance.
Find old checkpoints and remove un-referenced checkpoints as shown below in offline tar compaction.
Restart your AEM instance.
Go to System console config manager , search for Apache Jackrabbit oak Segment NodeStore Service .
Make sure the PausedCompaction is set to false(unchecked) as well as CloneBinaries (If want to run compaction on binary also).


Go to the maintenance dashboard -> Daily Maintenance Window http://localhost:4502/libs/granite/operations/content/maintenance/window.html/mnt/overlay/granite/operations/config/maintenance/_granite_daily
Click on Add Task —> select Revision Clean up from drop down and click OK.
By Default it will pick a time around 2 am for running daily revision clean up.
Hover on the window and click Play button to trigger Revision Clean up.
Green Color– Revision clean up task is scheduled.
Orange Color– Revision clean up task is currently running.
Red Color– Revision clean up task is failed.

Refer SegmentNodeStoreService Class for more info about each field and Oakrun.jar commands

Steps to Run Offline Tar Compaction in AEM:
Make sure that you are using correct version of oakrun jar that matches you repository or aem repository version (Refer faq below on how to find correct version of oakrun.jar). Offline compaction scripts is basically divided into 5 parts:-
Shutdown AEM Instance
Find Old Checkpoints
Remove Unreferenced Checkpoints
Compact Oak
Restart AEM Instance

Below command is for Linux/Unix Machine-
#!/bin/bash
now="$(date +'%d-%m-%Y')"
logfile="compact-$now.log"
installfolder="/data/aem"
aemfolder="$installfolder/crx-quickstart"
oakrun="$installfolder/help/oak-run-1.2.7jar"

## Shutdown AEM Instance
$aemfolder/bin/stop
echo "AEM Shutdown >> $installfolder/help/logs/$logfile

## Find old checkpoints
echo "Finding old checkpoints"
java -Dtar.memoryMapped=true -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Delete unreferenced checkpoints
echo "Deleting unreferenced checkpoints"
java -Dtar.memoryMapped=true -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore rm-unreferenced >> $installfolder/help/logs/$logfile

## Run compaction
echo "Running compaction. This may take a while"
java -Dtar.memoryMapped=true -Xmx8g -jar $oakrun compact $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Report Completed
echo "Compaction complete. Please check the log at:"
echo "$installfolder/help/logs/$logfile"

## Start AEM back up
echo "Starting up AEM"
$aemfolder/bin/start
echo "AEM Startup" >> $installfolder/help/logs/$logfile


Note: Above command run on linux/unix machine as windows does not support -Dtar option.

Command for Windows Machine-
Below command is for running offline tar compaction, similarly you can also use command for finding checkpoints and deleting them.

## Run compaction
echo "Running compaction. This may take a while"
java -jar oakrun.jar compact install-folder/crx-quickstart/repository/segmentstore


Note: Use as much heap memory as possible for faster I/O operations. It is recommended to use at least eight gigabytes for most common deployments -Xmx8g. You can increase it according to available heap size.

Increase Performance of offline tar compaction:
I have seen many teams are still using old scripts without -Dtar option, but you can increase the performance of offline tar compaction by using dtar option as suggested by adobe.

After oak version 1.0.22, the oak-run tool introduces several features with an aim to increase the performance of the revision cleanup process and minimize the maintenance window as much as possible. Below are few commands that we can use:-

-Dtar.memoryMapped:- It is highly recommended that you enable this feature in order to speed up tar compaction. You can set this as true or false.

-Dupdate.limit:- Defines the threshold for the flush of a temporary transaction to disk. The default value is 5000000.

-Dcompress-interval:- Number of compaction map entries to keep until compressing the current map. The default is 1000000. You should increase this value to an even higher number for faster throughput, if enough heap memory is available.

-Dcompaction-progress-log:- The number of compacted nodes that will be logged. The default value is 1500000, which means that the first 1500000 compacted nodes will be logged during the operation. Use this in conjunction with the next parameter documented below.

-Dlogback.configurationFile:- Use a configuration file for logging.

Note: Memory-mapped file operations -Dtar.memoryMapped do not work correctly on Windows. As tar is meant for linux/unix.

Frequently Asked Questions:
Below are a few questions that might arise in your mind about tar compaction in AEM.

How frequently you should run Offline Revision Cleanup?
It depends on the repository growth rate. In general , it is recommended that you perform revision cleanup every 2 weeks for an author instance, and once per quarter for a publish instance(I recommend to run monthly on publish again it depends upon repository growth rate).

What factors determine the duration of the Offline Revision Cleanup?
The repository size and the number of revisions that need to be cleaned up determine the duration of the cleanup.
How to find the correct version of the oak-run jar?
Go to Felix console –> bundles and search for oak, note the version mention across each oak bundle. Now go to MVN Repository and download the respective oak-run.jar file.


What can happen if you do not perform revision cleanup?
The AEM instance will run out of disk space, which will cause outages in production. It is highly recommended that you monitor the disk usage and perform tar compaction if disk space consumed is more than 60%.

What is the difference between a revision clean up and version purging or clean up?
Oak revision:
Oak organizes all content in a tree hierarchy that consists of nodes and properties. Each snapshot or revision of this content tree is immutable, and changes to the tree are expressed as a sequence of new revisions. Typically, each content modification triggers a new revision. For more info visit http://jackrabbit.apache.org/dev/ngp.html.
Version: Versioning creates a “snapshot” of a page at a specific point in time. Typically, a new version is created when a page is activated.


By aem4beginner

April 12, 2020
Estimated Post Reading Time ~

Midnight at the lost and found

Have you worked out that TAR Optimiser does not run at midnight?

Normally, the OOTB default for running the TAR optimizer is 2am - 5am. This can be changed in the repository.xml/workspace.xml files. But, if you specify a start time of 00:00 it won't run.

I'm sure I've posted this elsewhere but just to re-iterate you can make the TAR optimizer run faster & do more work by reducing the optimize sleep parameter. We've managed to get away with 0.25 without any noticeable performance impact on the live servers (CQ 5.3).


By aem4beginner

April 7, 2020
Estimated Post Reading Time ~

Oak TarMK Compaction



If we are using Tar files as the storage, it tends to grow in size and starts claiming disk space every time when data is created or updated as data in tar files are never overwritten rather it keeps adding new versions. To mitigate the same, AEM has garbage collection mechanism which is known as ‘Tar Compaction’ to remove the unused data and reclaim the disk space.

We can be triggered from ‘Revision Clean Up’ in the Operations Dashboard (http://<host>:<port>/libs/granite/operations/content/maintenance.html). However, it can done faster via offline compaction. Follow the below steps to do the same

Step1: Download the ‘Oak-run’, Tar Compaction Tool – http://mvnrepository.com/artifact/org.apache.jackrabbit/oak-run/

Make sure you download the right version of the tool based on your oak repository version. Latest version of oak with AEM 6.1 and SP1 is 1.2.11



Step2: Shutdown the AEM instance. Take the backupjava –jar oak-run-*.jar backup <aem-folder>/crx-quickstart/repository/segmentstore <backup>

Note:
<aem-folder> – is the path where the aem jar file resides
<backup> – is the path where the backup has to be stored

Step3: Find all the checkpoints using the oak-run tool with the below command. This finds all the unreferenced pointsjava -jar oak-run-*.jar checkpoints <aem-folder>/crx-quickstart/repository/segmentstore
checkpoints

Step4: Remove all the unreferenced checkpointsjava -jar oak-run-*.jar checkpoints <aem-folder>/crx-quickstart/repository/segmentstore rm-unreferenced

You will see how many checkpoints get removed, if you had any!



Step4: Now, run the compaction of the tar filesjava -jar oak-run-*.jar compact <aem-folder>/crx-quickstart/repository/segmentstore



Step5: Check your repository file size. It would have reduced drastically!compact completion

We can also create a script combining all the above steps to automate the same

#!/bin/bash

today = "$(date +'%d-%m-%Y')"

logfile = "tarcompact-$today.log"

aeminstallfolder = "/opt/data/aem"

aemfolder = "$aeminstallfolder/crx-quickstart"

oakrun = "$aeminstallfolder/help/oak-run-1.2.11.jar"

## Shutdown AEM

printf "Shutting down AEM.\n"

$aemfolder / bin / stop

now = "$(date)"

echo "AEM Shutdown at: $now" >> $aeminstallfolder / help / logs / $logfile

## Find old checkpoints

printf "Finding old checkpoints.\n"

java - jar $oakrun checkpoints $aemfolder / repository / segmentstore >> $aeminstallfolder / help / logs / $logfile

## Delete unreferenced checkpoints

printf "Deleting unreferenced checkpoints.\n"

java - jar $oakrun checkpoints $aemfolder / repository / segmentstore rm - unreferenced >> $aeminstallfolder / help / logs / $logfile

## Run compaction

printf "Running compaction. This may take a while.\n"

java - jar $oakrun compact $aemfolder / repository / segmentstore >> $aeminstallfolder / help / logs / $logfile

## Report Completed

printf "Compaction complete. Please check the log at:\n"

printf "$aeminstallfolder/help/logs/$logfile\n"

## Start AEM back up

now = "$(date)"

printf "Starting up AEM.\n"

$aemfolder / bin / start

echo "AEM Startup at: $now" >> $aeminstallfolder / help / logs / $logfile


By aem4beginner

March 28, 2020
Estimated Post Reading Time ~

TAR Compaction for AEM Performance optimization

TARMK Compaction
We require this when we see growth in TarMk files in the repository. As we all know that tar file data is never overwritten and they always do append the data. So the disk usage increases even when only updating existing data. To avoid such increase in the repository,

AEM provides this Tar Compaction. This mechanism will reclaim disk space by removing obsolete data from the repository.

We have two kinds of Tar Compactions.
➢ Online Compaction (AEM 6.2 Doesn’t recommend it anymore)
➢ Offline Compaction

Even before jumping on to these details, let us discuss a bit of automatic compaction triggered manually.

Revision Clean Up:
The automatic compaction can be triggered manually in the Operations Dashboard via a maintenance job called Revision Clean Up.

To Start Revision Clean Up you need to:

❏ Go to AEM Welcome Screen.rm
❏ In the main AEM window, go to Tools → Operations → Dashboard → Maintenance
❏ Or directly browse below.
http://localhost:4502/libs/granite/operations/content/maintenance.html
❏ You see the screen as below.

❏ Now click on Daily Maintenance Window
❏ Hover over the Revision Clean Up window and press the start button like below.
❏ Click on the “Run” icon as seen on the above screenshot.
❏ The icon will turn orange to indicate Revision Clean Up job is running.

You can stop it at any time by hovering the mouse over the icon and pressing the Stop button.

Invoking Revision Garbage Collection via the JMX Console
➔ Open the JMX console as
http://localhost:4502/system/console/jmx
➔ Click RevisionGarbageCollection MBean
➔ In the next window, click startRevisionGC() and then Invoke to start the Revision Garbage Collection job.

TAR OFFLINE COMPACTION:
NOTE: Never do offline compaction when the repository is up and running. Not even checkpoints should be done while the server is up and running.

The procedure is called offline compaction because the repository needs to be shut down in order to properly run the Oak-run tool.

For faster compaction of the Tar files and situations where normal garbage collection does not work, Adobe provides a manual Tar compaction tool called Oak-run. It can be downloaded at the following location: http://mvnrepository.com/artifact/org.apache.jackrabbit/oak-run/

Note: We use Oak-run jar depending upon the version of our current Oak in the AEM server. So make sure we have the right version of the oak-run jar.

The procedure to run the tool is:
➔ Always make sure we have a recent working backup of the AEM instance
➔ Shutdown AEM
➔ Use the tool to find old checkpoints:

java -jar oak-run.jar checkpoints <aem-inst-folder>/crx-quickstart/repository/segmentstore

➔ When you run the above command you should be able to see the references of the nodes like below which we need to clear them before compaction takes place.

➔ Now delete the unreferenced checkpoints using below command.
java -jar oak-run.jar checkpoints <aem-inst-folder>/crx-quickstart/repository/segmentstore rm-unreferenced

➔ Finally run the compaction and wait for it to complete
java -jar oak-run.jar compact <aem-inst-folder>/crx-quickstart/repository/segmentstore

➔ You should be see something like below when you run the above command.

➔ It should display all files under segmentstore directory. After a while, you should be able to see Cleaning up message like below.

➔ Once it cleans up you should be able to see the below message.

➔ It will display the tarfiles again with less count after compaction.

We can create a log file to track all these changes in the log file using the below configurations in the server where we are running the compaction.

This is a one-time activity and we need to use the command below to log the information/errors into the log file.

➔ Create the below config file the same place where we have oak-run-*.jar file
➔ Name it as “logback-compaction.xml” and add the below in the lines in xml file.

<configuration>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.apache.jackrabbit.oak.plugins.segment.Compactor" level="INFO"/>
<root level="warn">
<appender-ref ref="STDERR" />
</root>
</configuration>


➔ Now run the below command to log the error/info into the log file.
nohup java -Dtar.memoryMapped=true -Dupdate.limit=5000000 -Dcompaction-progress-log=1500000 -Dcompress-interval=10000000 -Doffline-compaction=true -Dlogback.configurationFile=logback-compaction.xml -Xmx10g -jar <oak jar file path> compact <aem-installation-path> > tarcompaction.log 2>&1

➔ Now should be able to see the file name “tarcompaction.log” the place where you created the above xml config.

TAR OFFLINE COMPACTION PREREQUISTICS:
· How to find correct version of oak-run jar?
Go to felix console (/system/console/bundles) –> and search for oak, take version across each oak bundle.

Find Check Points:
· java -jar /folderPath/aem/oak-run.jar checkpoints F:/AEM/AEM-4502/crx-quickstart/repository/segmentstore

Run below command on linux/unix machine as windows does not support -Dtar option
· java -Dtar.memoryMapped=true -Xmx8g -jar /folderPath/aem/oak-run-jar/oak-run-1.2.7.jar checkpoints /folderPath/aem/crx-quickstart/repository/segmentstore

Remove CheckPoints:
· java -Dtar.memoryMapped=true -Xmx4g -jar /folderPath/aem/oak-run-jar/oak-run-1.2.7.jar checkpoints /folderPath/aem/crx-quickstart/repository/segmentstore rm-unreferenced

Finally Run Compact:
· java -Dtar.memoryMapped=true -Xmx8g -jar /folderPath/aem/oak-run-jar/oak-run-1.2.7.jar compact /folderPath/aem/crx-quickstart/repository/segmentstore >> /folderPath/aem/help/logs/compactLog

Running Script File:
· Go to the respective script file in the folder path.
· Running below command will execute all the above 3 commands (i.e. finding checkpoints, deleting checkpoints, compacting) are incorporated within that script file.

Command: ./scriptFileName

ONLINE COMPACTION:
For situations where the AEM cannot be shut down for maintenance, compaction can also be performed while the instance is running. This is called Online Compaction.

You can configure Online Compaction by doing the following:
➔ Go to the folder where AEM is installed, then browse to crx-quickstart\install
➔ Open the org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStoreService.config file.
➔ If that doesn’t exist create one and add the following line to the configuration file
repository.home=${repository.home}/segmentstore
tarmk.size=256
pauseCompaction=false
➔ Restart AEM

To verify the configuration has taken place, check here.
➔ Go to the JMX console by pointing your browser to
http://localhost:4502/system/console/jmx
➔ Search for CompactionStrategy and click the MBean that shows up in the search.
➔ Next, verify that the value for PausedCompaction is set to false. This confirms that online compaction is set to run.

➔ Next, verify if Online Compaction is running properly. You can do this by first going to the Operations Dashboard and checking what is the time interval configured for the Daily Maintenance Window. By default, it is scheduled to run between 2 and 5 AM.
➔ Now, inspect the error.log file for events logged during the time of the daily maintenance window to see if online compaction ran correctly.
➔ Example Log:
[TarMK compaction thread [/author/crx-quickstart/repository/segmentstore], active since Thu Mar 19 02:00:10 EDT 2015, previous max duration 1369831ms] org.apache.jackrabbit.oak.plugins.segment.file.FileStore TarMK compaction started
19.03.2015 02:00:30.441 *INFO* [pool-9-thread-2] com.adobe.granite.taskmanagement.impl.jcr.TaskArchiveService archiving tasks at: 'Thu Mar 19 02:00:30 EDT 2015'
19.03.2015 02:01:01.699 *INFO* [TarMK compaction thread [/author/crx-quickstart/repository/segmentstore], active since Thu Mar 19 02:00:10 EDT 2015, previous max duration 1369831ms] org.apache.jackrabbit.oak.plugins.segment.file.FileStore Estimated compaction in 51.47 s, gain is 69% (1018859520/3343598080) or (1.0 GB/3.3 GB), so running compaction

➔ Log to make sure online compaction is completed.

[TarMK compaction thread [/author/crx-quickstart/repository/segmentstore], active since Thu Mar 19 02:00:10 EDT 2015, previous max duration 1369831ms] org.apache.jackrabbit.oak.plugins.segment.file.FileStore TarMK compaction completed in 1310939ms

How to automate the offline compaction process.
Offline Tar Compaction is still the Adobe recommended way of compacting Oak.
Below is the script which automates the entire process.
For the above process download a version of Oak Run that matches your repository version.

Steps to follow:
Shutdown AEM
Find Old Checkpoints
Remove Unreferenced Checkpoints
Compact Oak (using compact keyword in command).
Restart AEM

SCRIPT:
#!/bin/bash
todayDate="$(date +'%d-%m-%Y')"
logfile="compact-$ todayDate.log"
installfolder="/data/aem"
aemfolder="$installfolder/crx-quickstart"
oakrun="$installfolder/help/oak-run-1.0.18.jar"

## Shutdown AEM
printf "Shutting down AEM.\n"
$aemfolder/bin/stop
todayDate ="$(date)"
echo "AEM Shutdown at: $ todayDate " >> $installfolder/help/logs/$logfile

## Find old checkpoints
printf "Finding old checkpoints.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Delete unreferenced checkpoints
printf "Deleting unreferenced checkpoints.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun checkpoints $aemfolder/repository/segmentstore rm-unreferenced >> $installfolder/help/logs/$logfile

## Run compaction
printf "Running compaction. This may take a while.\n"
java -Dtar.memoryMapped=true -Xms8g -Xmx8g -jar $oakrun compact $aemfolder/repository/segmentstore >> $installfolder/help/logs/$logfile

## Report Completed
printf "Compaction complete. Please check the log at:\n"
printf "$installfolder/help/logs/$logfile\n"

## Start AEM back up
todayDate ="$(date)"
printf "Starting up AEM.\n"
$aemfolder/bin/start
echo "AEM Startup at: $ todayDate " >> $installfolder/help/logs/$logfile

http://experiencemanaged.com/posts/scripting-aem-oak-compaction.html
https://jackrabbit.apache.org/oak/docs/command_line.html


By aem4beginner