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
|
#!/usr/bin/python
'''
targetclid
This file is part of targetcli-fb.
Copyright (c) 2019 by Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''
from __future__ import print_function
from targetcli import UIRoot
from targetcli import __version__ as targetcli_version
from configshell_fb import ConfigShell
from os import getuid, getenv, unlink
from threading import Thread
import sys
import socket
import struct
import fcntl
import signal
err = sys.stderr
class TargetCLI:
def __init__(self):
'''
initializer
'''
# socket for unix communication
self.socket_path = '/var/run/targetclid.sock'
# pid file for defending on multiple daemon runs
self.pid_file = '/var/run/targetclid.pid'
self.NoSignal = True
# shell console methods
self.shell = ConfigShell(getenv("TARGETCLI_HOME", '~/.targetcli'))
self.con = self.shell.con
self.display = self.shell.con.display
self.render = self.shell.con.render_text
# Handle SIGINT SIGTERM SIGHUP gracefully
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGHUP, self.signal_handler)
try:
self.pfd = open(self.pid_file, 'w+')
except IOError as e:
self.display(
self.render(
"opening pidfile failed: %s" %str(e),
'red'))
sys.exit(1)
self.try_pidfile_lock()
is_root = False
if getuid() == 0:
is_root = True
try:
root_node = UIRoot(self.shell, as_root=is_root)
root_node.refresh()
except Exception as error:
self.display(self.render(str(error), 'red'))
if not is_root:
self.display(self.render("Retry as root.", 'red'))
self.pfd.close()
sys.exit(1)
# Keep track, for later use
self.con_stdout_ = self.con._stdout
self.con_stderr_ = self.con._stderr
def __del__(self):
'''
destructor
'''
if hasattr(self, 'pfd'):
self.pfd.close()
def signal_handler(self, signum, frame):
'''
signal handler
'''
self.NoSignal = False
def try_pidfile_lock(self):
'''
get lock on pidfile, which is to check if targetclid is running
'''
# check if targetclid is already running
lock = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
try:
fcntl.fcntl(self.pfd, fcntl.F_SETLK, lock)
except Exception:
self.display(self.render("targetclid is already running...", 'red'))
self.pfd.close()
sys.exit(1)
def release_pidfile_lock(self):
'''
release lock on pidfile
'''
lock = struct.pack('hhllhh', fcntl.F_UNLCK, 0, 0, 0, 0, 0)
try:
fcntl.fcntl(self.pfd, fcntl.F_SETLK, lock)
except Exception as e:
self.display(
self.render(
"fcntl(UNLCK) on pidfile failed: %s" %str(e),
'red'))
self.pfd.close()
sys.exit(1)
self.pfd.close()
def client_thread(self, connection):
'''
Handle commands from client
'''
still_listen = True
# Receive the data in small chunks and retransmit it
while still_listen:
data = connection.recv(65535)
if b'-END@OF@DATA-' in data:
connection.close()
still_listen = False
else:
self.con._stdout = self.con._stderr = f = open("/tmp/data.txt", "w")
try:
# extract multiple commands delimited with '%'
list_data = data.decode().split('%')
for cmd in list_data:
self.shell.run_cmdline(cmd)
except Exception as e:
print(str(e), file=f) # push error to stream
# Restore
self.con._stdout = self.con_stdout_
self.con._stderr = self.con_stderr_
f.close()
with open('/tmp/data.txt', 'r') as f:
output = f.read()
var = struct.pack('i', len(output))
connection.sendall(var) # length of string
if len(output):
connection.sendall(output.encode()) # actual string
def usage():
print("Usage: %s [--version|--help]" % sys.argv[0], file=err)
print(" --version\t\tPrint version", file=err)
print(" --help\t\tPrint this information", file=err)
sys.exit(0)
def version():
print("%s version %s" % (sys.argv[0], targetcli_version), file=err)
sys.exit(0)
def usage_version(cmd):
if cmd in ("help", "--help", "-h"):
usage()
if cmd in ("version", "--version", "-v"):
version()
def main():
'''
start targetclid
'''
if len(sys.argv) > 1:
usage_version(sys.argv[1])
print("unrecognized option: %s" % (sys.argv[1]))
sys.exit(-1)
to = TargetCLI()
# Make sure file doesn't exist already
try:
unlink(to.socket_path)
except:
pass
# Create a TCP/IP socket
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
except socket.error as err:
to.display(to.render(err.strerror, 'red'))
sys.exit(1)
# Bind the socket path
try:
sock.bind(to.socket_path)
except socket.error as err:
to.display(to.render(err.strerror, 'red'))
sys.exit(1)
# Listen for incoming connections
try:
sock.listen(1)
except socket.error as err:
to.display(to.render(err.strerror, 'red'))
sys.exit(1)
while to.NoSignal:
try:
# Wait for a connection
connection, client_address = sock.accept()
except socket.error as err:
to.display(to.render(err.strerror, 'red'))
break
thread = Thread(target=to.client_thread, args=(connection,))
thread.start()
try:
thread.join()
except:
to.display(to.render(str(error), 'red'))
to.release_pidfile_lock()
if not to.NoSignal:
to.display(to.render("Signal received, quiting gracefully!", 'green'))
sys.exit(1)
if __name__ == "__main__":
main()
|