-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathservice_implementation.py
More file actions
3133 lines (2587 loc) · 117 KB
/
service_implementation.py
File metadata and controls
3133 lines (2587 loc) · 117 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
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
"""
Module:
unicon.plugins.generic.service_implementation
Authors:
pyATS TEAM (pyats-support@cisco.com, pyats-support-ext@cisco.com)
Description:
This module contains dual-rp and single rp service implementation
code for generic platform. These services are implemented by subclassing
BaseService and handle majority of platforms.
"""
import io
import os
import re
import copy
import logging
import collections
import ipaddress
from itertools import chain
import time
import warnings
from datetime import datetime, timedelta
from time import sleep
from unicon.bases.routers.services import BaseService
from unicon.core.errors import SubCommandFailure, StateMachineError, \
CopyBadNetworkError, TimeoutError, UniconBackendDecodeError, \
UniconAuthenticationError, CredentialsExhaustedError
from unicon.eal.dialogs import Dialog
from unicon.eal.dialogs import Statement
from unicon.plugins.generic.statements import (
chatty_term_wait,
custom_auth_statements,
buffer_settled,
default_statement_list)
from unicon.plugins.generic.service_statements import reload_statement_list, \
ping_dialog_list, extended_ping_dialog_list, copy_statement_list, \
ha_reload_statement_list, switchover_statement_list, \
standby_reset_rp_statement_list, trace_route_dialog_list
from unicon.plugins.generic.service_patterns import CopyPatterns
from unicon.utils import AttributeDict, to_plaintext
from unicon import logs
from unicon.logs import UniconStreamHandler, UNICON_LOG_FORMAT
from unicon.plugins.generic.utils import GenericUtils
from .service_statements import execution_statement_list, configure_statement_list
from .statements import disable_enable_transition_statements
from unicon.plugins.generic.statemachine import config_transition
utils = GenericUtils()
ReloadResult = collections.namedtuple('ReloadResult', ['result', 'output'])
class SwitchoverResult:
def __init__(self, result, output, **kwargs):
self.result = result
self.output = output
def invalid_state_change_action(spawn, err_state, sm):
msg = "Expected device to reach '{}' state, but landed on '{}' state."\
.format(sm.current_state, err_state.name)
# Update device current state with unexpected state.
sm.update_cur_state(err_state)
raise StateMachineError(msg)
class Send(BaseService):
"""Service to send the command/string with "\\r" to spawned channel.
If target is passed as standby, command will be sent to standby spawn.
Arguments:
command: Command to be sent.
target: Target connection, Defaults to active.
Returns:
True: on Success
Raises:
SubCommandFailure: on failure.
Example:
.. code-block:: python
rtr.send("show clock\\r")
rtr.send("show clock\\r", target='standby')
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, command, target=None, *args, **kwargs):
spawn = self.get_spawn(target)
try:
spawn.send(command, *args, **kwargs)
except Exception as err:
raise SubCommandFailure("Failed to send the command to spawn",
err) from err
self.result = True
def get_service_result(self):
return self.result
class Sendline(BaseService):
""" Sendline Service
Service to send the command/string to spawned channel,
"\\r" will be appended to command by sendline. If target
is passed as standby, command will be sent to standby
spawn.
Arguments:
command: Command to be sent
target: Target connection, Defaults to active
Returns:
True: on Success
Raises:
SubCommandFailureError: On failure of service
Example:
.. code-block:: python
rtr.sendline("show clock")
rtr.sendline("show clock", target='standby')
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, command='', target=None, *args, **kwargs):
spawn = self.get_spawn(target)
try:
spawn.sendline(command, *args, **kwargs)
except Exception as err:
raise SubCommandFailure("Failed to send the command to spawn",
err) from err
self.result = True
def get_service_result(self):
return self.result
class Expect(BaseService):
"""match a list of pattern again the buffer
Arguments:
patterns: list of patterns.
timeout: time to wait for any of the patterns to match.
size: read size in bytes for reading the buffer.
trim_buffer: whether to trim the buffer after a successful match.
target: ``standby`` to match a list of patterns against the buffer on standby spawn channel.
search_size: maximum size in bytes to search at the end of the buffer
Returns:
ExpectMatch instance.
* It contains the index of the pattern that matched.
* matched string.
* re match object.
Raises:
TimeoutError: In case no match is found within the timeout period
or raise SubCommandFailure on failure.
Example:
.. code-block:: python
rtr.sendline("a command")
rtr.expect([r'^pat1', r'pat2'], timeout=10, target='standby')
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, patterns, timeout=None,
size=None, trim_buffer=True,
target=None, *args, **kwargs):
spawn = self.get_spawn(target)
try:
self.result = spawn.expect(patterns, timeout, size, *args, **kwargs)
except Exception as err:
raise SubCommandFailure("Failed to match buffer on spawn",
err) from err
def get_service_result(self):
return self.result
class ReceiveService(BaseService):
"""match a pattern from spawn buffer
Arguments:
pattern: regular expression pattern to match. If r'nopattern^' is used then
no pattern is match and all data till timeout period will be matched.
timeout: time to wait for the pattern to match.
size: read size in bytes for reading the buffer.
trim_buffer: whether to trim the buffer after a successful match. Default is True.
target: ``standby`` to match a list of pattern against the buffer on standby spawn channel.
search_size: maximum size in bytes to search at the end of the buffer
Returns:
Bool: True or False
True: If data is matched by provided pattern.
False: If nothing is matched by pattern.
Data matched by pattern is set to receiveBuffer attribute of connection object.
Raises:
No Exception is raised if pattern does not get match or timeout happens.
SubCommandFailure will be raised if any Exception is raised apart from TimeoutError.
Example:
.. code-block:: python
rtr.sendline("a command")
rtr.receive(r'some_pattern', timeout=10, target='standby')
"""
def __init__(self, connection, context, **kwargs):
super().__init__(connection, context, **kwargs)
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, pattern, timeout=None,
size=None, trim_buffer=True,
target=None, *args, **kwargs):
spawn = self.get_spawn(target)
self.result = False
self.connection.receiveBuffer = ''
try:
if pattern == r'nopattern^':
sleep(timeout or 10)
self.connection.receiveBuffer = spawn.expect(r'.*', size, *args, **kwargs).match_output
else:
self.connection.receiveBuffer = spawn.expect(pattern, timeout, size, *args, **kwargs).match_output
self.result = True
except TimeoutError:
pass
except Exception as err:
raise SubCommandFailure("Receive service failed", err) from err
def get_service_result(self):
return self.result
class ReceiveBufferService(BaseService):
"""Returns data match by receive() service pattern.
Returns:
String: Data matched by receive() service pattern.
Raises:
SubCommandFailure: If this is called without calling receive() service.
Example:
.. code-block:: python
rtr.sendline("a command")
rtr.receive(r'some_pattern', timeout=10, target='standby')
output = rtr.receive_buffer()
"""
def __init__(self, connection, context, **kwargs):
super().__init__(connection, context, **kwargs)
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self):
try:
self.result = self.connection.receiveBuffer
except AttributeError as err:
raise SubCommandFailure("receive_buffer should be invoked after receive call", err)
except Exception as err:
raise SubCommandFailure("Error in receive_buffer", err) from err
def get_service_result(self):
result = copy.copy(self.result)
delattr(self.connection, 'receiveBuffer')
return result
class LogUser(BaseService):
""" Service to enable or disable a device logs on screen.
Arguments:
enable: True/False
Example:
.. code-block:: python
rtr.log_user(enable=True)
rtr.log_user(enable=False)
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, enable, target=None, *args, **kwargs):
conn = self.connection
if enable:
conn.log.info("+++ log_user: enable +++")
# does it exist already
for hdlr in conn.log.handlers:
if type(hdlr) in (logs.UniconStreamHandler,
logs.UniconScreenHandler):
break
else:
# add it
try:
from pyats.log import managed_handlers # noqa
except Exception:
sh = logs.UniconStreamHandler()
sh.setFormatter(logging.Formatter(fmt='[%(asctime)s] %(message)s'))
conn.log.addHandler(sh)
else:
conn.log.addHandler(logs.UniconScreenHandler())
else:
conn.log.info("+++ log_user: disable +++")
for hdlr in conn.log.handlers:
if type(hdlr) in (logs.UniconStreamHandler,
logs.UniconScreenHandler):
conn.log.removeHandler(hdlr)
self.result = True
def get_service_result(self):
return self.result
class LogFile(BaseService):
""" Service to get or change Device FileHandler file.
If no argument passed then it return current filename of FileHandler.
Return True, if file handlers updated with new filename.
Arguments:
filename: file name in which device logs to dump.
Example:
.. code-block:: python
rtr.log_file(filename='/some/path/uut.log')
rtr.log_file()
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, filename=None, *args, **kwargs):
conn = self.connection
file_handler = ''
self.result = False
for hdlr in conn.log.handlers:
if isinstance(hdlr, logs.UniconFileHandler):
file_handler = hdlr
break
if filename:
filename = os.path.abspath(filename)
conn.log.info("+++ logfile: {} +++".format(filename))
if file_handler:
file_handler.close()
conn.log.removeHandler(file_handler)
fh = logs.UniconFileHandler(filename)
fh.setFormatter(logging.Formatter(fmt='[%(asctime)s] %(message)s'))
conn.log.addHandler(fh)
self.result = True
else:
if file_handler:
self.result = file_handler.baseFilename
def get_service_result(self):
return self.result
class ExpectLogging(BaseService):
r""" Service to enable expect internal logging.
Arguments:
enable: True/False for enabling and disabling the expect_log
Example:
.. code::
rtr.expect_log(enable=True)
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, enable=False,
*args, **kwargs):
con = self.connection
if enable:
con.log.info("+++ enable debug logging +++")
con.log.setLevel(logging.DEBUG)
else:
con.log.info("+++ disable debug logging +++")
con.log.setLevel(logging.INFO)
self.result = True
def get_service_result(self):
return self.result
class Enable(BaseService):
""" Brings device to enable
Service to change the device mode to enable from any state.
Brings the standby handle to enable state, if standby is passed as input.
Arguments:
target= Target connection, Defaults to active
Returns:
True on Success, raise SubCommandFailure on failure
Example:
.. code-block:: python
rtr.enable()
rtr.enable(target='standby')
"""
def __init__(self, connection, context, **kwargs):
# Connection object will have all the received details
super().__init__(connection, context, **kwargs)
self.start_state = 'enable'
self.end_state = 'enable'
self.dialog = Dialog(disable_enable_transition_statements)
self.__dict__.update(kwargs)
def pre_service(self, *args, **kwargs):
self.prompt_recovery = self.connection.prompt_recovery
if 'prompt_recovery' in kwargs:
self.prompt_recovery = kwargs.get('prompt_recovery')
def call_service(self, target=None, command='', *args, **kwargs):
handle = self.get_handle(target)
spawn = self.get_spawn(target)
sm = self.get_sm(target)
timeout = kwargs.get('timeout', None) or handle.settings.ENABLE_TIMEOUT
# If the device is in rommon, enable() will use the
# image_to_boot info to boot the image specified
# by the user. This is used by boot_image in iosxe/statements.py
# (IOSXE only implementation at this time.)
handle.context["image_to_boot"] = \
kwargs.get("image_to_boot", kwargs.get('image', ''))
# override command to be enable when command is given
if command:
disable = sm.get_state('disable')
enable = sm.get_state('enable')
pt = sm.get_path(disable, enable)
sm.paths[sm.paths.index(pt)].command = command
try:
sm.go_to(self.start_state,
spawn,
context=handle.context,
timeout=timeout)
except (UniconAuthenticationError, CredentialsExhaustedError):
# Don't wrap auth errors - re-raise them directly
raise
except Exception as err:
raise SubCommandFailure("Failed to Bring device to Enable State",
err) from err
self.result = True
class Disable(BaseService):
"""Service to change the device to disable mode from any state.
Brings the standby handle to disable state, if standby is passed as
input.
Arguments:
target: Target connection, Defaults to active
Returns:
True on Success, raise SubCommandFailure on failure
Example:
.. code-block:: python
rtr.disable()
rtr.disable(target='standby')
"""
def __init__(self, connection, context, **kwargs):
super().__init__(connection, context, **kwargs)
self.start_state = 'disable'
self.end_state = 'disable'
self.__dict__.update(kwargs)
def call_service(self, target=None, *args, **kwargs):
handle = self.get_handle(target)
spawn = self.get_spawn(target)
sm = self.get_sm(target)
try:
sm.go_to(self.start_state,
spawn,
context=handle.context)
except Exception as err:
raise SubCommandFailure("Failed to Bring device to Disable State",
err) from err
self.result = True
class Execute(BaseService):
""" Execute Service implementation
Service to executes exec_commands on the device and return the
console output. reply option can be passed for the interactive exec
command.
By default, device start state should be same as end state. If device
ends in some other state, StateMachineError exception is raised. For not to
raise exception on state change, use allow_state_change=True.
Arguments:
command: string or list of strings
reply: Additional Dialog patterns for interactive exec commands.
timeout : Timeout value in sec, Default Value is 60 sec
error_pattern: list of regex to detect command errors
search_size: maximum size in bytes to search at the end of the buffer
allow_state_change: Boolean. Default is None. If True, end state can be any state.
service_dialog: Instance of Dialog that overrides the execute service dialog.
matched_retries: retry times if state pattern is matched, default is 1
matched_retry_sleep: sleep between matched_retries, default is 0.05 sec
Returns:
String for single command, list for repeated single command,
dict for multiple commands.
raises SubCommandFailure on failure
raises StateMachineError when device fail to reach original state
Example:
.. code-block:: python
output = rtr.execute("show clock")
"""
def __init__(self, connection, context, **kwargs):
# Connection object will have all the received details
super().__init__(connection, context, **kwargs)
self.start_state = 'any'
self.end_state = 'any'
self.timeout = connection.settings.EXEC_TIMEOUT
self.__dict__.update(kwargs)
self.utils = utils
self.dialog = Dialog(execution_statement_list)
self.matched_retries = connection.settings.EXECUTE_MATCHED_RETRIES
self.matched_retry_sleep = connection.settings.EXECUTE_MATCHED_RETRY_SLEEP
self.state_change_matched_retries = connection.settings.EXECUTE_STATE_CHANGE_MATCH_RETRIES
self.state_change_matched_retry_sleep = connection.settings.EXECUTE_STATE_CHANGE_MATCH_RETRY_SLEEP
self.detect_state = True
def log_service_call(self):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, command=[], # noqa: C901
reply=Dialog([]),
timeout=None,
error_pattern=None,
append_error_pattern=None,
search_size=None,
allow_state_change=None,
matched_retries=None,
matched_retry_sleep=None,
detect_state=None,
*args, **kwargs):
con = self.connection
sm = self.get_sm()
if allow_state_change is None:
allow_state_change = con.settings.EXEC_ALLOW_STATE_CHANGE
self.detect_state = detect_state if detect_state is not None else self.detect_state
timeout = timeout or self.timeout
if error_pattern is None:
self.error_pattern = con.settings.ERROR_PATTERN
else:
self.error_pattern = error_pattern
if append_error_pattern:
if not isinstance(append_error_pattern, list):
raise ValueError('append_error_pattern should be a list')
self.error_pattern += append_error_pattern
# user specified search buffer size
if search_size is not None:
con.spawn.search_size = search_size
else:
con.spawn.search_size = con.settings.SEARCH_SIZE
matched_retries = self.matched_retries \
if matched_retries is None else matched_retries
matched_retry_sleep = self.matched_retry_sleep \
if matched_retry_sleep is None else matched_retry_sleep
if (reply is None) or (reply == []):
reply = Dialog([])
elif not isinstance(reply, Dialog):
raise SubCommandFailure(
"dialog passed via 'reply' must be an instance of Dialog")
# service_dialog overrides the default execution dialogs
if 'service_dialog' in kwargs:
service_dialog = kwargs['service_dialog']
if (service_dialog is None) or (service_dialog == []):
service_dialog = Dialog([])
elif not isinstance(service_dialog, Dialog):
raise SubCommandFailure(
"dialog passed via 'service_dialog' must be an instance of Dialog")
dialog = self.service_dialog(
service_dialog=service_dialog + reply,
matched_retries=matched_retries,
matched_retry_sleep=matched_retry_sleep
)
else:
dialog = self.dialog + self.service_dialog(
service_dialog=reply,
matched_retries=matched_retries,
matched_retry_sleep=matched_retry_sleep
)
# add default execution statements
custom_auth_stmt = custom_auth_statements(con.settings.LOGIN_PROMPT,
con.settings.PASSWORD_PROMPT)
if custom_auth_stmt:
dialog += Dialog(custom_auth_stmt)
if self.detect_state:
# Add all known states to detect state changes.
for state in sm.states:
# The current state is already added by the service_dialog method
if state.name != sm.current_state:
if allow_state_change:
dialog.append(Statement(
pattern=state.pattern,
matched_retries=self.state_change_matched_retries,
matched_retry_sleep=self.state_change_matched_retry_sleep
))
else:
dialog.append(Statement(
pattern=state.pattern,
action=invalid_state_change_action,
args={'err_state': state, 'sm': sm},
matched_retries=self.state_change_matched_retries,
matched_retry_sleep=self.state_change_matched_retry_sleep
))
# store the last used dialog, used by unittest
self._last_dialog = dialog
if isinstance(command, str):
if len(command) == 0:
commands = ['']
else:
commands = command.splitlines()
elif isinstance(command, list):
commands = command
else:
raise ValueError('Command passed is not of type string or list (%s)' % type(command))
if con.settings.IGNORE_CHATTY_TERM_OUTPUT:
# clear buffer log messages
chatty_term_wait(con.spawn, trim_buffer=True)
command_output = {}
for command in commands:
message = f"executing command '{command}'"
super().log_service_call(message)
con.sendline(command)
try:
dialog_match = dialog.process(
con.spawn,
timeout=timeout,
prompt_recovery=self.prompt_recovery,
context=con.context
)
if dialog_match:
self.result = dialog_match.match_output
self.result = self.get_service_result()
sm.detect_state(con.spawn, con.context)
except StateMachineError:
raise
except UniconBackendDecodeError:
pass
except Exception as err:
raise SubCommandFailure("Command execution failed", err) from err
if self.result:
output = self.utils.truncate_trailing_prompt(
sm.get_state(sm.current_state),
self.result,
hostname=con.hostname,
result_match=dialog_match,
)
output = self.extra_output_process(output)
output = output.replace(command, "", 1)
# only strip first newline and leave formatting intact
output = re.sub(r"^\r?\r\n", "", output, count=1)
output = output.rstrip()
if command in command_output:
if isinstance(command_output[command], list):
command_output[command].append(output)
else:
command_output[command] = [command_output[command], output]
else:
command_output[command] = output
if len(command_output) == 1:
self.result = list(command_output.values())[0]
else:
self.result = command_output
# revert search size to default
con.spawn.search_size = con.settings.SEARCH_SIZE
if self.end_state != 'any':
sm.go_to(self.end_state, con.spawn,
prompt_recovery=self.prompt_recovery,
context=con.context)
def extra_output_process(self, output):
# remove backspace and ansi escape sequence from output
# scenario 1: it prevents correct command replacement, on linux terminals
# scenario 2: router with '\x1b[KSomething\x08 \x08\x08 \x08\x08 \x08\x08 \x08\x08\x1b[K'
return utils.remove_backspace_ansi_escape(output)
class Configure(BaseService):
"""Service to configure device with single or list of `commands`.
Config without config_command will take device to config mode.
Commands Should be list, if `config_command` are more than one.
reply option can be passed for the interactive config command.
Arguments:
commands : list/single config command
reply: Addition Dialogs for interactive config commands.
timeout : Timeout value in sec, Default Value is 30 sec
error_pattern: list of regex to detect command errors
allow_state_change: If True allow the state change during the
configuration otherwise raise state machine error if the state
changes during configuration.
target: Target RP where to execute service, for DualRp only
lock_retries: retry times if config mode is locked, default is 0
lock_retry_sleep: sleep between retries, default is 2 sec
bulk: If False, send all commands in one sendline,
If True, send commands in chunked mode,
default is False
bulk_chunk_lines: maximum number of commands to send per chunk,
default is 50,
0 means to send all commands in a single chunk
bulk_chunk_sleep: sleep between sending command chunks,
default is 0.5 sec
result_check_per_command: boolean option, check results after
each command (default: True)
Returns:
command output on Success, raise SubCommandFailure on failure
Example:
.. code-block:: python
output = rtr.configure()
output = rtr.configure('no logging console')
cmd =['hostname si-tvt-7200-28-41', 'no logging console']
output = rtr.configure(cmd)
"""
def __init__(self, connection, context, **kwargs):
super().__init__(connection, context, **kwargs)
self.start_state = 'config'
self.end_state = 'enable'
self.timeout = connection.settings.CONFIG_TIMEOUT
self.dialog = Dialog(configure_statement_list)
self.commit_cmd = ''
self.bulk = connection.settings.BULK_CONFIG
self.bulk_chunk_lines = connection.settings.BULK_CONFIG_CHUNK_LINES
self.bulk_chunk_sleep = connection.settings.BULK_CONFIG_CHUNK_SLEEP
self.valid_transition_commands = ['end', 'exit']
self.valid_transition_states = ['config_pki_hexmode']
self.state_change_matched_retries = connection.settings.EXECUTE_STATE_CHANGE_MATCH_RETRIES
self.state_change_matched_retry_sleep = connection.settings.EXECUTE_STATE_CHANGE_MATCH_RETRY_SLEEP
self.__dict__.update(kwargs)
class ConfigUtils(GenericUtils):
def truncate_trailing_prompt(self, con_state,
result,
hostname=None,
result_match=None):
host_idx = result.rfind(hostname)
result = result[:host_idx] if host_idx \
else result
return result
self.utils = ConfigUtils()
def pre_service(self, *args, **kwargs):
sm = self.get_sm()
self.prompt_recovery = kwargs.get('prompt_recovery', False)
# Backward compatibility with old config lock implementation
con = self.connection
settings = con.settings
settings.CONFIG_LOCK_RETRIES = kwargs.get('lock_retries', settings.CONFIG_LOCK_RETRIES)
settings.CONFIG_LOCK_RETRY_SLEEP = kwargs.get('lock_retry_sleep', settings.CONFIG_LOCK_RETRY_SLEEP)
super().pre_service(*args, **kwargs)
def post_service(self, *args, **kwargs):
pass
def call_service(self, # noqa: C901
command=[],
reply=Dialog([]),
timeout=None,
error_pattern=None,
append_error_pattern=None,
allow_state_change=None,
target=None,
bulk=None,
bulk_chunk_lines=None,
bulk_chunk_sleep=None,
result_check_per_command=True,
*args,
**kwargs):
self.result_check_per_command = result_check_per_command
con = self.connection
sm = self.get_sm()
handle = self.get_handle(target)
timeout = timeout or self.timeout
if allow_state_change is None:
allow_state_change = con.settings.CONFIGURE_ALLOW_STATE_CHANGE
if error_pattern is None:
self.error_pattern = \
handle.settings.CONFIGURE_ERROR_PATTERN
else:
self.error_pattern = error_pattern
if append_error_pattern:
if not isinstance(append_error_pattern, list):
raise ValueError('append_error_pattern should be a list')
self.error_pattern += append_error_pattern
bulk = self.bulk if bulk is None else bulk
bulk_chunk_lines = self.bulk_chunk_lines \
if bulk_chunk_lines is None else bulk_chunk_lines
bulk_chunk_sleep = self.bulk_chunk_sleep \
if bulk_chunk_sleep is None else bulk_chunk_sleep
if not isinstance(reply, Dialog):
raise SubCommandFailure('"reply" must be an instance of Dialog')
def config_state_change(spawn, from_state, sm):
last_cmd = spawn.last_sent.strip()
# check if the last command is not in the list of valid commands and the state is not in the list of valid states
# for transition
if last_cmd not in self.valid_transition_commands and from_state.name not in self.valid_transition_states:
invalid_state_change_action(
spawn, err_state=from_state, sm=sm)
else:
sm.update_cur_state(from_state)
# Flatten multi-line input into one-command-per-line list.
flat_cmd_list = list(self.utils.flatten_splitlines_command(command) if command else [])
self.result = ''
if flat_cmd_list:
dialog = self.dialog + self.service_dialog(handle=handle, service_dialog=reply)
# Add all known states to detect state changes.
for state in sm.states:
# The current state is already added by the service_dialog method
if state.name != sm.current_state:
if allow_state_change:
dialog.append(Statement(
pattern=state.pattern,
matched_retries=self.state_change_matched_retries,
matched_retry_sleep=self.state_change_matched_retry_sleep
))
else:
dialog.append(Statement(
pattern=state.pattern,
action=config_state_change,
args={'from_state': state, 'sm': sm},
matched_retries=self.state_change_matched_retries,
matched_retry_sleep=self.state_change_matched_retry_sleep
))
# Use flattened command list
pre_lines, banner_lines, post_lines, banner_delim = self.get_banner_lines(flat_cmd_list)
# Populate context for banner_text_handler only if banner was detected
if banner_lines:
self.connection.log.info('Banner detected, configuring banners without state detection')
for cmd in pre_lines:
handle.spawn.sendline(cmd)
self.update_hostname_if_needed([cmd])
self.process_dialog_on_handle(handle, dialog, timeout)
# Send banner lines
for line in banner_lines:
handle.spawn.sendline(line)
time.sleep(0.1)
handle.spawn.read_update_buffer()
self.process_dialog_on_handle(handle, dialog, timeout)
post_cmds = chain(post_lines, [self.commit_cmd]) if self.commit_cmd else post_lines
for cmd in post_cmds:
handle.spawn.sendline(cmd)
self.update_hostname_if_needed([cmd])
self.process_dialog_on_handle(handle, dialog, timeout)
elif bulk:
indicator = handle.settings.BULK_CONFIG_END_INDICATOR
cmd_lst = list(chain(flat_cmd_list, [indicator]))
if bulk_chunk_lines == 0:
chunks = [cmd_lst]
else:
chunks = [cmd_lst[i:i + bulk_chunk_lines]
for i in range(0, len(cmd_lst), bulk_chunk_lines)]
for idx, chunk in enumerate(chunks, 1):
chunk_cmd = '\n'.join(chunk)
handle.spawn.sendline(chunk_cmd)
if idx != len(chunks):
sleep(bulk_chunk_sleep)