Windows service volume shadow copy service

Снятие снапшота — именно с этого начинается любой бекап. До тех пор, пока мы не знаем, как сбросить все буфера на диск и привести файлы с данными в консистентное состояние, мы не бекапы делаем, а занимаемся копированием файлов с непредсказуемым содержимым внутри. Понимая важность снапшотов, все вендоры стараются дать нам если не полностью готовую функцию (типа Time Mashine в MacOS), то хотя бы набор ручек, за которые можно подёргать (вроде модуля dm-snap в ядре Linux). 

Но сегодня речь пойдёт про самую распространённую ОС — Microsoft Windows, где эта задача решается с помощью Volume Shadow Copy сервиса, известного в народе под аббревиатурой VSS (Volume Snapshot Service). А нашего внимания он удостоился из-за того, что, несмотря на всю популярность своего материнского корабля, сам он окутан вуалью из тайн и мистических слухов. Давайте уже как-то разберёмся с этой штукой.

А, собственно, что с ним за проблема? Вот есть документация, где вполне адекватно и красиво описано, как всё работает. Есть утилита vssadmin, позволяющая вполне годно создавать и удалять снапшоты. Что не так-то, и где сложности?

Но проблема в том, что более лучшая документация, намного правильнее отражающая происходящие процессы, несколько сложна для понимания. Microsoft вообще написал по этой теме какое-то неслыханное количество документов. Но даже когда вам как-то удаётся выстроить в голове работу этого алгоритма, вы сразу сталкиваетесь с тем, что на практике многие вещи работают совершенно не так, как описаны. Или вообще не работают. А что-то не описано совсем, хотя этому мы уже давно не удивляемся. Но не хвататься же сразу за дебагер и дизассемблер, да?

Хотя упомянутый выше vssadmin как-то вроде и работает, и снапшоты даже делает, и вообще молодец. Но это всё до того момента, пока ты не начинаешь вникать в тонкости, где может выясниться, что репорт об успешно созданном снапшоте — это репорт о чём угодно, только не об успешно созданном снапшоте.

Вот поэтому и захотелось немного поговорить о том, как же на самом деле работает VSS. И да, строго говоря, результатом работы VSS является созданная shadow copy. Но дабы не ломать язык и не мучить вас транслитом, давайте просто писать снапшот.

Какова роль VSS

Не сомневаюсь, что 90% читающих прекрасно понимают, зачем нужны снапшоты, но ради оставшихся 10% потерпите несколько предложений. Или сразу идите в следующий раздел.

Итак, все кто остался, давайте представим, что есть у нас некий диск, на котором находятся файлы, с которыми кто-то работает и как-то их изменяет. Изменения эти накапливаются, а иногда очень хочется иметь возможность взять и вернуться во времени назад. И желательно откатывать изменения не для всего диска, а только для выбранных папок и файлов. Для этого и был придуман механизм теневых копий.

Сами снапшоты ничего не знают про ваши файлы и папки. Они работают на уровень ниже файловой системы — с блочными устройствами и блоками данных. Если придерживаться терминологи Microsoft, то снапшот — это место, именуемое Shadow Storage, куда записываются изменённые блоки данных и откуда их можно извлекать с целью переписать данные на оригинальном диске. Тут можно запомнить для себя два нюанса. Первый — только что сделанный спапшот занимает ровно ноль байт. Это просто пре-алоцированное место, куда файловая система может копировать измененные блоки (или наоборот, новые блоки, но не суть).  И второй — теневая копия суть есть дифференциальный бекап. Все данные, которые вы изменили, не удаляются, а отправляются на хранение в этой зоне.

Где найти VSS

Обнаружить следы VSS можно двумя классическими способами: через GUI или в консоли. В зависимости от конкретной версии системы пути могут немного отличаться, но суть будет одинакова. Итак, есть у меня в лабе Windows Server 2019, и если сделать ПКМ на любом диске в проводнике, мы увидим два пункта: Configure Shadow Copies и Restore previous versions.

Если зайти в мастер настроек, то можно включить создание теневых копий для любого диска, задать расписание, по которому они будут создаваться и, что самое интересное, указать место хранения этих копий. Строго говоря, даже не самих копий, а так называемой diff area — места, куда сбрасываются перезаписанные на оригинальном томе сектора. То есть мы запускаем создание снапшота одного диска, а его данные физически храним на другом. Функция архиполезная и позволяет не просто снижать нагрузку на конкретном диске, но и делать фокусы а-ля снимаем снапшот одной ноды в кластере и цепляем его к другой.

После того, как вы всё настроите на свой вкус, появляется смысл в пункте Restore previous versions. Чисто технически туда и до этого можно было зайти, однако внутри, скорее всего, будет только гнетущая пустота. 

Но всё это баловство с графическим интерфейсом, и как мы знаем, до добра это не доводит, поэтому открываем powershell (или даже cmd, почему нет) — и там у нас имеется два варианта из коробки: vssadmin и diskshadow. Первая утилита есть практически на любой системе, начиная с WinXP/Win2003. Нет её только на Windows 8. По какой-то таинственной причине из “восьмёрки” вырезали инструменты управления теневыми копиями, но потом осознали свою неправоту и вернули всё на место. А вот diskshadow доступен только на серверных вариантах Windows. Это уже более продвинутый вариант vssadmin, позволяющий работать не только в интерактивном режиме, но и выполнять целые скрипты, написанные на понятном этому интерпретатору языке. Да и просто это более адекватный и поддающийся контролю инструмент.

И запоминаем самое важное: это две разные утилиты, существующие в разных контекстах. Теневая копия, сделанная в одной утилите, будет видна другой, однако статус у неё будет неоперабельный.

Вот отличный пример: мы создали снимок в diskshadow и пытаемся удалить его с помощью vssadmin. Сам снимок мы видим, но он не в нашем контексте, поэтому сорян, у нас нет здесь власти.

Вот отличный пример: мы создали снимок в diskshadow и пытаемся удалить его с помощью vssadmin. Сам снимок мы видим, но он не в нашем контексте, поэтому сорян, у нас нет здесь власти.

Технически ничего не мешает одновременно делать снимки с помощью vssadmin и diskshadow. Хотя есть вероятность, что получите сообщение типа Another shadow copy is in progress. Но это так, к слову пришлось. Не надо пытаться одновременно делать несколько снапшотов разными программами.

Как появился VSS

Итак, судя по написанному выше, всё просто: нам надо просто брать появляющиеся блоки и сохранять их куда-то в сторонку, чтобы при необходимости вынимать обратно. Сразу возникает первый вопрос: а что именно надо сохранять в нашем теневом хранилище? Ведь действительно, можно просто писать в него все приходящие новые блоки и сохранять в метаданные, на какое место они (блоки) должны были быть записаны. А можно поступить чуть сложнее и записывать новые блоки сразу на полагающееся им место, а в хранилище отправлять содержимое перезаписываемых блоков. Что лучше и как выбрать? На самом деле право на жизнь имеют оба варианта, и какой выбрать — зависит исключительно от воли вендора. Первый подход (redirect-on-write, RoW, если оперировать грамотными терминами) быстро пишется, но долго читается. Зато если надо откатиться на первоначальное состояние, это делается моментально — мы просто удаляем наше теневое хранилище. Второй подход (copy-on-write, CoW) пишется медленней, читается быстрее и моментально удаляет копии предыдущих состояний. VSS, к слову, придерживается парадигмы CoW, а в снапшотах VMware реализован RoW.

Но на самом деле этот вопрос не самый важный из тех, которые стоит себе задать перед тем, как начать перехватывать появляющиеся блоки и складывать их в сторонке. Главный вопрос — в какой именно момент надо осуществлять перехват?

Давайте рассмотрим хрестоматийную ситуацию с файлом базы данных. (И если у вас уже заскрипел песок на зубах, смело пропускайте следующие два абзаца.) Итак: у нас есть банальная SQL Server база данных в виде mdf файла, и тут к нам прилетает какой-то запрос. SQL, как порядочное приложение, начинает старательно вносить изменения в файл, а мы старательно перехватываем каждый новый блок данных падающих на диск и пишем в нашу теневую копию. Всё хорошо и здорово, но тут выключили свет. Потом свет включили, сервер запустили и мы даже базу восстановили из нашей теневой копии, но тут оказывается, что SQL не запускается. Говорит — база в не консистентном состоянии. Это значит следующее: во время нормальной работы завершение каждой транзакции помечается специальным флагом. Сервер его видит и знает, что всё хорошо. А тут сервер загружается, видит, что из его базы торчит какой-то кусок данных, флага нет и, следовательно, что с этим всем делать — он понятия не имеет. То ли удалить, то ли дописать, то ли ещё что-то. Но у нас тут не угадайка, а всё должно быть однозначно и консистентно. Поэтому он принимает решение выключиться, дабы не поломать базу ещё сильнее.

Хорошо, но как избежать подобных приключений? Отличным вариантом будет подождать, пока SQL сервер допишет свою транзакцию, пометит её как завершённую, и потом мы быстренько заберём все появившиеся новые блоки. Отличный вариант, который надо срочно реализовывать! Вот только есть небольшая проблема: до этого мы говорили про одно приложение и один файл, с которым оно работает. Научиться общаться с условным SQL Server много ума не надо, но что делать с остальными миллиардами существующих приложений? А что делать, в конце концов, с самой ОС, у которой внутри огромное количество своих процессов и открытых файлов? Вот примерно с такими проблемами и столкнулись учёные мужи из Microsoft, когда пришли к выводу, что надо реализовать некий общий интерфейс, через который можно будет сразу всем прокричать нечто вроде: “Сейчас мы будем делать снапшот, так что быстренько сворачиваемся и сбрасываем буфера на диск! Приостанавливайте свою кипучую деятельность и приводите данные в консистентный вид!”. Ну а назвать эту штуку они решили, как вы уже догадались, Volume Snapshot Service. Или просто VSS.

И тут можно воскликнуть — но ведь в Windows 2008 был представлен Kernel Transaction Manager! Это разве не то же самое? Он же как раз занимается тем, что приводит файлы на диске в консистентное состояние. А вот и нет! То есть да, KTM приводит, но отвечает только за дисковые операции, а что там происходит с приложениями — его мало волнует. А ведь многим из этих приложений важна не просто целостность файлов, но и что в них записано. Классический пример — это Exchange и Active Directory. И тут мы подошли к важной теме:

Как устроен VSS

Чтобы не прыгать с места в карьер громады страшных терминов и процессов, начнём с высокоуровневого описания. Поэтому ограничимся таким списком компонентов:

  • VSS Writer. В кириллическом простонародье известен как просто райтер, поэтому так и будем его называть в дальнейшем, вызывая праведный гнев ненавистников англицизмов. 

    Райтер занимается тем, что выстраивает мостик взаимодействия между VSS подсистемой и конкретным приложением. Поэтому а) в любой системе их будет достаточно много (проверьте у себя с помощью vssadmin list writers) б) райтер всегда пишется поставщиком приложения, ибо кроме него никто не знает, что там и как должно происходить во время создания снапшота. 

    Соответственно, райтер по своей сути выполняет роль “регулировщика”: сначала он говорит приложению подготовиться к снапшоту, затем даёт отмашку VSS сервису делать снапшот. Или не даёт, если приложение не смогло за установленный промежуток времени подготовить свои файлы.

    Также хочется отметить, что райтеры — это какие-то невероятно нежные ребята, которые зачастую ломаются без каких-либо внешних признаков. Поэтому если в выводе vssadmin list writers в поле State вы увидите что-то, отличающееся от Stable, это надо чинить, ибо сделать консистентный бекап, увы, не получится.

  • VSS Provider. Тот самый парень, который занимается созданием и управлением снапшотами. Известен тем, что бывает софтовый или хардовый. Список установленных в системе провайдеров можно посмотреть с помощью команды vssadmin list providers. По дефолту, с системой идет Microsoft Software Shadow Copy provider. Он даже отлично и замечательно работает, но до тех пор, пока вы не подключите к системе брендовую СХД. Хорошие вендоры всегда снабжают свои железки управляющим софтом, в составе которого находится и родной провайдер к этой железяке. Благодаря этому можно уже делать всякие хитрые трюки, которые реализованы в вашем оборудовании, и именно поэтому мы в Veeam так гордимся списком интеграций с железом.

  • VSS Requestor. Участник процесса, который инициирует создание VSS снапшота или восстановление данных. Можно сказать, что реквестор — это бекапное приложение, которое общается с райтерами и провайдерами. Может показаться, что его роль незначительна, однако от грамотности реализации реквестора зависит качество получаемого результата. То есть VSS не будет за вас думать, что и в каком виде надо сделать. Чем более чёткие инструкции выдаст реквестор, тем более предсказуемым будет результат.

Как в итоге всё выглядит на самом высоком уровне: реквестор стучится в Volume Shadow Copy сервис, тот отдаёт команду райтерам предупредить приложения о надвигающемся снапшоте, райтеры рапортуют об успехе, а сервис отдаёт команду провайдерам делать снапшоты. О результатах докладывается реквестору.

Но на деле, очевидно, всё несколько сложнее. На первом шаге реквестор проверяет, что вообще есть в наличии и с кем предстоит общаться. Затем после составления списка райтеров он обращается к провайдеру, объясняя, что он хочет заснапшотить и где должен располагаться снапшот. Это называется SnapshotSet. В большинстве случаев он будет располагаться на том же вольюме, что и оригинальный диск. А меньшинство случаев — это те самые хардварные провайдеры, которые поставляются вместе с СХД. Для них нормой считается создавать отдельный вольюм для снапшота, который называется storage snapshot. А в определённых случаях можно так и вообще перемещать снапшот на другое физическое устройство, чтобы выкачивать данные уже оттуда, а не с прода. Без хардварных провайдеров сделать такое не выйдет. 

Следом начинается стадия, именуемая Prepare for backup. На этом этапе мы должны уже не просто изучить метаданные райтеров, а запросить их реальные статусы и приготовиться к самой жаркой поре: все райтеры должы будут отработать один за другим. Причём каждый должен уложиться в отведённое ему время, которое по умолчанию равно 60 секундам. Так решили в Microsoft, забыв уточнить причины. Но есть ещё приложения-чемпионы, например, Exchange. Его авторы посчитали, что 20 секунд более чем достаточно, и остановились на таком лимите. А чем чревато невыполнение этого этапа, который в документации называется OnFreeze? Тем, что райтер вернёт сообщение об ошибке, и снапшот не будет сделан. После чего в интерфейсе Veeam появится одна из каноничных ошибок вроде “VSSControl: Failed to freeze guest, wait timeout». Тут радует одно: в логах VSS всегда будет написано, какой именно райтер завалил задание. А по самим ошибкам уже столько KB написано, что вспоминать страшно. Но если вы вдруг сомневаетесь, то точно вам говорю — написанному в них можно смело верить. И если после всего получается, что у вас слишком медленное хранилище, и за отведённое время не получается сбросить все кэши на диск, ну, значит, так оно и есть. Физику не обманешь, а вот железо надо хоть иногда обновлять.

Но это был пессимистичный вариант (прошу понять меня правильно, но беды с VSS — это очень частная причина обращений в сапорт), а в оптимистичном можно начинать самый важный этап. Как только райтеры рапортуют, что всё, вся деятельность в системе заморожена, а кеши сброшены на диск, у нас есть десять(!!!) секунд на создание снапшота, после чего райтеры будут принудительно разморожены, и всё закрутится вновь. И можно сказать, что на этом процесс бекапа заканчивается, и всё что нужно — это просто импортировать наш снапшот и скачать его куда-то к себе, чтобы сохранить под семью замками. Однако есть одно важное Но — log truncate. Фундаментально это вообще не связанные операции и транкейт зависит только от бекапа логов, но как все мы понимаем — на пользовательском уровне эти вещи связаны в единый процесс. То есть, прежде чем выкачивать снапшот, надо не забыть выдать команду backup log, которая запустит операцию транкейта. И после этого совесть наша чиста.

Но что дальше происходит с данными? Если мы действительно используем какое-то приложение для бекапов, которое запустило весь этот процесс, дождалось его завершения и скачало данные в своё хранилище, то снимок можно просто удалить одной командой. Поскольку VSS пропагандирует CoW подход, то речь здесь действительно о банальном удалении нашей аллоцированной зоны, ведь все новые данные сразу пишутся на оригинальный диск. Это называется non-persistent shadow copy, и она не имеет никакого смысла без оригинального диска.

Чтобы пройти этот путь вручную, достаточно открыть консоль и набрать:

PS C:\Windows\system32> diskshadow
Microsoft DiskShadow version 1.0
Copyright (C) 2013 Microsoft Corporation
On computer:  VEEAM,  17.05.2021 19:18:44

DISKSHADOW> add volume c: # добавляем в задание диск С

DISKSHADOW> create	# создаём снапшот
Alias VSS_SHADOW_1 for shadow ID {a1eef71e-247e-4580-99bc-ee62c42221d6} set as environment variable.
Alias VSS_SHADOW_SET for shadow set ID {cc9fab4d-3e7d-44a5-9a4d-0df11dd7219c} set as environment variable.

Querying all shadow copies with the shadow copy set ID {cc9fab4d-3e7d-44a5-9a4d-0df11dd7219c}

        * Shadow copy ID = {a1eef71e-247e-4580-99bc-ee62c42221d6}               %VSS_SHADOW_1%
                - Shadow copy set: {cc9fab4d-3e7d-44a5-9a4d-0df11dd7219c}       %VSS_SHADOW_SET%
                - Original count of shadow copies = 1
                - Original volume name: \\?\Volume{7fd0c79d-0000-0000-0000-602200000000}\ [C:\]
                - Creation time: 17.05.2021 19:19:45
                - Shadow copy device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2
                - Originating machine: veeam.university.veeam.local
                - Service machine: veeam.university.veeam.local
                - Not exposed
                - Provider ID: {b5946137-7b9f-4925-af80-51abd60b20d5}
                - Attributes:  Auto_Release Differential

Number of shadow copies listed: 1

Здесь мы видим, что успешно создался снапшот со своим Shadow copy ID, и для удобства ему сразу присвоили алиас VSS_SHADOW_1. Этими данными вполне можно оперировать, если возникает такое желание. Однако не будем уходить в сторону и попробуем прочитать содержимое этого снимка. Для чего подмонтируем его в качестве диска.

DISKSHADOW> expose {a1eef71e-247e-4580-99bc-ee62c42221d6} Z:
The shadow copy is a non-persistent shadow copy. Only persistent shadow copies can be exposed.

Однако на такое, казалось бы, простое и законное желание мы получили не менее законный отлуп, ибо сделали non-persistent снимок, а, значит, единственное, на что он годится — это записать его поверх родного, удалив на нём всю информацию, которая появилась после создания этого снимка. Но такая история нас не устраивает, поэтому стираем всё безжалостно.

DISKSHADOW> delete shadows all # или только нужный ID
Deleting shadow copy {a1eef71e-247e-4580-99bc-ee62c42221d6} on volume \\?\Volume{7fd0c79d-0000-0000-0000-602200000000}\ from provider {b5946137-7b9f-4925-af80-51abd60b20d5} [Attributes: 0x00420000]...

Number of shadow copies deleted: 1

И начинаем всё заново, только теперь укажем, что нам нужна персистентная копия, чтобы мы могли использовать её как полноценный диск.

DISKSHADOW> add volume C:

DISKSHADOW> set context persistent # вот этот момент

DISKSHADOW> create
Alias VSS_SHADOW_1 for shadow ID {346d896b-8722-4c01-bf01-0f38b9abe20a} set as environment variable.
Alias VSS_SHADOW_SET for shadow set ID {785983be-e09d-4d2a-b8b7-a4f722899896} set as environment variable.

Querying all shadow copies with the shadow copy set ID {785983be-e09d-4d2a-b8b7-a4f722899896}

        * Shadow copy ID = {346d896b-8722-4c01-bf01-0f38b9abe20a}               %VSS_SHADOW_1%
                - Shadow copy set: {785983be-e09d-4d2a-b8b7-a4f722899896}       %VSS_SHADOW_SET%
                - Original count of shadow copies = 1
                - Original volume name: \\?\Volume{7fd0c79d-0000-0000-0000-602200000000}\ [C:\]
                - Creation time: 17.05.2021 19:38:45
                - Shadow copy device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy3
                - Originating machine: veeam.university.veeam.local
                - Service machine: veeam.university.veeam.local
                - Not exposed
                - Provider ID: {b5946137-7b9f-4925-af80-51abd60b20d5}
                - Attributes:  No_Auto_Release Persistent Differential

Number of shadow copies listed: 1

Как мы видим: Attributes:  No_Auto_Release Persistent Differential. Поэтому если теперь вы сделаете expose, то снапшот примаунтится как полноценный диск, по которому можно перемещаться и копировать с него файлы. Диск, само собой, виртуальный и состоит из блоков оригинального диска, плюс блоки изменившихся данных, читая которые, мы можем видеть состояние оригинального диска на момент снапшота. Всё просто.

Только учтите, пожалуйста, такой момент, если вдруг решите, что нашли святой грааль: в таком режиме нельзя занимать данными больше 50% места на диске. Один блок свыше — и всё, диск переполнился.

Что тут хочется ещё сказать, а вернее, спросить: если всё так просто, то почему же я говорю, что всё так сложно? Проблема в том, что, отдавая на боевом сервере команду vssadmin create shadow, мы, конечно, создаём какой-то снимок, но как себя будут чувствовать приложения после отката на этот снимок, мы предсказать не можем. Это не шутка: команда create признаёт наличие ошибок при выполнении как вариант нормы. Райтер не вернул вовремя Ок от приложения? Да кому это надо, го делать снапшот, я создал. 

Поэтому когда за дело берётся настоящее бекапное приложение вроде Veeam Backup & Replication, то речь идёт не об одной команде, а о целой россыпи предварительных запросов, в результате которых формируется огромнейшая команда (это не метафора для красного словца, а реальность), в которой учитываются состояния райтеров и приложений на целевой системе, с жестким требованием соответствия всех статусов необходимым. Словом, количество мест, где что-то может пойти не так, вырастает на порядок. Ведь нам главное — не снапшот создать, закрыв глаза на сопутствующие потери, а гарантировать консистентность данных внутри него.

Как лечить VSS

Сразу, не отходя от кассы, открою вам тайну самого лучшего метода лечения большинства проблем с VSS — перезагрузка. Понимаю, что это кощунство и кошмар наяву для всех свидетелей аптайма, но суровая правда жизни такова, то можно сколь угодно долго биться с пациентом, чтобы потом всё починилось само от перезагрузки. Да, именно так. Это тот случай, когда само сломалось и само починилось. 

Другая проблема — это железо. Помните про временные рамки для райтеров? Про десять секунд на снапшот? Для многих это ограничение становится проблемой из-за того, что СХД физически не успевает сделать требуемые действия за отведённое время. Как это лечится? А вот никак. Или покупаем более мощное железо, или ищем пути снижения нагрузки, чтобы операция была проведена за выделенный промежуток времени.

Если посмотрите одно из самых популярных KB1680: VSS Timeout when backing up Exchange VM, то легко обнаружите, что первые три шага для решения всех проблем с VSS — сделайте снапшот вручную и посмотрите чтобы это заняло менее 20 секунд, перезагрузитесь и попробуйте снизить нагрузку. Вот так и живём, да. 

И что же делать, если VSS падает, в ивентах ничего нет, а понять, что происходит надо? Тут я могу порекомендовать три хороших статьи:

  • КВ от Veeam, посвящённое анализу поведения VSS с помощью diskshadow.

  • Другое KB от Veeam, посвящённое сбору информации с помощью vsstrace из Windows SDK. Но скажу сразу, это уже не для слабых духом.

  • И видео от моего коллеги, где он наглядно показывает, как работать с информацией из первых двух пунктов =) Рассказывает он действительно хорошо, но с непривычки голова у вас от объёма информации заболит, это я вам обещаю.

Также в гугле можно найти массу толковых советов по поводу приведения VSS в чувства, только рекомендую не бросаться на первый попавшийся случай, а постараться найти наиболее похожий именно на вашу проблему. По коду ошибки, например. Потому что слишком много возможных комбинаций ошибок, приложений и причин их возникновения.

А на сегодня всё. Я и так хотел кратенько, но получилось больше десяти страниц текста. Поэтому самое время закругляться. Если хочется раскрытия какой-то другой темы или углубиться в детали VSS, то обязательно пишите об этом в комментариях.

From Wikipedia, the free encyclopedia

Shadow Copy

Previous Versions in Windows Vista, a part of Windows Explorer that allows persistent shadow copies to be created.

Other names
  • Volume Snapshot Service[1]
  • Previous Versions
  • Shadow Copies for Shared Folders8
  • VSS[2]
Developer(s) Microsoft
Operating system Microsoft Windows
Service name VSS[2]

Shadow Copy (also known as Volume Snapshot Service,[1] Volume Shadow Copy Service[2] or VSS[2]) is a technology included in Microsoft Windows that can create backup copies or snapshots of computer files or volumes, even when they are in use. It is implemented as a Windows service called the Volume Shadow Copy service. A software VSS provider service is also included as part of Windows to be used by Windows applications. Shadow Copy technology requires either the Windows NTFS or ReFS filesystems in order to create and store shadow copies. Shadow Copies can be created on local and external (removable or network) volumes by any Windows component that uses this technology, such as when creating a scheduled Windows Backup or automatic System Restore point.

Overview[edit]

VSS operates at the block level of volumes.

A snapshot is a read-only point-in-time copy of the volume. Snapshots allow the creation of consistent backups of a volume, ensuring that the contents do not change and are not locked while the backup is being made.

The core component of shadow copy is the Volume Shadow Copy service, which initiates and oversees the snapshot creation process. The components that perform all the necessary data transfer are called providers. While Windows comes with a default System Provider, software and hardware vendors can create their own software or hardware providers and register them with Volume Shadow Copy service. Each provider has a maximum of 10 seconds’ time to complete the snapshot generation.[3]

Other components that are involved in the snapshot creation process are writers. The aim of Shadow Copy is to create consistent reliable snapshots. But sometimes, this cannot simply be achieved by completing all pending file change operations. Sometimes, it is necessary to complete a series of inter-related changes to several related files. For example, when a database application transfers a piece of data from one file to another, it needs to delete it from the source file and create it in the destination file. Hence, a snapshot must not be between the first deletion and the subsequent creation, or else it is worthless; it must either be before the deletion or after the creation. Enforcing this semantic consistency is the duty of writers. Each writer is application-specific and has 60 seconds to establish a backup-safe state before providers start snapshot creation. If the Volume Shadow Copy service does not receive acknowledgement of success from the corresponding writers within this time-frame, it fails the operation.[3]

By default, snapshots are temporary; they do not survive a reboot. The ability to create persistent snapshots was added in Windows Server 2003 onward. However, Windows 8 removed the GUI portion necessary to browse them. (§ History)

Windows software and services that support VSS include Windows Failover Cluster,[4] Windows Server Backup,[5] Hyper-V,[6] Virtual Server,[7] Active Directory,[8] SQL Server,[9] Exchange Server[10] and SharePoint.[11]

The end result is similar to a versioning file system, allowing any file to be retrieved as it existed at the time any of the snapshots was made. Unlike a true versioning file system, however, users cannot trigger the creation of new versions of an individual file, only the entire volume. As a side-effect, whereas the owner of a file can create new versions in a versioning file system, only a system administrator or a backup operator can create new snapshots (or control when new snapshots are taken), because this requires control of the entire volume rather than an individual file. Also, many versioning file systems (such as the one in VMS) implicitly save a version of files each time they are changed; systems using a snapshotting approach like Windows only capture the state periodically.

History[edit]

This section needs to be updated. Please help update this article to reflect recent events or newly available information. (August 2015)

Windows XP and Server 2003[edit]

Volume Snapshot Service was first added to Microsoft Windows in Windows XP. It can only create temporary snapshots, used for accessing stable on-disk version of files that are opened for editing (and therefore locked). This version of VSS is used by NTBackup.

The creation of persistent snapshots (which remain available across reboots until specifically deleted) has been added in Windows Server 2003, allowing up to 512 snapshots to exist simultaneously for the same volume. In Windows Server 2003, VSS is used to create incremental periodic snapshots of data of changed files over time. A maximum of 64 snapshots are stored on the server and are accessible to clients over the network. This feature is known as Shadow Copies for Shared Folders and is designed for a client–server model.[12] Its client component is included with Windows XP SP2 or later, and is available for installation on Windows 2000 SP3 or later, as well as Windows XP RTM or SP1.[13]

vssadmin

Developer(s) Microsoft
Stable release

1.1

Operating system Microsoft Windows
Type Command
License Proprietary commercial software
Website docs.microsoft.com/en-us/windows-server/administration/windows-commands/vssadmin

Windows XP[14] and later include a command line utility called vssadmin that can list, create or delete volume shadow copies and list installed shadow copy writers and providers.[15]

Windows Vista, 7 and Server 2008[edit]

Microsoft updated a number of Windows components to make use of Shadow Copy. Backup and Restore in Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 use shadow copies of files in both file-based and sector-by-sector backup. The System Protection component uses VSS when creating and maintaining periodic copies of system and user data on the same local volume (similar to the Shadow Copies for Shared Folders feature in Windows Server); VSS allows such data to be locally accessed by System Restore.

System Restore allows reverting to an entire previous set of shadow copies called a restore point.[16][17]
Prior to Windows Vista, System Restore depended on a file-based filter that watched changes for a certain set of file extensions, and then copied files before they were overwritten.[18][19][20] In addition, a part of Windows Explorer called Previous Versions allows restoring individual files or folders locally from restore points as they existed at the time of the snapshot, thus retrieving an earlier version of a file or recovering a file deleted by mistake.

diskshadow

Developer(s) Microsoft
Operating system Microsoft Windows
Type Command
License Proprietary commercial software
Website docs.microsoft.com/en-us/windows-server/administration/windows-commands/diskshadow

Finally, Windows Server 2008 introduces the diskshadow utility which exposes VSS functionality through 20 different commands.[21]

The system creates shadow copies automatically once per day, or when triggered by the backup utility or installer applications which create a restore point.[22][23] The «Previous Versions» feature is available in the Business, Enterprise, and Ultimate editions of Windows Vista[24] and in all Windows 7 editions. The Home Editions of Vista lack the «Previous Versions» feature, even though the Volume Snapshot Service is included and running. Using third-party tools it is still possible to restore previous versions of files on the local volume.[25]
Some of these tools also allow users to schedule snapshots at user-defined intervals, configure the storage used by volume-shadow copies and compare files or directories from different points-in-time using snapshots.[26]
Windows 7 also adds native support through a GUI to configure the storage used by volume-shadow copies.

Windows 8 and Server 2012[edit]

While supporting persistent shadow copies, Windows 8 lacks the GUI portion necessary to browse them; therefore the ability to browse, search or recover older versions of files via the Previous Versions tab of the Properties dialog of files was removed for local volumes. However, using third party tools (such as ShadowExplorer) it is possible to recover that functionality. The feature is fully available in Windows Server 2012.[27]

Windows 10[edit]

Windows 10 restored the Previous Versions tab that was removed in Windows 8; however, in earlier builds it depended upon the File History feature instead of Volume Shadow copy. Current builds now allow restoration from both File History and System Protection (System Restore) points, which use Volume Shadow Copy.[28]

Windows 11[edit]

Windows 11 continues to have a similar system as windows 10. The File History and Volume Shadow copy. It is disabled by default but can be turned on with options in settings and control panel.[29]

Samba Server[edit]

Samba on Linux is capable of providing Shadow Copy Service on an LVM-backed storage or with an underlying ZFS or btrfs.[30][31][32]

Compatibility[edit]

While the different NTFS versions have a certain degree of both forward and backward compatibility, there are certain issues when mounting newer NTFS volumes containing persistent shadow copies in older versions of Windows. This affects dual-booting, and external portable hard drives. Specifically, the persistent shadow copies created by Windows Vista on an NTFS volume are deleted when Windows XP or Windows Server 2003 mount that NTFS volume. This happens because the older operating system does not understand the newer format of persistent shadow copies.[33] Likewise, System Restore snapshots created by Windows 8 are deleted if they are exposed to a previous version of Windows.[34]

See also[edit]

  • List of Microsoft Windows components
  • Snapshot (computer storage)
  • Copy-on-write

References[edit]

  1. ^ a b «Volume Snapshot Service (VSS)». Glossary. Symantec. Retrieved 2 May 2013.
  2. ^ a b c d «Volume Shadow Copy Service Overview». MSDN Library. Microsoft. 5 November 2012. Retrieved 2 May 2013.
  3. ^ a b «How Volume Shadow Copy Service Works». TechNet. Microsoft. 28 March 2003. Retrieved 4 January 2011.
  4. ^ Archiveddocs. «What’s New in Failover Clusters in Windows Server 2008». technet.microsoft.com. Retrieved 18 March 2018.
  5. ^ JasonGerend. «Volume Shadow Copy Service». docs.microsoft.com. Retrieved 11 August 2019.
  6. ^ scooley. «Hyper-V Integration Services». docs.microsoft.com. Retrieved 11 August 2019.
  7. ^ scooley. «Microsoft Virtualization and Virtual Server 2005 R2 SP1». docs.microsoft.com. Retrieved 11 August 2019.
  8. ^ mcleanbyron. «VSS Backup and Restore of the Active Directory — Windows applications». docs.microsoft.com. Retrieved 11 August 2019.
  9. ^ MandiOhlinger. «SQL Server database mirroring, Volume Shadow Copy service and AlwaysOn — BizTalk Server». docs.microsoft.com. Retrieved 11 August 2019.
  10. ^ msdmaguire. «Exchange Server data protection, Exchange disaster recovery, Exchange backup, Exchange VSS Writer, VSS Backup Exchange, Exchange Server data recovery, Exchange data recovery». docs.microsoft.com. Retrieved 11 August 2019.
  11. ^ spdevdocs. «Back up and restore a search service application in SharePoint using VSS». docs.microsoft.com. Retrieved 11 August 2019.
  12. ^ «Shadow Copy Client Download». TechNet. Microsoft. Retrieved 21 October 2014.
  13. ^ Oltean, Adi (17 December 2004). «Tips for deploying Shadow copies [sic] for Shared Folders». Antimail. Microsoft. Retrieved 21 April 2009.
  14. ^ «Windows XP — Volume Shadow Copy Service». MSDN. Microsoft. Retrieved 31 May 2013.
  15. ^ «Vssadmin». Windows Server 2008 and Windows Server 2008 R2 documentations. TechNet Library. Microsoft. 28 September 2007. Windows Server Commands, References, and Tools. Retrieved 27 March 2012.
  16. ^
    Compare:«Information about SPP folder in Windows vista». Microsoft Community. Microsoft. 20 August 2010. Retrieved 22 July 2015. SPP stand for Shared Protection Point and is used by windows to store information on restore point.
  17. ^
    Compare:
    Barreto, Jose (16 September 2009). «Diagnosing Failures in Windows Server Backup – Part 1 (VSS/SPP Errors)». Storage at Microsoft: The official blog of the Windows and Windows Server storage engineering teams. Microsoft Corporation. Retrieved 11 September 2017. […] the origin of the error is in an underlying layer such as Volume Shadow Copy Service (VSS), Shared Protection Point (SPP), or other applications that plug into VSS framework.
  18. ^ Russinovich, Mark E.; Solomon, David A. (2005). Microsoft Windows Internals: Microsoft Windows Server 2003, Windows XP, and Windows 2000 (4 ed.). Redmond, WA: Microsoft Press. pp. 706–711. ISBN 0-7356-1917-4.
  19. ^ «Windows Backup». Windows Vista portal. Microsoft. Archived from the original on 10 May 2007. Retrieved 11 January 2014.
  20. ^ Fok, Christine (September 2007). «A Guide to Windows Vista Backup Technologies». TechNet Magazine. Microsoft. Retrieved 11 January 2014.
  21. ^ «Diskshadow». Windows Server 2008 and Windows Server 2008 R2 documentations. TechNet Library. Microsoft Corporation. 28 September 2007. Windows Server Commands, References, and Tools. Retrieved 27 March 2012.
  22. ^ «Selected Scenarios for Maintaining Data Integrity with Windows Vista». TechNet. Microsoft Corporation.
  23. ^ «A Guide to Windows Vista Backup Technologies». Microsoft.
  24. ^ «Volume Shadow Copy and «Previous Versions» feature in Windows Vista». Microsoft Corporation.
  25. ^
    ShadowExplorer allows restoring lost or altered files
  26. ^
    TimeTraveler adds a timeline to Windows Explorer allowing the user to open, restore or compare files or directories from points-in-time
  27. ^ «Previous versions UI removed for local volumes (Windows)». Retrieved 17 November 2012.
  28. ^ Saluste, Margus. «File History in Windows 8, 8.1 and 10». WinHelp.us. Archived from the original on 25 December 2020. Retrieved 18 March 2018.
  29. ^ Huc, Mauro (8 March 2023). «How to enable Previous Versions to recover files on Windows 11 — Pureinfotech». Pureinfotech • Windows 10 & Windows 11 help for humans. Archived from the original on 27 May 2023. Retrieved 19 July 2023.
  30. ^ «Samba HOWTO Collection, Part III. Advanced Configuration». Retrieved 2 October 2012.
  31. ^ «zfsonlinux/zfs-auto-snapshot». GitHub. Retrieved 18 March 2018.
  32. ^ «[GUIDE] Windows Previous Versions and Samba (Btrfs — Atomic COW — Volume Shadow Copy)». openmediavault.
  33. ^ «How restore points and other recovery features in Windows Vista are affected when you dual-boot with Windows XP». File Cabinet Blog. Microsoft. 14 July 2006. Archived from the original on 18 July 2006. Retrieved 21 March 2007.
  34. ^ «Calling SRSetRestorePoint». MSDN Library. Microsoft. Retrieved 1 February 2015. Snapshots of the boot volume created by System Restore running on Windows 8 may be deleted if the snapshot is subsequently exposed by an earlier version of Windows.

Further reading[edit]

  • Russinovich, Mark E.; Solomon, David A.; Ionescu, Alex (2009). «Storage Management». Windows Internals (5th ed.). Microsoft Press. pp. 688–698. ISBN 978-0-7356-2530-3.
  • «Selected Scenarios for Maintaining Data Integrity with Windows Vista». Microsoft TechNet. Microsoft Corporation. Retrieved 4 January 2011.
  • Russinovich, Mark; Solomon, David (December 2001). «Windows XP: Kernel Improvements Create a More Robust, Powerful, and Scalable OS». TechNet Magazine. Microsoft. Retrieved 2 May 2013.
  • Oltean, Adi (19 September 2006). «A bit of black magic: How to assign drive letters to VSS shadow copies… on Windows XP!». Antimail. Microsoft Corporation. Retrieved 4 January 2011.
  • Oltean, Adi (14 December 2004). «Creating shadow copies from the commandline». MSDN Blogs. Microsoft Corporation. Retrieved 4 January 2011.
  • «Volume Shadow Copy Service (VSS) Express Writers». Microsoft Corporation.

Служба теневого копирования томов — Volume Shadow Copy Service (VSS) впервые на платформе Windows появилась целых десять лет назад еще в Windows Server 2003, однако до сих пор далеко не все администраторы Windows используют функционал данной службы. Даже существует мнение, что при наличии грамотной политике резервного копирования использовать теневое копирование тома нецелесообразно. Однако это далеко не всегда так.

Возьмем в качестве примера файловый сервер с множеством каталогов и большим количеством пользователей, бэкап которого выполняется, допустим, ежедневно. Представим ситуацию, что пользователь в начале рабочего дня внес важные изменения в некий сверхкритичный документ, а в течении рабочего дня, случайно его модифицировал или удалил. Восстановить данный документ из резервной копии не получится, т.к. он в нее просто не попал. Настроить традиционный бэкап файлового сервера в течении рабочего дня технически затруднительно (да и сама процедура создания и восстановления из такого бэкапа может занять довольно много времени, усугубляющаяся использованием инкрементального или дифференциального бэкапа). В такой ситуации «спасти» положение может теневое копирование данных с помощью службы Volume Shadow Copy Service.

Эта статья посвящена настройке теневого копирования томов (Volume Shadow Copy) в новой серверной ОС Windows Server 2012.

Рассмотрим основные преимущества службы VSS по сравнению с классическими средствами резервного копирования данных:

  • Высокая скорость создания резервных копий
  • Возможность самостоятельного восстановления файлов пользователями (при наличии прав на запись в каталог)
  • Возможность копирования используемых (заблокированных) пользователями файлов
  • Небольшой размер копий (по информации MS около 30 Мб на 1 Гб данных)

Основные особенности работы службы теневого копирования томов

Что же такое теневая копия? По сути это снапшот (снимок) всей информации, хранящейся на диске. После создания теневой копии служба VSS начинает отслеживать изменение данных на диске. VSS разбивает все данные на блоки по 16Кб каждый, и если данные в таком блоке были изменены, служба записывает в файл теневой копии этот блок целиком. Таким образом получается, что при создании следующей теневой копии данных система не копирует данные целиком, а только лишь блочные изменения. Благодаря этому система теневого копирования позволяет существенно сэкономить место на диске. Теневые копии могут храниться на том же диске, на котором хранятся данные, либо на отдельном (решение для высоконагруженных систем с большой частотой изменения данных). Все файлы теневых копий хранятся в служебном каталоге System Volume Information. Эти файлы можно отличить по имени, все они содержат в имени идентификатор службы VSS — 3808876b-c176-4e48-b7ae-04046e6cc752.

Еще несколько особенностей VSS:

  • По-умолчанию максимальное количество хранимых снапшотов для диска – 64. При превышении этого значения, служба VSS начинает циклическую перезапись теневых копий, удаляя самые ранние снапшоты.
  • Под теневые копии система выделяет 10% емкости раздела, однако это значение можно изменить.
  • Теневое копирование включается для тома целиком, и включить его для отдельной общей папки невозможно.
  • Microsoft не рекомендует создавать снапшоты чаще, чем раз в час (однако, это всего лишь рекомендации).

Настройка теневого копирования сетевого каталога в Windows Server 2012

Попробуем настроить теневое копирование данных общей сетевой папки, расположенной на отдельном диске сервера с ОС Windows Server 2012.

Откройте оснастку «Управление компьютером» («Computer Management»), разверните блок «Служебные программы», щелкните правой кнопкой мыши по элементу Общие папки и выберите Все задачи -> Настроить теневые копии.

Настройка shadow copy в windows server 2012

Затем нужно включить теневое копирование для раздела, на котором хранятся общие сетевые папки. Для этого выберите нужный том и нажмите кнопку «Включить». В этот момент будет создана первая теневая копия раздела (снапшот).

Включить теневое копирование тома на windows server 2012

Далее необходимо задать максимальный размер копий и периодичность (расписание) их создания. Нажмите кнопку Параметры.

Настройка параметров слуюбы volume shadow copy services

В данном примере настроим создание теневых копий по следующей схеме: снапшоты общих папок должны создаваться ежедневно в течении рабочего дня (с 9:00 до 19:00) каждые 10 минут. Вы, естественно, основываясь на особенности бизнес-процессов компании, можете настроить собственное расписание. Расписание создания теневых копий данных

Если через некоторое время открыть свойства общей папки и перейти на вкладку «Предыдущие версии», то можно увидеть список доступных на данный момент теневых копий.

Вкладка "Предудущие версии" - список доступных теневых копий

Далее у пользователя есть три варианта действия: просмотреть содержимое копии (Открыть), скопировать данные из копии в другое место (Копировать) или восстановить данные с перезаписью (Восстановить)

Скопировать данные из резервной теневой копии

При попытке восстановить содержимое копии на момент снапшота появится соответствующее предупреждение.

Восстановить данные из теневой копии с перезаписью

VSS — отличное средство, позволяющее пользователям в течении дня оперативно и в удобной форме восстановить удаленный файл или откатиться к предыдущей версии документа. Нужно не забывать, что теневое копирование не отменяет необходимость выполнения классического резервного копирования данных, позволяющего восстановить данные даже в случае аппаратного сбоя.

Отметим также, что функция теневого копирования в Windows 8 была заменена на функцию File History

VSS

This is my repository for VSS related utilities.

For details of the individual utilities, see individual readme files in the respective folders:

  • Vshadow (the untouched original repository): /vshadow.
  • Shadowrun (my own utility based on vshadow): /shadowrun.

Volume Shadow Copy Service (VSS) background information

Motivation

From Microsoft TechNet Library:

Backing up and restoring critical business data can be very complex due to the following issues:

  • The data usually needs to be backed up while the applications that produce the data are still running.
    This means that some of the data files might be open or they might be in an inconsistent state.
  • If the data set is large, it can be difficult to back up all of it at one time.

About

From Wikipedia:

Shadow Copy (also known as Volume Snapshot Service, Volume Shadow Copy Service or VSS) is a technology included
in Microsoft Windows that can create backup copies or snapshots of computer files or volumes, even when they are
in use. It is implemented as a Windows service called the Volume Shadow Copy service. A software VSS provider
service is also included as part of Windows to be used by Windows applications. Shadow Copy technology requires
either the Windows NTFS or ReFS filesystems in order to create and store shadow copies. Shadow Copies can be
created on local and external (removable or network) volumes by any Windows component that uses this technology,
such as when creating a scheduled Windows Backup or automatic System Restore point.

From Microsoft in Windows Developer Center:

The Volume Shadow Copy Service (VSS) is a set of COM interfaces that implements a framework to allow volume
backups to be performed while applications on a system continue to write to the volumes.

Use in Windows

VSS is in use in Windows for various features.

System Protection

The System Protection feature in Windows regularly creates what it calls «system restore points», which are basically
VSS shadow copies of your drive. It can be used to restore your entire system, or to restore previous versions of
individual files through the Previous Versions pane in file properties. By default, System Protection is turned
on for system drive (C: drive), and allowed to use up to 5% of its storage capacity.
When the limit is reached, it will automatically delete the oldest restpore points. You can manually delete restore points
from the System Protection pane in the System Properties dialog in Windows, and the Disk Clean-up will also delete old restore points.

Backup

Windows has a built-in backup feature, which also utilizes VSS.

Administration

Vssadmin

Very basic command line utility included in Windows which displays basic information about volume shadow copies, and lets you delete
based on different criteria.

Delete Shadows        - Delete volume shadow copies
List Providers        - List registered volume shadow copy providers
List Shadows          - List existing volume shadow copies
List ShadowStorage    - List volume shadow copy storage associations
List Volumes          - List volumes eligible for shadow copies
List Writers          - List subscribed volume shadow copy writers
Resize ShadowStorage  - Resize a volume shadow copy storage association

https://learn.microsoft.com/windows-server/administration/windows-commands/vssadmin

VShadow

VShadow is a more advanced command-line tool that you can use to also create and manage many aspects of volume shadow copies.
It is not included in Windows, but in Windows SDK which you would normally install as part of Visual Studio, but can
also download and install from Microsoft Developer Downloads.

It is actually intended as a sample for demonstrating the use of the Volume Shadow Copy Service (VSS) COM API.
It even bears the name «Volume Shadow Copy sample client«, still, but even so it is highly usable.

For more information about the VShadow tool and its command-line options,
see VShadow Tool and Sample
and VShadow Tool Examples.

The source code (C++) is published in Windows classic samples repository, with Visual Studio project file ready
for building (requires ATL, but other than that no external dependencies). License is MIT, with basically the
only demand that a copyright notice are included in «all copies or substantial portions of the software».

Note: The repository contains two slightly different copies of the source code, see notes below

Usage:
   VSHADOW [optional flags] [commands]

List of optional flags:
  -?                 - Displays the usage screen
  -p                 - Manages persistent shadow copies
  -nw                - Manages no-writer shadow copies
  -nar               - Creates shadow copies with no auto-recovery
  -tr                - Creates TxF-recovered shadow copies
  -ad                - Creates differential HW shadow copies
  -ap                - Creates plex HW shadow copies
  -scsf              - Creates Shadow Copies for Shared Folders (Client Accessible)
  -t={file.xml}      - Transportable shadow set. Generates also the backup components doc.
  -bc={file.xml}     - Generates the backup components doc for non-transportable shadow set.
  -wi={Writer Name}  - Verify that a writer/component is included
  -wx={Writer Name}  - Exclude a writer/component from set creation or restore
  -mask              - BreakSnapshotSetEx flag: Mask shadow copy luns from system on break.
  -rw                - BreakSnapshotSetEx flag: Make shadow copy luns read-write on break.
  -forcerevert       - BreakSnapshotSetEx flag: Complete operation only if all disk signatures revertable.
  -norevert          - BreakSnapshotSetEx flag: Do not revert disk signatures.
  -revertsig         - Revert to the original disk's signature during resync.
  -novolcheck        - Ignore volume check during resync. Unselected volumes will be overwritten.
  -script={file.cmd} - SETVAR script creation
  -exec={command}    - Custom command executed after shadow creation, import or between break and make-it-write
  -wait              - Wait before program termination or between shadow set break and make-it-write
  -tracing           - Runs VSHADOW.EXE with enhanced diagnostics


List of commands:
  {volume list}                   - Creates a shadow set on these volumes
  -ws                             - List writer status
  -wm                             - List writer summary metadata
  -wm2                            - List writer detailed metadata
  -wm3                            - List writer detailed metadata in raw XML format
  -q                              - List all shadow copies in the system
  -qx={SnapSetID}                 - List all shadow copies in this set
  -s={SnapID}                     - List the shadow copy with the given ID
  -da                             - Deletes all shadow copies in the system
  -do={volume}                    - Deletes the oldest shadow of the specified volume
  -dx={SnapSetID}                 - Deletes all shadow copies in this set
  -ds={SnapID}                    - Deletes this shadow copy
  -i={file.xml}                   - Transportable shadow copy import
  -b={SnapSetID}                  - Break the given shadow set into read-only volumes
  -bw={SnapSetID}                 - Break the shadow set into writable volumes
  -bex={SnapSetID}                - Break using BreakSnapshotSetEx and flags, see options for available flags
  -el={SnapID},dir                - Expose the shadow copy as a mount point
  -el={SnapID},drive              - Expose the shadow copy as a drive letter
  -er={SnapID},share              - Expose the shadow copy as a network share
  -er={SnapID},share,path         - Expose a child directory from the shadow copy as a share
  -r={file.xml}                   - Restore based on a previously-generated Backup Components document
  -rs={file.xml}                  - Simulated restore based on a previously-generated Backup Components doc
  -revert={SnapID}                - Revert a volume to the specified shadow copy
  -addresync={SnapID},drive       - Resync the given shadow copy to the specified volume
  -addresync={SnapID}             - Resync the given shadow copy to it's original volume
  -resync=bcd.xml                 - Perform Resync using the specified BCD

(https://docs.microsoft.com/windows/win32/vss/vshadow-tool-and-sample)

Diskshadow

Documented here, but not sure if this is still availble?

https://docs.microsoft.com/windows-server/administration/windows-commands/diskshadow

VSS administration utilities

The «Volume Shadow Copy sample client» (vshadow.exe) utility can be used for some basic
administration of volume shadow copies, like listing the existing volume shadow copies
on the system, delete specific ones etc. Windows 10 includes a utility called
«Volume Shadow Copy Service administrative command-line tool» (vssadmin.exe),
which can do some of the same most basic this (list and delete). It does not support
the creation of new ones though, there are a lot more functionality in vshadow.

Projects in this repository

VShadow

Contains the original source code of the Volume Shadow Copy sample client from Microsoft’s
Windows classic samples repository — the
Windows 8 version: https://github.com/microsoft/Windows-classic-samples/tree/master/Samples/VShadowVolumeShadowCopy.

This source requires ATL, a dependency removed from my own utilities based on the same source.

See separate readme (the one from the original repository) in /vshadow.

Building

You can build the application using latest version of Visual Studio. You would need the C++ workload, with at least
MSVC build tools, Windows 10 SDK, as well as ATL. The included project file only include 32-bit (Win32) build configuration,
and as you probably are using a 64-bit version of Windows you need to create a 64-bit (x64) build configuration for the
application to work (the 32-bit build will fail with COM related errors).

ShadowRun

My own project for a utility based on the VShadow source code, but focused on a very specific feature:
The creation of temporary read-only shadow copy and running of a specified utility that
can work on this, before it is cleaned up.

See separate readme in /shadowrun.

Notes

Vshadow source code

Microsofts Windows classic samples repository contains
two slightly different copies of the source code:

  • One at Samples/Win7Samples/winbase/vss/vshadow
  • Another at Samples/VShadowVolumeShadowCopy

The sources are very similar, but with a few differences:

  • The Win7Samples/winbase/vss/vshadow (I will just be calling it the Win7 version from now on)
    contains project file for Visual Studio 2005, while Samples/VShadowVolumeShadowCopy (which I will call Win8 version from now on)
    contains upgraded project file for Visual Studio 2013.
  • Win7 version defines the preprocessor directive VSS_SERVER in its project file, the Win8 version does not.
  • The COM security initialization call to CoInitializeSecurity in VssClient::Initialize uses some different options:
    • Win7 version sets dwCapabilities to EOAC_NONE («No special options»), Win8 to EOAC_DYNAMIC_CLOAKING («Cloaking»).
    • Win7 version sets dwImpLevel to RPC_C_IMP_LEVEL_IDENTIFY, Win8 to RPC_C_IMP_LEVEL_IMPERSONATE
  • The Win8 version checks that the Windows version is at lest Windows 8 (hence my nickname for it).
  • The Win8 version adds support for UNC paths as arguments.

The executable included in Windows 10 SDK, which identifies itself as version 3.0:

  • Does support UNC paths (like the Win8 version)
    • You can check by executing a command like the following (the file exec.cmd must exist):
      vshadow -nw -script=temp.cmd -exec=exec.cmd C: somethingrandom
    • The Win7 version will write «Parameter %s is expected to be a volume!»
    • The Win8 version will write «Parameter %s is expected to be a volume or a file share path
  • Is built with VSS_SERVER preprocessor directive (like the Win7 version)
    • You can see it from the help text printed when executing vshadow /?,
      a lot of options are only shown when VSS_SERVER is enabled, for example the option -nw.

I guess the Windows 10 SDK inluded version is based on the Win8 version (if its even built on the same source, although
the Windows 10 SDK included exeuctable still calls itself by the same «sample client» name and with a copyright statement
for with year 2005!) but using a different build configuration from the one published. The project files in both
repositories are for a quite old version of Visual Studio, and they don’t even include 64-bit build configuration
which is needed for it to run on 64-bit versions of Windows.

For any enterprise application that you deploy on your Windows Server infrastructure, if data integrity and consistency are important, then one of the first things you need to verify is whether it supports backups using the Volume Shadow Copy Service (VSS).  Data consistency means that the information for the application or file is complete and not corrupted so that when it is restored from a backup, it works as expected.  For example, if you restore a Hyper-V virtual machine (VM), you want to make sure that it is not corrupted and runs normally, or else the backup effectively worthless.  Being able to take a backup of an application, rather than the entire disk, is also advantageous because it provides more flexibility when creating the backup, more granularity when restoring the application’s data, and it can save storage space.

This article will explain how VSS works with applications and some common tools used to manage the process.

The Volume Shadow Copy Service (VSS) is a set of Windows COM interfaces and commands that create complete backups while the target application continues to run.  Since enterprise applications need to continually serve customers and are rarely taken offline, they need to be backed up while they are online and still generating data.  This means that the data files are often large, remain open, and in an inconsistent state, while the data is constantly changing.  VSS provides coordination between the running enterprise application (such as a Hyper-V VM), backup application (such as Altaro VM Backup), the storage management software (such as Windows Server), and the storage hardware.  VSS is built into both Windows and Windows Server.

Volume Shadow Copy Service consists of the following components:

  • VSS Service – The Windows Service which coordinates and communicates between the application and backup components.
  • VSS Requester – This is the backup software that creates and manages the VSS copies. Windows Server Backup and System Center Data Protection Manager are commonly used in the Microsoft ecosystem, but almost every third-party backup solution for Windows also supports VSS, including Altaro VM Backup.
  • VSS Provider – This is the component that creates and manages the shadow copies and can run in either the software on the operating system or in the hardware.
  • VSS Writer – This application-specific component ensures that the data is consistent when it is backed up and is usually included with each enterprise application. As a best practice, make sure that your application includes a VSS writer as it typical with all Microsoft enterprise applications.

Due to the component/segmented feature nature of Windows, Windows Server includes the following 34 built-in VSS writers right out of the box:

  • Active Directory Domain Services (NTDS) VSS Writer
  • Active Directory Federation Services Writer
  • Active Directory Lightweight Directory Services (LDS) VSS Writer
  • Active Directory Rights Management Services (AD RMS) Writer
  • Automated System Recovery (ASR) Writer
  • Background Intelligent Transfer Service (BITS) Writer
  • Certificate Authority Writer
  • Cluster Service Writer
  • Cluster Shared Volume (CSV) VSS Writer
  • COM+ Class Registration Database Writer
  • Data Deduplication Writer
  • Distributed File System Replication (DFSR)
  • Dynamic Host Configuration Protocol (DHCP) Writer
  • File Replication Service (FRS)
  • File Server Resource Manager (FSRM) Writer
  • Hyper-V Writer
  • IIS Configuration Writer
  • IIS Metabase Writer
  • Microsoft Message Queuing (MSMQ) Writer
  • MSSearch Service Writer
  • NPS VSS Writer
  • Performance Counters Writer
  • Registry Writer
  • Remote Desktop Services (Terminal Services) Gateway VSS Writer
  • Remote Desktop Services (Terminal Services) Licensing VSS Writer
  • Shadow Copy Optimization Writer
  • Sync Share Service Writer
  • System Writer
  • Task Scheduler Writer
  • VSS Metadata Store Writer
  • Windows Deployment Services (WDS) Writer
  • Windows Internal Database (WID) Writer
  • Windows Internet Name Service (WINS) Writer
  • WMI Writer

As mentioned in the definition of VSS writer above, these writers allow the targeted applications/features to gracefully “pause” in such a way that allows the backup application to back up the associated configuration and data without bringing the application or service down. This could be a VM running on Hyper-V, an on-prem Exchange server, a SQL box, a domain controller running AD. Any constantly running service or application that you want to run backups against should have a supported VSS writer. Without a supported VSS writer for an application, the application will be backed up in whatever state it’s in at the time of backup.

For example, let’s say you have a MySQL Database. There currently is no supported VSS writer for MySQL. In this situation, let’s say you run a backup against it. All may seem fine on the surface, but there is a good chance that there were pending data writes in memory as the backup was happening. When you go to restore the database, the tables associated with that pending data will likely be wrong. Worst case, you could run into full-blown corruption of the MySQL database upon restoration, which is not a good time to be finding out about database corruption. The alternative in this situation, where you have no supported VSS Writer, is to use a scheduled task to gracefully stop the service in question prior to the backup and then start it again after the backup has been completed. This certainly isn’t an ideal scenario, but if you’re using an application with no supported VSS writer (they are few and far between anyway), your hands are somewhat tied.

Alternatively, if you run into this situation, it would be a good point in time to take a good hard look at the affected application and ask yourself if it can be replaced with something that has a supported VSS writer. In the long-term, a legacy application like this will not scale well for your organization and will continue to cause headache after headache.

System, Software, and Hardware Providers

Organizations can select from several options for the VSS provider, including the built-in system providers, a third-party software provider, or a hardware provider.  The system provider comes with Windows Server as Windows Server Backup using the volsnap.sys driver and swprv.dll library.  This provider is perfectly fine to use if you do not have any advanced backup utilities and only need basic functionality.

Third-party software-based providers have a richer feature set than the system provider and may have more backup options, such as defining the location where shadow copies are stored or the number of copies, and when restoring from backups, there may be options to restore specific files or items.

Hardware-based providers are recommended if they support VSS.  By running the backup process from the hardware, it offloads the resource-intensive operation backup task from the server operating system so that more processing cycles can be consumed by the application.

How Volume Shadow Copy Service (VSS) Works

In terms of a textbook description, it’s hard to beat Microsoft’s exhaustive documentation on this well-established service. So I suggest you read that if you want an ultra-comprehensive look into the inner workers of VSS. That said, if you want a quick overview that will cover 90% of situations, then read on!

When a backup is created using VSS, a series of actions are triggered to coordinate the snapshot across the service, provider, requester, and writer.

  1. When a user creates a manual backup or a task triggers an automatic backup, the requester (backup application) asks VSS to prepare the system.
  2. The writer gathers metadata about the application and data that needs to be backed up, how the application will be restored, and provides a list of application components that can be individually backed up.
  3. Once the components are selected by the requester, the writer will prepare the data so it is in a consistent state and can be successfully restored.  This will usually include completing open transactions, temporarily pausing any new write requests, and flushing any buffers or caches.  Since the application is still running, it can still accept new read requests.
  4. Once the application’s data is effectively “frozen,” the VSS service tells the provider to create the shadow copy, which can last up to a maximum of 10 seconds.
  5. The backup is now complete.

NOTE: If the freeze takes longer than 60 seconds or the shadow copy commitment takes longer than 10 seconds, then the operation is aborted and will be retried later, ideally at a time when the application is processing less data so the operation can be completed faster.

Once the backup is complete or if the task has been aborted, then the application is unfrozen or “thawed.”  First, the VSS service will release then flush all the paused file system write requests, and the application returns to its normal disk writing behavior.  The VSS service then returns the file location back to the requestor so that it can be tracked and recovered in the event of a disaster.

Volume Shadow Copy (VSS) Tools

There are two free tools provided by Microsoft to help administrators manage their snapshots, VssAdminandDiskShadow.  Additionally, there are several registry settings that can be configured.

VssAdmin is a tool used to manage shadow copies and includes commands to create a shadow copy, delete a shadow copy to reclaim storage space, list all registered VSS providers, list all registered VSS writers, and change the size of the storage area.  However, this tool will only work with the built-in system provider, so if you are using a third-party provider, you would use that storage management utility.

DiskShadow is a VSS requester used to manage any software or hardware snapshots on Windows Server.  It lets admins perform a variety of tasks for shadow copies, including listing all writers, providers, and shadow copies, setting file data and metadata, loading metadata, listing writers, adding volumes, creating a shadow copy, starting a full backup, ending a full backup, starting a restore, ending a restore, simulating a restore, deleting a shadow copy, importing a shadow copy, and managing volume drive letters.

There are three registry settings that admins may also want to change using the Regedit utility.VssAccessControl is a security setting that defines which users have access to the shadow copies.  MaxShadowCopiesspecifies the maximum number of shared copies for shared folders, which can be stored on each volume of the computer.  MinDiffAreaFileSize defines the initial size of the shadow copy storage area.

By using Volume Shadow Copy tools, you can ensure that your running applications can be backed up successfully with data consistency.  For more information about the Volume Shadow Copy Service, check out Microsoft’s official documentation at https://docs.microsoft.com/en-us/windows/desktop/vss/volume-shadow-copy-service-portal.

  • Windows shift м ответ 1
  • Windows serviceprofiles localservice appdata local temp
  • Windows service start error 1053
  • Windows shopping перевод на русский
  • Windows service pack windows 7 64 bit скачать торрент