Branchcache windows 10 что это

Привет.

Ранее я уже написал две статьи по BranchCache – про BranchCache в изначальном варианте и про BranchCache в Windows Server 2012 R2 и Windows 8.1. Эта статья будет про новую версию – BranchCache в Windows 10 и в Windows Server 2016 – а также будет включать в себя более глубокий материал, чем по предыдущей версии.

На данный момент с BranchCache в Windows 10 сложилась странная ситуация – “новый функционал” про то, что “Ваша ОС теперь может скачивать обновления не только с Интернета, но и с соседних компьютеров!” подаётся как ультрановая фича со стороны Microsoft, а со стороны злопыхателей этот же функционал подаётся как “вот видите, злобная Windows 10 шарит по соседним компам со смутными целями, дескать обновления качает, но мы-то знаем что всё совсем не так!”. Всё это – про функционал, который есть ещё с Vista, достаточно несложный, предсказуемый, и при должной настройке очень эффективный. Давайте разберёмся в данной технологии, а заодно прикопаем один из мифов про Страшно Ворующую Данные Винду.

Предварительная подготовка

Я предполагаю, что вы владеете знаниями по Windows Server на уровне , а также установили в Central Store своего домена обновлённые ADMX-шаблоны для Windows 10 RTM. Все скриншоты и тесты я буду делать на Windows 10 и Windows Server 2016 TP2. Про специфику и ограничения BranchCache первой версии, т.е. оригинального варианта из Windows Server 2008 R2, я буду упоминать, но минимально.

Я постараюсь разобрать полноценную процедуру развёртывания BranchCache, чтобы не было как на авторизованных курсах – “установите компонент с таким названием и дальше оно как-то само”. Это не наши методы! :)

Оглавление

  • Что такое BranchCache
  • Требования BranchCache к операционной системе
  • Сценарии BranchCache
  • Роли участников в BranchCache
  • Развёртывание BranchCache
  • BranchCache на клиентских ОС
    • Разрешаем трафик BranchCache на клиентах
    • Включаем Offline Files для BranchCache
    • Включаем BITS для BranchCache
    • Настраиваем локальный кэш BranchCache на клиентах
    • Включаем BranchCache на клиентах
    • Настраиваем версию BranchCache для клиентов
    • Настраиваем режим работы BranchCache для клиентов
  • BranchCache на файл-сервере
    • Ставим компонент BranchCache for Network Files
    • Настройка BranchCache на файл-сервере
  • BranchCache на web-сервере
    • Ставим компонент BranchCache для веб-сервера
  • Настройка выделенного сервера кэширования BranchCache – Hosted Cache
    • Настройка BranchCache Hosted Cache для Windows Server 2008 R2
    • Настройка BranchCache Hosted Cache для Windows Server 2012 R2 и Windows Server 2016
  • Тюнинг BranchCache
    • Смена номеров портов у BranchCache
    • Дефрагментация кэша у сервера BranchCache
    • Ускорение первого ответа у контент-сервера BranchCache
    • Безопасность BranchCache
  • BranchCache и обновления для Windows 10

Начнём.

Что такое BranchCache

BranchCache – это встроенный в NT 6.x механизм распределённого кэширования трафика. Кэшироваться может SMB-трафик (в том числе подписанный), HTTP и HTTPS-трафик, а также трафик протокола BITS (который, конечно, почти HTTP, но всё же API у него отдельное). Кэширование происходит прозрачно для приложения – т.е. оно, допустим, запрашивает по SMB файл, и, если BranchCache корректно настроен, то он “стягивает” этот файл с соседей. Это крайне удобно в сценариях вида “региональный офис из 5 компов без сервера”, когда файл скачивается более чем 1м клиентом и более чем 1 раз – допустим, первый пришедший на работу открывает с корпоративного SharePoint большой файл, а когда приходят другие, они, открывая этот же файл, заберут его копию из кэша первооткрывателя. Плюсов множество – это и ускорение работы, того же портала на базе SharePoint или любого другого веб-ресурса, и автоматическое ускорение скачивания обновлений Windows в сценарии, когда в филиале нет своего сервера WSUS, и более быстрая работа с удалённым файл-сервером (с поддержкой DFS или без), и множество другого.
 
Иными словами, любое ПО, которое обращается к штатному API для передачи данных с использованием указанных протоколов, получает преимущества BranchCache без каких-либо затрат и необходимости переписывания приложения.
 
В плане сетевых протоколов BranchCache поддерживает и IPv4, и IPv6.
 
Весь сетевой трафик BranchCache защищается, применяется алгоритм AES-128 (наилучшее соотношение скорости к надёжности защиты), который вдобавок ко всему сейчас на новых процессорах Intel ускоряется на аппаратном уровне, т.е. дополнительной защиты, например, применяя доменные политики IPSec, не нужно. Всё, что нужно, в общем-то уже есть, осталось настроить и использовать.
 
Технически BranchCache работает с данными, разбивая их на блоки по 64К (либо, в обновлённом варианте с Windows Server 2012, меньше) и считая хэш каждого блока. Хэш считается по алгоритму SHA-256, т.к. в NT 6.x данный алгоритм, в отличии от NT 5.x есть “из коробки” (коробка называется CNG). Пачка подряд идущих блоков называется сегментом и имеет свой личный хэш. По сути, если рамочно, BranchCache при поиске контента делает следующее – запрашивает по протоколу WS-Discovery у соседей либо у выделенного сервера “есть ли у кого сегмент с таким-то хэшем” (запрос хэша сегмента позволяет ощутимо уменьшить сетевой трафик), и если сегмент есть – заметьте, даже частично – то идёт обмен вида “давай уточним, у кого что от этого сегмента есть – если у тебя есть блок с хэшем таким-то, то отдай такой блок мне, а я тебе отсутствующие у тебя отправлю“. Т.е. единица передачи – файл – делится на блоки фиксированной длины, у каждого блока считается хэш, блоки объединяются в крупные куски – сегменты, и BranchCache позволяет синхронизировать как отсутствующие сегменты целиком, так и отдельные блоки внутри сегментов.
 
Дополнительный плюс в том, что если вы даже скачиваете одиночный файл, то в случае с BranchCache, если у файла есть одинаковые блоки, вы скачаете их только разово. Т.е. для начала вы обратитесь на источник контента – он пришлёт вам список хэшей; после того, как выяснится, что некоторые из них одинаковые, вы будете запрашивать или у соседей, или у выделенного сервера (зависит от сценария использования) только один экземпляр такого блока – ведь нет смысла много раз качать то, SHA-256 хэш чего одинаков.

Требования BranchCache к операционной системе

BranchCache доступен на клиентских ОС с Windows 7, начиная с редакции Enterprise. В серверных ОС он присутствует во всех редакциях (исключение составит лишь Windows Server Core 2008 R2 Standard – в этом случае роль “выделенного кэширующего сервера BranchCache” (Hosted Cache) недоступна).
 
Добавление поддержки BranchCache в Windows Vista / Windows Server 2008 также возможно – надо просто обновить их встроенный BITS 3.0 до BITS 4.0 (см. BITS 4.0), и всё будет ОК – в случае, когда контент будет запрашиваться с использованием BITS, они смогут искать этот контент у своих соседей по сети. Технология эта называется PeerCache, работает с BITS 3.5 (эта версия отдельно для загрузки не встречается) и мало известна.
 
Если вы уже чуток запутались, то всё просто:
 
Есть BITS – это подсистема передачи данных, используемая различными сервисами Windows (например, Windows Update).
 
Есть PeerCache – это фича BITS, которая появляется с версии 4.0 и позволяет запрашивать у соседей по сети список хэшей блоков скачиваемого файла.
 
Есть BranchCache – это технология, в которую будут входить и клиенты с BITS, и сервера, формирующие данные, и механизм обнаружения хранилищ через Active Directory, и всё остальное.

Сценарии BranchCache

Сценарии работы BranchCache делятся на 3 варианта:
 

  • Hosted Cache Mode – в этом случае в сети есть выделенный сервер BranchCache, с которого забирают трафик все клиенты (в регионе; в организации серверов может быть несколько). Сервер Hosted Cache может как находиться с клиентами в одной IPv4 / IPv6 – сети, так и быть доступным через роутинг.
  • Distributed Cache Mode – в этом случае в сети нет выделенного сервера BranchCache, загрузка контента идёт с любого соседа по IPv4 / IPv6 – сети, у которого обнаружены нужные блоки данных.
  • Hybrid Cache Mode – когда сеть большая, в части регионов может использоваться сценарий Hosted Cache, а в части – Distributed.

Сценарии не задаются глобально заранее – как развернёте, так и будет работать. Подчеркну ещё раз, что самый простой вариант – Distributed Cache – нацелен на сценарий “все в одной L3-сети”. В случае, если в регионе несколько IP-сетей (допустим, клиенты-десктопы в одной, а те, кто через WiFi – в другой), сценарий будет не рабочим – для оптимальной работы надо разворачивать Hosted Cache.
Сценарий Distributed Cache привлекателен отсутствием сервера, но имеет два фундаментальных минуса:
 

  1. В случае отсутствия в сети или недоступности клиента, на котором закэширован исходный файл (допустим, человек с утра пришёл с ноутом, а потом ушёл на совещание), кэш недоступен. В Hosted Cache такого нет – сервер никуда не уйдёт.
  2. Всё работает в пределах одного сетевого сегмента – если сетей несколько, эффективность резко снижается. Сервер же с Hosted Cache доступен из любой сети и ему не надо быть в одном L3-сегменте с клиентом.

Роли участников в BranchCache

По сути, ролей будет три:
 

  • Клиент (Client BranchCache) – тот, кто может использовать сервисы BranchCache. Ему нужен лишь BITS 4.0 и старше, ну и некоторые настройки через Group Policy. Он может раздавать контент другим, если применяется модель Distributed Cache.
  • Кэш-сервер (Hosted Cache BranchCache) – выделенный сервер для кэширования данных BranchCache. Бывает только в части сценариев (отсутствует в Distributed Cache Mode).
  • Контент-сервер (Content Server BranchCache) – тот, с кого изначально забирается контент для кэширования. Это обычный файловый или HTTP-сервер с поддержкой BranchCache.

Учтите, что контент-сервером BranchCache должна быть система, поддерживающая BranchCache и корректно настроенная – а не любой HTTP- или SMB-сервер. Ведь контент-сервер должен в ответ на обычный запрос файла высылать дополнительную информацию про хэши блоков и сегментов.
 
Теперь посмотрим, какие компоненты надо поставить и настроить, чтобы всё это заработало.

Развёртывание BranchCache

Начнём с самого простого – настройки клиентов.

BranchCache на клиентских ОС

Ставить ничего не надо – сервис PeerCache входит в BITS, соответственно, надо лишь обновить BITS в случае ОС Vista / 2008 до 4.0. Это несложно – качаем Windows Management Framework 4.0 и ставим. В Windows Server 2012 и Windows 8 уже входит BITS 5.0, обновлять ничего не надо. Конечно, можно обновить Windows 7 и старше и Windows 2008 R2 и старше до Windows Management Framework 5.0, но оный ещё не вышел на дату написания этой статьи.
 
Технически BITS реализован библиотекой QMgr.dll, лежащей в /System32, поэтому можно просто убедиться, что её версия старше 7.5.nnnn.nnnn.
 

Разрешаем трафик BranchCache на клиентах

Первым делом – разрешения в Windows Advanced Firewall. Нам надо включить трафик MS-PCCRD (Peer Content Caching and Retrieval Discovery Protocol). Этот трафик идёт внутри Web Services Dynamic Discovery (WS-Discovery) и использует мультикаст – 239.255.255.250 в случае IPv4 и FF02::C в варианте IPv6. Порт одинаковый – 3702 UDP. Разрешите этот трафик как для отправки мультикаста по этим адресам наружу на указанный номер порта (чтобы клиент мог информировать соседей), так и для приёма на данный порт запросов на подключение.
 
В случае однорангового режима работы – Distributed Cache Mode – клиенты будут использовать порты 80 и 443й. Это потому что в BITS на клиенте встроен мини-сервер PeerCache. Эти порты также надо будет открыть для соседей по локальной сети – именно для них, подчеркну, а не для всех вообще, т.к. Distributed Cache будет работать только внутри сегмента. Поэтому данное включение безопасно – если же хочется сделать его ещё безопаснее, просто закройте трафик в пределах одной сети IPsec’ом с аутентификацией по Kerberos, и тогда ходить друг к другу смогут только хосты из одного домена, только в пределах одной IP-сети и трафик будет зашифрован.

Включаем Offline Files для BranchCache

Без механизма Offline Files BranchCache работать не будет, поэтому придётся включить этот вредный спорный в части полезности механизм.
 
Зайдём в групповую политику, в раздел Computer Configuration / Administrative Templates / Network / Offline Files и выберем параметр Allow of Disallow use of the Offline Files feature (настраивать лучше здесь, т.к. настройки в этом разделе перекроют пользовательские в случае наличия оных)
 

и сразу же настроим шифрование папки Offline Files (параметр Encrypt the Offline Files cache) – оно не помешает:

Теперь настроим BITS.

Включаем BITS для BranchCache

Без правильно настроенного BITS работа в варианте Distributed Cache не будет возможна, т.к. именно в BITS настраивается работа сервиса PeerCache. Зайдём в Computer Configuration / Administrative Templates / Network / Background Intelligent Transfer Service и включим Allow BITS peercaching:

ОК, сам механизм PeerCache мы включили – теперь надо указать, какую роль может играть эта клиентская система – и предоставлять контент и запрашивать его, или что-то одно? Плюс, сразу же укажем, что нам надо ограничить полосу пропускания у механизма PeerCache – выберем 52428800 bps (это 50 mbit/sec). Учитывайте, что по умолчанию BITS использует максимум 30% полосы пропускания самого медленного интерфейса – это значит, что если на рабочей станции работает WiFi или Bluetooth, то будет скачиваться максимум 0.3*текущую скорость самого медленного из них, что может быть крайне мало. 50 mbit/sec же – это половина обычного LAN-интерфейса, и никак не навредит, допустим, доступу в Интернет или WAN-ресурсы предприятия. Включаем и настраиваем по порядку, вначале параметр Do not allow the BITS client to use Windows Branch Cache:

и Do not allow the computer to act as a BITS Peercaching client:

Включаем возможность отдачи контента в сценарии Distributed Cache (параметр Do not allow the computer to act as a BITS Peercaching server)- если в сети будет выделенный сервер Hosted Cache, то этот пункт надо наоборот выключить:

И устанавливаем максимальную полосу пропускания для PeerCache (параметр Limit the maximum network bandwidth used for Peercaching):

Теперь настроим размер и логику работы локального кэша BranchCache.

Настраиваем локальный кэш BranchCache на клиентах

Размер локального кэша BranchCache – важная штука, потому что он откусывает проценты пространства на том диске, который помечен как system (т.е. где %WINDIR%). По умолчанию он 1%, максимальный лимит – 80%, мы выставим в 5%. Почему это важно? Думаю, вы хорошо помните Update Rollup’ы для Windows 8.1, каждый из которых – по 800 с лишним мегабайт. Конечно же удобно, чтобы такое обновление раздавалось в локальной сети без загрузки WAN-канала – поэтому надо обеспечить, чтобы оно помещалось в кэш. Вы можете подобрать любое значение, учитывая минимальный размер системного раздела на рабочих станциях (параметр Limit the BITS Peercache size).

Устаревание блоков в кэше – тоже важный момент. По сути, особого смысла стирать старые блоки нет – но может быть такая ситуация, когда данные действительно нужны недолго – например, кэшируются часто изменяющиеся документы с корпоративного портала SharePoint (ежедневный прайс-лист и список товарных позиций), или количество абонентов невелико (3-5 локальных ноутбуков, которые ставят обновления автоматически). В этом случае можно снизить время жизни блоков в кэше до 30 дней, а то и ниже – мы же выставим (параметр Limit the age of files in the BITS Peercache) долгоживущий вариант, подходящий для большой сети – 120 дней.

Ну а теперь, настроив все подсистемы, включим на клиенте сам BranchCache.

Включаем BranchCache на клиентах

Включение самого компонента несложно и делается опять же через групповые политики (параметр Turn on BranchCache):

Эта настройка включит BranchCache именно как клиентский сервис – т.е. он включится даже на серверах, которые подпадут под неё. Поэтому будьте осмотрительны – настройка именно для клиентов, не включайте её глобально на домене, потому что во многих сценариях она не нужна (допустим, серверам в DMZ или edge-системам).

Теперь настроим версию BranchCache – это важная настройка, тут можно остановиться поподробнее

Настраиваем версию BranchCache для клиентов

В начале статьи я уже расскажывал, что BranchCache работает с разными блоками данных. В первой версии (это Windows Server 2008 R2 / Windows 7 Enterprise, и Vista с установленным BITS 4.0) данные разбивались на фиксированные блоки по 64К, от которых брался хэш, а пачка блоков называлась сегментом и тоже обладала своим хэшем. Это достаточно крупное разбиение, да и реализация этой схемы обладала неприятной деталью – в случае изменений в середине большого файла, надо было докачать не только фактически изменённый блок в 64К, но и все последующие. Что, конечно, резко снижало КПД технологии в случае сценария “часто обновляем файл, в котором правится какая-то мелочь в середине”. Этот вариант хэша называется первой версией – BranchCache V1.

В Windows Server 2012 / Windows 8 ситуация поменялась. Теперь файлы разделяются на блоки динамически, используя тот же алгоритм, что и во встроенной в Windows Server 2012 дедупликации – Rabin fingerprint. Суть достаточно проста – границы блоков подбираются исходя из контента, и количество совпадений хэша резко возрастает в отличии от ранней схемы с фиксированным размером блока в 64К. Блоков становится больше (обычно они по 16К-32К, и до 128К), но при каждом изменении надо закачать гораздо меньше данных (КПД вырастает в 3-4 раза только за счёт того, что уменьшился размер блока, а дополнительно вырастает ещё больше, потому что теперь не надо скачивать весь “хвост” файла после изменений). Также появляется эффект от синергии с дедупликацией (про это чуть дальше). Это – BranchCache V2.

Данные могут отправляться от сервера к клиенту только или в V1, или в V2, поэтому вам надо выбрать в явном виде, какой подойдёт. Иначе ваш продвинутый клиент на базе, допустим, Windows 8.1, закэширует ответ сервера, которым не сможет поделиться с системой на базе Windows 7. На момент написания этой статьи нет способа обновить BITS на Windows Server 2008 R2 / Windows 7 до версии 5.0, поэтому если в сети есть машины ниже NT 6.2, и им надо использовать BranchCache, вам придётся выбрать первый вариант. Эта настройка (параметр Configure Client BranchCache Version Support), по сути, возможность downgrade версии для старших систем. У серверов будет своя настройка “какие варианты хэшей отдавать”, она другая.

Теперь выберем между Distributed Cache и Hosted Cache.

Настраиваем режим работы BranchCache для клиентов

Клиенту надо явно указать – будет ли он, при включённом BranchCache, искать контент по соседям в своей локальной сети, или обратится к выделенному серверу. В первом случае мы включим параметр Set BranchCache Distributed Cache mode и на этом настройка режима работы закончится:

В варианте же “Использовать выделенный сервер Hosted Cache” ситуация будет различной для различных клиентских ОС. В случае NT 6.1 (Windows 7 / Windows Server 2008 R2 / примкнувшая к ним Vista) надо будет включить использование выделенного сервера параметром Set BranchCache Hosted Cache mode, явно указав его FQDN:

В новом варианте BranchCache, начиная с Windows 8 и Windows Server 2012, ситуация другая – появилось автообнаружение серверов Hosted Cache и теперь сервер BranchCache может опубликовать в Active Directory свой SCP (Service Connection Point) и клиенты автоматически найдут ближайший к себе. Это гораздо удобнее и настраивается через параметр Enable Automatic Hosted Cache Discovery by Service Connection Point:

Можно, кстати, и задать сервер в явном виде, как в предыдущей версии BranchCache – теперь это тоже стало удобнее и можно задать целый список (параметр Configure Hosted Cache Servers):

Учтите, что данные параметры для разных версий BranchCache не пересекаются – Windows 7 Enterprise будет читать свои, а Windows 8 / Windows 8.1 / Windows 10 – свои.

Что ж, клиент настроен – теперь посмотрим, как включать раздачу контента BranchCache на различных типах серверов.

BranchCache на файл-сервере

Файл-сервером с точки зрения BranchCache будет любая система, на которой есть общие папки и произведены нужные настройки. Сразу же хочу предупредить, что включать BranchCache на серверах просто так – не нужно, потому что добавление в ответ клиенту списка хэшей увеличивает сетевой трафик, и если клиент не понимает этих данных, то доступ к файлам лишь замедлится. Притом первичный доступ замедлится достаточно заметно – представьте себе, что на общей папке лежит большой файл в несколько гигабайт – вот при первом обращении к нему надо будет (если файловая система, на которой он лежит, не ReFS – там это уже сделано) посчитать хэши всех его блоков и для начала отправить клиенту этот дайджест.

Ставим компонент BranchCache for Network Files

Данный компонент отвечает за дополнительную функциональность для SMB shares. Добавить его просто, он внутри базовой роли File and Storage Services:

После его добавления включим отправку BranchCache-хэшей на новой общей папке, используя интерфейс Windows Server 2016:

и

Можно, безусловно, и просто включить на существующей – учитывайте только, что механизм включается на папке целиком, и будет возвращать BranchCache-данные при обращении к любому её элементу.

ОК, но это лишь включение – давайте настроим SMB-ресурс, чтобы BranchCache работал качественно и предсказуемо.

Настройка BranchCache на файл-сервере

Настройка SMB-параметров начнётся с раздела Computer Configuration / Administrative Templates / Network / LanMan Server . Первый параметр – Hash Version support for BranchCache. Он скажет, какие хэши генерить в ответе клиенту. Здесь, в отличии от клиентской настройки, можно будет выбрать генерацию и V1 и V2-хэшей. Это удобно, потому что один сервер, раздающий контент, может одновременно генерить данные и для Vista / Windows 7 / Windows Server 2008 R2, и для более новых систем. Помните, хэши генерятся именно на content-сервере – остальные лишь кэшируют блоки данных с этими хэшами – поэтому данная настройка удобна для гибридных сценариев (хотя, конечно, первичное обращение клиента в случае включения и V1 и V2 замедляется):

Теперь выберем режим работы BranchCache – настройка позволит глобально включить BranchCache на всех общих папках, а не только на тех, которые указаны явно:

ОК, в общем всё – теперь настроим для другого вида контента, BITS / HTTP / HTTPS.

BranchCache на web-сервере

Здесь всё будет даже проще, чем с SMB.

Ставим компонент BranchCache для веб-сервера

Для работы с HTTP-содержимым нам надо будет установить на контент-сервер другой компонент:

После установки убедитесь, что сервис BranchCache запущен и работает:

Всё ОК – теперь BranchCache, если вы используете Distributed Cache, настроен – но если используете режим Hosted Cache, то теперь надо настроить сервера кэширования. Приступим.

Настройка выделенного сервера кэширования BranchCache – Hosted Cache

Настройка будет двух вариантов – для первой версии BranchCache и для современной, которая используется в Windows Server 2016 и Windows 10. Первая версия настраивается чуть дольше – ей нужно настроить сертификат для контента, вторая же не требует сертификата. Общим действием для всех версий будет установка компонента BranchCache (так же, как мы делали для веб-сервера) – поэтому не буду повторяться (хотя добавлю – можно поставить его и через PowerShell, вот так – Install-WindowsFeature BranchCache -IncludeManagementTools

Настройка BranchCache Hosted Cache для Windows Server 2008 R2

В сценарии с выделенным сервером необходимо, чтобы сервер мог подтвердить свою подлинность клиентам. Это делается путём привязки одноги из сертификатов в локальном хранилище сервера к службе BranchCache. Сделать это несложно. Зайдите на сервер, который держит роль Hosted Cache, откройте локальное хранилище сертификатов для компьютера, выберете там тот, который содержит Server Authentication в поле EKU (c OID=1.3.6.1.5.5.7.3.1) – он будет доверенным для клиентов, выберите у него поле Thumbprint и скопируйте куда-нибудь хэш (например, в блокнот), а после выполните команду:
netsh http add sslcert ipPort=IP-адрес, на котором слушаются запросы BranchCache : номер порта certhash=значение поля Thumbprint у сертификата appID={d673f5ee-a714-454d-8de2-492e4c1bd8f8}

Здесь appID – GUID службы BranchCache, а IP-адрес будет нужен только если вы не хотите, чтобы клиент с несколькими L3-интерфейсами работал по всем адресам – если хотите, то поставьте адрес 0.0.0.0. Теперь BranchCache “знает”, какой сертификат предъявлять клиентам, подключающимся по HTTPS для синхронизации содержимого.

Настройка BranchCache Hosted Cache для Windows Server 2012 R2 и Windows Server 2016

Ничего привязывать не нужно – зато можно зарегистрировать в Active Directory свой SCP, чтобы клиенты могли нас найти. Если нам это не надо – просто запустим работу:
 
Enable-BCHostedServer
 
Если надо (т.е. клиенты будут использовать механизм поиска в Active Directory):
 
Enable-BCHostedServer -RegisterSCP
 
Windows Server 2016 запретит нам делать это действие, если мы пытаемся поднять роль Hosted Cache на DC – учитывайте это при планировании.
 
В общем всё – развёртывание завершено. Можно поговорить про дополнительные интересные функции.

Тюнинг BranchCache

Базовое развёртывание со всеми деталями завершено – а теперь чуть-чуть про доп.настройки.

Смена номеров портов у BranchCache

Эта операция нужна для сценария Hosted Cache – и будет выполняться в два этапа – смена портов со стороны сервера и со стороны клиентов. Хитрость в том, что в Hosted Cache используются оба web-порта – и 80й, и 443й, но для разных задач – по 80му порту клиенты скачивают с сервера данные (т.н. “Retrieval Protocol Port”), а по 443му – заливают ему недостающие в его кэше блоки (т.н. “Hosted Cache Protocol Port”). Поэтому смена будет выглядеть так – со стороны сервера меняем значения этих ключей:
 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PeerDist\HostedCache\Connection\
 
и
 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PeerDist\DiscoveryManager\Connection\
 
В каждом из них создаём параметр ListenPort типа DWORD32 и указываем новые значения – первый ключ отвечает за Hosted Cache Protocol, т.е. там тот порт, который вместо 443го, а второй ключ – за Retrieval Protocol, там тот порт, который вместо 80го. Менять можно и один – сервисы конфигурируются независимо.
 
У клиентов ключи те же, но другой подключ:
 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PeerDist\HostedCache\Peers\Connection\
 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PeerDist\DiscoveryManager\Peers\Connection\
 
Там создаём параметр ConnectPort типа DWORD и указываем новые номера портов.
 
После всех этих манипуляций надо будет обязательно перезапустить сервис Branchcache – PeerDistSvc (и на клиентах, и на сервере), можно например так: net stop peerdistsvc && net start peerdistsvc

Дефрагментация кэша у сервера BranchCache

Кэш BranchCache тоже может фрагментироваться – и это снижает его быстродействие. Для хранения данных BranchCache в сценарии Hosted Cache (только в нём – в остальных вариантах – просто каталог) используется механизм ESE – тот самый MicrosoftJet (который и в DHCP сервере, и в WINS’е, и в ADDS, и даже в Exchange) продвинутой версии – поэтому у него так же, как и у упомянутых сервисов, будет возможность онлайн-дефрагментации. Запустив команду
 
Set-BCCache -Defragment
 
вы дефрагментируете кэш. Это можно делать по расписанию, допустим, раз в сутки, создав работу в стандартном scheduler’е Windows Server.

Ускорение первого ответа у контент-сервера BranchCache

Про эту проблему я уже писал выше – суть проста; самый первый запрос файла подразумевает, что до начала отправки клиенту заголовка с хэшами надо:

  • Загрузить файл для прикидок, на какие куски его выгоднее поделить
  • Посчитать хэши блоков

В случае больших файлов и загруженных серверов это может вызвать приличные лаги. Вариантов решения несколько:

  • Используйте дедупликатор Windows Server (начиная с 2012). Он генерит такие же хэши, как и BranchCache, и первое обращение становится таким же быстрым, как и следующие
  • Используйте ReFS – там тоже генерятся хэши от частей файлов и их тоже может использовать BranchCache

Безопасность BranchCache

Система сама по себе спроектирована грамотно – ни клиент, ни кэширующий сервер Hosted Cache не может сам создать или добавить контент – список хэшей всегда запрашивается у контент-сервера и является аксиомой. Можно лишь добавить некоторые дополнительные ограничения для безопасности.
 
Если вы хотите, чтобы к серверу Hosted Cache могли подключаться только клиенты из его Active Directory, то включите доменную аутентификацию:
 
Set-BCAuthentication –ClientAuthenticationMode Domain
 
Если в вашем регионе два сервера Hosted Cache в кластере, то они будут кэшировать данные с контент-сервера независимо. Чтобы этого не происходило, надо задать им одинаковый preshared secret – тогда хэши сегментов будут генериться одинаково и совпадать:
 
Set-BCSecretKey -Passphrase atraining.ru
 
Если на этот момент запутались с хэшами, то всё просто:

  • Контент-сервер рубит файл по мелким блокам, и от каждого считает хэш SHA-256;
  • Когда много мелких блоков готовл, делается HoD – Hash of Data – это хэш от всех хэшей части мелких блоков;
  • Из него вычисляется Segment Secret – берётся HMAC-функция от HoD и серверного preshared secret;

Поэтому для того, чтобы исключить возможность подделки данных со стороны недобросовестных клиентов (ведь клиент может в своём кэше поменять данные в блоке, пересчитать SHA-256 и в случае выхода на связь с сервером Hosted Cache и отсутствия у сервера этого блока, сервер заберёт его к себе и будет раздавать другим клиентам), нужно раздать всем серверам Hosted Cache разные секреты.

BranchCache и обновления для Windows 10

Ну вот, мы и добрались до страшных ужасов работы BranchCache для обновлений домашней Windows 10. Говоря просто, теперь BranchCache в Distributed Cache Mode может работать на домашней системе и в случае более чем одного хоста на Windows 10 дома вы просто получите ускорение скачивания обновлений – в случае, как понятно, если хосты в одной IP-сети.

Если вам этого не хочется – выключите этот сервис, да и всё. На клиентских ОС Windows его не получится удалить, т.к. он часть BITS – зато можно зайти в локальные настройки (через gpedit.msc) и выключить.

Думаю, дочитав до этого момента и поняв, что это за технология, вы сильно критичнее станете относиться к крикам про “тайные мистические непонятные схемы кражи данных”. Если копнуть каждое такое непонятное – в основе будет что-то вполне понимаемое, практичное и нужное для работы. Но, учитывая уровень современной IT-журналистики, да и большинства “икспертов” – безусловно, для самопиара лучше что-то погромче и пострашнее – на такое чаще кликают в Интернете.

Ну а так – сами видите, технология полезная и, в случае правильной настройки – очень эффективная.

Удачного применения!

BranchCache Introduction

BranchCache is a WAN optimization technology that is included in some editions of Windows starting from Windows 7 and Windows Server 2008 R2.

How does it work? And what are the modes of operation for such technology? That is what we will be discussing in this post.

First, from client perspective, some editions of Windows have already the BranchCache client. If you go to your services on your Windows, you will see a service called BranchCache.

BranchCache technology is an enhancement of the (Peer Distribution) technology that existed in Windows Vista. In some TechNet pages, you will see this technology referred by (Peer Distribution) instead of BranchCache.

It is important to know that BranchCache will not speed up your YouTube browsing for example or any Internet browsing experience, instead it will speed up your access to internal portals like SharePoint, corporate portals, and it can speed up your access to remote File Shares on your main site. WSUS, SCCM, and SharePoint are famous candidates for this technology.

BranchCache works only with two main protocols [HTTP [including the HTTPS traffic], and SMB [or CIFS] which is the protocol used to access file shares.

So far, we know that you don’t need to install anything on your Windows machines if you picked the right edition, and that BranchCache will only work for Internal HTTP (HTTPS) sites and file shares. Now, let us talk about what is required from the server perspective. Your servers that you want your clients to cache content from are called [Content Servers]. Those content servers should be running BranchCache supported Windows server.

Branchcache 1

BranchCache modes of operation

BranchCache Technology operates in two modes:

  • Distributed Cache Mode
  • Hosted Cache Mode

In BranchCache Distributed Cache mode, each machine in the branch will cache content in its local disk, and when another machine in the same site needs to access the same file, it will pull it from neighbor machines.

In BranchCache Hosted Cache mode, you need to install a Windows Server (BranchCache supported Server editions only) in the branch, called Hosted Cache Server. Whenever a client downloads a file from a BranchCache capable server, it will copy the file to that hosted cache server. When another machine wants to download the same file, it will contact the hosted cache server and get it from there.

Distributed Mode

Bob walks at the office 7 AM in the morning, fires up his windows PC and wants to download the company newsletter that is hosted on a remote BranchCache enabled server in the main office. Since he is configured to use BranchCache, his laptop will start downloading identifiers or hashes that describe the data instead of the data itself and those identifiers are so small [Step 1].

So, he pulls down those very quickly (couple of kilobytes), and he uses them to do something called multicast shout, searching for a peer on the local subnet in the branch that has already downloaded that data [step 2]. But since he is the first one who views this content, he shouts, nobody there, so he goes back to the WAN link and does a complete download of the data [Step 3].

It takes a little bit longer, but once he is done, his computer keeps that data locally so that it can be made available to other peers.

Branchcache 2

Now, 15 minutes later, Alice comes at the office, fires her Windows computer, and tries to access the same newsletter. She downloads the identifiers [Step 4], does a multicast shouts [Step 5]. Bam… finds Bob PC, and downloads the content very quickly [Step 6].

You can see that you don’t need to have any servers in the branch office. All what need to be done, is to enable BranchCache on those branch clients, which can be done easily via group policies.

Keep in mind that you need some disk space on client machines to host cache files, and some extra processing to reply to cache request from neighbor machines. Also, you can notice that cache availability in the branch will drop when laptops go offline or hibernate. The more computers in the branch, the more available content on site, the more multicast shouts and replies. When you have large site with a lot of machines, going to the hosted cache BranchCache mode would make more senses.

Hosted Mode

Hosted Cache Mode for BranchCache requires an Enterprise Edition of Windows Server 2008 R2 or Windows 2012 (called Hosted Cache Server) in the branch office. Any client which downloads a file from a BranchCache capable server, will share this file with the hosted cache server, so other machines on the branch can benefit from.

So, how does it work? As seen in the figure below, Bob shows up early, poor Bob. He goes to view that company newsletter, pulls the identifiers [Step 1].

Branchcache 3

This time, instead of doing that multicast shout, he does a unicast query for the hosted cache server and asks, do you have this stuff that I want [Step 2].

The hosted cache Server doesn’t have that content as no body downloaded it yet. Bob goes back to that WAN link, downloads the whole file, and once he is done [Step 3], his PC advertise the fact he got that newsletter to the hosted cache Server, and pushes up the identifiers [Step 4].

In some point then, the hosted cache server connects back to him and pulls down the data, so it can be available to other users in the branch [Step 5 and 6].

Alice 15 minutes later, fires her PC, tries to download the same company newsletter, downloads the identifiers [Step 7], searches the hosted cache server, and gets the data fast from there [Step 8 and 9].

One of the advantages of this mode of operation, is that all cache content on the branch is available on the hosted cache server, and it will not consume disk space on client machines.

Another advantage is that the since this mode of operation doesn’t depend on multicast shouts, but on unicast traffic, clients on different subnets can benefit from the cache server. For example, if you have a branch office that has machines on different subnets, then you may consider this mode of operation. Also, content will be always available, even if many machines are turned off, as the content is now hosted on the cache server.

The only disadvantage of this mode of operation, is that you need to have a server on the branch office that is running Windows 2008 R2/2012 Enterprise Edition.

HTTP Integration

How BranchCache works with http traffic? And how things really work when you cache http(s) traffic? This is what we will be discussing here. Let me tell you a story.

The picture shows the networking stack on the client machine, and on the server side. On the client, we have IE, which makes use of wininet, which is one of the client http stacks that ships with Windows, and below that we have the BranchCache service.

The client opens IE, you know Bob, going to view that company newsletter and he is going to open a URL. IE makes use of wininet component which is BranchCache capable, and here we make our http get which is transmitted across the wire, hits the web server and interrupted by http.sys which is BranchCache capable [Step 1 and 2].

Branchcache 4

What we are doing here, is making a normal http request, only marking it as BranchCache capable. So, the web server says (hey this client knows BranchCache, so I am going to send him some hashes rather than the full data). Http.sys gets the data from IIS [Step 3 and 4], uses those Peer distribution APIs, and sends the data to the BranchCache service [Step 5] where it cuts them into chunks [Step 6], and calculates hashes for those chunks. After that, those hashes are sent to http.sys [Step 7] which replies to the client with BranchCache response that contains something called (content information structure), which is a list of all hashes describing those chunks of the data [Step 8].

On the client side, wininet gets that, and remember it is BranchCache capable, so it uses those Peer Distribution APIs and goes down to the BranchCache Service [Step 9].

BranchCache service looks for that data on a peer computer or a hosted cache server depending on how the client is configured [Step 10]. Once we get the data, we verify it across the list of hashes we get from the web server and we pass it up to wininet and back to IE [Step 1 and 12].

SMB Integration

BranchCache is hocked in the Client Side Caching (CSC) component on SMB (same component that allows us to use offline files technology) and it is the integration point for BranchCache. So, what happened when a client makes a BranchCache SMB request?

The application makes a read file operation on a remote SMB server [Step 1] and that is intercepted by the CSC driver. A request is then made to the CSC service to go and pre-fetch the file that the app is looking for.

Branchcache 5

CSC service will then go and pre-fetch the hashes of the file instead of the complete file [Step 2 and 3].  The cache download is going to happen over the SMB protocol. We are going to download hashes instead of data. The server will then will try to pull those hashes from a cache hash [Step 4].

Hashes come back to the client [Step 5], to the CSC service, and then Peer distribution APIs are called so we can find the data on a peer client or on the hosted cache server. After the content is retrieved from a peer client or hosted cache server, we will supply it back to the CSC driver, then to the APP, and finally we will put it in the CSC cache [Step 6 and 7].

Subsequent access to the same file is served from the CSC cache and not the branch cache.

Now back to the point where “Hashes on the file server are stored on the hash cache”. There are different ways to fill it up. There is a service that will calculate hashes when the CPU utilization is low on the server and the second way is using a tool called HashGen that you can run against the share and it will force generation of those hashes.

Note

The first time that a file is requested from a file share or web server, it must generate hashes of the data as they are moving through the network stack. Generating hashes is not that big deal, but does take a little of time, so we don’t hold up a client requesting a file just to generate hashes. We will give him the data right away and we will calculate hashes as the data is moving through the network stack. So, if you are going to play with BranchCache, remember that the third hit is when you will notice some improvement.

BranchCache Deployment

We will talk about how we can deploy BranchCache. First all workstations should be running supported version of Windows. The content server (your IIS or File Server) should be running BranchCache supported version of Windows Server.

After that, we need to install the optional Windows BranchCache component on the Windows web or file server on the main site (those are called Content Servers). This can be done by going to Add Features and choose “Windows BranchCache” component for web servers, or “if we are talking about file servers”, by going to File Services from Server Manager, choose “Select Role Services” and click “BranchCache for network files”.

For BranchCache clients to operate on a distributed cache mode, a GPO should be applied to configure the clients to act as BranchCache clients. We can also configure the percentage of disk space that BranchCache files will consume on the local disk (by default 5%).

For BranchCache in hosted cache mode, we need the hosted cache server to be running supported version of Windows. This is a big limitation as you need to license an Enterprise Edition of Windows for the branch hosted cache server. The hosted cache server also requires a digital certificate so that clients can authenticate it before downloading cache content.

BranchCache group policy is the best way to configure clients to use this technology. A client can only be operating in either Distributed Cache mode or Hosted Cache mode but not both. The below figure shows how GPO can be used to enable BranchCache on clients and choose the mode of operation. If Hosted Cache mode is selected, then you need to type the FQDN of the Hosted Cache server existing in the branch. You can also set the percentage of the local disk that can be used for cache content in case you are using Distributed Cache mode.

Branchcache 6

Blocks, Segments and Hashes

We will dig inside BranchCache technology and describe how the content server will cut the data into blocks and generate hashes that are required for BranchCache to function.

The content servers (your Windows web server or file share) are the source of the data that need to be cached. Think of it as the SharePoint nodes or your WSUS server.

Content servers will divide data into Segments that are big in size, and then will generate hashes for each segment (S1, S2…etc.). Segments are unit of discovery, and when a BranchCache client wants to access any file, it will download those segment hashes, and uses them to ask neighbor peers or the hosted cache server: “does anyone have a file that is structured from segments with hashes S1,S2….Sn? “.

Segments are also divided to smaller units called Blocks, and hashes for those blocks are calculated on the content server and returned to the clients (B1, B2,,etc). Once a BranchCache client gets a reply from a source on his branch that it has data with segment hash S1 for example, it will download the blocks (B1, B2…Bn) that construct that segment.

Think of segments as unit of discovery and Blocks as unit of download from neighbor clients.

So why do we have segments and each segment is divided to Blocks? We need the unit of discovery to be big in size so that we don’t flood the network with discovery packets. That is why we use hashes of segments to describe data. For example, if a file is 100k in size, and the segment size is 25k, then the file is divided to 4 segments and we only need to send 4 multicast discovery packets in the local branch subnet to discover that data (in case of distributed cache mode).

Once that 100k file is discovered, and if the block size is 5k in size, then we will download the 5*4 blocks from the cache source in the branch (each segment contains 5 blocks and we have 4 segments).

The reason why we use blocks to download data instead of segments, in case a source cache machine went down for any reason, we will still download other blocks from another source without losing much data because the block size is small in size.

Branchcache 7

After Deployment

 After you have deployed BranchCache in your network, how can you measure or confirm that it is working, and how can you troubleshoot BranchCache issues after deployment?

There are amazing performance counters in Windows client that can tell you exactly how your BranchCache deployment is behaving.

Just go to your Start icon, type PerfMon, and the Performance Monitor snap in will open, click on Performance Monitor icon, then right click any empty area in the middle pane, and chose Add Counters. Now scroll to BranchCache, and choose all the sub counters and then click Add and OK.

Then change the Graph Type to Reports as shown in the below figure. Watch those counters:

  • Bytes from cache indicates the amount of data that the client retrieve from a neighbor peer of from the Hosted Cache server.
  • Bytes from server, is an indication of data moving across the WAN.

Branchcache 8

Another effective way to configure and monitor your BranchCache activity and behavior is by using the netsh BranchCache command.

Open a command window, and type the following command. This will show you a summary of the BranchCache settings on that client..

netsh branchcache show localcache

You can also flush the BranchCache content cache on your client Windows  machine by typing the following command on elevated cmd:

netsh branchcache flush

To see if the Windows  machine is configured with BranchCache and to know in which mode it is operating, type:

netsh branchcache show status

Branchcache 10

As you can see form the output, the first line is showing that the client is configured with BranchCache in Distributed Cache mode.

The second line shows that this machine (which happened to be a laptop), will not serve clients from its cache if it is running on battery power, so that your laptop will not run out of power while processing BranchCache requests from neighbor peers.

The last line shows that the BranchCache service is running which does not necessary indicates that the client is configured with BranchCache. Only the first line from the output indicates that this client is configured with BranchCache.

BranchCache file location

We will be talking about some parameters to consider when deploying BranchCache. Mainly where the cache content files are stored.

Clients will always store cache files + the hashes of those files that describe the data in the following location: C:\Windows\ServiceProfiles\NetworkService\AppData\Local\PeerDistRepub.

To change this location on your Windows  BranchCache clients, use this command:

netsh branchcache set localcache directory=D:\MyCacheFiles

Now The size of that cache is by default 5% of the whole hard disk, to change the max size of cache content, use one of those commands:

To change the cache size to a fix value in bytes, type:

Netsh branchcache set cachesize 20971520

To change the cache size to a percentage of disk space, type:

Netsh branchcache set cachesize size=20 percent=TRUE

Now, let us move to the content servers (your WSUS and file shares). Those content servers will generate hashes for their content, so that BranchCache clients can download them instead of the whole content. The location of those hashes is called (Publication Cache). By default, it is under %WINDIR%\ServiceProfiles\NetworkService\AppData\Local\PeerDistPub.

To change the location of the Publication Cache, use this command:

netsh branchcache set publicationcache directory=D:\BranchCache\

By default, Publication Cache will consume 1% from the hard disk. To change this number, use one of the following commands:

Netsh branchcache set publicationcachesize 20971520 

Netsh branchcache set publicationcachesize size=20 percent=TRUE

Note

If a BranchCache client wants to access a remote file share, the BranchCache will sense the latency to the remote file share server. If the latency is below 80 ms (default value), then the client will not use BranchCache. This is only applicable for accessing remote file shares and note web sites (not applicable for http or BITS traffic).

To change this value, run this command to configure the SMB latency to 20 ms for example:

Netsh branchcache smb set latency latency=20

 Another important note that laptops on battery will not participate in BranchCache if it is participating in Distributed Cache mode. This is the default behavior to preserver power.

Content Server Hashes

As explained before, content servers are those servers with content that you want to cache content from. Examples are you WSUS server or file share servers.

Those content servers will generate hashes for content that is requested only. So, when the first client requests a certain file, the file is downloaded completely and the hashes start to generate on the server. You need three different clients to request the same file to start getting benefit from BranchCache.

Also note that hashes are generated for files bigger than 64k in size, so you will not benefit from BranchCache when dealing with files less than 64 in size.

Hashes on the content servers will be lost or deleted if the BranchCache service restarted. BranchCache service will then start generated hashes again when files are accessed.

 Q: What are the requirements for clients to participate in BranchCache Technology?

A: Clients should be running supported edition of Windows and have the BranchCache local service set to Automatic. After that, the clients should be under the scope of a group policy that will enable them for BranchCache and will open couple of local Windows firewall exceptions.

Q: What are the requirements for my WSUS server or file server so that clients can cache content from?

A: Your WSUS or your file server, are called (Content Servers) and should be running supported edition of Windows. You then have to go and add the feature that is called (BranchCache) from the Add Features Wizard.

Q: Do I need to open anything on my firewalls or to contact my ISP provider for any changes in order to deploy BranchCache?

A: Absolutely NO. The clients will use native original ports when connecting to your WSUS/IIS/File servers.

Q: In Distributed Cache mode, clients will cache content locally on their hard disk. Can you tell me more and will it fill up the client hard disk?

A: By default, clients configured for BranchCache in Distributed Cache mode will download content on the C drive of their hard disk under “C:\Windows\ServiceProfiles\NetworkService\AppData\Local\PeerDistPub”. By default, BranchCache will only consume 5% of the total disk space. Make sure that you have enough space on your C drive to handle cache files. When those 5% are consumed, BranchCache service will start overwriting old content (least accessed).

 Q: If my machines are using BranchCache, is it possible that they may get old cached data from neighbor peers?

A: NO. You will never ever get old data. BranchCache is designed to ensure it can work perfectly even with the most dynamic web sites that have content changing very quickly. The reason why this is true, is that clients will always connect to the live web site or share, get the newest hashes, and then requesting it from its neighbor machines if they have such data in their cache.

Q: If the main link between the branch and the main site is down, will my branch machines continue getting cached content from their neighbor peers?

A: NO. Because each machine should connect to the content server first that is located in the main site, to get those hashes that describe the data, before requesting the complete data from neighbor peers.

Q: What should I do if I want to troubleshoot a problem from my BranchCache client that cannot access a certain internal web site or file share? How can I temporarily disable BranchCache on that machine so I can troubleshoot the problem?

A: Just stop the BranchCache Service, troubleshoot your problem, and then enable it again.

Q: What do you recommend: Distributed Cache mode or Hosted Cache mode?

A: Well, it depends .Hosted Cache mode is excellent if the branch office has more than 50 machines (numbers are changed in Windows 8) because you don’t need to consume disk space on branch machines or introduce slight processing overhead on their machines for replying to BranchCache requests from neighbor machines. But this requires that you install a server in the branch site with BranchCache supported edition from Windows Server.

Finally, always remember to have your Windows client machines with good space on their C drive just in case.

Q: Is it possible for neighbor machines to request access to cache content on my machine without being authorized to do so?

A: NO. Because each BranchCache client will encrypt the data with a unique key that is shared with the content server. So neighbor machines should connect to the content server first, authenticate, get that encryption key, before asking your machine for cache content.

Q: I am concerned about security and I am not sure if I can trust such technology and have sensitive files cached everywhere.

A: Take it easy. We didn’t mention everything yet. BranchCache security is a long and complicated topic that I will be very pleased to discuss it with you if you drop me an email, and I will explain to you how BranchCache uses effective cryptography to protect data. For now, just take it from me: IT IS SECURE.

Q: What will happen if the BranchCache service fail to download content from neighbor peer or from the content server?

A: When BranchCache is unable to retrieve data from a peer or from the Hosted Cache, the upper layer protocol will return to the server for content. If a failure occurs in the Branch Caching component, the upper layer protocol should seamlessly download content from the server. No BranchCache misconfiguration or failure should prevent the display of a webpage or connection to a share.

Before you start

Objectives: Learn what is BranchCache and how we can use it to speed up data transfer over WAN links from branch to central offices.

Prerequisites: you have to know what is WAN.

Key terms: BranchCache, definition, configuration, netsh, Group Policy


 What is BranchCache

When we have branch offices, we automatically have a challenge for providing good quality connection with the central office. BranchCache helps to cope with those challenges. BranchCache caches (stores) content from remote servers (e.g. file and web servers), so users from branch offices can access information more quickly.

The BranchCache feature is only available on certain versions and editions of Windows. For example, when it comes to Windows 7, it is only available in Enterprise and Ultimate editions. Also, it can only cache content from certain Windows Servers (file and web servers). BranchCache becomes active when it takes more than 80 ms to get to the BranchCache-enabled Windows Server and back. The transfer is protected using HTTPS and IPsec encryption.

Several checks will occur when the client uses BranchCache. The client verifies that the Server hosting the requested data supports BranchCache. Then it checks the round trip time to make sure it is less than 80 ms. Once these are verified, the client checks the branch office cache to determine if the requested data has already been cached or not, and if the client has permissions has access to it. If the data is not already cached, the data is retrieved from the main server and cached in the main office.

BranchCache Modes

BranchCache can be configured to operate in two different modes. Those are:

  • Hosted Cache – the data is centrally cached on a BranchCache-enabled server running Windows Server (hosted cache server). The server doesn’t necessarily need to be dedicated to BranchCache. It can be used for other functions. In Hosted Cache mode, the cache is always available. We need to designate the address of this server on the clients. For this mode we have to have AD Certificate Services infrastructure running.
  • Distributed Cache – if we don’t have Windows Server with BranchCache capabilities, we can use Distributed Cache mode. In this mode, parts of the cache are stored on different clients (peer caching). This means that each client that is a member of the Distributed Cache mode hosts part of the cache. No single host caches all the files. When a client retrieves content over the WAN, it places this content in its own cache. If another BranchCache client attempts to access the same content, it will be able to access it directly from that first client, rather then retrieve it from over the WAN. Also, it will make a copy of that information into its own cache. The advantage of this mode is that we can deploy it without having a dedicated server in each branch office. The drawback of this mode is that the content of the cache can become unavailable if the clients hosting them shut down. So, in this case, the cache depends on the running clients. It is used in single subnet (data is cached once per subnet).

BranchCache Configuration

To configure our computer as a BranchCache client, we first have to enable it. Then we have to select if we want to use Hosted or Distributed Cache mode. Finally, we need to configure Windows Firewall to allow BranchCache traffic. The rules we open in firewall depend the mode we choose.

We can configure BranchCache trough Group Policy or by using the Netsh.exe command line tool. Some of the Group Policy settings related to BranchCache are:

  • Turn on BranchCache – enables BranchCache and configures the BranchCache service to start manually when we attempt to access data on a compatible server that exceeds the round trip time of 80 ms.
  • Set BranchCache Distributed mode – sets the client to use Distributed Cache mode.
  • Set BranchCache Hosted mode – sets the client to use Hosted Cache mode. In this mode we have to specify the server name that hosts the cache. This must match the name in the SSL certificate installed on the server.
  • Configure BranchCache for Network Files – allows us to specify the round trip latency value that triggers the use of BranchCache. The default value is 80 ms.
  • Set Percentage of Disk Space – allows us to configure space that is used to store BranchCache files. Default is 5% of total disk space on client computer.

Firewall Rules

We need to configure firewall rules only when we configure BranchCache trough Group Policy. We can use the predefined firewall rules for BranchCache. Regardless of the method we choose, we need to configure the following rules using Windows Firewall Advanced Security Snap-in:

  • BranchCache-ContentRetrieval – the rule which allows inbound and outbound HTTP traffic on TCP port 80. It is used for both Hosted and Distributed Cache modes.
  • BranchCache-PeerDiscovery – allows the inbound and outbound traffic on UDP port 3702. This rule is only required when using Distributed Cache mode.
  • BranchCache-Hosted Cache Client – allows the outbound HTTPS traffic on port 443 using TCP. This rule is only required when using Hosted Cache mode.

Netsh.exe

As we mentioned, we can use netsh.exe to configure BranchCache. When we use netsh.exe, necessary firewall rules will be automatically enabled. Any configuration set using netsh.exe, will be overwritten by Group Policy settings. We need to use elevated CMD when using netsh command to set BranchCache. Some of the common “netsh branchcache” command options are:

  • -reset – resets the current BranchCache configuration. It will stop and disable the service, reset registry values, delete any cache files. It also disables BranchCache firewall rules. We can use it if we don’t want to use BranchCache any more.
  • -show status – displays the current service mode being used, how it was configured, and the status of the service.
  • set service mode = {distributed | local | hostedclient | disabled } – sets the cache mode. If we set it to “distributed”,  it sets the client to use Distributed Cache mode, starts the BranchCache service, changes the startup type to manual, and sets firewall rules. If we set it to “local”, it sets the client to Local Cache mode. It doesn’t enable any firewall rules. In Local mode, client stores data from WAN in local cache, without sharing it with other clients on the network. This mode is only available trough netsh command. If we set it to “hostedclient” mode, we have to specify the location parameter with the IP address or the name of the server which hosts the cache. This command sets the client to use Hosted Cache mode, enables BranchCache service, and sets firewall rules. If we set it to “disabled”, it will disable BranchCache.
  • -set cachesize – allows us to set the size of the local cache as a percentage or in number of bytes.
  • -set localcache – allows us to set the location of the local cache on our computer.

Keep in mind that BranchCache service startup must be set to manual and not automatic. The service will automatically start itself any time it needs to access the BranchCache data.

Examples

What is BranchCache?

BranchCache is a feature in Microsoft Windows operating systems that enables faster access to files and data in branch office environments. It allows remote offices to cache content from a central server, reducing the need for data to be constantly transmitted over the network.

What are the benefits of using BranchCache?

By using BranchCache, you can significantly reduce the amount of data transferred over the wide area network (WAN), resulting in improved network performance and reduced bandwidth consumption. It also enhances the user experience by providing faster access to frequently accessed files and data.

How does BranchCache improve the efficiency of network data transfers?

BranchCache improves the efficiency of network data transfers by reducing the amount of network traffic that needs to be sent over a WAN or VPN. When a file or document is accessed for the first time, it’s retrieved from the main server and a copy is stored in the local BranchCache. Subsequent requests for the same data can be served from this local cache, instead of retransmitting the data across the network. This decreases the load on the network, reduces latency, and increases the speed of data access for end users.

Can BranchCache work with any type of content?

BranchCache is compatible with a wide range of file types, including documents, images, videos, and software updates. It can be used with any application or service that relies on file transfers over the network.

When should I consider implementing BranchCache in my organization?

BranchCache is particularly useful in scenarios where there is limited bandwidth between a central office and remote branch offices. If your organization has frequent file transfers or relies on accessing centralized data from remote locations, implementing BranchCache can significantly improve network performance and user productivity.

Can BranchCache be used in combination with other network optimization technologies?

Yes, BranchCache can be used with other network optimization technologies to enhance network performance. For example, it can be combined with wide area network (WAN) optimization solutions to reduce bandwidth usage and accelerate file transfers across the network.

What security measures are in place when using BranchCache?

BranchCache incorporates several security measures to ensure the integrity and confidentiality of cached content. This includes the use of cryptographic hashes to verify the integrity of data, encryption of content during transmission, and access control mechanisms to prevent unauthorized access to cached files.

Can BranchCache be used in a hybrid cloud environment?

Yes, BranchCache can be utilized in a hybrid cloud environment. When branch offices have access to both on-premises servers and cloud-based resources, BranchCache can cache content from both sources, improving performance for users accessing data from either location.

Does BranchCache work with encrypted files?

BranchCache is compatible with encrypted files, whether they are encrypted at the file level or transmitted over a secure connection. However, it’s important to note that BranchCache does not decrypt the files itself. It caches and transfers the encrypted files as they are, so the encryption and decryption processes remain intact.

Can BranchCache help reduce latency in remote offices?

Yes, BranchCache can significantly reduce latency in remote offices. By caching frequently accessed files locally, users experience faster access times without the need to transmit data over the network repeatedly. This reduces the impact of network latency on user productivity and improves overall responsiveness.

Can I monitor the performance and usage of BranchCache in my network?

Yes, you can monitor the performance and usage of BranchCache through various tools and utilities provided by Microsoft. Performance Monitor (PerfMon) can be used to track metrics such as cache utilization, hit rates, and data transfer rates. Additionally, Windows Server includes Event Viewer, which logs relevant events and errors related to BranchCache.

What are the minimum system requirements for running BranchCache?

The minimum system requirements for running BranchCache depend on the version of Windows in use. For client computers, Windows 7 or later is required, while server computers must be running Windows Server 2008 or later. Adequate storage space should be available for cache storage, and network connectivity between the central server and branch offices should be stable and reliable.

Can BranchCache be used in a virtualized environment?

Yes, BranchCache can be implemented in a virtualized environment. Virtual machines can utilize BranchCache to improve file access performance within the virtual environment. However, it’s important to ensure that the underlying virtualization platform supports the necessary networking configurations and that there is sufficient storage capacity for cache storage within the virtual machines.

Does BranchCache work with all file transfer protocols?

BranchCache is protocol-agnostic and can work with various file transfer protocols, including hypertext transfer protocol (HTTP), server message block (SMB), and background intelligent transfer service (BITS). If the file transfer protocol is supported by the operating system, BranchCache can optimize file transfer using that protocol.

Can BranchCache be used in a multi-site environment with multiple branch offices?

Yes, BranchCache is designed to work in multi-site environments with multiple branch offices. Each branch office can have its own local cache, allowing users to access content faster without relying on the central server.

Does BranchCache work with web content accessed through browsers?

Yes, BranchCache can optimize the delivery of web content accessed through browsers. It can cache web objects such as images, scripts, and hypertext markup language (HTML) files, reducing the need to download them repeatedly from the web server.

Does BranchCache support file-level deduplication?

No, BranchCache does not perform file-level deduplication. Its focus is on caching and optimizing the transfer of files, rather than eliminating duplicate file content within the cache.

Does BranchCache work with streaming media content?

Yes, BranchCache can optimize the delivery of streaming media content. It can cache segments of the media stream, reducing the need to repeatedly download the same segments from the media server.

Does BranchCache require any additional network configuration beyond the default settings?

No, BranchCache does not require any additional network configuration beyond the default settings. It works with standard network protocols and does not require special routing or firewall rules.

Would BranchCache benefit small branch offices with only a few users?

Yes, BranchCache can still provide benefits to small branch offices with only a few users. Even in such scenarios, caching frequently accessed files locally can improve access times and reduce network congestion.

When should I use Distributed Cache Mode instead of Hosted Cache Mode?

Distributed Cache Mode is typically suitable for branch offices with a smaller number of client computers, while Hosted Cache Mode is more appropriate for larger branch offices with dedicated cache servers.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 10 profile picture
  • Pause updates windows 10
  • Virtual machine platform windows server
  • Windows ui xaml controls
  • Как зайти в аккаунт администратора windows 10