.. Reminder for header structure:
  Parts (H1)          : #################### with overline
  Chapters (H2)       : ******************** with overline
  Sections (H3)       : ====================
  Subsections (H4)    : --------------------
  Subsubsections (H5) : ^^^^^^^^^^^^^^^^^^^^
  Paragraphs (H6)     : """""""""""""""""""""

.. meta::
 :description: Quickstart - WAPT Peercache
 :keywords: Quickstart, WAPT, Peercache

.. role:: green
.. role:: orange
.. role:: red

.. _peercache:

######################################
PEERCACHE by WAPT |enterprise_feature|
######################################

************
Introduction
************

Peercache is a WAPT feature that allows client workstations to share WAPT packages and Windows updates within the same subnet.
This reduces the load on the WAPT server and speeds up downloads for clients.

Peercache offers several significant advantages, but it also has some drawbacks to consider.

.. list-table::
  :header-rows: 1
  :widths: auto
  :align: center

  * - :green:`Advantages`
    - :red:`Disadvantages`
  * - :green:`Bandwidth reduction`: Packages are downloaded once from the server and shared among client workstations.
    - :red:`Additional open ports`: Peercache requires opening UDP and TCP ports 8099, which can pose security problems if the network is not properly configured.
  * - :green:`Faster downloads`: Clients can download packages from other local workstations, which is generally faster than from the central WAPT server.
    - :red:`Configuration complexity`: Setting up and configuring peercache can be complex and requires a good understanding of your network.
  * - :green:`Reduced server load`: The WAPT server is less solicited, improving its overall performance.
    -

*******************
How Peercache Works
*******************

|

Basic Principle
===============

Peercache allows client workstations to share WAPT packages and Windows updates. Here are the main steps of how it works:

**Enabling Peercache**: On each client workstation, peercache is enabled by having the line :guilabel:`peercache_enable=1` in the :file:`wapt-get.ini` file.

**Package Retention**: Packages installed on the machine are Packages installed on the machine are retained in the agent's cache directory (C:\\\Program Files (x86)\\\wapt\\\private\\\cache). This directory contains :file:`.cache` files with a checksum (md5, sha1 or sha256). specific to each package.

**Broadcasting Information**: A port (8099) is opened to broadcast information about the packages that the machine has in its peercache.

**Package Download**: When a client workstation needs a package, it sends a request to its neighbors to see if any of them have the package. The default broadcast delay is 0.2 seconds. If a neighbor has the package, it downloads it from that neighbor. Otherwise, it downloads it from the WAPT server. By default, if several neighbors have the package, the client workstation will select the one with the best bandwidth.

|

Example of Operation
====================

    - *First Workstation*: The first workstation retrieves the `vlc` package from the WAPT server and keeps it in its non-persistent cache.
    - *Second Workstation*: The second workstation needs the `vlc` package. It consults the WAPT server's index file to get information about the package. Then, it sends a request to its neighbors and waits 0.2 seconds to see if a neighbor has the package.
    - *Download*: If a neighbor has the package, the second workstation downloads it from that neighbor. Otherwise, it downloads it from the WAPT server.

********************
Setting Up Peercache
********************

To **enable peercache**, there are two ways to do it: either through a **configuration package** or by enabling it by **default on all agents**.

.. note::

  This only applies to machines connected to a private network or domain, not a public one.

|

Via the Agent Build:
====================

Add peercache to all agents during the creation of the agent following a WAPT upgrade (Tools → Build WAPT Agent → :guilabel:`Enable peercache on agent`).

.. figure:: wapt-resources/build_agent_with_peercache.png
  :align: center
  :scale: 75%
  :alt: build agent with peercache

  Build agent with peercache

.. note::

    Enabling peercache via the agent will open port 8099 for incoming UDP and TCP traffic.

|

Via the Configuration Package:
==============================

Add peercache via a configuration package (Packages inventory → :guilabel:`Make package template from setup file` → :guilabel:`Host agent dynamic configuration` → global → :guilabel:`Use peercache`).

.. figure:: wapt-resources/configuration_package_to_enable_peercache.png
  :align: center
  :scale: 75%
  :alt: configuration package to enable peercache

  Configuration package to enable peercache

.. note::
    To allow peercache to function via a configuration package, it is necessary to open UDP and TCP ports 8099. 

    If you are using the windows firewall, you can use these commands

    .. code-block::

      run(r'netsh.exe advfirewall firewall add rule name="Waptget peercache UDP listener" program="C:\Program Files (x86)\wapt\wapt-get.exe" action=allow dir=in profile=private,domain protocol=udp localport=8099')
      run(r'netsh.exe advfirewall firewall add rule name="Waptget peercache HTTP server" program="C:\Program Files (x86)\wapt\wapt-get.exe" action=allow dir=in profile=private,domain protocol=tcp localport=8099')

  
    :red:`Firewall configuration is specific to each tool used in your company.`

|

This will add the following configuration to the client workstation's :file:`wapt-get.ini` file:

.. code-block::

    [global]
    peercache_enable=1

*****************************
Verifying Peercache Operation
*****************************

To verify that peercache is working, here is a simple method.

**Prerequisites:**

* Have two workstations available on the same subnet.
* Create a new empty WAPT package.
* Have peercache enabled on the workstations.

**Setup:**

1. Create a new empty WAPT package.

2. Install the package on the first workstation.
   In the logs, you should see → downloading tis-test_peercache → **(using Default)**.

   *Using Default* indicates that the package was retrieved using the default mode, which means it was downloaded from the WAPT server.

.. code-block::

    Download completed for tis-message-user(=1-6). 13.94Kb/s https://srvwapt.jarnaud.tranquil.it/wapt/tis-message-user_1-6_PROD.wapt 951f584dfca4d264ed8e3d8d9c34a1de (using Default) Debug steps:["wgsUrlFile","wgsFileName","wgsHead","wgsFromScratch","wgsNewStream","wgsAlternateBroadcast","wgsAlternateGet","wgsAlternateSuccess","wgsAlternateCopiedInCache","wgsLastMod","wgsAlternateRename"]

3. Once the package is successfully installed on the first workstation, the package file in `.cache` format should appear in the agent's directory under "C:\\\Program Files (x86)\\\wapt\private\\\cache\\\temp".

4. Add the package as a dependency on the second machine and install it.

5. In the task log in the WAPT console, you should see the following:
   downloading tis-test_peercache → **(using Peercache)**.

   *Using Peercache* means that the package was successfully retrieved via peercache.

.. code-block::

    Download completed for tis-message-user(=1-6). 13.94Kb/s https://srvwapt.jarnaud.tranquil.it/wapt/tis-message-user_1-6_PROD.wapt 951f584dfca4d264ed8e3d8d9c34a1de (using Peercache) Debug steps:["wgsUrlFile","wgsFileName","wgsHead","wgsFromScratch","wgsNewStream","wgsAlternateBroadcast","wgsAlternateGet","wgsAlternateSuccess","wgsAlternateCopiedInCache","wgsLastMod","wgsAlternateRename"]

********************************************
Auditing PeerCache Usage in Your Environment
********************************************

To assess the effectiveness of PeerCache after deploying it across your network, you can use the following SQL query. This query will help you determine the proportion of package installations handled by PeerCache, compared to other sources.

.. code-block::

  SELECT
    value->>'source_type' AS source_type,
    COUNT(*)              AS nb,
    ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS pct
  FROM HostAuditData
  WHERE value_section = 'host_metrics'
    AND value_key = 'peercache'
    AND (value->>'end_time')::timestamp >= timestamp '2024-01-01 00:00:00'
  GROUP BY value->>'source_type'
  ORDER BY nb DESC;

**Expected Output:**

Running this query will generate a result similar to the following:

.. list-table::
  :header-rows: 1
  :widths: auto
  
  * - source_type
    - nb
    - pct
  * - Peercache
    - 35
    - 38.46
  * - Default
    - 25
    - 27.47
  * - AlreadyExisting
    - 21
    - 23.08
  * - LocalPeercache
    - 10
    - 10.99

**Interpreting the Results:**

Peercache (38.46%): Packages were successfully installed using PeerCache, meaning they were retrieved from another peer machine in the network.
Default (27.47%): Packages were downloaded directly from the WAPT server upon request from the agent.
AlreadyExisting (23.08%): Packages were already installed on the machine, so no additional download or installation was required.
LocalPeercache (10.99%): Packages were reinstalled from a locally cached copy on the machine itself.

In my infrastructure since 2024 (Peercache enable in 2025), I can note that 30% of packages come from the traditional agent-server process, while nearly 50% of distributed packages are handled through PeerCache.
