-
Notifications
You must be signed in to change notification settings - Fork 147
/
dumpsterFireFactory.py
1640 lines (1181 loc) · 48.2 KB
/
dumpsterFireFactory.py
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Filename: dumpsterFireFactory.py
#
# Version: 1.0.1
#
# Author: Joe Gervais (TryCatchHCF)
#
# Summary:
#
# Create and execute time-delayed, distributed security incidents for Red- and Blue
# Team exercises. Allows repeatable, trackable
#
# User interface for creating, reviewing, editing, and executing DumpsterFires.
# Menu-driven with in-context help, walks the user through each step of the process.
#
# Description:
#
# dumpsterFire.py enters an event-driven menu loop, walking the user through all
# of the steps for creating, reviewing, editing, and igniting DumpsterFires. Help
# files and a simple walk-through are available for the user to reference. Each
# menu
#
# Each DumpsterFire includes one or more Fire modules
#
# To ignite an existing DumpsterFire in "headless" mode, use 'igniteDumpsterFire.py'
# script located in the same directory.
#
# Example:
#
# $ ./dumpsterFireFactory.py
#
import os, sys, getopt, datetime, time, random, importlib, json, igniteDumpsterFire
# Each DumpsterFire includes one or more DumpsterFire Elements
class FireNode:
mFireName = ""
mOffsetHours = 0
mOffsetMinutes = 0
mConfigStr = ""
class DumpsterFire:
mName = ""
mDescription = ""
mFires = [] # List of FireNodes
mDelayLaunch = False
# Set default launch date to now, basically "Immediately", so we have a valid date initialized
mLaunchDateTimeUTC = datetime.datetime.utcnow() # Default to now, basically "Immediate"
kDumpsterFireDirectory = "DumpsterFires/"
kLabelDumpsterFireName = "Name:"
kLabelDumpsterFireDescription = "Description:"
kLabelDelayedIgnition = "Delayed Ignition:"
kLabelDelayedIgnitionStart = "Delayed Ignition Start:"
kLabelDelayedIgnitionStartUTC = "Delayed Ignition Start (UTC):"
# Used to filter out the required "__init__.py" files from displayed FireModule lists
kLabelDirInitFile = "__init__.py"
# Create lists of DumpsterFires, Fire Categories, and Fires
# Global variables can be a source of trouble, and yet here I am...
# Used for menu-driven interaction while browsing DumpsterFires and Fires
gDumpsterFires = []
gFireCategories = []
gFires = []
gDumpsterFire = DumpsterFire
# Load the list of saved DumpsterFires
for root, dirs, files in os.walk( "./DumpsterFires" ):
for file in files:
if file.endswith('.fyr'):
gDumpsterFires.append( file )
# Load the list of available Fire Categories, basically any directory in "./FireModules/"
for root, dirnames, filenames in os.walk( "./FireModules" ):
for dir in dirnames:
gFireCategories.append( dir )
# Lists of Fires are loaded based on user's selection of a Category, dynamically
# populates per Category
# ================================================================================================
#
# Function: PrintBannerFlames()
#
# Description: Print those little ASCII flames to give some visual flavor to menu-driven interfaces
#
# ================================================================================================
def PrintBannerFlames():
print ""
print " ( ( "
print " )\ ) ) )\ ) "
print " (()/( ( /( ( ( (()/( ( ( "
print " /(_)) ( ) )\()) ))\ )( /(_)) )\ )( ( "
print " (_))_ ))\ ( ` ) ( (_))/ /((_)(()\ (_))_|((_)(()\ ))\ "
return
# ================================================================================================
#
# Function: BuildDumpsterFire()
#
# Description: High level method to that walks the user through the process of building
# DumpsterFires. Prints in-context help describing the process, then moves into the steps.
# See the printed context help below for a description of the workflow.
#
# ================================================================================================
def BuildDumpsterFire():
newDumpsterFire = DumpsterFire()
PrintBannerFlames()
print ""
print "---------------------------------------------------------------------"
print "===================== Build a Dumpster Fire ====================="
print "---------------------------------------------------------------------"
print ""
print "Recipe:"
print ""
print " - Build a list of Fires, in the desired order of execution"
print " + Select a Fire Category"
print " + Review and Select a Fire from Category"
print " + Repeat until list is complete"
print " - Review list of selected Fires"
print " - Configure the Fires"
print " + Fires that have configuration options will prompt you for input"
print " - Choose timing of sequential Fire execution: Immediate or Relative Offset"
print " + Immediate: Each Fire starts immediately after previous Fire completes"
print " + Relative Offset: Fire delays for [hours:minutes] after previous Fire completes"
print " * Assign separate Relative Offset for each Fire in your Dumpster Fire"
print " - Review Dumpster Fire"
print " - Save new Dumpster Fire for future use"
print ""
newDumpsterFire.mName = "Unnamed"
AddFires( newDumpsterFire )
print ""
choice = raw_input("Continue building this Dumpster Fire? [y/n]: ")
if choice == "y":
print ""
ConfigureDumpsterFire( newDumpsterFire )
print ""
PrintDumpsterFireConfig( newDumpsterFire )
print ""
print ""
choice = raw_input("Save this Dumpster Fire? [y/n]: ")
if choice == "y":
SaveDumpsterFire( newDumpsterFire )
gDumpsterFire = newDumpsterFire
print ""
# Delete the allocated DumpsterFire, else things get cluttered between iterations
del newDumpsterFire.mFires[ : ]
del newDumpsterFire
return
# ================================================================================================
#
# Function: ConfigureExistingDumpsterFire()
#
# Description: Prompts user to select a saved DumpsterFire, then walks them through the process
# of updating its configuration.
#
# ================================================================================================
def ConfigureExistingDumpsterFire():
selection = SelectDumpsterFire()
print ""
if ( selection > -1 ):
thisDumpsterFire = LoadDumpsterFireConfig( kDumpsterFireDirectory + gDumpsterFires[ selection ] )
ConfigureDumpsterFire( thisDumpsterFire )
PrintDumpsterFireConfig( thisDumpsterFire )
print ""
print "Storing Dumpster Fire..."
SaveDumpsterFire( thisDumpsterFire )
print ""
# Free up the allocated space or gets mucked up from repeated calls to this method
del thisDumpsterFire.mFires[ : ]
del thisDumpsterFire
return
# ================================================================================================
#
# Function: ConfigureDumpsterFire()
#
# Description: Loops through the provided DumpsterFire's list of Fire modules.
#
# First creates the Python package name that leads to the current Fire module. Next, loads
# the matching Fire class and its own Configuration() method, which prompts the user for any
# needed config settings.
#
# ================================================================================================
def ConfigureDumpsterFire( thisDumpsterFire ):
# Edit DumpsterFire Time Delay
# TO DO - TO DO - TO DO
# DEBUG DEBUG DEBUG
print "==== Configure DumpsterFire ===="
print ""
# Loop over Fires
# Create Python package name from Fire name
# Load matching Fire and its classes
# Call Fire's Configure() method
i = 0
while ( i < len( thisDumpsterFire.mFires )):
currentFire = thisDumpsterFire.mFires[ i ]
print "---------------------------------------------------------"
print ""
print "Current Fire: ", currentFire.mFireName
print ""
# Convert Fire's filepath to Python package '.'-format
pythFormatPathStr = currentFire.mFireName.replace( "/", "." )
# Set root path to Fire modules, strip trailing ".py" from Fire module's name
fireModulePathStr = "FireModules." + pythFormatPathStr[ :-3 ]
# Extract Fire name from end of converted Fire module path
# Convert filepath of Fire module to Python's '.'-notation
fireModulePathElementList = fireModulePathStr.split( "." )
fireModuleNameStr = fireModulePathElementList[ -1 ]
try:
# Load Fire module (Python class)
currentFireClass = getattr( importlib.import_module( fireModulePathStr, fireModuleNameStr ), fireModuleNameStr )
# Create instance of Fire, with parameters that were stored in parent DumpsterFire
thisFire = currentFireClass( "" )
try:
thisFire.Configure()
currentFire.mConfigStr = thisFire.GetParameters()
except:
print "### Error while running Fire's Configure() method"
except:
print "### ConfigureDumpsterFire(): Error loading fire."
print "Module Path:", fireModulePathStr
print "Fire Name:", fireModuleNameStr
i = i + 1
currentDT_UTC = datetime.datetime.utcnow()
print ""
print "----------------- DumpsterFire Name -----------------"
print ""
print "NOTE: DumpsterFire names must only contain letters, numbers, hyphens, and underscores"
print ""
thisDumpsterFire.mName = raw_input( "Enter name for new Dumpster Fire: " )
print ""
print "-------------- DumpsterFire Time Delay --------------"
print ""
print "DumpsterFire Time Delay (UTC):", thisDumpsterFire.mLaunchDateTimeUTC.strftime( "%x %X" )
print "Current Time (UTC):", currentDT_UTC.strftime("%x %X")
print ""
choice = raw_input( "Create new time-delay for dumpster fire? [y/n]: ")
if choice == "y":
thisDumpsterFire.mLaunchDateTimeUTC = BuildDateTime()
thisDumpsterFire.mDelayLaunch = True
return
# ================================================================================================
#
# Function: AddFires()
#
# Description: Prompts the user through browsing the Fire Categories and selecting Fires from
# each, building a list of Fires to the current DumpsterFire
#
# ================================================================================================
def AddFires( thisDumpsterFire ):
done = False
fireCount = 0
# Empty out and Fires that may be left over from previous ops
del thisDumpsterFire.mFires[ : ]
while not done:
print ""
print "==== Select a Fire Category ===="
print ""
fireCategoryNum = SelectFireCategory()
fireCategory = gFireCategories[ fireCategoryNum ]
print "Selected Fire Category: ", fireCategory
print ""
print "==== Select a Fire ===="
print ""
fireNum = SelectFire( fireCategory )
thisDumpsterFire.mFires.append( FireNode() )
thisDumpsterFire.mFires[ fireCount ].mFireName = fireCategory + "/" + gFires[ fireNum ]
fireCount = fireCount + 1
choice = raw_input("Add another Fire? [y/n]: ")
if not ( choice == "y" ):
done = True
ReviewFires( thisDumpsterFire )
print ""
choice = raw_input("Add time offsets to each Fire? [y/n]: ")
print ""
if choice == "y":
thisDumpsterFire = AddTimeOffsetsToFires( thisDumpsterFire )
return ( thisDumpsterFire )
# ================================================================================================
#
# Function: ReviewFires()
#
# Description: Just prints of list of Fire names in the given DumpsterFire, used to check
# progress while building a new DumpsterFire
#
# ================================================================================================
def ReviewFires( thisDumpsterFire ):
print ""
print "==== Review Dumpster Fire ===="
print ""
print "Selected Fires (in order of execution):"
print ""
i = 0
while ( i < len( thisDumpsterFire.mFires )):
print "\t", thisDumpsterFire.mFires[ i ].mFireName
i = i+1
return
# ================================================================================================
#
# Function: AddTimeOffsetsToFires
#
# Description: Adds a relative offset time delay to wait before igniting the associated Fire.
# Useful for building more believable event narratives with a DumpsterFire. When the previous
# Fire in the queue finishes running, the Fire will wait HH:MM before igniting itself.
#
# ================================================================================================
def AddTimeOffsetsToFires( thisDumpsterFire ):
print ""
print "======= Add Time Offsets To Fires ======="
print ""
print "Select time offsets for each Fire"
print ""
done = 0
i = 0
while ( i < len( thisDumpsterFire.mFires )):
while ( done == 0 ):
thisDumpsterFire.mFires[ i ] = BuildTimeOffsetForFire( thisDumpsterFire.mFires[ i ] )
keepTimeOffset = raw_input( "Keep time offset? (y/n): " )
if ( keepTimeOffset == "y" ):
done = 1
else:
thisDumpsterFire.mFires[ i ].mOffsetHours = 0
thisDumpsterFire.mFires[ i ].mOffsetMinutes = 0
done = 0
i = i+1
return( thisDumpsterFire )
# ================================================================================================
#
# Function: BuildTimeOffsetForFire()
#
# Description: Helper function for AddTimeOffsetsToFires()
#
# ================================================================================================
def BuildTimeOffsetForFire( thisFire ):
hour = 0
minute = 0
print "Assigning time offset for Fire: ", thisFire.mFireName
print ""
done = 0
while ( done == 0 ):
try:
hours = int ( raw_input( "Enter Hour (0-23): " ))
if ( hours < 0 or hours > 23 ):
print "Invalid hour, try again..."
else:
done = 1
except ValueError:
print "Invalid hour, try again..."
done = 0
while ( done == 0 ):
try:
minutes = int ( raw_input( "Enter Minutes (0-59): " ))
if ( minutes < 0 or minutes > 59 ):
print "Invalid minutes, try again..."
else:
done = 1
except ValueError:
print "Invalid minutes, try again..."
print ""
print "Time offset for Fire '" + thisFire.mFireName + "': ", \
str( hours ).zfill( 2 ), "hours,", str( minutes ).zfill( 2 ), "minutes"
print ""
thisFire.mOffsetHours = hours
thisFire.mOffsetMinutes = minutes
return( thisFire )
# ================================================================================================
#
# Function: BrowseFires()
#
# Description: Guides the user through selecting Fire Categories, prints the included
# Fires (and their respective descriptions) for an overview.
#
# ================================================================================================
def BrowseFires():
PrintBannerFlames()
print "---------------------------------------------------------------------"
print "========================= BROWSE FIRES =========================="
print "---------------------------------------------------------------------"
print ""
print "Fires are the individual action elements that make up a Dumpster Fire."
print ""
print "Select a Fire Category to view its member Fires and their descriptions."
print ""
done = 0
while ( done == False ):
print ""
print "==== Select a Fire Category ===="
print ""
fireCategoryNum = SelectFireCategory()
fireCategory = gFireCategories[ fireCategoryNum ]
print "Selected Fire Category: ", fireCategory
print ""
PrintBannerFlames()
print "---------------------------------------------------------------------"
print " ", fireCategory, "Fire Details"
print "---------------------------------------------------------------------"
print ""
# Clear values from list to avoid duplicate crud building up
del gFires[ : ]
# Populate the Fire modules from the supplied Fire Category
for root, dirs, files in os.walk( "./FireModules/" + fireCategory ):
for file in files:
# Filter out the required __init__.py file in Fire directories
if ( file != kLabelDirInitFile ):
if file.endswith('.py'):
gFires.append( file )
i = 0
while i < len( gFires ):
PrintFireDetails( fireCategory, gFires[ i ] )
i = i + 1
choice = raw_input("Browse more Fires? [y/n]: ")
if not ( choice == "y" ):
done = True
return
# ================================================================================================
#
# Function: PrintFireDetails()
#
# Description: Utility function for printing the details of a Fire (name, configuration,
# and time delays) in a friendly layout that won't make the user's eyes burn.
#
# ================================================================================================
def PrintFireDetails( fireCategory, fireName ):
try:
fullFirePath = fireCategory + "/" + fireName
# Convert Fire's filepath to Python '.'-format
pythFormatPathStr = fullFirePath.replace( "/", "." )
# Set root path to Fire modules, strip trailing ".py" from Fire module's name
fireModulePathStr = "FireModules." + pythFormatPathStr[ :-3 ]
# Extract Fire name from end of converted Fire module path
# Convert filepath of Fire module to Python's '.'-notation
fireModulePathElementList = fireModulePathStr.split( "." )
fireModuleNameStr = fireModulePathElementList[ -1 ]
except:
print "### PrintFireDetails(): Error accessing Fire details for", fireModuleNameStr
print ""
try:
# Load Fire module (Python class)
currentFireClass = getattr( importlib.import_module( fireModulePathStr, fireModuleNameStr ), fireModuleNameStr )
# Create dummy instance of Fire so we can call its Description() method
thisFire = currentFireClass( "" )
except:
print "### PrintFireDetails(): Error loading / creating new Fire"
print "Module Path:", fireModulePathStr
print "Fire Name:", fireModuleNameStr
print ""
try:
print "**", fireName
print ""
print "\t", thisFire.Description()
print ""
except:
print "### IgniteFire: Error while calling Fire's Description()"
print ""
return
# ================================================================================================
#
# Function: StoreDumpsterFireConfig()
#
# Description: Creates a JSON-format snapshot of the DumpsterFire, saves to "DumpsterFires/"
# directory.
#
# ================================================================================================
def StoreDumpsterFireConfig( theDumpsterFire ):
# Store theDumpsterFire in JSON format in our DumpsterFires/ directory
rawConfigList = []
try:
configFile = open( "DumpsterFires/" + theDumpsterFire.mName + ".fyr", 'w' )
except:
print "Error opening config file DumpsterFires/" + theDumpsterFire.mName + ".fyr"
print ""
try:
rawConfigList.append( theDumpsterFire.mName )
rawConfigList.append( theDumpsterFire.mDescription )
rawConfigList.append( theDumpsterFire.mLaunchDateTimeUTC.strftime("%m/%d/%Y %H:%M:00"))
rawConfigList.append( theDumpsterFire.mDelayLaunch )
rawConfigList.append( len( theDumpsterFire.mFires ))
# Launch Date/Time are not stored in the config file - those are runtime settings
#
# Onward to storing the member Fires and their settings...
i = 0
while i < len( theDumpsterFire.mFires ):
fire = theDumpsterFire.mFires[ i ]
rawConfigList.append( fire.mFireName )
rawConfigList.append( fire.mOffsetHours )
rawConfigList.append( fire.mOffsetMinutes )
rawConfigList.append( fire.mConfigStr )
i = i + 1
json.dump( rawConfigList, configFile )
except:
print "Error streaming JSON to config file."
print ""
try:
configFile.close()
except:
print "Error closing config file."
print ""
return
# ================================================================================================
#
# Function: LoadDumpsterFireConfig()
#
# Description: Reads in the JSON-format saved DumpsterFire file, creates a new DumpsterFire
# object and populates it with the saved values.
#
# ================================================================================================
def LoadDumpsterFireConfig( dumpsterFireFilePath ):
# Open DumpsterFire config file
# Read saved JSON format and assign values to data members
newDumpsterFire = DumpsterFire()
rawConfigStr = []
try:
configFile = open( dumpsterFireFilePath, 'r' )
except:
print "Error opening config file " + dumpsterFireFilePath
print ""
# Some ugly brittleness ahead - hardcoded indexing of fields. Won't cause any
# problems unless you start modifying the number of fields that are stored
# when saving/loading DumpsterFires
try:
# Load raw config strings into list, assign them to DumpsterFire members
rawConfigStr = json.load( configFile )
newDumpsterFire.mName = rawConfigStr[ 0 ]
newDumpsterFire.mDescription = rawConfigStr[ 1 ]
newDumpsterFire.mLaunchDateTimeUTC = datetime.datetime.strptime( rawConfigStr[ 2 ], "%m/%d/%Y %H:%M:%S" )
newDumpsterFire.mDelayLaunch = rawConfigStr[ 3 ]
fireCount = rawConfigStr[ 4 ]
i = 0
while i < fireCount:
newDumpsterFire.mFires.append( FireNode() )
offset = i * 4
newDumpsterFire.mFires[ i ].mFireName = rawConfigStr[ offset + 5 ]
newDumpsterFire.mFires[ i ].mOffsetHours = rawConfigStr[ offset + 6 ]
newDumpsterFire.mFires[ i ].mOffsetMinutes = rawConfigStr[ offset + 7 ]
newDumpsterFire.mFires[ i ].mConfigStr = rawConfigStr[ offset + 8 ]
i = i + 1
except:
print "Error reading values from config file."
print ""
try:
configFile.close()
except:
print "Error closing config file."
print ""
return( newDumpsterFire )
# ================================================================================================
#
# Function: SaveDumpsterFire()
#
# Description: Helper function for storing DumpsterFires via StoreDumpsterFireConfig().
# First prints out the details so the user gets an overview of what they're storing.
#
# ================================================================================================
def SaveDumpsterFire( newDumpsterFire ):
print ""
newDumpsterFire.mDescription = raw_input( "Enter description of new Dumpster Fire: " )
print ""
print "** Saving new Dumpster Fire: "
PrintDumpsterFireConfig( newDumpsterFire )
StoreDumpsterFireConfig( newDumpsterFire )
print ""
print ""
print "** Successfully saved:", newDumpsterFire.mName
print ""
choice = raw_input( "Press return to continue... " )
return
# ================================================================================================
#
# Function: PrintDumpsterFireConfig()
#
# Description: Helper function, prints the DumpsterFire's configuration in a nice format.
#
# ================================================================================================
def PrintDumpsterFireConfig( thisDumpsterFire ):
i = 0
print ""
print "\t", kLabelDumpsterFireName, thisDumpsterFire.mName
print "\t", kLabelDumpsterFireDescription, thisDumpsterFire.mDescription
if ( thisDumpsterFire.mDelayLaunch == False ):
print "\t", kLabelDelayedIgnition, "No"
else:
print "\t", kLabelDelayedIgnition, "Yes"
print "\t", kLabelDelayedIgnitionStartUTC, thisDumpsterFire.mLaunchDateTimeUTC.strftime("%x %X")
print ""
print "\tFires (In order of execution):"
print ""
while ( i < len( thisDumpsterFire.mFires )):
print "\t** ", thisDumpsterFire.mFires[ i ].mFireName
print "\t Relative Time Delay (HH:MM): ", \
str( thisDumpsterFire.mFires[ i ].mOffsetHours ).zfill(2) + ":" + \
str( thisDumpsterFire.mFires[ i ].mOffsetMinutes ).zfill(2)
print "\t Config: " + thisDumpsterFire.mFires[ i ].mConfigStr
i = i+1
return
# ================================================================================================
#
# Function: IgniteDumpsterFire()
#
# Description: Where the good stuff happens.
#
# If DumpsterFire has fuse delay, loop and wait until triggered
# Loop over Fires in thisDumpsterFire
# For each Fire
# Parse each Fire name into FireModulePath and FireName
# Convert FireModulePath + FireName into Python package format
# (Replace '/' with '.' in path)
# Copy fireName from last field of FireModulePath
# Load Fire module
# Set Configs for Fire
# Check for Fire's delayed fuse, wait as needed
# Call IgniteFire() of Fire
# Exit
#
# ================================================================================================
def IgniteDumpsterFire( thisDumpsterFire, withUserInteraction ):
i = 0
# If this DumpsterFire has delayed ignition, loop and wait until triggered
if ( thisDumpsterFire.mDelayLaunch == True ):
print "Delayed ignition selected. Standing by until UTC",
print thisDumpsterFire.mLaunchDateTimeUTC.strftime("%x %X")
print ""
waitTime = thisDumpsterFire.mLaunchDateTimeUTC - datetime.datetime.utcnow()
if ( waitTime.total_seconds() > 1 ):
time.sleep( waitTime.total_seconds() )
print "Igniting Dumpster Fire..."
# Loop through the member Fires of the DumpsterFire, igniting them in turn
while ( i < len( thisDumpsterFire.mFires )):
currentFire = thisDumpsterFire.mFires[ i ]
print ""
print "---------------------------------------------------------"
PrintDateTimeStamps()
print ""
# If this Fire has a relative delayed ignition, loop and wait until triggered
if ( currentFire.mOffsetHours > 0 or currentFire.mOffsetMinutes > 0 ):
print "Delayed Fire ignition detected. Pausing for (HH:MM)", \
str( currentFire.mOffsetHours ).zfill(2) + ":" + \
str( currentFire.mOffsetMinutes ).zfill(2)
print "(Waiting...)"
delaySeconds = ( int(currentFire.mOffsetMinutes) * 60 ) + ( int(currentFire.mOffsetHours) * 60 * 60 )
time.sleep( delaySeconds )
print ""
PrintDateTimeStamps()
print ""
print "Igniting Fire: ", currentFire.mFireName
if ( currentFire.mConfigStr == "" ):
print "Using ConfigStr: (None)"
else:
print "Using ConfigStr: ", currentFire.mConfigStr
# Convert Fire's filepath to Python '.'-format
pythFormatPathStr = currentFire.mFireName.replace( "/", "." )
# Set root path to Fire modules, strip trailing ".py" from Fire module's name
fireModulePathStr = "FireModules." + pythFormatPathStr[ :-3 ]
# Extract Fire name from end of converted Fire module path
# Convert filepath of Fire module to Python's '.'-notation
fireModulePathElementList = fireModulePathStr.split( "." )
fireModuleNameStr = fireModulePathElementList[ -1 ]
# Time to ignite the current Fire...
IgniteFire( fireModulePathStr, fireModuleNameStr, currentFire.mConfigStr )
i = i+1
print "---------------------------------------------------------"
PrintDateTimeStamps()
print ""
print "All Fires burned. DumpsterFire complete."
print ""
return
# ================================================================================================
#
# Function: StartDumpsterFire()
#
# Description: Sets up all of the housekeeping needed to ignite the DumpsterFire.
#
# ================================================================================================
def StartDumpsterFire():
PrintBannerFlames()
print ""
print "---------------------------------------------------------------------"
print "===================== Start a Dumpster Fire ====================="
print ""
print "Recipe:"
print ""
print " - Select an available Dumpster Fire"
print " - Choose immediate ignition or time-delayed"
print " - Review Dumpster Fire settings"
print " - Ignite Dumpster Fire"
print ""
print ""
print "---------------------------------"
print "==== Select a Dumpster Fire ===="
print ""
selection = SelectDumpsterFire()
if ( selection < 0 ):
return
hotDumpsterFire = LoadDumpsterFireConfig( kDumpsterFireDirectory + gDumpsterFires[ selection ] )
print ""
print ""
print "---------------------------------"
print "==== Select Timing of Fire ===="
print ""
# DEBUG DEBUG DEBUG
fuseDelayStr = hotDumpsterFire.mLaunchDateTimeUTC.strftime("%x %X")
currentDT_UTC = datetime.datetime.utcnow()
waitTime = hotDumpsterFire.mLaunchDateTimeUTC - datetime.datetime.utcnow()
if ( waitTime.total_seconds() < 1 ):
fuseDelayStr = "None (immediate ignition)"
print "DumpsterFire Time Delay (UTC):", fuseDelayStr
print "Current Time (UTC):", currentDT_UTC.strftime("%x %X")
fuseDelayStr = hotDumpsterFire.mLaunchDateTimeUTC.strftime("%x %X")
print ""
choice = raw_input( "Create new time-delay for dumpster fire? [y/n]: ")
print ""
if choice == "y":
hotDumpsterFire.mLaunchDateTimeUTC = BuildDateTime()
fuseDelayStr = hotDumpsterFire.mLaunchDateTimeUTC.strftime("%x %X")
hotDumpsterFire.mDelayLaunch = True
elif ( waitTime.total_seconds() < 1 ):
fuseDelayStr = "None (immediate ignition)"
hotDumpsterFire.mDelayLaunch = False
print ""
print "---------------------------------------------------"
print "========= Review Dumpster Fire Settings ========="
print ""
print "About to ignite a Dumpster Fire using the following configuration:"
PrintDumpsterFireConfig( hotDumpsterFire )