From 39aaa32e40c9e7da70984dba39778d4302247ba7 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 9 Feb 2017 19:42:05 -0500 Subject: [PATCH] adds socket usage to network common (#21196) * updates network common the reconstruct the persistent connection socket --- lib/ansible/module_utils/network_common.py | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/ansible/module_utils/network_common.py b/lib/ansible/module_utils/network_common.py index 31a5d69f4ab..82c0cc9f8f8 100644 --- a/lib/ansible/module_utils/network_common.py +++ b/lib/ansible/module_utils/network_common.py @@ -25,6 +25,12 @@ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +import socket +import struct +import signal + +from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils.six import iteritems def to_list(val): @@ -95,3 +101,43 @@ class ComplexList: objects.append(obj) return objects +def send_data(s, data): + packed_len = struct.pack('!Q',len(data)) + return s.sendall(packed_len + data) + +def recv_data(s): + header_len = 8 # size of a packed unsigned long long + data = to_bytes("") + while len(data) < header_len: + d = s.recv(header_len - len(data)) + if not d: + return None + data += d + data_len = struct.unpack('!Q',data[:header_len])[0] + data = data[header_len:] + while len(data) < data_len: + d = s.recv(data_len - len(data)) + if not d: + return None + data += d + return data + +def exec_command(module, command): + try: + sf = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sf.connect(module._socket_path) + + data = "EXEC: %s" % command + send_data(sf, to_bytes(data.strip())) + + rc = int(recv_data(sf), 10) + stdout = recv_data(sf) + stderr = recv_data(sf) + except socket.error: + exc = get_exception() + sf.close() + module.fail_json(msg='unable to connect to socket', err=str(exc)) + + sf.close() + + return (rc, to_native(stdout), to_native(stderr))