PiFlash.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« PiFlash/MediaWriter.pm ↑ Summary PiFlash/Inspector.pm »
1 # PiFlash - flash a Raspberry Pi image to an SD card, with safety checks to avoid erasing wrong device
2 # This module/script uses sudo to perform root-privileged functions.
3 # by Ian Kluft
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use v5.14.0; # require 2011 or newer version of Perl
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use PiFlash::State;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use PiFlash::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use PiFlash::Command;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 0 ▶use PiFlash::Inspector;
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use PiFlash::MediaWriter;
12  
13 package PiFlash;
14 $PiFlash::VERSION = '0.4.3';
15 use autodie; # report errors instead of silently continuing ("die" actions are used as exceptions - caught & reported)
16 use Getopt::Long qw(GetOptionsFromArray); # included with perl
17 use File::Basename; # included with perl
18 use File::Path qw(make_path); # RPM: perl-File-Path, DEB: included with perl
19  
20 # ABSTRACT: Raspberry Pi SD-flashing script with safety checks to avoid erasing the wrong device
21  
22  
23 # return default list of state category names
24 # this is made available externally so it can be accessed for testing
25 sub state_categories {
26 return (
27 "cli_opt", # options received from command line
28 "config", # configuration settings loaded from YAML $XDG_CONFIG_DIR/piflash
29 "hook", # hook functions: callbacks managed by PiFlash::Hook
30 "input", # input file info from PiFlash::Inspector
31 "log", # log of commands and events
32 "output", # output device info from PiFlash::Inspector
33 "plugin", # plugin modules assigned storage here
34 "system", # system info from PiFlash::Inspector
35 );
36 };
37  
38 # return list of command-line options in Getopt::Long-compatible format
39 sub cli_def
40 {
41 return (
42 "config:s", # configuration file
43 "help", # display help/usage and exit
44 "logging", # command logging (similar to verbose mode without printing anything)
45 "plugin:s", # list of user-enabled plugins (also enabled from config file)
46 "resize", # resize root filesystem after writing to SD card
47 "sdsearch", # display list of SD card devices and exit
48 "test:s%", # set test flags (used by unit tests only)
49 "verbose", # log and print lots of actions for troubleshooting
50 "version", # print version number and exit
51 );
52 }
53  
54 # print program usage message
55 sub usage
56 {
57 my @msg;
58 if (@_) {
59 push @msg, shift;
60 foreach (@_) {
61 push @msg, " $_";
62 }
63 }
64 push @msg, "usage: ".basename($0)." [--verbose | --logging] [--resize] [--config conf-file] input-file output-device";
65 push @msg, " ".basename($0)." [--verbose | --logging] [--config conf-file] --SDsearch";
66 push @msg, " ".basename($0)." --version";
67 die join("\n", @msg)."\n";
68 }
69  
70 # print numbers with readable suffixes for megabytes, gigabytes, terabytes, etc
71 # handle more prefixes than currently needed for extra scalability to keep up with Moore's Law for a while
72 sub num_readable
73 {
74 my $num = shift;
75 my @suffixes = qw(bytes KB MB GB TB PB EB ZB);
76 my $magnitude = int(log($num)/log(1024));
77 if ($magnitude > scalar @suffixes) {
78 $magnitude = scalar @suffixes;
79 }
80 my $num_base = $num/(1024**($magnitude));
81 return sprintf "%4.2f%s", $num_base, $suffixes[$magnitude];
82 }
83  
84 # command-line argument processing
85 # this is used by PiFlash mainline and unit tests
86 sub process_cli
87 {
88 my $cmdline = shift // \@ARGV;
89  
90 # collect and validate command-line arguments
91 {
92 my @warn;
93 local $SIG{__WARN__} = sub {
94 if (length $_[0] > 0) {
95 push @warn, $_[0];
96 }
97 };
98 my $getopt_result = eval { GetOptionsFromArray ($cmdline, PiFlash::State::cli_opt(), PiFlash::cli_def())
99 };
100 if ($@) {
101 # in case of failure, add state info if verbose or logging mode is set
102 usage("command option error: ", $@);
103 } elsif (@warn) {
104 chomp @warn;
105 my $line1 = shift @warn;
106 usage("command option error: $line1", @warn);
107 } elsif (!$getopt_result) {
108 usage("command option error");
109 }
110 }
111  
112 # check for errors such as insufficient parameters or missing files
113 my @errors;
114 my $cli_query_mode = 0;
115 foreach my $opt ( qw(help sdsearch version) ) {
116 if (PiFlash::State::has_cli_opt($opt)) {
117 $cli_query_mode = 1;
118 last;
119 }
120 }
121 my $test_flags = PiFlash::State::cli_opt("test");
122 if (scalar @$cmdline < 2) {
123 if (not $cli_query_mode) {
124 push @errors, "missing argument - need an existing source file and destination device";
125 }
126 } else {
127 if (not -e $cmdline->[0]) {
128 push @errors, "source file parameter $cmdline->[0] does not exist";
129 } elsif (not -f $cmdline->[0]) {
130 push @errors, "source file parameter $cmdline->[0] is not a regular file";
131 }
132 if (not exists $test_flags->{skip_block_check}) {
133 # test that the block device exists and is really a block device
134 # note: this may be skipped by "--test skip_block_check=1" for testing CLI options
135 if (not -e $cmdline->[1]) {
136 push @errors, "destination device parameter $cmdline->[1] does not exist";
137 } elsif (not -b $cmdline->[1]) {
138 push @errors, "destination device parameter $cmdline->[1] is not a block device";
139 }
140 }
141 }
142 # TODO insert subcommand processing here
143  
144 # if there were errors, print them with program usage info and exit
145 if (@errors) {
146 usage(@errors);
147 }
148 }
149  
150 # PiFlash main routine
151 sub piflash
152 {
153 # initialize program state storage
154 PiFlash::State->init(state_categories());
155  
156 # process command line
157 process_cli();
158  
159 # if --help option was selected, print usage info and exit
160 if (PiFlash::State::has_cli_opt("help")) {
161 usage();
162 }
163  
164 # if --version option was selected, print the version number and exit
165 if (PiFlash::State::has_cli_opt("version")) {
166 say $PiFlash::VERSION;
167 return;
168 }
169  
170 # read configuration
171 my $config_file;
172 if (PiFlash::State::has_cli_opt("config")) {
173 $config_file = PiFlash::State::cli_opt("config");
174 } else {
175 my $config_dir = $ENV{XDG_CONFIG_DIR} // ($ENV{HOME}."/.local");
176 make_path($config_dir);
177 $config_file = $config_dir."/piflash";
178 }
179 if ( -f $config_file ) {
180 PiFlash::State::read_config($config_file);
181 }
182  
183 # initialize enabled plugins
184 # this has to be done after command line and configuration processing so we know what the user has enabled
185 # since PiFlash runs root code, plugins are disabled by default
186 PiFlash::Plugin->init_plugins();
187  
188 # collect system info: kernel specs and locations of needed programs
189 PiFlash::Inspector::collect_system_info();
190  
191 # if --SDsearch option was selected, search for SD cards and exit
192 if (PiFlash::State::has_cli_opt("sdsearch")) {
193 # SDsearch mode: print list of SD card devices and exit
194 PiFlash::Inspector::sd_search();
195 return;
196 }
197  
198 # call hook for after reading command-line options
199 PiFlash::Hook::cli_options();
200  
201 # set input and output paths
202 PiFlash::State::input("path", $ARGV[0]);
203 PiFlash::State::output("path", $ARGV[1]);
204 say "requested to flash ".PiFlash::State::input("path")." to ".PiFlash::State::output("path");
205 say "output device ".PiFlash::State::output("path")." will be erased";
206  
207 # check the input file
208 PiFlash::Inspector::collect_file_info();
209
210 # check the output device
211 PiFlash::Inspector::collect_device_info();
212  
213 # check input file and output device sizes
214 if (PiFlash::State::input("size") > PiFlash::State::output("size")) {
215 PiFlash::State->error("output device not large enough for this image - currently have: "
216 .num_readable(PiFlash::State::output("size")).", minimum size: "
217 .num_readable(PiFlash::State::input("size")));
218 }
219 # check if SD card is recommended 8GB - check for 6GB since it isn't a hard limit
220 if (PiFlash::State::has_input("NOOBS") and PiFlash::State::output("size") < 6*1024*1024*1024) {
221 PiFlash::State->error("NOOBS images want 8GB SD card - currently have: "
222 .num_readable(PiFlash::State::output("size")));
223 }
224  
225 # test access to root privilege
226 # sudo should be configured to not prompt for a password again on this session for some minutes
227 say "verify sudo access";
228 do { PiFlash::Command::cmd("sudo test", PiFlash::Command::prog("sudo"), PiFlash::Command::prog("true")); };
229 if ($@) {
230 # in case of failure, report that root privilege is required
231 PiFlash::State->error("root privileges required to run this script");
232 }
233  
234 # flash the device
235 PiFlash::MediaWriter::flash_device();
236 }
237  
238 # run main routine and catch exceptions
239 sub main
240 {
241 local $@; # avoid interference from anything that modifies global $@
242 do { piflash(); };
243  
244 # catch any exceptions thrown in main routine
245 if (my $exception = $@) {
246 if (ref $exception) {
247 # exception is an object - try common output functions in case they include more details
248 # these are not generated by this program - but if another module surprises us, try to handle it gracefully
249 if ($exception->can('as_string')) {
250 # typical of Exception::Class derivative classes
251 PiFlash::State->error("[".(ref $exception)."]: ".$exception->as_string());
252 }
253 if ($exception->can('to_string')) {
254 # typical of Exception::Base derivative classes
255 PiFlash::State->error("[".(ref $exception)."]: ".$exception->to_string());
256 }
257 # if exception object was not handled, fall through and print whatever it says as if it's a string
258 }
259  
260 # print exception as a plain string
261 # don't run this through PiFlash::State->error() because it probably already came from there
262 say STDERR "$0 failed: $@";
263 return 1;
264 } else {
265 if (PiFlash::State::verbose() or PiFlash::State::logging()) {
266 say "Program state dump...\n".PiFlash::State::odump($PiFlash::State::state,0);
267 }
268 }
269  
270 # return success
271 return 0;
272 }
273  
274 1;
275  
276 __END__
« PiFlash/MediaWriter.pm ↑ Summary PiFlash/Inspector.pm »