-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPsMapRedux.psm1
More file actions
654 lines (536 loc) · 38.5 KB
/
Copy pathPsMapRedux.psm1
File metadata and controls
654 lines (536 loc) · 38.5 KB
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
642
643
644
645
646
647
648
649
650
651
652
653
654
#
# Date: March 27 2012
# Daniel Dittenhafer
# MapReduce framework module for PowerShell
function New-MapReduxItem
{
Param
(
[Parameter(Position=0, Mandatory=$true)]
[string] $Name,
[ValidateNotNullOrEmpty()]
[Parameter(Position=1, Mandatory=$true)]
[ScriptBlock] $MapFunction,
[ValidateNotNullOrEmpty()]
[Parameter(Position=2, Mandatory=$true)]
[ScriptBlock] $ReduceFunction
)
process
{
$Obj = New-Object PSObject;
$Obj | Add-Member -Type NoteProperty -Name Name -Value $Name;
$Obj | Add-Member -type NoteProperty -Name Map -Value $MapFunction;
$Obj | Add-Member -type NoteProperty -Name Reduce -Value $ReduceFunction;
$Obj;
}
<#
.SYNOPSIS
Creates a new instance the "MapReduxItem" structure used by the Invoke-MapRedux function.
.Description
.PARAMETER MapFunction
The script block that performs the mapping with a subset of the dataset. This scriptblock should take the form shown in the example.
.PARAMETER ReduceFunction
The script block that performs the reducer activities with the results of the map function.
.EXAMPLE
$aMap = {
Param
(
[PsObject] $dataset
)
# Indicate the job is running on the remote node.
Write-Host ($env:computername + "::Map");
# The hashtable to return
$list = @{};
# ... Perform the mapping work and prepare the $list hashtable result with your custom PSObject...
# ... The $dataset has a single 'Data' property which contains an array of data rows
# which is a subset of the originally submitted data set.
# Return the hashtable (Key, PSObject)
Write-Output $list;
}
# A Reduce scriptblock
$aReduce =
{
Param
(
[object] $key,
[PSObject] $dataset
)
Write-Host ($env:computername + "::Reduce - Count: " + $dataset.Data.Count)
# The hashtable to return
$redux = @{};
# Return
Write-Output $redux;
}
# Create the item data
$Mr = New-MapReduxItem "My Example MapRedux Job" $MyMap $MyReduce
.LINK
http://geekswithblogs.net/dwdii
.NOTES
Name: New-MapReduxItem
Author: Daniel Dittenhafer
#>
}
function New-MapReduxJob
{
Param
(
[ValidateNotNullOrEmpty()]
[string] $NodeName,
[ValidateNotNullOrEmpty()]
[object] $DataSet
)
process
{
$Obj = New-Object PSObject;
$Obj | Add-Member -Type NoteProperty -Name NodeName -Value $NodeName;
$Obj | Add-Member -type NoteProperty -Name DataSet -Value $DataSet;
$Obj | Add-Member -type NoteProperty -Name Job -Value $null;
$Obj;
}
}
function New-NodeState
{
Param
(
[ValidateNotNullOrEmpty()]
[string] $Name,
[ValidateNotNullOrEmpty()]
[bool] $Enabled,
[ValidateNotNullOrEmpty()]
[bool] $Active
)
process
{
$Obj = New-Object PSObject;
$Obj | Add-Member -Type NoteProperty -Name Name -Value $Name;
$Obj | Add-Member -type NoteProperty -Name Enabled -Value $Enabled;
$Obj | Add-Member -type ScriptProperty -Name Active -Value { ActiveJobs -gt 0}
$Obj | Add-Member -type NoteProperty -Name MaxJobs -Value 5
$Obj | Add-Member -type NoteProperty -Name ActiveJobs -Value 0
$Obj | Add-Member -type NoteProperty -Name TotalJobsProcessed -Value 0
$Obj;
}
}
function Initialize-MapReduxNode
{
Param
(
[ValidateNotNullOrEmpty()]
[string[]] $ComputerName
)
process
{
#Local Variables
$nodes = @{};
# Map - Loop for each node...
foreach($cn in $ComputerName)
{
# track the node.
$nodes.Add($cn, (New-NodeState -Name $cn -Enabled $true -Active $false))
}
# Return
$nodes;
}
}
function Get-MapChunk
{
Param
(
[ValidateNotNullOrEmpty()]
[object[]] $DataSet,
[int] $SubsetCount,
[int] $CurPart
)
process
{
$start = $CurPart * $SubsetCount
$max = $start + $SubsetCount;
ConvertTo-MapReduxDataSet -DataSet $DataSet[$start..($max - 1)] | Write-Output
}
}
function ConvertTo-MapReduxDataSet
{
Param
(
[object] $DataSet
)
process
{
$Obj = New-Object PSObject;
$Obj | Add-Member -Type NoteProperty -Name Data -Value $DataSet;
$Obj;
}
}
function New-MapReduxInvocation
{
Param
(
[hashtable] $Nodes
)
process
{
$Obj = New-Object PSObject;
$Obj | Add-Member -type NoteProperty -Name Nodes -Value $Nodes;
$Obj | Add-Member -Type NoteProperty -Name Maps -Value @{};
$Obj | Add-Member -Type NoteProperty -Name PsJobs -Value @{};
$Obj | Add-Member -Type NoteProperty -Name Reducers -Value @{};
$Obj | Add-Member -type NoteProperty -Name Partitions -Value @{};
$Obj | Add-Member -type NoteProperty -Name FinalResults -Value @();
$Obj;
}
}
function Start-MapReduxMapper
{
Param
(
[PSObject] $Mri,
[object[]] $DataSet
)
process
{
$CurPart = 0;
$NodeJobsMax = $Mri.Nodes.Count * $Mri.Nodes[0].MaxJobs;
$SubsetCount = $DataSet.Count / ($Mri.Nodes.Count);
# Map - Loop for each node...
foreach($n in $mri.Nodes.Values)
{
# Split into a 'managable' junk for the mapper
$subset = Get-MapChunk -DataSet $DataSet -SubsetCount $SubsetCount -CurPart $CurPart
# Run job on a node
$mj = Submit-MapReduxJob -Nodes $nodes -MapReduceFx $MapReduceItem.Map -DataSet $subset
# Add to our job list
$mri.PsJobs.Add($mj.Job.Id, $mj.Job);
$mri.Maps.Add($mj.Job.Id, $mj);
$CurPart++;
}
# Return
Write-Output $Mri;
}
}
function Complete-MapperStep
{
Param
(
[PSObject] $Job,
[hashtable] $MapResults,
[PSObject] $Mri
)
process
{
# Partition
foreach($key in $mapResults.Keys)
{
if($Mri.Partitions.ContainsKey($key))
{
$Mri.Partitions.Item($key) += $mapResults.Item($key);
}
else
{
$Mri.Partitions.Add($key, @($mapResults.Item($key)));
}
}
# Update Maps list.
$Mri.Maps.Remove($Job.Id);
# Return
Write-Output $Mri;
}
}
function Complete-ReducerStep
{
Param
(
[PSObject] $Job,
[hashtable] $ReducerResults,
[PSObject] $Mri
)
process
{
# Get the map results
$Mri.FinalResults += $ReducerResults
# Update Reducers list.
$Mri.Reducers.Remove($Job.Id);
# Return
Write-Output $Mri
}
}
function Complete-MapReduxStep
{
Param
(
[PSObject] $Mri,
[PSObject] $MapReduceFx,
[ScriptBlock] $CompletionFx,
[switch] $ReceiveFailureResults
)
process
{
$bCompletedOrFailed = $true;
# Wait for at least one job to finish, and then we can start partitioning...
do
{
$jobsarray = @(1..($Mri.PsJobs.Count))
$Mri.PsJobs.Values.CopyTo($jobsarray, 0);
Wait-Job -Job $jobsarray -Any | Out-Null
do
{
# Switch back and forth...
if($bCompletedOrFailed)
{
$state = "Completed";
}
else
{
$state = "Failed";
}
# Get a job with the given state...
$job = $jobsarray | Where-Object {$_.State -eq $state} | Select-Object -First 1
$bCompletedOrFailed = -not $bCompletedOrFailed;
}
while(($job -eq $null) -and ($jobsarray.Count -gt 0))
# Are we done?
if($job -eq $null)
{
# NO OP
}
else
{
if($job.State -eq "Completed")
{
# Call the completion routine...
#
# Get the map results
Write-Verbose ("Receiving results from " + $job.Location + "...");
$results = Receive-Job -Job $job
# Call the completion routine itself
$Mri = Invoke-Command -ScriptBlock $CompletionFx -ArgumentList ($Job, $results, $Mri)
# Finish...
Remove-Job -Job $job
$Mri.PsJobs.Remove($job.Id)
$node = $Mri.Nodes.Item($job.Location);
$node.ActiveJobs--;
$node.Enabled = $true;
$node.TotalJobsProcessed++;
}
else
{
if($job.State -eq "Failed")
{
# Get the cooresponding mapjob
$mj = $Mri.Maps.Item($job.Id)
if($mj -eq $null)
{
$mj = $Mri.Reducers.Item($job.Id);
$bReducer = $true;
}
# If node is still enabled, then report to screen...
$node = $Mri.Nodes.Item($mj.NodeName);
if($node.Enabled -eq $true)
{
# Warning....
Write-Warning ("Node failed (" + $node.Name + ") - Marked as disabled and resubmitting job");
if($ReceiveFailureResults.IsPresent)
{
# See what comes back...
$results = Receive-Job -Job $job
}
}
# Need to mark the map node as 'down' and resubmit this job to another node...
$node.Enabled = $false;
$node.ActiveJobs--;
# Resubmit the Map job...
$mj = Submit-MapReduxJob -Nodes $Mri.Nodes -MapReduceFx $MapReduceFx -DataSet $mj.DataSet
if($mj -eq $null)
{
Write-Verbose ("All nodes busy, waiting briefly to resubmit...");
Start-Sleep -Milliseconds 100
}
else
{
# Cleanup
Remove-Job -Job $job
$Mri.PsJobs.Remove($job.Id)
if($bReducer)
{
$Mri.Reducers.Remove($job.Id)
$Mri.Reducers.Add($mj.Job.Id, $mj);
}
else
{
$Mri.Maps.Remove($job.Id)
$Mri.Maps.Add($mj.Job.Id, $mj);
}
$Mri.PsJobs.Add($mj.Job.Id, $mj.Job)
}
}
}
}
}
while($mri.PsJobs.Count -gt 0)
# Return
Write-Output $Mri
}
}
function Start-MapReduxReducer
{
Param
(
[PSObject] $Mri,
[object[]] $Keys
)
process
{
# Now we can start the Reducer jobs...
foreach($key in $Keys)
{
# Run job on a node
$reducerData = ConvertTo-MapReduxDataSet -DataSet ($mri.Partitions.Item($key))
$mj = Submit-MapReduxJob -Nodes $mri.Nodes -MapReduceFx $MapReduceItem.Reduce -DataSet ($key, $reducerData) #-AsLocal
# Add to our job list
if($mj.Job -eq $null)
{
# No Job Created!
$failedToStart += $key;
Write-Warning "Reducer job failed to initiate for key $key!"
}
else
{
$mri.PsJobs.Add($mj.Job.Id, $mj.Job);
$mri.Reducers.Add($mj.Job.Id, $mj);
}
}
# Return
Write-Output $failedToStart;
}
}
function Invoke-MapRedux
{
[CmdletBinding()]
Param
(
[ValidateNotNullOrEmpty()]
[Parameter(Position=0, Mandatory=$true)]
[PSObject] $MapReduceItem,
[ValidateNotNullOrEmpty()]
[Parameter(Position=1, Mandatory=$true)]
[string[]] $ComputerName,
[ValidateNotNullOrEmpty()]
[Parameter(Position=2, Mandatory=$true)]
[object[]] $DataSet
)
process
{
$nodes = Initialize-MapReduxNode -ComputerName $ComputerName
$mri = New-MapReduxInvocation -Nodes $nodes
$finalresults = @();
$retry = $mri.Partitions.Keys;
$newRetry = @();
# Start mapping...
$mri = Start-MapReduxMapper -Mri $mri -DataSet $DataSet
# Wait for mapper to finish, and perform partioning
$mri = Complete-MapReduxStep -Mri $mri -MapReduceFx $MapReduceItem.Map -CompletionFx ${function:Complete-MapperStep} -ReceiveFailureResults
do
{
# Run the Reducer jobs...
$newRetry = @();
$newRetry = Start-MapReduxReducer -Mri $mri -Keys $retry
$retry = @();
$retry = $newRetry;
}
while($retry.Count -gt 0)
# Read the results of the reducers...
$mri = Complete-MapReduxStep -Mri $mri -MapReduceFx $MapReduceItem.Reduce -CompletionFx ${function:Complete-ReducerStep}
#$finalresults += Invoke-Command -ScriptBlock $MapReduceItem.Reduce -ArgumentList ($key, $mri.Partitions.Item($key))
# Save the invocation data so the caller can refer to it...
$global:MapReduxInvocation = $mri;
# Return the final results to the caller...
Write-Output $mri.FinalResults;
}
<#
.SYNOPSIS
Initiates a MapRedux distributed computation to the specified nodes using the specified MapReduxItem (Map and Reduce functions) and dataset.
.Description
Requires WinRM to be enabled on the remote computers (i.e. winrm quickconfig).
.PARAMETER MapReduceItem
The object created by New-MapReduxItem containing a name for the invocation and the Map and Reduce scriptblocks.
.PARAMETER ComputerName
An array of one or more computers whichi will act as nodes for this distributed computation.
.PARAMETER DataSet
An array of objects which are the starting data set for this distributed computation. This can be an array of DataRows returned
from the SQL Server PowerShell Provider's Invoke-QueryCmd function, or a any custom array of data.
.EXAMPLE
# Import the SQL Server Module.
Import-Module “sqlps” -DisableNameChecking
# Query for the starting dataset
Set-Location SQLSERVER:\sql\dbserver1\default\databases\myDb
$query = "SELECT Key, Date, Value1 FROM BigData ORDER BY Key";
Write-Host "Query: $query"
$dataset = Invoke-SqlCmd -query $query
# Wrap the Map and Reduce scriptblocks
$Mr = New-MapReduxItem "My Test MapReduce Job" $MyMap $MyReduce
# The remote nodes for processing
$MyNodes = ("node1",
"node2",
"node3",
"node4")
# Run the Map Reduce routine...
Measure-Command { $MyMrResults = Invoke-MapRedux -MapReduceItem $Mr -ComputerName $MyNodes -DataSet $dataset -Verbose}
# Show the results
$MyMrResults | Out-GridView
.LINK
http://geekswithblogs.net/dwdii
.NOTES
Name: Invoke-MapRedux
Author: Daniel Dittenhafer
#>
}
function Submit-MapReduxJob
{
Param
(
[ScriptBlock] $MapReduceFx,
[object] $DataSet,
[hashtable] $Nodes,
[switch] $AsLocal
)
process
{
# Local Variables
$mj = $null;
$theNode = $null;
# We pick an enabled node?
if($Nodes -ne $null)
{
foreach($n in $Nodes.Values)
{
if($n.Enabled -eq $true -and $n.ActiveJobs -lt $n.MaxJobs)
{
$theNode = $n;
$n.ActiveJobs++;
break;
}
}
}
# Node specified?
if($theNode -eq $null)
{
Write-Warning ("No nodes available for job!")
}
else
{
# Run job on a node
$mj = New-MapReduxJob -NodeName $theNode.Name -DataSet $DataSet
if($AsLocal.IsPresent)
{
$results = Invoke-Command -ScriptBlock $MapReduceFx -ArgumentList ($mj.DataSet)
}
else
{
$mj.Job = Invoke-Command -ComputerName $mj.NodeName -AsJob -JobName ($MapReduceItem.Name) -ScriptBlock $MapReduceFx -ArgumentList $mj.DataSet
}
# Verbose...
Write-Verbose ($mj.NodeName + ": Job submitted"); # + $mj.DataSet.Data.length.ToString() + " rows submitted");
}
# Return
Write-Output $mj
}
}