×

Over time, API objects created in OpenShift Container Platform can accumulate in the cluster’s etcd data store through normal user operations, such as when building and deploying applications.

Cluster administrators can periodically prune older versions of objects from the cluster that are no longer required. For example, by pruning images you can delete older images and layers that are no longer in use, but are still taking up disk space.

Basic pruning operations

The CLI groups prune operations under a common parent command:

$ oc adm prune <object_type> <options>

This specifies:

  • The <object_type> to perform the action on, such as groups, builds, deployments, or images.

  • The <options> supported to prune that object type.

Pruning groups

To prune groups records from an external provider, administrators can run the following command:

$ oc adm prune groups \
    --sync-config=path/to/sync/config [<options>]
Table 1. oc adm prune groups flags
Options Description

--confirm

Indicate that pruning should occur, instead of performing a dry-run.

--blacklist

Path to the group blacklist file.

--whitelist

Path to the group whitelist file.

--sync-config

Path to the synchronization configuration file.

Procedure
  1. To see the groups that the prune command deletes, run the following command:

    $ oc adm prune groups --sync-config=ldap-sync-config.yaml
  2. To perform the prune operation, add the --confirm flag:

    $ oc adm prune groups --sync-config=ldap-sync-config.yaml --confirm

Pruning deployment resources

You can prune resources associated with deployments that are no longer required by the system, due to age and status.

The following command prunes replication controllers associated with DeploymentConfig objects:

$ oc adm prune deployments [<options>]

To also prune replica sets associated with Deployment objects, use the --replica-sets flag. This flag is currently a Technology Preview feature.

Table 2. oc adm prune deployments flags
Option Description

--confirm

Indicate that pruning should occur, instead of performing a dry-run.

--keep-complete=<N>

Per the DeploymentConfig object, keep the last N replication controllers that have a status of Complete and replica count of zero. The default is 5.

--keep-failed=<N>

Per the DeploymentConfig object, keep the last N replication controllers that have a status of Failed and replica count of zero. The default is 1.

--keep-younger-than=<duration>

Do not prune any replication controller that is younger than <duration> relative to the current time. Valid units of measurement include nanoseconds (ns), microseconds (us), milliseconds (ms), seconds (s), minutes (m), and hours (h). The default is 60m.

--orphans

Prune all replication controllers that no longer have a DeploymentConfig object, has status of Complete or Failed, and has a replica count of zero.

--replica-sets=true|false

If true, replica sets are included in the pruning process. The default is false.

This flag is a Technology Preview feature.

Procedure
  1. To see what a pruning operation would delete, run the following command:

    $ oc adm prune deployments --orphans --keep-complete=5 --keep-failed=1 \
        --keep-younger-than=60m
  2. To actually perform the prune operation, add the --confirm flag:

    $ oc adm prune deployments --orphans --keep-complete=5 --keep-failed=1 \
        --keep-younger-than=60m --confirm

Pruning builds

To prune builds that are no longer required by the system due to age and status, administrators can run the following command:

$ oc adm prune builds [<options>]
Table 3. oc adm prune builds flags
Option Description

--confirm

Indicate that pruning should occur, instead of performing a dry-run.

--orphans

Prune all builds whose build configuration no longer exists, status is complete, failed, error, or canceled.

--keep-complete=<N>

Per build configuration, keep the last N builds whose status is complete. The default is 5.

--keep-failed=<N>

Per build configuration, keep the last N builds whose status is failed, error, or canceled. The default is 1.

--keep-younger-than=<duration>

Do not prune any object that is younger than <duration> relative to the current time. The default is 60m.

Procedure
  1. To see what a pruning operation would delete, run the following command:

    $ oc adm prune builds --orphans --keep-complete=5 --keep-failed=1 \
        --keep-younger-than=60m
  2. To actually perform the prune operation, add the --confirm flag:

    $ oc adm prune builds --orphans --keep-complete=5 --keep-failed=1 \
        --keep-younger-than=60m --confirm

Developers can enable automatic build pruning by modifying their build configuration.

Automatically pruning images

Images that are no longer required by the system due to age, status, or exceed limits are automatically pruned. Cluster administrators can configure the Pruning Custom Resource, or suspend it.

Prerequisites
  • Cluster administrator permissions.

  • Install the oc CLI.

Procedure
  • Verify that the object named imagepruners.imageregistry.operator.openshift.io/cluster contains the following spec and status fields:

spec:
  schedule: 0 0 * * * (1)
  suspend: false (2)
  keepTagRevisions: 3 (3)
  keepYoungerThanDuration: 60m (4)
  keepYoungerThan: 3600000000000 (5)
  resources: {} (6)
  affinity: {} (7)
  nodeSelector: {} (8)
  tolerations: [] (9)
  successfulJobsHistoryLimit: 3 (10)
  failedJobsHistoryLimit: 3 (11)
status:
  observedGeneration: 2 (12)
  conditions: (13)
  - type: Available
    status: "True"
    lastTransitionTime: 2019-10-09T03:13:45
    reason: Ready
    message: "Periodic image pruner has been created."
  - type: Scheduled
    status: "True"
    lastTransitionTime: 2019-10-09T03:13:45
    reason: Scheduled
    message: "Image pruner job has been scheduled."
  - type: Failed
    staus: "False"
    lastTransitionTime: 2019-10-09T03:13:45
    reason: Succeeded
    message: "Most recent image pruning job succeeded."
1 schedule: CronJob formatted schedule. This is an optional field, default is daily at midnight.
2 suspend: If set to true, the CronJob running pruning is suspended. This is an optional field, default is false. The initial value on new clusters is false.
3 keepTagRevisions: The number of revisions per tag to keep. This is an optional field, default is 3. The initial value is 3.
4 keepYoungerThanDuration: Retain images younger than this duration. This is an optional field. If a value is not specified, either keepYoungerThan or the default value 60m (60 minutes) is used.
5 keepYoungerThan: Deprecated. The same as keepYoungerThanDuration, but the duration is specified as an integer in nanoseconds. This is an optional field. When keepYoungerThanDuration is set, this field is ignored.
6 resources: Standard pod resource requests and limits. This is an optional field.
7 affinity: Standard pod affinity. This is an optional field.
8 nodeSelector: Standard pod node selector. This is an optional field.
9 tolerations: Standard pod tolerations. This is an optional field.
10 successfulJobsHistoryLimit: The maximum number of successful jobs to retain. Must be >= 1 to ensure metrics are reported. This is an optional field, default is 3. The initial value is 3.
11 failedJobsHistoryLimit: The maximum number of failed jobs to retain. Must be >= 1 to ensure metrics are reported. This is an optional field, default is 3. The initial value is 3.
12 observedGeneration: The generation observed by the Operator.
13 conditions: The standard condition objects with the following types:
  • Available: Indicates if the pruning job has been created. Reasons can be Ready or Error.

  • Scheduled: Indicates if the next pruning job has been scheduled. Reasons can be Scheduled, Suspended, or Error.

  • Failed: Indicates if the most recent pruning job failed.

The Image Registry Operator’s behavior for managing the pruner is orthogonal to the managementState specified on the Image Registry Operator’s ClusterOperator object. If the Image Registry Operator is not in the Managed state, the image pruner can still be configured and managed by the Pruning Custom Resource.

However, the managementState of the Image Registry Operator alters the behavior of the deployed image pruner job:

  • Managed: the --prune-registry flag for the image pruner is set to true.

  • Removed: the --prune-registry flag for the image pruner is set to false, meaning it only prunes image metatdata in etcd.

  • Unmanaged: the --prune-registry flag for the image pruner is set to false.

Manually pruning images

The pruning custom resource enables automatic image pruning. However, administrators can manually prune images that are no longer required by the system due to age, status, or exceed limits. There are two methods to manually prune images:

  • Running image pruning as a Job or CronJob on the cluster.

  • Running the oc adm prune images command.

Prerequisites
  • To prune images, you must first log in to the CLI as a user with an access token. The user must also have the system:image-pruner cluster role or greater (for example, cluster-admin).

  • Expose the image registry.

Procedure

To manually prune images that are no longer required by the system due to age, status, or exceed limits, use one of the following methods:

  • Run image pruning as a Job or CronJob on the cluster by creating a YAML file for the pruner service account, for example:

    $ oc create -f <filename>.yaml
    Example output
    kind: List
    apiVersion: v1
    items:
    - apiVersion: v1
      kind: ServiceAccount
      metadata:
        name: pruner
        namespace: openshift-image-registry
    - apiVersion: rbac.authorization.k8s.io/v1
      kind: ClusterRoleBinding
      metadata:
        name: openshift-image-registry-pruner
      roleRef:
        apiGroup: rbac.authorization.k8s.io
        kind: ClusterRole
        name: system:image-pruner
      subjects:
      - kind: ServiceAccount
        name: pruner
        namespace: openshift-image-registry
    - apiVersion: batch/v1
      kind: CronJob
      metadata:
        name: image-pruner
        namespace: openshift-image-registry
      spec:
        schedule: "0 0 * * *"
        concurrencyPolicy: Forbid
        successfulJobsHistoryLimit: 1
        failedJobsHistoryLimit: 3
        jobTemplate:
          spec:
            template:
              spec:
                restartPolicy: OnFailure
                containers:
                - image: "quay.io/openshift/origin-cli:4.1"
                  resources:
                    requests:
                      cpu: 1
                      memory: 1Gi
                  terminationMessagePolicy: FallbackToLogsOnError
                  command:
                  - oc
                  args:
                  - adm
                  - prune
                  - images
                  - --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt
                  - --keep-tag-revisions=5
                  - --keep-younger-than=96h
                  - --confirm=true
                  name: image-pruner
                serviceAccountName: pruner
  • Run the oc adm prune images [<options>] command:

    $ oc adm prune images [<options>]

    Pruning images removes data from the integrated registry unless --prune-registry=false is used.

    Pruning images with the --namespace flag does not remove images, only image streams. Images are non-namespaced resources. Therefore, limiting pruning to a particular namespace makes it impossible to calculate its current usage.

    By default, the integrated registry caches metadata of blobs to reduce the number of requests to storage, and to increase the request-processing speed. Pruning does not update the integrated registry cache. Images that still contain pruned layers after pruning will be broken because the pruned layers that have metadata in the cache will not be pushed. Therefore, you must redeploy the registry to clear the cache after pruning:

    $ oc rollout restart deployment/image-registry -n openshift-image-registry

    If the integrated registry uses a Redis cache, you must clean the database manually.

    If redeploying the registry after pruning is not an option, then you must permanently disable the cache.

    oc adm prune images operations require a route for your registry. Registry routes are not created by default.

    The Prune images CLI configuration options table describes the options you can use with the oc adm prune images <options> command.

    Table 4. Prune images CLI configuration options
    Option Description

    --all

    Include images that were not pushed to the registry, but have been mirrored by pullthrough. This is on by default. To limit the pruning to images that were pushed to the integrated registry, pass --all=false.

    --certificate-authority

    The path to a certificate authority file to use when communicating with the OpenShift Container Platform-managed registries. Defaults to the certificate authority data from the current user’s configuration file. If provided, a secure connection is initiated.

    --confirm

    Indicate that pruning should occur, instead of performing a test-run. This requires a valid route to the integrated container image registry. If this command is run outside of the cluster network, the route must be provided using --registry-url.

    --force-insecure

    Use caution with this option. Allow an insecure connection to the container registry that is hosted via HTTP or has an invalid HTTPS certificate.

    --keep-tag-revisions=<N>

    For each imagestream, keep up to at most N image revisions per tag (default 3).

    --keep-younger-than=<duration>

    Do not prune any image that is younger than <duration> relative to the current time. Alternately, do not prune any image that is referenced by any other object that is younger than <duration> relative to the current time (default 60m).

    --prune-over-size-limit

    Prune each image that exceeds the smallest limit defined in the same project. This flag cannot be combined with --keep-tag-revisions nor --keep-younger-than.

    --registry-url

    The address to use when contacting the registry. The command attempts to use a cluster-internal URL determined from managed images and image streams. In case it fails (the registry cannot be resolved or reached), an alternative route that works needs to be provided using this flag. The registry hostname can be prefixed by https:// or http://, which enforces particular connection protocol.

    --prune-registry

    In conjunction with the conditions stipulated by the other options, this option controls whether the data in the registry corresponding to the OpenShift Container Platform image API object is pruned. By default, image pruning processes both the image API objects and corresponding data in the registry.

    This option is useful when you are only concerned with removing etcd content, to reduce the number of image objects but are not concerned with cleaning up registry storage, or if you intend to do that separately by hard pruning the registry during an appropriate maintenance window for the registry.

Image prune conditions

You can apply conditions to your manually pruned images.

  • To remove any image managed by OpenShift Container Platform, or images with the annotation openshift.io/image.managed:

    • Created at least --keep-younger-than minutes ago and are not currently referenced by any:

      • Pods created less than --keep-younger-than minutes ago

      • Image streams created less than --keep-younger-than minutes ago

      • Running pods

      • Pending pods

      • Replication controllers

      • Deployments

      • Deployment configs

      • Replica sets

      • Build configurations

      • Builds

      • --keep-tag-revisions most recent items in stream.status.tags[].items

    • That are exceeding the smallest limit defined in the same project and are not currently referenced by any:

      • Running pods

      • Pending pods

      • Replication controllers

      • Deployments

      • Deployment configs

      • Replica sets

      • Build configurations

      • Builds

  • There is no support for pruning from external registries.

  • When an image is pruned, all references to the image are removed from all image streams that have a reference to the image in status.tags.

  • Image layers that are no longer referenced by any images are removed.

The --prune-over-size-limit flag cannot be combined with the --keep-tag-revisions flag nor the --keep-younger-than flags. Doing so returns information that this operation is not allowed.

Separating the removal of OpenShift Container Platform image API objects and image data from the registry by using --prune-registry=false, followed by hard pruning the registry, can narrow timing windows and is safer when compared to trying to prune both through one command. However, timing windows are not completely removed.

For example, you can still create a pod referencing an image as pruning identifies that image for pruning. You should still keep track of an API object created during the pruning operations that might reference images so that you can mitigate any references to deleted content.

Re-doing the pruning without the --prune-registry option or with --prune-registry=true does not lead to pruning the associated storage in the image registry for images previously pruned by --prune-registry=false. Any images that were pruned with --prune-registry=false can only be deleted from registry storage by hard pruning the registry.

Running the image prune operation

Procedure
  1. To see what a pruning operation would delete:

    1. Keeping up to three tag revisions, and keeping resources (images, image streams, and pods) younger than 60 minutes:

      $ oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m
    2. Pruning every image that exceeds defined limits:

      $ oc adm prune images --prune-over-size-limit
  2. To perform the prune operation with the options from the previous step:

    $ oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m --confirm
    $ oc adm prune images --prune-over-size-limit --confirm

Using secure or insecure connections

The secure connection is the preferred and recommended approach. It is done over HTTPS protocol with a mandatory certificate verification. The prune command always attempts to use it if possible. If it is not possible, in some cases it can fall-back to insecure connection, which is dangerous. In this case, either certificate verification is skipped or plain HTTP protocol is used.

The fall-back to insecure connection is allowed in the following cases unless --certificate-authority is specified:

  1. The prune command is run with the --force-insecure option.

  2. The provided registry-url is prefixed with the http:// scheme.

  3. The provided registry-url is a local-link address or localhost.

  4. The configuration of the current user allows for an insecure connection. This can be caused by the user either logging in using --insecure-skip-tls-verify or choosing the