Перейти к содержимому

Usn rollback что это

  • автор:

Usn rollback что это

Instead of using U-Move , if you attempt to move or copy Active Directory using a disk image utility (for example VMware, Symantec Ghost, or Acronis True Image), you may encounter errors with replication due to “USN rollback”.

When USN rollback occurs the following message may appear in the Event Log: “The Active Directory database has been restored using an unsupported restoration procedure. Active Directory will be unable to log on users while this condition persists.” (NTDS General, Event ID 2103)

What is USN Rollback?

A domain controller tracks objects in AD based on their Update Sequence Numbers (USN). Every object in AD has a USN. As objects are modified, the USN increases monotonically, like an odometer on a car. The latest USN on each DC is called the “high water mark”. During replication each DC compares its USN high water mark with the USN high water mark of its neighbors.

USN rollback happens when an older copy of Active Directory is restored but the computer fails to notify the other domain controllers that it was rolled back to an out-of-date copy of AD (and therefore that its high water mark has rolled back).

When you use U-Move to restore AD it notifies the other DCs that it has been rolled back. The other DCs respond by “playing back” all changes made to AD since then, bringing the restored computer up to date.

However, if you use a disk imaging utility (for example, if you restore an old disk image created with Symantec Ghost or Acronis True Image), the computer will be unaware that it has been rolled back. If the restored disk is older than the most recent actual disk that successfully replicated with the other domain controllers, any more recent changes made to AD on other domain controllers will not be “played back” to the out-of-date DC. This is because the restored DC is unaware that it has been rolled back.

USN Rollback With VMware or Hyper-V

USN rollback can happen if you use VMware or Hyper-V to roll back a virtual DC to a prior snapshot without simultaneously rolling back all the other virtual DCs. .

When running a DC inside a virtual machine (VM), USN Rollback is generally not an issue if the guest OS is running Windows Server 2012 or later and the VM host is running at least VMware version 9 or Hyper-V version 3. This is because VMware and Hyper-V will change the VM Generation ID to allow the restored VM to notify the other DCs that it was rolled back.

Consequences of USN Rollback

When another DC detects a replication request with a rolled-back USN, it instructs the rolled-back DC to initiate the following “quarantine” procedure:

  • Pause the NETLOGON service in order to prevent the processing of any further user logon requests or user password change requests
  • Disable any further replication
  • Generate Event ID 2103 in the Directory Service event log
  • Generate Event ID 2095 in the Directory Service event log: “During an Active Directory replication request, the local domain controller (DC) identified a remote DC which has received replication data from the local DC using already-acknowledged USN tracking numbers. Because the remote DC believes it is has a more up-to-date Active Directory database than the local DC, the remote DC will not apply future changes to its copy of the Active Directory database or replicate them to its direct and transitive replication partners that originate from this local DC. The most probable cause of this situation is the improper restore of Active Directory on the local domain controller. User Actions: If this situation occurred because of an improper or unintended restore, forcibly demote the DC.”

How to Avoid USN Rollback

To prevent USN rollback always use an Active Directory-aware backup utility such as U-Move to restore or move Active Directory. U-Move can restore AD from any disk image including a VM snapshot. U-Move will contact the other DCs and arrange to play back all changes to bring the restored DC up to date.

How to Fix USN Rollback

If the DC has been quarantined due to USN rollback, use one of the following procedures to recover the DC:

  • Restore Active Directory from a System State backup that was taken before Event ID 2095 was generated. Note that the System State can only be restored on the same VM or computer from where the backup was taken.
  • Use U-Move to replace the bad AD database with a good copy. The good copy can come from from any supported source such as a VM snapshot, a Volume Shadow Copy (Previous Version) snapshot, an unbootable hard disk, a .BKF file, or a Windows Server Backup image. U-Move will arrange to play back all changes to bring the good copy up to date. (If the Windows Server Backup was written to DVD or BD disks use a utility such as U-Recover to read the backup image from the disks.)
  • Run DCPROMO or Server Manager to demote the domain controller, then re-promote it again. This requires that you have a second good DC that is serving the domain. You might need to erase the metadata for the demoted DC before promoting it again. (See the technical articles below).

To avoid this problem in the future, run U-Move on each DC to schedule quick automatic daily backups of AD.

For more information

For more information about USN rollback see the Microsoft articles:

    . This article contains a good explanation of USN rollback and how to avoid it. (KB875495)

The above articles discuss using an “Active Directory-aware backup utility” versus other methods. U-Move is an “Active Directory-aware backup utility”.

What is usn rollback?

A USN rollback occurs when an older version of an Active Directory database is incorrectly restored or pasted into place. When a USN rollback occurs, modifications to objects and attributes that occur on one domain controller do not replicate to other domain controllers in the forest.

How do I fix USN rollback?

  1. Restore Active Directory from a System State backup that was taken before Event ID 2095 was generated. .
  2. Use U-Move to replace the bad AD database with a good copy. .
  3. Run DCPROMO or Server Manager to demote the domain controller, then re-promote it again.

What is USN Roll No?

An update sequence number (USN) is a 64-bit number in Active Directory that increases as changes occur. Local counters on every domain controller assign USNs. Whenever an object is changed, its USN is incremented. . USNs can also be used in domain controllers to ease recovery if a failure occurs.

What is a USN?

Definitions of USN. the navy of the United States of America; the agency that maintains and trains and equips combat-ready naval forces.

What is a non authoritative restore?

Non-authoritative restore of Active Directory Domain Services—in this mode, it is assumed that one of your domain controllers is failed and you don’t want to add an additional DC in the domain. . In this case, the AD database on the restored DC is considered primary, and its objects are replicated to all other DCs.

Active directory replication issue after USN rollback

35 related questions found

What is difference between authoritative and Nonauthoritative restore?

Authoritative restore is distributing the restored object changes to another DC’s in the domain where as non-authoritative restore is accepting the change to bring to earlier stage from other DC’s in the domain.

What is the difference between authoritative and Nonauthoritative DNS?

Authoritative DNS servers are responsible for the proper mapping of records and to respond to the recursive servers with important information for each website, such as; corresponding IP addresses and other necessary DNS records. Non-authoritative name servers do not contain the original zone files.

How do I find my USN?

One way to detect a USN rollback is to use the Windows Server version of Repadmin.exe to run the repadmin /showutdvec command. This version of Repadmin.exe displays the up-to-dateness vector USN for all domain controllers that replicate a common naming context.

What does USN Protein mean?

USN — Ultimate Sports Nutrition.

What is a USN legal aid?

The USN (unique submission number) is unique to each form you create. This number is used to track the application and you will need to record this number on the Mandate form. The red ? help symbol will provide further information where applicable.

Is Microsoft an Active Directory?

Active Directory (AD) is a directory service developed by Microsoft for Windows domain networks.

What is USNChanged in Active Directory?

The Active Directory attribute uSNChanged stores the local update sequence number (USN) of the regarding domain controller at the time of last update on that user object.

Can you restore a domain controller from a snapshot?

Since Windows Server 2012 domain controllers can also be restored via snapshot using an appropriate hypervisor. Among other things Microsoft introduced the Generation ID with Windows Server 2012. This makes a restore from of a virtual domain controller snapshot possible.

What happens when a DC gets into USN rollback state?

A USN rollback occurs when an older version of an Active Directory database is incorrectly restored or pasted into place. When a USN rollback occurs, modifications to objects and attributes that occur on one domain controller do not replicate to other domain controllers in the forest.

How do I restore my Windows server?

  1. Go to Restore tab and choose Select Task or Select Image File to locate the system image you want to restore.
  2. Choose Restore this system backup and click Next.
  3. Confirm the operation and click Start Restore.

What is Invocation ID in Active Directory?

An invocation ID is an identification number that uniquely identifies a database within Active Directory. . If these numbers aren’t reset, there will be gaps between the restored domain controller and other domain controllers throughout Active Directory.

Is Glutamine good for men?

It’s important for removing excess waste products, healthy immune system function, and may play a role in normal brain function and digestion. Benefits: Research suggests glutamine may help speed recovery from injuries and stop the breakdown of muscles and stimulate muscle tissue growth.

What are the side effects of mass gainer?

  • Dehydration. To enhance its effect, manufacturers include creatine and caffein in mass gainers. .
  • Weight Gain. The supplements are bitter in taste. .
  • Health Issues. Taking mass gainer in higher proportion can lead to several health issues.

Can whey cause liver damage?

Considering that thousands of people take whey protein without liver problems, this single case provides insufficient evidence that whey protein can damage the liver. Although, a high protein intake may harm people who have cirrhosis, a chronic liver disease ( 25 , 26 ).

What is USN in application form?

USN — Unique Service Name.

What is university ID number?

It is a random number assigned to all individuals affiliated with the University for purposes of identification. The University ID number will be used to identify you in a variety of on-campus systems. It replaces using the social security number as an inter-campus id.

Active Directory Replication Overview & USN Rollback: What It Is & How It Happens

If you have experienced event id #2095, then you understand how a USN Rollback can negatively affect AD consistency.

What is a USN?

The USN (Update Sequence Number) is an Active Directory database instance counter that increments every time a single change is committed to the AD database on a Domain Controller. The USN is unique to each DC and has no correlation to a USN on another DC (and that doesn’t matter, as you will see why later on in this article). Active Directory replication keeps track of every Domain Controller’s USN and uses this information to determine when replication is required. Active Directory has two basic types of writes to the AD database, a replicated write (where the change is performed on another DC) and an originating write (where the change is performed on the local DC). AD Replicates and leverages the information about what changes were performed on which DCs and then replicated out.

Every Domain Controller has a server object in the site container stored within the Configuration partition. This object has a child object called “NTDS Settings” which has a GUID (Globally Unique IDentifier) attribute which is replicated as part of replication metadata and used by the KCC to build the replication topology. Each DC has its own copy of the Active Directory database stored in the ntds.dit file and this unique database instance on a DC is identified with its own GUID-type identifier called the “Invocation ID”. The Invocation ID is created when the DC is promoted and only changes when the AD database is restored using a supported method or an application partition is added or removed. The reason for this is so that when an AD database is restored to an earlier point in time, the USN is also restored to that point in time. This means that any change from the restored USN value until the original, pre-restored USN value would be ignored by other DCs pulling replication from the restored DC (since they track other DCs USNs that they replicate with and only pull updates when the destination DC’s USN increments above the last stored update value USN the DC has for it – more on this later). In order to avoid this situation, the DC’s AD database generates a new Invocation ID and stores the old Invocation ID is stored in an attribute on the server’s NTDS Settings object called retiredReplDSASignatures. In this manner, the DCs will treat a new Invocation ID as a new database and ensure it gets updates from it moving forward. You can see a DC’s Invocation ID and Server GUID by running repadmin /showrepl.

Much of the DC information is visible when running the Get-ADDomainController PowerShell commandlet:

PS C:\> import-module activedirectory ;
get-addomaincontroller -identity “ADSecurityORGDC01.ADSecurity.org”

ComputerObjectDN : CN=ADSECURITYORGDC01,OU=Domain Controllers,DC=ADSecurity,DC=org
DefaultPartition : DC=ADSecurity,DC=org
Domain : ADSecurity.org
Enabled : True
Forest : ADSecurity.org
HostName : ADSecurityORGDC01.ADSecurity.org
InvocationId : f2e96b87-bb2a-4572-a911-0c79721e7b4f
IPv4Address : 10.10.10.11
IPv6Address :
IsGlobalCatalog : True
IsReadOnly : False
LdapPort : 389
Name : ADSECURITYORGDC01
NTDSSettingsObjectDN : CN=NTDS Settings,CN=ADSECURITYORGDC01,CN=Servers,CN=WashingtonDC,CN=Sites,CN=Configuration,DC
=ADSecurity,DC=org
OperatingSystem : Windows Server 2008 R2 Enterprise
OperatingSystemHotfix :
OperatingSystemServicePack : Service Pack 1
OperatingSystemVersion : 6.1 (7601)
OperationMasterRoles :
Partitions : nfiguration,DC=ADSecurity,DC=org, CN=Configuration,DC=ADSecurity,DC=org…>
ServerObjectDN : CN=ADSECURITYORGDC01,CN=Servers,CN=WashingtonDC,CN=Sites,CN=Configuration,DC=ADSecurity,DC=org
ServerObjectGuid : 214c2f5d-f9eb-4b0c-b1fa-4829fc8be2fc
Site : WashingtonDC
SslPort : 636

Notice in the Get-ADDomainController ouput above, there is a Computer Object DN and a Server Object DN?

  • The Computer Object DN is where the Domain Controller’s computer object is stored in the domain partition (DC=ADSecurity,DC=org in the example) and represents the DC in the domain.
  • The Server Object DN is representation of the DC as a replication object and is stored in the configuration partition under the site object (…,CN=Sites,CN=Configuration,DC=ADSecurity,DC=org in the example).

Every replicated change includes the following pieces of information:

  • The Replication Source DC’s GUID replicating the change (originating or replicated write)
  • The Replication Source DC’s USN
  • The Originating DC’s GUID (the DC where the AD update was first performed)
  • The Originating DC’s USN

NOTE: If the Originating Source DC’s GUID & the Originating DC’s GUID are the same, then this is an originating write. If they are different, then the change operation is a replicated write and the replication system uses the Up-To-Dateness Vector. The DCs use all of this information inlcuding the Up-To-Dateness Vector & the High Water Mark as part of “Propagation Dampening” to ensure that replication doesn’t get stuck in a loop.

There are two primary mechanism that leverage a DC’s USN to track replication updates:

  1. The Up-to-Dateness-Vector(UTDV) is a method by which DC replication partners can quickly identify when data needs to be replicated. Each DC has a UDV that keeps track of the USN for every DC hosting a replicated partition. Every DC in the AD forest hosts the same base partitions and replicates these partitions separately: Configuration & Schema and frequently the Domain DNS & Forest DNS application partitions. All of the DCs in the same domain host the same domain partition. Each partition has an associated UDV with all DCs hosting the partition and their associated USN.Simply put, the UTDV is a table of all the DCs for a replicated partition and their replicated USNs and date/time when the DC last replicated. The UTDV is sent to the Source DC by the requesting Destination DC (replicating data is always a pull even though the notification may be a push action) to filter out updates the Destination DC already has. At the end of the replication cycle the Source DC sends the Destination DC its UTDV.Here’s an example of what it looks like:Repadmin: running command /showutdvec against full DC ADSECURITYORGDC02.ADSecurity.org
    Caching GUIDs.
    ..
    WashingtonDC\ADSECURITYORGDC02 (retired) @ USN 65593 @ Time 2012-01-21 12:29:38
    WashingtonDC\ADSECURITYORGDC02 @ USN 62096 @ Time 2012-01-23 21:47:00
    ae7a0f8e-e7bd-4d4f-83df-1c731cdd8e47 @ USN 46734 @ Time 2012-01-21 14:17:26
    WashingtonDC\ADSECURITYORGDC01 @ USN 59160 @ Time 2012-01-23 21:46:33Notice how DC02 has 2 different entries, one with a USN of 65593 (marked Retired) and one with a USN of 62096. AD replication ignores the (Retired) Invocation ID’s USN and uses the current one for replication decisions, though it does keep it in the UTDV to ensure the USNs are kept separate.
  2. The High Water Mark (HWM) on a DC tracks the highest USN replicated from each DC and uses that to identify when replication is required.Simply put, the HWM tracks the last USN replicated by one of the local DC’s replication partner. The HWM is used to track the most recent changes (objects and attributes) a Destination DC has received from Source DCs for a specific partition.For example, we have DC01 and DC02:DC01’s USN: 3300
    DC02’s USN: 2200DC01 has a HWM of 2000 for DC02 and DC02 has a HWM of 3300 for DC01. When a change is performed on DC01, the USN is incremented to 3301 and when DC02 requests updates, it requests any changes since USN 3300. DC01 sends DC02 change #3301 and DC02 performs a replicated write to its AD database incrementing its local USN to 2201. What’s interesting about this is that at this point, DC01 has a HWM of 200 still and DC02 now has a USN of 2201. Since the DCs have the information about the originating DC and the originating DC’s USN, they know that this change has already been replicated so they update their HWM and wait for the next change.

What is USN Rollback?

Since updates are replicated when the USN on the source DC is larger than the destination DC has for the source DC (according to the UTDV & HWM), a USN Rollback scenario on a DC prevents replication of AD updates on that DC to any other. Typically when a USN goes backwards, it is due to a supported restore from backup. When this process occurs, the invocation ID changes. Since all replica partners track replication based on DC GUID, Invocation ID, and USNs, a supported restore method keeps the previous invocation ID as “retired” and effectively ignores it. The new database Invocation ID & associated USN are used to get AD changes from the DC… except when the USN rolls back with NO change in Invocation ID. This means that when a DC is in a state of USN Rollback, AD updates can be performed on that DC with NONE of the changes replicated to its replication partners. That’s bad news.

Examples help clarify concepts, so I’ll use one here.

DC01, DC02 & DC03 are Domain Controllers for the Active Directory domain ADSecurity.org.
DC01 is running on physical hardware and DC02 & DC03 are virtual DCs running on VMWare ESX.

The AD admin copies the DC02 virtual files on Monday and on Wednesday, DC02 fails.
The admin uses the DC02 VM files from Monday to get DC02 up and running on Thursday (ASAP, right?).

During the next replication cycle, DC01 & DC03 send DC02 the last update USN they have for DC02 (USN #31,131). DC02 checks its local USN and notes that the local USN (USN #29,000) is less than the ones sent (USN #31,131), so no update is replicated to DC01 or DC03. As changes to Active Directory are performed on DC02, they are not replicated to the other ADSecurity.org DCs until DC02’s USN increments past the USN the other DCs have for DC02. This means that 2,131 modifications occur on DC02 before the other DCs receive a single update – and then only changes from USN 31,132 on.

Note that in this situation, any change performed on DC02 is NOT replicated to any other DC. This means that modifications to AD on DC02 only exist on DC02 while other DCs may have different versions of the same objects, including passwords and group membership. See, bad news.

Day 01 – Sunday:
DC01’s USN #34,951
DC02’s USN #28,539
DC03’s USN #22,360

Day 02 – Monday:
DC01’s USN #35,123
DC02’s USN #29,000 (VM copied)
DC03’s USN #23,101

Day 03 – Tuesday:
DC01’s USN #36,432
DC02’s USN #31,131 – FAILS
DC03’s USN #24,555

Day 04 – Wednesday:
DC01’s USN #38,012
DC02 OFFLINE
DC03’s USN #25,010

Day 05 – Thursday:
DC01’s USN #39,951
DC02 Back online with USN #29,000
DC03’s USN #27,360

What causes USN Rollback to occur?

There are several scenarios that Microsoft has identified that can cause USN Rollback on a DC (i.e. unsupported configurations). All of these include the same common theme and that is taking an earlier state of a DC (backup or copy) and running it.

  • Starting an Active Directory domain controller whose Active Directory database file was restored (copied) into place by using an imaging program such as Norton Ghost.
  1. Promote a domain controller in a virtual hosting environment.
  2. Create a snapshot or alternative version of the virtual hosting environment.
  3. Let the domain controller continue to inbound replicate and to outbound replicate.
  4. Start the domain controller image file that you created in step 2.

These scenarios pretty much always involve a virtual environment, so if you have virtual DCs you may want to ensure backups are done on the physical DCs (you can never go wrong with performing backups on the FSMOs to start) and/or ensure that the Windows Backup tool is used to backup the AD database (SUPPORTED backup method is key).

Detecting USN Rollback

Detecting USN Rollback is extremely difficult since DCs running Windows 2000 or Windows 2003 RTM didn’t check for repeating USNs for the same Invocation ID. There are no errors in the NTDS Replication event log or when using the replication utility Repadmin. There is a manual method for detecting a USN Rollback using Repadmin and Microsoft KB 875495 describes this process:

One way to detect a USN rollback is to use the Windows Server version of Repadmin.exe to run the repadmin /showutdvec command. This version of Repadmin.exe displays the up-to-dateness vector USN for all domain controllers that replicate a common naming context. To detect a USN rollback, compare the output of the repadmin /showutdvec command on the domain controller with the output of the same command on the domain controller’s replication partners. If the direct replication partners have a higher USN number for the domain controller than the domain controller has for itself, and the repadmin /showreps command does not report replication errors between direct replication partners, you have compelling evidence of a USN rollback.

C:\>Repadmin /showutdvec dc1 dc=contoso,dc=com
Caching GUIDs…
Site1\DC1 @ USN 10 @ Time 2004-08-04 15:07:15
Site2\DC2 @ USN 24805 @ Time 2004-08-04 15:06:59
C:\>Repadmin /showutdvec dc2 dc=contoso,dc=com
Caching GUIDs…
Site1\DC1 @ USN 50 @ Time 2004-08-04 15:07:15
Site2\DC2 @ USN 24805 @ Time 2004-08-04 15:06:59

Note in the example repadmin output above, DC2 has a USN of 50 for DC1 while DC1 has a USN of 10 for itself.

Starting with Windows 2003 Sp1 or newer (or earlier with the KB 875495 hotfix), DCs track and flag when another DC (source DC) sends a USN that was previously acknowledged with the same invocation id.

When a USN Rollback is identified on a Windows 2003 Sp1 or newer (or earlier with the KB 875495 hotfix), the following actions are performed on that DC:

  • The DC write event 2095 to the DC’s Directory Services event log.
  • The DC disables inbound and outbound replication.
  • The DC recognizes the USN Rollback and pauses its Netlogon service. This prevents any changes from being performed on the DC.

Windows 2003 SP 1 and newer Domain Controllers that detect a USN Rollback state on a replication source DC, log the following event:

Event Type: Error
Event Source: NTDS Replication
Event Category: Replication
Event ID: 2095
Date: 3/10/2005
Time: 4:26:51 PM
User: USN\2B25VB$
Computer: 2B9A
Description: During an Active Directory replication request, the local domain controller (DC) identified a remote DC which has received replication data from the local DC using already-acknowledged USN tracking numbers. Because the remote DC believes it is has a more up-to-date Active Directory database than the local DC, the remote DC will not apply future changes to its copy of the Active Directory database or replicate them to its direct and transitive replication partners that originate from this local DC. If not resolved immediately, this scenario will result in inconsistencies in the Active Directory databases of this source DC and one or more direct and transitive replication partners. Specifically the consistency of users, computers and trust relationships, their passwords, security groups, security group memberships and other Active Directory configuration data may vary, affecting the ability to log on, find objects of interest and perform other critical operations. To determine if this misconfiguration exists, query this event ID using http://support.microsoft.com or contact your Microsoft product support. The most probable cause of this situation is the improper restore of Active Directory on the local domain controller. User Actions: If this situation occurred because of an improper or unintended restore, forcibly demote the DC. Remote DC: b55ee67f-ed73-4970-b2d4-7dc6f571439f Partition: CN=Configuration,DC=usn,DC=loc USN reported by Remote DC: 24707 USN reported by Local DC: 20485 For more information, see Help and Support Center at http://support.microsoft.com.

On the DC with USN Rollback the following events are logged:

Event Type: Warning
Event Source: NTDS General
Event Category: Replication
Event ID: 1113
Date: 3/10/2005
Time: 4:26:51 PM
User: USN\2B25VB$
Computer: 2B9A
Description: Inbound replication has been disabled by the user. For more information, see Help and Support Center at http://support.microsoft.com.

Event Type: Warning
Event Source: NTDS General
Event Category: Replication
Event ID: 1115
Date: 3/10/2005
Time: 4:26:51 PM
User: USN\2B25VB$
Computer: 2B9A
Description: Outbound replication has been disabled by the user. For more information, see Help and Support Center at http://support.microsoft.com

Event Type: Error
Event Source: NTDS General
Event Category: Service Control
Event ID: 2103
Date: 3/10/2005
Time: 4:26:51 PM
User: USN\2B25VB$
Computer: 2B9A
Description: The Active Directory database has been restored using an unsupported restoration procedure. Active Directory will be unable to log on users while this condition persists. As a result, the Net Logon service has paused. User Action See previous event logs for details. For more information, see Help and Support Center at http://support.microsoft.com.

Resolving USN Rollback on a DC

Microsoft recommends two methods to resolve a USN Rollback state:

  1. Demote & re-promote the DC – this resets the Invocation ID & the USN.
  2. Restore the DC from a supported backup (preferably using Microsoft’s Backup utility).

I recommend performing resolution step #1. Since the typical scenarios that bring about a USN Rollback involve imaging or performing an un-supported restoration, having a USN Rollback in the environment typically points to process issues. Often this is related to improper restore procedures.

In this situation, it is best to demote the Domain Controller by running dcpromo /forceremoval and perform a metadata cleanup of that DC. If the demoted DC was hosting any of the FSMO roles, they must be seized to another DC.

Only run DCPromo on the server to re-promote it after the metadata cleanup is successful (and any FSMOs are transferred).

Чиню домены.

Представьте себе, что в один не очень прекрасный день вы решили восстановить один из ваших контроллеров домена (КД) из резервной копии, которую вы по привычке сделали старым проверенным средством снятия образа диска, типа Acronis TrueImage. Или решили откатить ваш виртуализованный КД к старому снимку, сделанному средствами гипервизора (и всё это работало не под Windows Server 2012). Или же вам, как и мне однажды, не повезло: из-за сбоя RAID-контроллера, который управляет аппаратным зеркальным томом, содержащим систему КД, некоторое время тому назад из этого зеркала вылетел один диск, а после перезапуска RAID-контроллер решил загрузить систему именно с этой, устаревшей половинки зеркала.

И вот, после перезагрузки вы обнаруживаете, что ваш контроллер домена — уже не совсем контроллер домена: он совершенно не желает авторизовывать пользователей и реплицировать изменения базы данных Active Directory (AD) с другими КД. Если провести стандартную диагностику проблем AD с помощью утилит dcdiag, то мы увидим следующее (часть выдачи dcdiag для краткости опущена, важные для дальнейшего изложения признаки выделены жирным шрифтом):

Doing primary tests

Testing server: Default-First-Site-Name\DC2
Starting test: Advertising
Warning: DsGetDcName returned information for \\DC1.domain.loc, when
we were trying to reach DC2.
SERVER IS NOT RESPONDING or IS NOT CONSIDERED SUITABLE.
……………………. DC2 failed test Advertising
…………………………………………………………………

Starting test: Replications
[Replications Check,Replications Check] Inbound replication is
disabled.
To correct, run «repadmin /options DC2 -DISABLE_INBOUND_REPL»
[Replications Check,DC2] Outbound replication is disabled.
To correct, run «repadmin /options DC2 -DISABLE_OUTBOUND_REPL»
……………………. DC2 failed test Replications
Starting test: RidManager
……………………. DC2 passed test RidManager
Starting test: Services
w32time Service is stopped on [DC2]
NETLOGON Service is paused on [DC2]
……………………. DC2 failed test Services
— то есть, контроллер домена не объявляет себя контроллером домена, репликация базы данных AD отключена, а служба Netlogon («Сетевой вход в систему» в русской версии) находится в приостановленном состоянии. Если вы посмотрите в журнал событий Active Directory, то вы обнаружите в нём два характерных сообщения об ошибках:

с Event ID 2095

Event2095

и с Event ID 2103

Event2103

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

Если вы наблюдаете эти признаки, то это означает, что вы столкнулись с героем этой статьи — USN Rollback: возвращением текущего максимального последовательного номера изменений (USN) КД к старому, меньшему значению (с помощью номеров последовательных изменений — USN — Active Directory отслеживает, какие именно изменения следует передавать при репликации между контроллерами домена, подробнее об этом ниже). Прочитать официальную информацию от Microsoft об этой проблеме можно в Technet Library (применительно к специфике виртуализованных контроллеров домена) или статье 885875 MS KB (на английском языке).

Хотя механизм возникновения данной проблемы изложен в указанных выше статьях, считаю необходимым для полноты изложения остановиться на нём и в этой статье (те, кому это не интересно или некогда это читать, могут перейти сразу к описанию процедуры восстановления в разделе Собственно рецепт). Потому что, чтобы понять, чем плохо возвращение текущего максимального универсального номера последовательных изменений к старому значению, нужно знать, как используются эти номера при обновлении копий базы данных Active Directory.

Active Directory спроектирована таким образом, чтобы при синхронизации (репликации) можно было передавать на целевой КД не всю базу данных, а только те изменения, которые не были ещё получены целевым КД. Для этого каждый измененный (в т.ч. вновь созанный) в базе данных AD объект или атрибут объекта маркируется в своих метаданных идентификатором КД (Invocation ID), на котором было первоначально произведено это изменение, и последовательным номером (USN) этого изменения на данном первоначальном КД (посмотреть метаданные для любого объекта и всех его атрибутов можно командой repadmin /showmeta ). При каждом изменении, первоначально произведенном на данном КД, этот номер увеличивается. Кроме того, каждый КД хранит у себя список максимальных номеров реплицированных изменений для каждого из известных ему КД-источников обновлений (идентифицируемых по Invocation ID) для каждого из разделов каталога — up-to-dateness vector (его можно посмотреть командой repadmin /showutdvec ). И при репликации КД запрашивает только те изменения, номер USN которых выше максимального номера уже полученного изменения.

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

Поскольку все алгоритмы работы AD опираются на то, что содержимое баз данных на разных КД является (или достаточно быстро становится) одинаковым, то описанное выше положение дел является недопустимым. Чтобы его избежать, в механизм репликации AD был добавлен элемент контроля, проверяющий в момент первой репликации КД, что текущий максимальный номер USN на контроллере домена не меньше, чем максимальный номер реплицированных изменений, известных его партнерам по репликации. Если это условие не соблюдается, то AD блокирует входящую и исходящую репликацию, а также помечает (в реестре) свою копию базы данных как недоступную для записи по причине возвращения номера USN к меньшему значению — что как раз вызывает те самые симптомы, что описаны в начале статьи.

Обнаружение USN Rollback срабатывает, к сожалению, не всегда. Если контроллер домена после восстановления из образа долго не имеет связи с другими КД, и на нём за это время происходит много изменений, то после восстановления связи может оказаться, что на момент первой репликации после восстановления текущий максимальный номер USN окажется больше максимального номера реплицированных изменений, то условие отсутствия USN Rollback будет формально соблюдено, фактически имевший место откат назад номеров изменений обнаружен не будет и часть изменений так и останется не реплицированной. Такой вариант вполне реален при восстановлении КД после катастрофического отказа где-нибудь в филиале, где из-за того же отказа пострадала и связь. Так что, обнаружив приведенные в начале статьи симптомы, можно даже порадоваться — всё могло быть и хуже.

Как лечить USN Rollback

Лучшее лечение — это, как известно, профилактика. В применении к теме данной статьи это означает: делать резервные копии базы данных AD (она входит в раздел Состояние системы для КД) регулярно, и делать их программой, которая знает, как копировать и, главное — как восстанавливать базу данных AD. Простейшая из таких программ — это встроенная Windows Server Backup. Использование правильных программ исключает большинство возможных случаев возникновения USN Rollback, а если вдруг такая беда случилась (например, из-за сбоя RAID-контроллера, зеркалирующего системный диск) — без особых проблем восстановить базу данных AD.

Но вот что делать если беда уже случилась, а резервной копии базы данных AD нет? Рекомендации производителя — Microsoft — просты и незатейливы: понизить принудительно контроллер домена, удалить его метаданные из AD и повысить обратно. Процедуры эти просты и многократно описаны, здесь я на них останавливаться не буду. В большинстве случаев это можно проделать вполне безболезненно, и, собственно говоря, при наличии возможности именно так и стоит делать.

Интереснее другой вопрос — что делать, если принудительное понижение с последующим понижением — не вариант? Например, если на КД стоит какая-то программа, которая, с немалой степенью вероятности, не перенесёт такие манипуляции. Или USN Rollback возник на единственном контроллере вновь созданного домена, в котором уже были созданы учётные записи новых пользователей. Или вот, например, был случай на русском форуме Technet, когда системный администратор умудрился загнать в состояние USN Rollback все контроллеры корневого домена леса — как сохранить лес? В таких случаях рекомендованный производителем способ решения проблемы не годится. Но выход, тем не менее, есть.Чтобы понять, как этот выход работает, следует рассмотреть две вещи: как при корректном восстановлении базы данных AD удаётся избежать USN Rollback, и какие именно изменения вносятся в конфигурацию КД при обнаружении этого состояния.

Для обеспечения корректности работы восстановленной базы данных программа восстановления делает одну простую вещь: она после завершения восстановления (а оно производится при загрузке в режиме службы восстановления каталогов) записывает в реестр новое значение для Invocation ID в параметр «HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NTDS\Parameters\New Database GUID», заставляя AD при запуске во время следующей загрузки в нормальном режиме сменить Invocation ID — то есть заставляет выглядеть (с точки зрения механизма репликации базы данных AD) восстановленный контроллер домена как новый, совершенно другой КД, изменения на котором учитываются независимо от прежних, сделанных его до восстановления.

Что же касается реакции на USN Rollback то она включает в себя две вещи: во-первых, для подверженного ей КД отключается (установкой флагов DISABLE_INBOUND_REPL и DISABLE_OUTBOUND_REPL в атрибуте Options объекта «NTDS Settings», связанного с объектом данного КД в разделе конфигурации) входящая и исходящая репликация, во-вторых в реестре этого КД в параметре «HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NTDS\Parameters\DSA not writeable» (типа REG_DWORD) фиксируется, что база данных AD не является допустимой по причине возникновения USN Rollback (значение параметра устанавливается равным 4). При обнаружении этого последнего параметра происходит запись в журнал события с кодом 2103, а служба Netlogon ставится в приостановленное состояние.

И в свете всего вышеизложенного становится понятно, что нужно делать, чтобы вывести контроллер домена из состояния USN Rollback:

Собственно рецепт.

Предупреждение. Приведенные ниже действия не опираются на официальные рекомендации Microsoft (хотя и проверены мной лично). Они могут привести к возникновению рассогласованных копий базы данных Active Directory на разных контроллерах доменов (см. ниже). Поэтому используйте их под свою ответственность и только в крайнем случае.

Предупреждение 2. Если на пострадавшем контроллере домена в БД AD были внесены какие-либо изменения после возникновения состояния USN Rollback, то эти изменения, скорее всего, никогда не будут реплицированы на другие контроллеры домена, даже после восстановления по указанной ниже процедуре (причины были рассмотрены в предыдущем разделе). Из-за этого произойдёт рассогласование копий БД. И впоследствии это может вылиться в странное поведение (например, несовпадающие пароли учётных записей) или даже в нарушение репликации (ошибка 8606). Если USN Rollback был обнаружен сразу же, и контроллер домена был вовремя заблокирован, то вероятность возникновения таких ошибок невелика. Но если это был, например, восстановленный из образа диска контроллер где-нибудь в филиале, то последствия могут быть весьма неприятными. Я надеюсь рассмотреть, как можно заранее вычислить такие изменения и сделать их доступным для репликации, в одной из следующих статей.

1. Заставить AD изменить Invocation ID. Хотя можно сделать это, напрямую записав соответствующий параметр в реестр, я считаю предпочтительным сделать это с помощью штатного Backup/Restore — это заодно устранит и возможные рассогласования копий папки SYSVOL на пострадавшем контроллере домена и других КД и позволит избедать возможных проблем с её репликацией (это другая тема, которую я тут не затрагиваю). Последовательность действий примерно следующая (я не расписываю подробно все шаги, поскольку они отражены во многих руководствах):

1а. Подготовительные действия. Установить, если ещё не установлен, компонент архивации и подготовить место, куда будет записана резервная копия (либо чистый локальный либо съёмный диск, либо пустую общую сетевую папку). Рекомендую также посмотреть (командой repadmin /showrepl ) зафиксировать текущий Invocation ID контроллера домена.

1б. Выполнить резервное копирование состояния системы (а лучше, если позволяет время и место на диске/папке — всего системного тома).

1в. Загрузиться в режиме восстановления службы каталогов и восстановить состояние системы. Рекомендую делать это от имени локальной учётной записи администратора режима восстановления службы каталогов (я наблюдал случаи, когда попытка восстановления состояния системы при регистрации под доменным администраторам приводила к необъяснимым сбоям).

1г. Загрузить контроллер домена в обычном режиме.

2. Разрешить входящую и исходящую репликацию для контроллера домена. Перед включением репликации в качестве меры предосторожности рекомендую проверить, что показываемое командой repadmin /showrepl значение Invocation ID изменилось по сравнению со старым, зафиксированным на шаге 1а

Включение репликации производится командами

repadmin /options имя_КД -DISABLE_INBOUND_REPL

repadmin /options имя_КД -DISABLE_OUTBOUND_REPL

3. Удалить отметку о том, что база данных AD находится в недопустимом для записи состоянии по причине USN Rollback. Для этого надо запустить редактор реестра, выбрать ключ HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NTDS\Parameters, найти в нём параметр «DSA not writeable» (его значение должно быть равно 4) и удалить этот параметр.

4. Запустить из приостановленного состояния (если она ещё не запустилась сама) службу Netlogon

После выполнения этих шагов я рекомендую (хотя это не обязательно) ещё раз перезагрузить контроллер домена и выполнить его диагностику с помощью команды dcdiag: после ликвидации USN Rollback могут проявиться и другие ошибки (см. например уже упоминавшийся случай на русском форуме Technet — там пришлось устранять и проблемы с SYSVOL, и не удалённые вовремя («застрявшие») из-за неработавшей репликации объекты).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *