[go: up one dir, main page]

File: command_process.py

package info (click to toggle)
kiwi 10.2.33-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,528 kB
  • sloc: python: 67,299; sh: 3,980; xml: 3,379; ansic: 391; makefile: 354
file content (249 lines) | stat: -rw-r--r-- 7,669 bytes parent folder | download
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
# Copyright (c) 2015 SUSE Linux GmbH.  All rights reserved.
#
# This file is part of kiwi.
#
# kiwi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kiwi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with kiwi.  If not, see <http://www.gnu.org/licenses/>
#
import os
import logging
from collections import namedtuple
from kiwi.command import CommandCallT
from typing import (
    NamedTuple, List, Callable
)

# project
from kiwi.utils.codec import Codec
from kiwi.logger import Logger

from kiwi.exceptions import KiwiCommandError

log = logging.getLogger('kiwi')


class PollT(NamedTuple):
    stdout_line: str
    stderr_line: str


class CommandProcess:
    """
    **Implements processing of non blocking Command calls**

    Provides methods to iterate over non blocking instances of
    the Command class with and without progress information

    :param subprocess command: instance of subprocess
    :param string log_topic: topic string for logging
    """
    def __init__(self, command: CommandCallT, log_topic='system') -> None:
        self.command = CommandIterator(command)
        self.log_topic = log_topic
        self.items_processed = 0

    def poll(self):
        """
        Iterate over process, raise on error and log output
        """
        for lineT in self.command:
            line = lineT.stdout_line
            if line:
                log.debug('%s: %s', self.log_topic, line)
        if self.command.get_error_code() != 0:
            raise KiwiCommandError(
                self.command.get_error_output()
            )

    def poll_show_progress(
        self, items_to_complete: List[str], match_method: Callable,
        with_stderr: bool = False
    ):
        """
        Iterate over process and show progress in percent
        raise on error and log output

        :param list items_to_complete: all items
        :param function match_method: method matching item
        """
        self._init_progress()
        for lineT in self.command:
            lines = [lineT.stdout_line]
            if with_stderr:
                lines.append(lineT.stderr_line)
            for line in lines:
                if line:
                    log.debug('%s: %s', self.log_topic, line)
                    self._update_progress(
                        match_method, items_to_complete, line
                    )
        self._stop_progress()
        if self.command.get_error_code() != 0:
            raise KiwiCommandError(
                self.command.get_error_output()
            )

    def poll_and_watch(self):
        """
        Iterate over process don't raise on error and log
        stdout and stderr
        """
        log.info(self.log_topic)
        log.debug('--------------out start-------------')
        for lineT in self.command:
            line = lineT.stdout_line
            if line:
                log.debug(line)
        log.debug('--------------out stop--------------')

        error_code = self.command.get_error_code()
        error_output = self.command.get_error_output()
        result = namedtuple(
            'result', ['stderr', 'returncode']
        )
        if error_output:
            log.debug('--------------err start-------------')
            for line in error_output.split(os.linesep):
                log.debug(line)
            log.debug('--------------err stop--------------')
        return result(
            stderr=error_output, returncode=error_code
        )

    def create_match_method(self, method):
        """
        create a matcher function pointer which calls the given
        method as method(item_to_match, data) on dereference

        :param function method: function reference

        :return: function pointer
        :rtype: object
        """
        def create_method(item_to_match, data):
            return method(item_to_match, data)
        return create_method

    def returncode(self):
        return self.command.get_error_code()

    def _init_progress(self):
        Logger.progress(
            0, 100, '[ INFO    ]: Processing'
        )

    def _stop_progress(self):
        Logger.progress(
            100, 100, '[ INFO    ]: Processing'
        )

    def _update_progress(
        self, match_method, items_to_complete, command_output
    ):
        items_count = len(items_to_complete)
        for item in items_to_complete:
            if match_method(item, command_output):
                self.items_processed += 1
                if self.items_processed <= items_count:
                    Logger.progress(
                        self.items_processed, items_count,
                        '[ INFO    ]: Processing'
                    )


class CommandIterator:
    """
    **Implements an Iterator for Instances of Command**

    :param subprocess command: instance of subprocess
    """
    def __init__(self, command: CommandCallT) -> None:
        self.command = command
        self.command_error_output = bytes(b'')
        self.command_output_line = bytes(b'')
        self.command_error_line = bytes(b'')
        self.output_eof_reached = False
        self.errors_eof_reached = False

    def __next__(self) -> PollT:
        line_stdout = ''
        line_stderr = ''
        if self.command.process.poll() is not None:
            if self.output_eof_reached and self.errors_eof_reached:
                raise StopIteration()

        if self.command.output_available():
            byte_read = self.command.output.read(1)
            if not byte_read:
                self.output_eof_reached = True
            elif byte_read == bytes(b'\n'):
                line_stdout = Codec.decode(self.command_output_line)
                self.command_output_line = bytes(b'')
            else:
                self.command_output_line += byte_read

        if self.command.error_available():
            byte_read = self.command.error.read(1)
            if not byte_read:
                self.errors_eof_reached = True
            elif byte_read == bytes(b'\n'):
                line_stderr = Codec.decode(self.command_error_line)
                self.command_error_line = bytes(b'')
                self.command_error_output += byte_read
            else:
                self.command_error_line += byte_read
                self.command_error_output += byte_read

        return PollT(
            stdout_line=line_stdout,
            stderr_line=line_stderr
        )

    def get_error_output(self):
        """
        Provide data which was sent to the stderr channel

        :return: stderr data

        :rtype: str
        """
        return Codec.decode(self.command_error_output)

    def get_error_code(self) -> int:
        """
        Provide return value from processed command

        :return: errorcode

        :rtype: int
        """
        return self.command.process.returncode

    def get_pid(self) -> int:
        """
        Provide process ID of command while running

        :return: pid

        :rtype: int
        """
        return self.command.process.pid

    def kill(self) -> None:
        """
        Send kill signal SIGTERM to command process
        """
        self.command.process.kill()

    def __iter__(self):
        return self