source: trunk/LATMOS-Accounts/lib/LATMOS/Accounts/Cli.pm @ 2286

Last change on this file since 2286 was 2286, checked in by nanardon, 5 years ago

OCHelper now return the name of created object

  • Property svn:keywords set to Id
File size: 10.7 KB
Line 
1package LATMOS::Accounts::Cli;
2
3# $Id: Cli.pm 2145 2018-08-29 18:15:46Z nanardon $
4
5use strict;
6use warnings;
7use Moose;
8use LATMOS::Accounts::Log;
9use LATMOS::Accounts::Utils;
10use Term::ReadLine;
11use Text::ParseWords;
12use Getopt::Long;
13use LATMOS::Accounts::Cli::Object;
14
15extends 'LATMOS::Accounts::Cli::Base';
16
17=head1 NAME
18
19LATMOS::Accounts::Cli - Command line interface functions
20
21=head1 DESCRIPTION
22
23This module handle envirronment and functons for L<la-cli> tools.
24
25=cut
26
27=head1 FUNCTIONS
28
29=cut
30
31=head2 globalenv
32
33Return the main envirronement object
34
35=cut
36
37sub BUILD {
38    my ( $self ) = @_;
39
40    my $labase = $self->base;
41    my $OUT = $self->Context->Out;
42
43    $self->add_func('ls', {
44            help => 'ls object_type - list object of type object_type', 
45            completion => sub {
46                if(!$_[2]) {
47                    return $_[0]->base->list_supported_objects
48                } else { () }
49            },
50            code => sub {
51                my $env = shift;
52                warn @_;
53                my @args = $self->getoption(
54                    {
55                        'fmt=s'      => \my $fmt,
56                        'filefmt=s'  => \my $filefmt,
57                    }, @_
58                );
59
60                my $otype = $args[0] or do {
61                    print $OUT "Object type missing\n";
62                    return 1;
63                };
64
65                if ($filefmt){
66                    open(my $hfmt, '<', $filefmt) or die "Cannot open $filefmt\n";
67                    $fmt ||= ''; # avoid undef warning
68                    while (<$hfmt>) {
69                        chomp($fmt .= $_);
70                    }
71                    close $hfmt;
72                }
73
74                if ($fmt) {
75                    foreach ($env->base->list_objects($otype)) {
76                        my $obj = $env->base->get_object($otype, $_) or next;
77                        print $OUT $obj->queryformat($fmt);
78                    }
79                    print $OUT "\n";
80                } else {
81                    print $OUT map { "$_\n" } $env->base->list_objects($otype);
82                }
83            },
84        });
85    $self->add_func('search', {
86            help => 'search objecttype filter1 [filter2...] - search object according filter',
87            completion => sub {
88                if(!$_[2]) {
89                    return $_[0]->base->list_supported_objects
90                } else { return() }
91            },
92            code => sub {
93                my ($self, @args) = @_;
94                if ($_[1]) {
95                    my @res = $self->base->search_objects(@args);
96                    print $OUT map { "$_\n" } @res;
97                    $self->{_lastsearch} = \@res;
98                    $self->{_lastsearchtype} = $args[0];
99                } else {
100                    print $OUT "Object type missing\n";
101                }
102            },
103        });
104    $self->add_func('expired', {
105        help => 'expired [delay] - list expired account more than delay (default is now)',
106        code => sub {
107            my ($self, $expire) = @_;
108            my @users = $self->base->find_expired_users($expire);
109            print $OUT map { "$_\n" } @users;
110            $self->{_lastsearchtype} = 'user';
111            $self->{_lastsearch} = \@users;
112        },
113    }) if ($self->base->can('find_expired_users'));
114    $self->add_func('expires', {
115        help => 'expires [delay] - list account expiring before delay (default is 1 month)',
116        code => sub {
117            my ($self, $expire) = @_;
118            my @users = $self->base->find_next_expire_users($expire);
119            print $OUT map { "$_\n" } @users;
120            $self->{_lastsearchtype} = 'user';
121            $self->{_lastsearch} = \@users;
122        },
123    }) if ($self->base->can('find_next_expire_users'));
124    $self->add_func('select', {
125            help => 'select object_type - select objects to perform action on it',
126            completion => sub {
127                if ($_[2]) {
128                    return $_[0]->base->list_objects($_[2]);
129                } else {
130                    return '@', $_[0]->base->list_supported_objects;
131                }
132            },
133            code => sub {
134                my ($self, $otype, @ids) = @_;
135                my @objs;
136                if ($otype eq '@') {
137                    if (@{$self->{_lastsearch} || []}) {
138                        $otype = $self->{_lastsearchtype};
139                        @ids = @{$self->{_lastsearch}};
140                    } else {
141                        print $OUT "No results store from previous search\n";
142                        return;
143                    }
144                }
145                if (!@ids) {
146                    print $OUT 'not enough arguments' . "\n";
147                    return;
148                }
149                foreach (@ids) {
150                    my $obj = $self->base->get_object($otype, $_) or do {
151                        print $OUT "Cannot get $otype $_\n";
152                        return;
153                    };
154                    push(@objs, $obj);
155                }
156                print $OUT "Selecting $otype " . join(', ', @ids) . "\n";
157                LATMOS::Accounts::Cli::Object->new(
158                    Parent  => $self,
159                    Context => $self->Context,
160                    otype   => $otype,
161                    objs    => \@objs,
162                )->cli();
163            },
164        });
165    $self->add_func('create', {
166            code => sub {
167                my ($self, $otype) = @_;
168                my $helper = $self->base->ochelper($otype);
169                my $info = undef;
170                while (1) {
171                    my $status;
172                    ($status, $info) = $helper->step($info);
173
174                    if ($status ne 'NEEDINFO') {
175                        if ($status eq 'CREATED') {
176                            print $OUT "Object created\n";
177                            $self->commit;
178                        } else {
179                            print $OUT "Nothing done\n";
180                            $self->rollback;
181                        }
182                        return;
183                    }
184
185                    if ($info->{name}{ask}) {
186                        my $line = $self->Context->Term->readline("Name of the object ?");
187                        $info->{name}{content} = $line;
188                    }
189                    foreach my $attr (@{$info->{ask} || []}) {
190                        $self->Context->Term->Attribs->{completion_function} = sub {
191                            $info->{contents}{$attr}
192                        };
193                        my $line = $self->Context->Term->readline(sprintf('  %s %s? ',
194                                $attr,
195                                $info->{contents}{$attr}
196                                ? '(' . $info->{contents}{$attr} . ') '
197                                : ''
198                            ));
199                        $info->{contents}{$attr} = $line if($line);
200                    }
201                }
202            },
203        }
204    );
205    $self->add_func('exchangeip', 
206        {
207            help => 'Exchange two IP on host',
208            code => sub {
209                my ($self, @args) = @_;
210                my ($ip1, $ip2) =
211                    grep { $_ && $_ =~ /\d+\.\d+\.\d+\.\d+/ } @args;
212                if (!$ip2) {
213                    print $OUT "Need two ip to exchange\n";
214                    return;
215                }
216                if ($self->base->nethost_exchange_ip($ip1, $ip2)) {
217                    print $OUT "$ip1 and $ip2 get exchange\n";
218                    $self->commit;
219                } else {
220                    $self->rollback;
221                }   
222            },
223            completion => sub {
224                my ($self, $carg, @args) = @_;
225                if ($args[-1] && $args[-1] !~ m/\d+\.\d+\.\d+\.\d+/) {
226                    if (my $obj = $self->base->get_object('nethost', $args[-1])) {
227                        return $obj->get_attributes('ip');
228                    }
229                } else {
230                    my @list = 
231                    ($self->base->attributes_summary('nethost', 'ip'),
232                        $self->base->list_objects('nethost'));
233                    return @list;
234                }
235            },
236        }
237    );
238
239    $self->add_func('loadcsv',
240        {
241            help => 'Load CSV file to create object',
242            code => sub {
243                my ($self, $otype, $file) = @_;
244
245                open(my $fh, '<', $file) or do {
246                   warn "Cannot open  $file $!\n";
247                   return;
248                };
249
250                my @ids;
251
252                loadCSV(
253                    $fh,
254                    cb => sub {
255                        my ($res, $linecount) = @_;
256
257                        my $ochelper = $labase->ochelper($otype);
258
259                        my $info = {
260                            contents => $res
261                        };
262                        if ($res->{name}) {
263                            $info->{name}{content} = $res->{name};
264                        }
265
266                        if (my $id = $ochelper->Automate($info)) {
267                            push(@ids, $id);
268                        } else {
269                            warn "Cannot create object line $linecount (not enough information ?)\n";
270                        }
271                    },
272                );
273
274                close($fh);
275
276                my @objs;
277                foreach (@ids) {
278                    my $obj = $self->base->get_object($otype, $_) or do {
279                        print $OUT "Cannot get $otype $_\n";
280                        return;
281                    };
282                    push(@objs, $obj);
283                }
284
285                print $OUT "Selecting $otype " . join(', ', @ids) . "\n";
286                LATMOS::Accounts::Cli::Object->new(
287                    Parent  => $self,
288                    Context => $self->Context,
289                    otype   => $otype,
290                    objs    => \@objs,
291                )->cli();
292            },
293            completion => sub {
294                if ($_[2]) {
295                    return Term::ReadLine::Gnu::filename_list(@_);
296                } else {
297                    return '@', $_[0]->base->list_supported_objects;
298                }
299            },
300        }
301    );
302
303    $self->add_func('user',  { alias => [qw'select user' ] });
304    $self->add_func('group', { alias => [qw'select group'] });
305    return $self
306}
307
3081;
309
310__END__
311
312=head1 SEE ALSO
313
314L<LATMOS::Accounts>
315
316=head1 AUTHOR
317
318Olivier Thauvin, E<lt>olivier.thauvin@latmos.ipsl.frE<gt>
319
320=head1 COPYRIGHT AND LICENSE
321
322Copyright (C) 2008, 2009, 2010, 2011, 2012 CNRS SA/CETP/LATMOS
323
324This library is free software; you can redistribute it and/or modify
325it under the same terms as Perl itself, either Perl version 5.10.0 or,
326at your option, any later version of Perl 5 you may have available.
327
328=cut
Note: See TracBrowser for help on using the repository browser.