SnapmirrorConvert.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
#############################################################################################
# HELPER FUNCTIONS for
# - logging log4net
# - pretty console output
# - load modules
# - connect to cdot cluster
#############################################################################################
function init_log4net{
    write-verbose "Loading log4net from path $PSScriptRoot\log4net.dll"
    $log4NetLocation = "$PSScriptRoot\log4net.dll" 
    [Reflection.Assembly]::LoadFrom($log4NetLocation) | Out-Null
    [log4net.LogManager]::ResetConfiguration();
}
function exit_log4net{
    [log4net.LogManager]::Shutdown();
    [log4net.LogManager]::ResetConfiguration();
}
function get_log4net_level($level){
    switch($level){
        "Debug" {return [log4net.Core.Level]::Debug}
        "Info" {return [log4net.Core.Level]::Info}
        "Warn" {return [log4net.Core.Level]::Warn}
        "Error" {return [log4net.Core.Level]::Error}
        "Off" {return [log4net.Core.Level]::Off}
        "Fatal" {return [log4net.Core.Level]::Fatal}
        "All" {return [log4net.Core.Level]::All}

    }
}
function set_log_level{
    param(
        $loggerInstance,
        [ValidateSet("All","Debug","Info","Warn","Error","Fatal","Off")]
        $level
    )
    $wrapper = [log4net.LogManager]::GetLogger($loggerinstance)
    $l = $wrapper.Logger
    $l.Level = get_log4net_level -level $level
    $l.Repository.Configured=$true

}
function add_appender($loggerinstance,$appender){
    if( $null -ne $appender ){
        $wrapper = [log4net.LogManager]::GetLogger($loggerinstance)
        $l = $wrapper.Logger
        $l.AddAppender($appender)
    }
}
function create_rolling_log_appender($name,$file,$Threshold="Info"){
    $rlf = new-object log4net.Appender.RollingFileAppender
    $rlf.MaximumFileSize = "50MB"
    $rlf.Name = $name
    $rlf.File = $file
    $rlf.RollingStyle = "Size"
    $rlf.StaticLogFileName = $true
    $rlf.MaxSizeRollBackups = "20"
    $rlf.Layout = new-object log4net.Layout.PatternLayout("[%date{yyyy-MM-dd HH:mm:ss.fff}] [%level] %message%n")
    $rlf.Threshold = (get_log4net_level -level $Threshold)
    $rlf.ActivateOptions()
    return $rlf
}
function get_logger($name){
    return [log4net.LogManager]::GetLogger($name)
}
Function clean_and_exit () { 

    Write-Log "[ EXIT ] Finished"
    exit_log4net
    break     

}
Function handle_error([object]$object){
    $ErrorMessage = $object.Exception.Message
    $FailedItem = $object.Exception.ItemName
    $Type = $object.Exception.GetType().FullName
    $CategoryInfo = $object.CategoryInfo
    $ErrorDetails = $object.ErrorDetails
    $Exception = $_.Exception
    $FullyQualifiedErrorId = $object.FullyQualifiedErrorId
    $InvocationInfoLine = $object.InvocationInfo.Line
    $InvocationInfoLineNumber = $object.InvocationInfo.ScriptLineNumber
    $PipelineIterationInfo = $object.PipelineIterationInfo
    $ScriptStackTrace = $object.ScriptStackTrace
    $TargetObject = $object.TargetObject
    Write-LogError  "Trap Error: [$ErrorMessage]"
    Write-LogDebug  "Trap Item: [$FailedItem]"
    Write-LogDebug  "Trap Type: [$Type]"
    Write-LogDebug  "Trap CategoryInfo: [$CategoryInfo]"
    Write-LogDebug  "Trap ErrorDetails: [$ErrorDetails]"
    Write-LogDebug  "Trap Exception: [$Exception]"
    Write-LogDebug  "Trap FullyQualifiedErrorId: [$FullyQualifiedErrorId]"
    Write-LogDebug  "Trap InvocationInfo: [$InvocationInfoLineNumber] [$InvocationInfoLine]"
    Write-LogDebug  "Trap PipelineIterationInfo: [$PipelineIterationInfo]"
    Write-LogDebug  "Trap ScriptStackTrace: [$ScriptStackTrace]"
    Write-LogDebug  "Trap TargetObject: [$TargetObject]"
}
function format-colorbrackets {
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [string] $Format,
        [switch] $FirstIsSpecial,
        [switch] $NoNewLine,
        [string] $ForceColor=""
    )

    $result = Select-String -Pattern '\[([^\]]*)\]' -InputObject $Format -AllMatches
    $i = 0
    $first = $true
    foreach($match in $result.Matches) {
        $group = $match.Groups[1]
        WriteHost $Format.Substring($i, $group.Index - $i) -NoNewline
        if(($first -and $FirstIsSpecial)){
            $color="green"
            if($ForceColor.length -gt 1){$color=$ForceColor}
            $first=$false
        }else{
            $color="cyan"
        }
        
        WriteHost $group.Value -NoNewline -ForegroundColor $color
        $i = $group.Index + $group.Length
    }

    if($i -lt $Format.Length){WriteHost $Format.Substring($i, $Format.Length - $i) -NoNewline }
    WriteHost "" -NoNewline:$NoNewLine

}
function import_module($name){
    if (-not(Get-Module -Name $name)) {
        if (Get-Module -ListAvailable | Where-Object { $_.name -eq $name }) {
            Import-Module $name  
            return $true
        } else {   
            return $false
        }
    } else{
        return $true
    }
}
function load_module($name){
    try {
        if (import_module $name) {
            Write-LogSuccess "Loaded module $name"
        } else {
            Write-LogError "Failed to load module $name"
            Write-Log "Did you install the module ? `n`r"
            Write-Log "[ Tip ] Install-Module $name `n`r" -forceColor Magenta -firstIsSpecial
            clean_and_exit 
        }
    } catch {
            Write-LogError "Failed to load module $name"
            Write-Log "Did you install the module ? `n`r"
            Write-Log "[ Tip ] Install-Module $name `n`r" -forceColor Magenta -firstIsSpecial
            clean_and_exit 
        handle_error -object $_
        clean_and_exit 
    }
}
function connect_controller($name,$type){
    if(-not $connections[$name]){
        $credentials = Get-Credential -Message "Provide credentials for $name [$type]"
        try{
            $connections[$name] = Connect-NcController $name -Credential $credentials -HTTPS
            Write-LogSuccess "Connected to $type cluster $name"
        }catch{
            Write-LogError "Failed to connect to $type cluster $name"
            handle_error $_
            clean_and_exit 
        }
    }
    return $connections[$name]
}
function WriteHost{
    param(
        [Parameter(Position=0, Mandatory=$true)]
        $Object,
        $ForegroundColor="white",
        [switch]$NoNewLine
    )

    Write-Host $Object -ForegroundColor $ForegroundColor -NoNewline:$NoNewLine

}
function Write-Brackets ([string]$mess,$status,$foregroundcolor) {
    if($mess){
        WriteHost "[" -NoNewLine
        WriteHost $status -ForegroundColor $foregroundcolor -NoNewLine
        WriteHost "] " -NoNewLine
        format-colorbrackets "$mess" -FirstIsSpecial -ForceColor yellow
    }
}
function Write-LogDebug ([string]$mess) {
    if($LogLevel -eq "Debug"){
        Write-Brackets -mess $mess -status " INFO " -foregroundcolor cyan
    }
    $Global:MasterLog.Debug($mess)
}
function Write-LogSuccess ([string]$mess) {
    Write-Brackets -mess $mess -status " OK " -foregroundcolor green
    $Global:MasterLog.Info($mess)
}
function Write-LogError ([string]$mess) {
    Write-Brackets -mess $mess -status " ERR " -foregroundcolor red
    $Global:MasterLog.Error($mess)  
}
function Write-LogWarn ([string]$mess) {
    Write-Brackets -mess $mess -status " WARN " -foregroundcolor yellow
    $Global:MasterLog.Warning($mess)  
}
function Write-Log ([string]$mess,[switch]$firstIsSpecial,[switch]$noNewLine,$forceColor) {

    format-colorbrackets "$mess" -FirstIsSpecial:$firstIsSpecial -NoNewLine:$noNewLine -ForceColor $forceColor
    $Global:MasterLog.Info($mess)
 
}
function Write-LogTitle ([string]$mess) {
    if($mess){
        WriteHost ("-" * $mess.Length)
        WriteHost $mess -ForegroundColor Magenta
        WriteHost ("-" * $mess.Length)
        $Global:MasterLog.Info($mess)
    }
}


#############################################################################################
# LOGIC STARTS HERE
#############################################################################################

<#
.Synopsis
   Convert snapmirror policy
.DESCRIPTION
   SRM and NetApp(c) SRA (currently) have no capability to properly run planned migrations
   or test migrations when the underlying SnapMirror(c) relationsships are Synchronous.
   The SRA was built for Asynchronous relations and certain underlying actions such as
   snapmirror update fail. Also, after migrations, the SRA create async relations.
 
   The cmdlet converts all snapmirrors, found in the volumes matching the config regular expressions,
   to the target snapmirror policy in the config file.
 
   So now you can run this cmdlet to convert sync to async (before srm testing).
   And to convert async to sync (after finishing testing).
     
   The final state, either broken-off or snapmirrored, will remain.
 
   TIPS : Use -WhatIf and -Confirm.
 
   DEPENDENCIES : Requires DataONTAP and Powershell-yaml (use install-module)
 
   CONFIG FILE : What convertion and in what direction on which snapmirrors is defined
                 in the config yaml file you need to pass.
.EXAMPLE
    Invoke-SrmScript -configfile .\srmsync\prod-dr-prep.yaml -LogLevel Debug -Confirm:$false
    ----------------
    Preparing script
    ----------------
    [ OK ] Loaded module dataOntap
    [ OK ] Loaded module powershell-yaml
    [ OK ] Loaded configfile
    [ INFO ] source_cluster : r2d2
    [ INFO ] destination_cluster : c3po
    [ INFO ] snapmirror_volume_regex : srm_sync.*
    [ INFO ] snapmirror_vserver_regex : srm_vserver.*
    [ INFO ] target_snapmirror_policy : MirrorAndVault
    [ OK ] Connected to cluster c3po
    [ OK ] Lookup volumes
    [ OK ] Lookup snapmirrors
    --------------------------------
    Found following matching volumes
    --------------------------------
    [broken-off][Sync][sync_mirror][srm_sync_volume] -> [srm_sync_volume_dest]
    ----------------------------
    Converting to MirrorAndVault
    ----------------------------
    [ INFO ] [already broken-off][srm_sync_volume] -> [srm_sync_volume_dest]
    [ OK ] [removed ][srm_sync_volume] -> [srm_sync_volume_dest]
    [ OK ] [released ][srm_sync_volume] -> [srm_sync_volume_dest]
    [ OK ] [recreated ][srm_sync_volume] -> [srm_sync_volume_dest]
    [ INFO ] [converted to async][srm_sync_volume] -> [srm_sync_volume_dest]
    [ EXIT ] Finished
#>

function Convert-SnapmirrorPolicy{
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
    param(
        # The path of the yaml file that contains the configuration
        # - determines the snapmirror direction (source, dest)
        # - determines the volume selection (volume & vserver regex)
        # - determines the target snapmirror policy
        #
        # Example :
        # source_cluster : "r2d2"
        # destination_cluster : "c3po"
        # snapmirror_volume_regex : "srm_sync.*"
        # snapmirror_vserver_regex : "srm_vserver.*"
        # target_snapmirror_policy : "MirrorAndVault"
        #
        [Parameter(Mandatory = $true)]
        [string]$ConfigFile,

        [ValidateSet("Debug", "Info", "Warn", "Error", "Fatal", "Off")]
        [string]$LogLevel = "Debug",

        [Parameter(Mandatory = $false)]
        [string]$LogFile = ".\SnapmirrorConvert.log",

        # Forces the resync in case the snapmirror is broken
        [switch]$ForceResync
    )

    $ErrorActionPreference = "stop"
    $connections = @{}
    $config = @{}
    $found_snapmirrors = @()

    ###########
    # init log
    ###########
    try{
        init_log4net
        $masterLogFileAppender = create_rolling_log_appender -name "srmsync.log" -file $LogFile -threshold $LogLevel
        add_appender -loggerinstance "srmsynclog" $masterLogFileAppender
        set_log_level -loggerinstance "srmsynclog" -level "All"
        $Global:MasterLog = get_logger -name "srmsynclog" 
    }catch{
        Write-Error "Failed to initialize log4net"
        clean_and_exit              
    }

    ###########
    # PREP
    ###########
    Write-LogTitle "Preparing script"

    # import modules
    load_module dataOntap
    load_module powershell-yaml

    # load config file
    try{
        $config = Get-Content $ConfigFile | ConvertFrom-Yaml
    }catch{
        Write-LogError "Failed to load ConfigFile $ConfigFile"
        handle_error $_
        clean_and_exit 
    }
    Write-LogSuccess "Loaded ConfigFile"
    Write-LogDebug ("source_cluster : {0}" -f $config.source_cluster)
    Write-LogDebug ("destination_cluster : {0}" -f $config.destination_cluster)
    Write-LogDebug ("snapmirror_volume_regex : {0}" -f $config.snapmirror_volume_regex)
    Write-LogDebug ("snapmirror_vserver_regex : {0}" -f $config.snapmirror_vserver_regex)
    Write-LogDebug ("target_snapmirror_policy : {0}" -f $config.target_snapmirror_policy)

    ##################
    # connect to both clusters
    ##################
    $source_controller = connect_controller $config.source_cluster -type "source"
    $destination_controller = connect_controller $config.destination_cluster -type "destination"

    $source_cluster_name = (Get-NcCluster -Controller $source_controller).ClusterName
    $destination_cluster_name = (Get-NcCluster -Controller $destination_controller).ClusterName

    ###################
    # policy check
    ###################
    $targetSnapmirrorPolicy = $config.target_snapmirror_policy
    $checkpolicy = Get-NcSnapmirrorPolicy -Name $targetSnapmirrorPolicy -Controller $destination_controller

    if(-not $checkpolicy){
        Write-LogError "$targetSnapmirrorPolicy does not exist on $destination_controller"
        clean_and_exit
    }else{
        Write-LogSuccess "$targetSnapmirrorPolicy is a valid snapmirror policy on destination $destination_controller"
    }

    ##################
    # get information
    ##################
    try{
        $source_volumes = Get-NcVol -Controller $source_controller
        Write-LogSuccess ("Lookup volumes on source {0}" -f $source_controller.name)
        Write-LogDebug ("Found {0}" -f @($source_volumes).Count)
        $source_volumes | %{
            Write-LogDebug (" - {0}" -f $_.name)
        }
        $peers = Get-NcVserverPeer -Controller $destination_controller
        $dest_snapmirrors = Get-NcSnapmirror -Controller $destination_controller
        $destination_snapmirrors = $dest_snapmirrors | %{
            $dsm = $_
            if(-not [bool]$dsm.SourceCluster -or -not [bool]$dsm.DestinationCluster){
                $peer = $peers | ?{$_.vserver -eq $dsm.DestinationVserver -and $_.RemoteVserverName -eq $dsm.SourceVserver}
                if($peer){
                    $dsm.SourceCluster = $peer.PeerCluster
                    $dsm.DestinationCluster = $destination_cluster_name
                    Write-LogDebug ("Corrected snapmirror relation with cluster info {0}->{1}" -f $dsm.SourceCluster,$dsm.DestinationCluster)
                    $dsm
                }else{
                    Write-LogDebug ("no vserver peering information found for Snapmirror {0}:{1} -> {2}:{3}" -f $_.SourceVserver,$_.SourceVolume,$_.DestinationVserver,$_.DestinationVolume)
                }
            }
        }
        Write-LogSuccess ("Lookup snapmirrors on destination {0}" -f $destination_controller.Name)
        Write-LogDebug ("Found {0}" -f @($destination_snapmirrors).Count)
        $destination_snapmirrors | %{
            Write-LogDebug (" - {0}:{1} -> {2}:{3}" -f $_.SourceVserver,$_.SourceVolume,$_.DestinationVserver,$_.DestinationVolume)
        }
    }catch{
        handle_error $_
        clean_and_exit 
    }

    # search maching volumes based on regex's
    Write-LogDebug ("Check regular expressions [{0}][{1}]" -f $config.snapmirror_vserver_regex,$config.snapmirror_volume_regex)
    foreach($v in $source_volumes){
        if($v.name -match $config.snapmirror_volume_regex -and $v.Vserver -match $config.snapmirror_vserver_regex){
            Write-LogDebug ("- {0}:{1} matches" -f $v.Vserver,$v.name)
            $found_snapmirrors +=[PSCustomObject]@{
                volume = $v.name
                mirror = ""
                policy = ""
                type = ""
            }
        }
    }

    # find mirrors on found volumes and complete info with snapmirror policy
    foreach($s in $found_snapmirrors){
        Write-LogDebug ("Checking potential snapmirror for volume {0}" -f $s.volume)
        foreach($sm in $destination_snapmirrors){
            
            try{
                $policy = Get-NcSnapmirrorPolicy -Name $sm.policy -Controller $destination_controller
            }catch{
                Write-LogError ("Failed to get snapmirror policy for {0}" -f $s.volume)
                handle_error
                clean_and_exit 
            }
            
            if($s.volume -eq $sm.sourceVolume -and $source_cluster_name -eq $sm.sourcecluster){

                Write-LogDebug ("Match found for {0} in {1} -> {2}" -f $s.volume,$sm.SourceVolume,$sm.DestinationVolume)
                $s.mirror = $sm
                $s.policy = $policy.Name
                $s.type = $policy.Type
            }else{
                Write-LogDebug ("No match found for {0} in {1} -> {2} and source cluster [{3}]=[{4}]" -f $s.volume,$sm.SourceVolume,$sm.DestinationVolume,$source_cluster_name,$sm.sourcecluster)
            }

        }
    }
    
    ##################
    # output to console
    ##################
    Write-LogTitle "Found following matching volumes"
    foreach($s in $found_snapmirrors){
        if($s.mirror){
            if($s.type -eq "snapmirrored"){
                $color = "green"
            }else{
                $color = "yellow"
            }
            Write-Log ("[{0}][{4}][{3}][{1}] -> [{2}]" -f $s.mirror.mirrorstate,$s.volume,$s.mirror.destinationvolume,$s.type,$s.policy) -firstIsSpecial -forceColor $color
        }else{
            Write-Log ("[missing][{0}] -> []" -f $s.volume) -firstIsSpecial -forceColor red
        }
    }

    ##################
    # start conversion
    ##################
    Write-LogTitle "Converting to $targetSnapmirrorPolicy"
    foreach($s in ($found_snapmirrors | ?{$_.mirror})){

        try{

            # implement whatif and confirm
            if($pscmdlet.ShouldProcess(("[{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume), "Convert Snapmirror to $targetSnapmirrorPolicy")){
    
                # if not broken, break
                if($s.mirror.MirrorState -ne "broken-off"){

                    # quiesce before break
                    try{
                        Invoke-NcSnapmirrorQuiesce -Controller $destination_controller `
                            -DestinationCluster $s.mirror.DestinationCluster `
                            -DestinationVserver $s.mirror.DestinationVserver `
                            -DestinationVolume $s.mirror.DestinationVolume `
                            -SourceCluster $s.mirror.sourceCluster `
                            -SourceVserver $s.mirror.sourceVserver `
                            -SourceVolume $s.mirror.sourceVolume `
                            -Confirm:$false 
                        Write-LogSuccess ("[queiscing ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)

                    }catch{
                        Write-LogError ("Failed to quiesce relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                        handle_error $_
                        clean_and_exit 
                    }

                    # break
                    $wait = 5
                    try{
                        Do{
                            $QuiesceCheck = Get-NcSnapmirror -Controller $destination_controller `
                                -DestinationCluster $s.mirror.DestinationCluster `
                                -DestinationVserver $s.mirror.DestinationVserver `
                                -DestinationVolume $s.mirror.DestinationVolume `
                                -SourceCluster $s.mirror.sourceCluster `
                                -SourceVserver $s.mirror.sourceVserver `
                                -SourceVolume $s.mirror.sourceVolume 

                            if($QuiesceCheck.Status -eq "quiesced"){
                                Write-LogSuccess ("[queisced ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)

                                Invoke-NcSnapmirrorBreak -Controller $destination_controller `
                                    -DestinationCluster $s.mirror.DestinationCluster `
                                    -DestinationVserver $s.mirror.DestinationVserver `
                                    -DestinationVolume $s.mirror.DestinationVolume `
                                    -SourceCluster $s.mirror.sourceCluster `
                                    -SourceVserver $s.mirror.sourceVserver `
                                    -SourceVolume $s.mirror.sourceVolume `
                                    -Confirm:$false
                            }else{
                                Write-LogDebug ("[{0}] Waiting for status quiesced" -f $QuiesceCheck.Status)
                                sleep -Seconds $wait
                            }
                        }while($QuiesceCheck.Status -ne "quiesced")
            
                        Write-LogSuccess ("[broken-off][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)

                    }catch{
                        Write-LogError ("Failed to break relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                        handle_error $_
                        clean_and_exit 
                    }
                }elseif($s.mirror.MirrorState -eq "broken-off"){
                    Write-LogDebug ("[already broken-off][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                }

                # remove
                try{
                    Remove-NcSnapmirror -Controller $destination_controller `
                        -DestinationCluster $s.mirror.DestinationCluster `
                        -DestinationVserver $s.mirror.DestinationVserver `
                        -DestinationVolume $s.mirror.DestinationVolume `
                        -SourceCluster $s.mirror.sourceCluster `
                        -SourceVserver $s.mirror.sourceVserver `
                        -SourceVolume $s.mirror.sourceVolume `
                        -Confirm:$false
            
                    Write-LogSuccess ("[removed ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)

                }catch{
                    Write-LogError ("Failed to remove relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                    handle_error $_
                    clean_and_exit 
                }

                # release on source
                try{
                    Invoke-NcSnapmirrorRelease -Controller $source_controller `
                        -DestinationCluster $s.mirror.DestinationCluster `
                        -DestinationVserver $s.mirror.DestinationVserver `
                        -DestinationVolume $s.mirror.DestinationVolume `
                        -SourceCluster $s.mirror.sourceCluster `
                        -SourceVserver $s.mirror.sourceVserver `
                        -SourceVolume $s.mirror.sourceVolume `
                        -RelationshipInfoOnly `
                        -Confirm:$false
            
                    Write-LogSuccess ("[released ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)

                }catch{
                    if($_.Exception.Message -match "not found"){
                        Write-LogDebug ("[no relation to release][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                    }else{
                        Write-LogError ("Failed to release relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                        handle_error $_
                        clean_and_exit 
                    }
                }

                # recreate with new policy
                try{
                    $out = New-NcSnapmirror -Controller $destination_controller `
                        -DestinationCluster $s.mirror.DestinationCluster `
                        -DestinationVserver $s.mirror.DestinationVserver `
                        -DestinationVolume $s.mirror.DestinationVolume `
                        -SourceCluster $s.mirror.sourceCluster `
                        -SourceVserver $s.mirror.sourceVserver `
                        -SourceVolume $s.mirror.sourceVolume `
                        -Policy $targetSnapmirrorPolicy

                    Write-LogSuccess ("[recreated ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
   
                }catch{
                    Write-LogError ("Failed to recreate relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                    handle_error $_
                    clean_and_exit 
                }

                if($s.mirror.MirrorState -ne "broken-off" -or $ForceResync){

                    if($s.mirror.MirrorState -eq "broken-off" -and $ForceResync){
                            Write-LogDebug ("[force resync][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                        }


                    try{

                        $out = Invoke-NcSnapmirrorResync -Controller $destination_controller `
                            -DestinationCluster $s.mirror.DestinationCluster `
                            -DestinationVserver $s.mirror.DestinationVserver `
                            -DestinationVolume $s.mirror.DestinationVolume `
                            -SourceCluster $s.mirror.sourceCluster `
                            -SourceVserver $s.mirror.sourceVserver `
                            -SourceVolume $s.mirror.sourceVolume `
                            -Confirm:$false
            
                        Write-LogSuccess ("[resynced ][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                    }catch{
                        Write-LogError ("Failed to resync relation [{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
                        handle_error $_
                        clean_and_exit 
                    }
                }

                Write-LogDebug ("[converted to $targetSnapmirrorPolicy][{0}] -> [{1}]" -f $s.volume,$s.mirror.destinationvolume)
            }
        }catch{
            handle_error $_
            clean_and_exit 
        }finally{
        }
    }
    clean_and_exit

}