FSM-Basic

 view release on metacpan or  search on metacpan

lib/FSM/Basic.pm  view on Meta::CPAN

Version 0.25

=cut

=head1 SYNOPSIS

A small finite state machine using a HASH data as description of the states
Mainly used to create fake bash or fake telnet server in the purpose to mimic some CLI device interface (like SWITCH or ROUTER interface)
Perhaps a little code snippet.
The HASH is easily using a JSON file

    use FSM::Basic;

    my $fsm = FSM::Basic->new( \%states, 'accept' );
    my $final = 0;
    my $out;
    my $extra;
    foreach my $in ( @ins )
    {
        ( $final, $out, $extra) = $fsm->run( $in );
        say $out;
        last if $final;
   }


=head1 SUBROUTINES/METHODS

=head2 new

my $fsm = FSM::Basic->new( \%states, 'accept' );

Create the FSM with the HASH ref as first paramter
and the initial state as second parameter

The HASH is like this:

 my %states = (
    'accept' => {
        'expect' => {
            'default' => {
                'final'    => 0,
                'matching' => 'prompt'
            }
        },
        'not_matching'           => 'accept',
        'not_matching0'          => 'close',
        'not_matching_info_last' => '% Bad passwords
',
        'output' => 'Password: ',
        'repeat' => 2
    },

    'close'  => {'final' => 1},
    'prompt' => {
        'expect' => {
            'not_matching' => 'prompt',
            'exit'         => {
                'matching'    => 'close',
                'final' => 0
            },
            'meminfo'     => {'do' => 'do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> }'},
            'h(elp)?|\\?' => {
                'output' => 'exit
meminfo
mem_usage
User> '
            },
            'mem_usage' => {'do' => 'my ( $tot,$avail) = (split /\\n/ ,do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf "%0.2f%%\\n",(100*($tot-$avail)/$tot); '},
        },
        'not_matching_info' => '% Unknown command or computer name, or unable to find computer address',
        'output'            => 'User> '
    }
);



The keys are the states name.
"expect" contain a sub HASH where the keys are word or REGEX expected as input


=over 1

=item In this hash, you have:

=back

=over 2

=item executable code:

"do" for perl code


"exec" for system code,


and 4 dedicated commands:

"cat" just reading the file content provided in parameter).

"catRAND" chose randomly one of the files provided in parameter space separated

"catWRAND" chose randomly (weighted) one of the files provided in parameter space separatedwith a : to separate the weight

e.g. 'catWRAND' => './t/test_cat.txt:1 ./t/test_cat1.txt:50',   in this case the file ./t/test_cat1.txt get 50 more chance to be selected than file ./t/test_cat.txt

"catSEQ" read sequentialy the next files provided in parameter space separated
        if "catSEQ_idx" is defined, that file is used to keep the state. Otherwise , the state file is named used
        all the files name from "catSEQ" concatenated with a final '.tate'. All spaces are replaced by an underscore

"catSEQn" read sequentialy a list of files but a specific number of time provided in parameter space separated
        if "catSEQn_idx" is defined, that file is used to keep the state. Otherwise , the state file is named used
        all the files name from "catSEQ" concatenated with a final '.tate'. All spaces are replaced by an underscore
        e.g.
          'cat' => { 
               'catSEQn' => '5,./t/test_cat.txt 2,./t/test_cat1.txt',
               'catSEQn_idx' => './t/test_cat_seqn.idx',
                'final'    => 0
           },
         This setup read 5 times the first file followed by 2 times the second file 

=back

=over 3

=item * It is possible to use a regex to allow optional commands


lib/FSM/Basic.pm  view on Meta::CPAN

These extra tag are returned from the run() function as third parameter HASH ref .
Check examples/fake_bash_ssh1.*
Take a look at timout and timer usage
In this example if destination IP from the SSH connection is available, the file IP.json is used as definition
(with fallback to fake_bash1.pl)

=cut

=back

B<run>

my ( $final, $out, $extra ) = $fsm->run( $in );

Run the FSM with the input and return the final state (0 or 1) , the expected output and a reference to an HASH with the extra tag key/value pair


=cut

=over 1

=back


B<EXAMPLE>


    use strict;
    use feature qw( say );
    use FSM::Basic;
    use JSON;
    use Term::ReadLine;

        my %states = (
        'accept' => {
            'expect' => {
                'default' => {
                    'final'    => 0,
                    'matching' => 'prompt'
                }
            },
            'not_matching'           => 'accept',
            'not_matching0'          => 'close',
            'not_matching_info_last' => '% Bad passwords
    ',
            'output' => 'Password: ',
            'repeat' => 2
        },

        'close'  => {'final' => 1},
        'prompt' => {
            'expect' => {
                'not_matching' => 'prompt',
                'exit'         => {
                    'matching' => 'close',
                    'final'    => 0
                },
                "read"         => {'cat' => 'file.txt'},
                "read_random"  => {'catRAND' => 'file1.txt file2.txt file3.txt'},
                "read_seq"     => {'catSEQ' => 'file1.txt file2.txt file3.txt', 'catSEQ_idx' => 'catSEQ_status'},
                'meminfo'      => {'do' => 'do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> }'},
                'mem'          => {
				   'do' => "my ( $tot,$avail) = (split /\n/ ,do { local( @ARGV, $/ ) = \"/proc/meminfo\" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf \"%0.2f%%\\n\",(100*($tot-$avail)/$tot);"
			          },
                'h(elp)?|\\?'  => {
                    'output' => 'exit
    read
    read_random
    read_seq
    meminfo
    mem_usage
    mem
    User> '
                },
                'mem_usage' => {'do' => 'my ( $tot,$avail) = (split /\\n/ ,do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf "%0.2f%%\\n",(100*($tot-$avail)/$tot); '},
            },
            'not_matching_info' => '% Unknown command or computer name, or unable to find computer address',
            'output'            => 'User> '
        }
    );
    my $history_file = glob( '/tmp/fsm.history' );
    my $prompt       = '> ';
    my $line;
    my $final   = 0;
    my $extra;
    my $term    = new Term::ReadLine 'bash';
    my $attribs = $term->Attribs->ornaments( 0 );
    $term->using_history();
    $term->read_history( $history_file );
    $term->clear_signals();

    my $fsm = FSM::Basic->new( \%states, 'accept' );
    my $out = "Password> ";
    while ( defined( $line = $term->readline( $out ) ) )
    {
        ( $final, $out, $extra ) = $fsm->run( $line );
        $term->write_history( $history_file );
        last if $final;
    }

    print $out if $final;


More sample code in the examples folder.


TODO

add "edit" to allow on the fly modification of the states definition

add "verify_states" to check all states are reachable from a original state

B<SEE ALSO>

FSA::Rules

https://metacpan.org/pod/FSA::Rules


B<AUTHOR>

DULAUNOY Fabrice, C<< <fabrice at dulaunoy.com> >>

B<BUGS>

Please report any bugs or feature requests to C<bug-FSM-basic at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=FSM-Basic>.  I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.

B<SUPPORT>

You can find documentation for this module with the perldoc command.

    perldoc FSM::Basic



( run in 0.568 second using v1.01-cache-2.11-cpan-8f98c5d2c55 )