Debian Codegraph @

ansible_collections/community/sap_libs/plugins/module_utils/sapstartsrv_client.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) 2022-2026 The Project Contributors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # For a detailed list of copyright holders and contribution history,
18 # please refer to the CONTRIBUTORS.md file in the project root.
19
20 from __future__ import (absolute_import, division, print_function)
21 __metaclass__ = type
22
23 import traceback
24 import socket
25 import os
26
27 try:
28 from urllib.request import HTTPHandler
29 except ImportError:
30 from ansible.module_utils.urls import (
31 UnixHTTPHandler as HTTPHandler,
32 )
33
34 try:
35 from http.client import HTTPConnection
36 except ImportError:
37 from httplib import HTTPConnection
38
39 try:
40 from suds.client import Client
41 from suds.sudsobject import asdict
42 from suds.transport.http import HttpAuthenticated, HttpTransport
43 HAS_SUDS_LIBRARY = True
44 SUDS_LIBRARY_IMPORT_ERROR = None
45
46 class LocalSocketHttpAuthenticated(HttpAuthenticated):
47 """Authenticated HTTP transport using Unix domain sockets."""
48 def __init__(self, socketpath, **kwargs):
49 HttpAuthenticated.__init__(self, **kwargs)
50 self._socketpath = socketpath
51
52 def u2handlers(self):
53 handlers = HttpTransport.u2handlers(self)
54 handlers.append(LocalSocketHandler(socketpath=self._socketpath))
55 return handlers
56
57 except ImportError:
58 HAS_SUDS_LIBRARY = False
59 SUDS_LIBRARY_IMPORT_ERROR = traceback.format_exc()
60
61 # Dummy class when suds is not available (keeps imports stable in tests)
62 class LocalSocketHttpAuthenticated(object):
63 def __init__(self, socketpath, **kwargs):
64 pass
65
66 def u2handlers(self):
67 return []
68
69 # Constant that defines accepted function prefixes, that are not doing changes.
70 READ_ONLY_FUNCTION_PREFIXES = (
71 "get",
72 "list",
73 "enqget",
74 "abapget",
75 "icmget",
76 "cmget",
77 "webdispget",
78 )
79
80 # Constants that define if force mode is required for certain functions.
81 FORCE_REQUIRED_PREFIXES = ("stop", "restart")
82 FORCE_REQUIRED_EXACT = ("shutdown", "instancestop")
83
84
85 class LocalSocketHttpConnection(HTTPConnection):
86 """HTTP connection class that uses Unix domain sockets."""
87 def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
88 source_address=None, socketpath=None):
89 super(LocalSocketHttpConnection, self).__init__(host, port, timeout, source_address)
90 self.socketpath = socketpath
91
92 def connect(self):
93 """Connect to Unix domain socket."""
94 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
95 self.sock.connect(self.socketpath)
96
97
98 class LocalSocketHandler(HTTPHandler):
99 """HTTP handler for Unix domain sockets."""
100 def __init__(self, debuglevel=0, socketpath=None):
101 self._debuglevel = debuglevel
102 self._socketpath = socketpath
103
104 def http_open(self, req):
105 return self.do_open(LocalSocketHttpConnection, req, socketpath=self._socketpath)
106
107
108 def is_read_only_function(function_name):
109 """Return True for read-only functions (e.g. Get*, List*)."""
110 if not function_name:
111 return False
112 fname = function_name.strip().lower()
113 return any(fname.startswith(prefix) for prefix in READ_ONLY_FUNCTION_PREFIXES)
114
115
116 def requires_force(function_name):
117 """Return True when function should require force=True."""
118 if not function_name:
119 return False
120 fname = function_name.strip().lower()
121 return fname in FORCE_REQUIRED_EXACT or fname.startswith(FORCE_REQUIRED_PREFIXES)
122
123
124 def recursive_dict(suds_object):
125 """Convert a suds object to a plain Python dict, recursively.
126
127 Example output: ``{'item': [{'name': 'hdbdaemon', 'value': '1'}]}``
128 """
129 out = {}
130 if isinstance(suds_object, str):
131 return suds_object
132 for k, v in asdict(suds_object).items():
133 if hasattr(v, '__keylist__'):
134 out[k] = recursive_dict(v)
135 elif isinstance(v, list):
136 out[k] = []
137 for item in v:
138 if hasattr(item, '__keylist__'):
139 out[k].append(recursive_dict(item))
140 else:
141 out[k].append(item)
142 else:
143 out[k] = v
144 return out
145
146
147 def connection(service_name, hostname, port, username, password, sysnr=None, is_socket=False):
148 """
149 Return a SOAP client for the given service (sapcontrol or saphostctrl).
150 """
151 # Prepare connection details before attempting to connect.
152 if is_socket:
153 # Use Unix domain socket for local connection
154 if sysnr is not None:
155 # sapcontrol: The socket name includes the system number
156 unix_socket = "/tmp/.sapstream5{0}13".format(str(sysnr).zfill(2))
157 else:
158 # saphostctrl: The socket name is fixed
159 unix_socket = "/tmp/.sapstream1128"
160
161 connection_url = "http://localhost/{0}?wsdl".format(service_name)
162
163 else:
164 # Use HTTP connection (original behavior)
165 connection_url = 'http://{0}:{1}/{2}?wsdl'.format(hostname, port, service_name)
166
167 # Attempt to connect using the appropriate method
168 try:
169 if is_socket:
170 if not os.path.exists(unix_socket):
171 raise Exception("SAP control Unix socket not found: {0}".format(unix_socket))
172
173 localsocket = LocalSocketHttpAuthenticated(unix_socket)
174 client = Client(connection_url, transport=localsocket)
175 else:
176 client = Client(connection_url, username=username, password=password, timeout=10)
177
178 return client
179
180 except Exception as e:
181 raise e
182
183
184 def call_sap_control(hostname, port, username, password, function, parameters, sysnr=None, is_socket=False):
185 client = connection(
186 "sapcontrol", hostname, port, username, password, sysnr=sysnr, is_socket=is_socket)
187 return call_function(client, function, parameters)
188
189
190 def call_sap_hostctrl(hostname, port, username, password, function, parameters, is_socket=False):
191 client = connection(
192 "SAPHostControl/", hostname, port, username, password, sysnr=None, is_socket=is_socket)
193 return call_function(client, function, parameters)
194
195
196 def call_function(client, function, parameters=None):
197 _function = getattr(client.service, function)
198 if parameters is not None:
199 if isinstance(parameters, dict):
200 result = _function(**parameters)
201 else:
202 result = _function(parameters)
203 else:
204 result = _function()
205 return result