libzypp 17.35.14
PluginScript.cc
Go to the documentation of this file.
1/*---------------------------------------------------------------------\
2| ____ _ __ __ ___ |
3| |__ / \ / / . \ . \ |
4| / / \ V /| _/ _/ |
5| / /__ | | | | | | |
6| /_____||_| |_| |_| |
7| |
8\---------------------------------------------------------------------*/
12#include <sys/types.h>
13#include <signal.h>
14
15#include <iostream>
16#include <sstream>
17
18#include <glib.h>
19
20#include <zypp/base/LogTools.h>
21#include <utility>
22#include <zypp-core/base/DefaultIntegral>
23#include <zypp/base/String.h>
24#include <zypp/base/Signal.h>
25#include <zypp/base/IOStream.h>
26
27#include <zypp/PluginScript.h>
29#include <zypp/PathInfo.h>
30
31using std::endl;
32
33#undef ZYPP_BASE_LOGGER_LOGGROUP
34#define ZYPP_BASE_LOGGER_LOGGROUP "zypp::plugin"
35
37namespace zypp
38{
39
40 namespace
41 {
42 const char * PLUGIN_DEBUG = getenv( "ZYPP_PLUGIN_DEBUG" );
43
47 struct PluginDebugBuffer
48 {
49 PluginDebugBuffer(const std::string &buffer_r) : _buffer(buffer_r) {}
50 PluginDebugBuffer(const PluginDebugBuffer &) = delete;
51 PluginDebugBuffer(PluginDebugBuffer &&) = delete;
52 PluginDebugBuffer &operator=(const PluginDebugBuffer &) = delete;
53 PluginDebugBuffer &operator=(PluginDebugBuffer &&) = delete;
54 ~PluginDebugBuffer()
55 {
56 if ( PLUGIN_DEBUG )
57 {
58 if ( _buffer.empty() )
59 {
60 L_DBG("PLUGIN") << "< (empty)" << endl;
61 }
62 else
63 {
64 std::istringstream datas( _buffer );
65 iostr::copyIndent( datas, L_DBG("PLUGIN"), "< " ) << endl;
66 }
67 }
68 }
69 const std::string & _buffer;
70 };
71
75 struct PluginDumpStderr
76 {
77 PluginDumpStderr(ExternalProgramWithStderr &prog_r) : _prog(prog_r) {}
78 PluginDumpStderr(const PluginDumpStderr &) = delete;
79 PluginDumpStderr(PluginDumpStderr &&) = delete;
80 PluginDumpStderr &operator=(const PluginDumpStderr &) = delete;
81 PluginDumpStderr &operator=(PluginDumpStderr &&) = delete;
82 ~PluginDumpStderr()
83 {
84 std::string line;
85 while ( _prog.stderrGetline( line ) )
86 L_WAR("PLUGIN") << "! " << line << endl;
87 }
88 ExternalProgramWithStderr & _prog;
89 };
90
91 inline void setBlocking( FILE * file_r, bool yesno_r = true )
92 {
93 if ( ! file_r )
94 ZYPP_THROW( PluginScriptException( "setNonBlocking" ) );
95
96 int fd = ::fileno( file_r );
97 if ( fd == -1 )
98 ZYPP_THROW( PluginScriptException( "setNonBlocking" ) );
99
100 int flags = ::fcntl( fd, F_GETFL );
101 if ( flags == -1 )
102 ZYPP_THROW( PluginScriptException( "setNonBlocking" ) );
103
104 if ( ! yesno_r )
105 flags |= O_NONBLOCK;
106 else if ( flags & O_NONBLOCK )
107 flags ^= O_NONBLOCK;
108
109 flags = ::fcntl( fd, F_SETFL, flags );
110 if ( flags == -1 )
111 ZYPP_THROW( PluginScriptException( "setNonBlocking" ) );
112 }
113
114 inline void setNonBlocking( FILE * file_r, bool yesno_r = true )
115 { setBlocking( file_r, !yesno_r ); }
116 }
117
119 //
120 // CLASS NAME : PluginScript::Impl
121 //
124 {
125 public:
126 Impl( Pathname &&script_r = Pathname(), Arguments &&args_r = Arguments() )
129 , _script(std::move( script_r ))
130 , _args(std::move( args_r ))
131 {}
132
133 Impl(const Impl &) = delete;
134 Impl(Impl &&) = delete;
135 Impl &operator=(const Impl &) = delete;
136 Impl &operator=(Impl &&) = delete;
137
139 try {
140 close();
141 } catch (...) {
142 }
143 }
144
145 public:
148
151
152 public:
153 const Pathname & script() const
154 { return _script; }
155
156 const Arguments & args() const
157 { return _args; }
158
159 pid_t getPid() const
160 { return _cmd ? _cmd->getpid() : NotConnected; }
161
162 bool isOpen() const
163 { return _cmd != nullptr; }
164
165 int lastReturn() const
166 { return _lastReturn; }
167
168 const std::string & lastExecError() const
169 { return _lastExecError; }
170
171 public:
172 void open( const Pathname & script_r = Pathname(), const Arguments & args_r = Arguments() );
173
174 int close();
175
176 void send( const PluginFrame & frame_r ) const;
177
178 Progress progress() const;
179
180 PluginFrame receive() const;
181
182 private:
185 scoped_ptr<ExternalProgramWithStderr> _cmd;
187 std::string _lastExecError;
188 };
190
192 inline std::ostream & operator<<( std::ostream & str, const PluginScript::Impl & obj )
193 {
194 return str << "PluginScript[" << obj.getPid() << "] " << obj.script();
195 }
196
198
199 namespace
200 {
201 const long PLUGIN_TIMEOUT = str::strtonum<long>( getenv( "ZYPP_PLUGIN_TIMEOUT" ) );
202 const long PLUGIN_SEND_TIMEOUT = str::strtonum<long>( getenv( "ZYPP_PLUGIN_SEND_TIMEOUT" ) );
203 const long PLUGIN_RECEIVE_TIMEOUT = str::strtonum<long>( getenv( "ZYPP_PLUGIN_RECEIVE_TIMEOUT" ) );
204 }
205
206 long PluginScript::Impl::_defaultSendTimeout = ( PLUGIN_SEND_TIMEOUT > 0 ? PLUGIN_SEND_TIMEOUT
207 : ( PLUGIN_TIMEOUT > 0 ? PLUGIN_TIMEOUT : 30 ) );
208 long PluginScript::Impl::_defaultReceiveTimeout = ( PLUGIN_RECEIVE_TIMEOUT > 0 ? PLUGIN_RECEIVE_TIMEOUT
209 : ( PLUGIN_TIMEOUT > 0 ? PLUGIN_TIMEOUT : 30 ) );
210
212
213 void PluginScript::Impl::open( const Pathname & script_r, const Arguments & args_r )
214 {
215 dumpRangeLine( DBG << "Open " << script_r, args_r.begin(), args_r.end() ) << endl;
216
217 if ( _cmd )
218 ZYPP_THROW( PluginScriptException( "Already connected", str::Str() << *this ) );
219
220 {
221 PathInfo pi( script_r );
222 if ( ! ( pi.isFile() && pi.isX() ) )
223 ZYPP_THROW( PluginScriptException( "Script is not executable", str::Str() << pi ) );
224 }
225
226 // go and launch script
227 // TODO: ExternalProgram::maybe use Stderr_To_FileDesc for script loging
229 args.reserve( args_r.size()+1 );
230 args.push_back( script_r.asString() );
231 args.insert( args.end(), args_r.begin(), args_r.end() );
232 _cmd.reset( new ExternalProgramWithStderr( args ) );
233
234 // Be protected against full pipe, etc.
235 setNonBlocking( _cmd->outputFile() );
236 setNonBlocking( _cmd->inputFile() );
237
238 // store running scripts data
239 _script = script_r;
240 _args = args_r;
242 _lastExecError.clear();
243
244 dumpRangeLine( DBG << *this, _args.begin(), _args.end() ) << endl;
245 }
246
248 {
249 if ( _cmd )
250 {
251 DBG << "Close:" << *this << endl;
252 bool doKill = true;
253 try {
254 // do not kill script if _DISCONNECT is ACKed.
255 send( PluginFrame( "_DISCONNECT" ) );
256 PluginFrame ret( receive() );
257 if ( ret.isAckCommand() )
258 {
259 doKill = false;
260 str::strtonum( ret.getHeaderNT( "exit" ), _lastReturn.get() );
261 _lastExecError = ret.body().asString();
262 }
263 }
264 catch (...)
265 { /* NOP */ }
266
267 if ( doKill )
268 {
269 _cmd->kill();
270 _lastReturn = _cmd->close();
271 _lastExecError = _cmd->execError();
272 }
273 DBG << *this << " -> [" << _lastReturn << "] " << _lastExecError << endl;
274 _cmd.reset();
275 }
276 return _lastReturn;
277 }
278
280 {
281 const PluginFrame frame_r = PluginFrame( "PLUGIN_PROGRESS" );
282 PluginFrame resp;
283 Progress ret(-1,-1);
284 this->send( frame_r );
285 resp = this->receive();
286 if(resp.empty())
287 return ret;
288
289 ret.first = atoi( resp.getHeaderNT("PLUGIN_PROGRESS_CURRENT", "-1").c_str() );
290 ret.second = atoi( resp.getHeaderNT("PLUGIN_PROGRESS_MAX", "-1").c_str() );
291
292 return ret;
293 }
294
295
296 void PluginScript::Impl::send( const PluginFrame & frame_r ) const
297 {
298 if ( !_cmd )
299 ZYPP_THROW( PluginScriptNotConnected( "Not connected", str::Str() << *this ) );
300
301 if ( frame_r.command().empty() )
302 WAR << "Send: No command in frame" << frame_r << endl;
303
304 // prepare frame data to write
305 std::string data;
306 {
307 std::ostringstream datas;
308 frame_r.writeTo( datas );
309 datas.str().swap( data );
310 }
311 DBG << *this << " ->send " << frame_r << endl;
312
313 if ( PLUGIN_DEBUG )
314 {
315 std::istringstream datas( data );
316 iostr::copyIndent( datas, L_DBG("PLUGIN") ) << endl;
317 }
318
319 // try writing the pipe....
320 FILE * filep = _cmd->outputFile();
321 if ( ! filep )
322 ZYPP_THROW( PluginScriptException( "Bad file pointer." ) );
323
324 int fd = ::fileno( filep );
325 if ( fd == -1 )
326 ZYPP_THROW( PluginScriptException( "Bad file descriptor" ) );
327
328 //DBG << " ->[" << fd << " " << (::feof(filep)?'e':'_') << (::ferror(filep)?'F':'_') << "]" << endl;
329 {
330 PluginDumpStderr _dump( *_cmd ); // dump scripts stderr before leaving
331 SignalSaver sigsav( SIGPIPE, SIG_IGN );
332 const char * buffer = data.c_str();
333 ssize_t buffsize = data.size();
334 do {
335 GPollFD watchFd;
336 watchFd.fd = fd;
337 watchFd.events = G_IO_OUT | G_IO_ERR;
338 watchFd.revents = 0;
339
340 errno = 0;
341 int retval = g_poll( &watchFd, 1, _sendTimeout * 1000 );
342 if ( retval > 0 ) // FD_ISSET( fd, &wfds ) will be true.
343 {
344 //DBG << "Ready to write..." << endl;
345 ssize_t ret = ::write( fd, buffer, buffsize );
346 if ( ret == buffsize )
347 {
348 //DBG << "::write(" << buffsize << ") -> " << ret << endl;
349 ::fflush( filep );
350 break; // -> done
351 }
352 else if ( ret > 0 )
353 {
354 //WAR << "::write(" << buffsize << ") -> " << ret << " INCOMPLETE..." << endl;
355 ::fflush( filep );
356 buffsize -= ret;
357 buffer += ret; // -> continue
358 }
359 else // ( retval == -1 )
360 {
361 if ( errno != EINTR )
362 {
363 ERR << "write(): " << Errno() << endl;
364 if ( errno == EPIPE )
365 ZYPP_THROW( PluginScriptDiedUnexpectedly( "Send: script died unexpectedly", str::Str() << Errno() ) );
366 else
367 ZYPP_THROW( PluginScriptException( "Send: send error", str::Str() << Errno() ) );
368 }
369 }
370 }
371 else if ( retval == 0 )
372 {
373 WAR << "Not ready to write within timeout." << endl;
374 ZYPP_THROW( PluginScriptSendTimeout( "Not ready to write within timeout." ) );
375 }
376 else // ( retval == -1 )
377 {
378 if ( errno != EINTR )
379 {
380 ERR << "select(): " << Errno() << endl;
381 ZYPP_THROW( PluginScriptException( "Error waiting on file descriptor", str::Str() << Errno() ) );
382 }
383 }
384 } while( true );
385 }
386 }
387
389 {
390 if ( !_cmd )
391 ZYPP_THROW( PluginScriptNotConnected( "Not connected", str::Str() << *this ) );
392
393 // try reading the pipe....
394 FILE * filep = _cmd->inputFile();
395 if ( ! filep )
396 ZYPP_THROW( PluginScriptException( "Bad file pointer." ) );
397
398 int fd = ::fileno( filep );
399 if ( fd == -1 )
400 ZYPP_THROW( PluginScriptException( "Bad file descriptor" ) );
401
402 ::clearerr( filep );
403 std::string data;
404 {
405 PluginDebugBuffer _debug( data ); // dump receive buffer if PLUGIN_DEBUG
406 PluginDumpStderr _dump( *_cmd ); // dump scripts stderr before leaving
407 do {
408 int ch = fgetc( filep );
409 if ( ch != EOF )
410 {
411 data.push_back( ch );
412 if ( ch == '\0' )
413 break;
414 }
415 else if ( ::feof( filep ) )
416 {
417 WAR << "Unexpected EOF" << endl;
418 ZYPP_THROW( PluginScriptDiedUnexpectedly( "Receive: script died unexpectedly", str::Str() << Errno() ) );
419 }
420 else if ( errno != EINTR )
421 {
422 if ( errno == EWOULDBLOCK )
423 {
424 // wait a while for fd to become ready for reading...
425 GPollFD rfd;
426 rfd.fd = fd;
427 rfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
428 rfd.revents = 0;
429
430 int retval = g_poll( &rfd, 1, _receiveTimeout * 1000 );
431 if ( retval > 0 ) // rfd.revents was filled
432 {
433 ::clearerr( filep );
434 }
435 else if ( retval == 0 )
436 {
437 WAR << "Not ready to read within timeout." << endl;
438 ZYPP_THROW( PluginScriptReceiveTimeout( "Not ready to read within timeout." ) );
439 }
440 else // ( retval == -1 )
441 {
442 if ( errno != EINTR )
443 {
444 ERR << "select(): " << Errno() << endl;
445 ZYPP_THROW( PluginScriptException( "Error waiting on file descriptor", str::Str() << Errno() ) );
446 }
447 }
448 }
449 else
450 {
451 ERR << "read(): " << Errno() << endl;
452 ZYPP_THROW( PluginScriptException( "Receive: receive error", str::Str() << Errno() ) );
453 }
454 }
455 } while ( true );
456 }
457 // DBG << " <-read " << data.size() << endl;
458 std::istringstream datas( data );
459 PluginFrame ret( datas );
460 DBG << *this << " <-" << ret << endl;
461 return ret;
462 }
463
465 //
466 // CLASS NAME : PluginScript
467 //
469
470 const pid_t PluginScript::NotConnected( -1 );
471
474
477
479 { Impl::_defaultSendTimeout = newval_r > 0 ? newval_r : 0; }
480
482 { Impl::_defaultReceiveTimeout = newval_r > 0 ? newval_r : 0; }
483
485 { return _pimpl->_sendTimeout; }
486
489
490 void PluginScript::sendTimeout( long newval_r )
491 { _pimpl->_sendTimeout = newval_r > 0 ? newval_r : 0; }
492
493 void PluginScript::receiveTimeout( long newval_r )
494 { _pimpl->_receiveTimeout = newval_r > 0 ? newval_r : 0; }
495
499
501 : _pimpl( new Impl( std::move(script_r) ) )
502 {}
503
505 : _pimpl( new Impl( std::move(script_r), std::move(args_r) ) )
506 {}
507
509 { return _pimpl->script(); }
510
512 { return _pimpl->args(); }
513
515 { return _pimpl->isOpen(); }
516
518 { return _pimpl->getPid(); }
519
521 { return _pimpl->lastReturn(); }
522
523 const std::string & PluginScript::lastExecError() const
524 { return _pimpl->lastExecError(); }
525
528
529 void PluginScript::open( const Pathname & script_r )
530 { _pimpl->open( script_r ); }
531
532 void PluginScript::open( const Pathname & script_r, const Arguments & args_r )
533 { _pimpl->open( script_r, args_r ); }
534
536 { return _pimpl->close(); }
537
538 void PluginScript::send( const PluginFrame & frame_r ) const
539 { _pimpl->send( frame_r ); }
540
543
546
548
549 std::ostream & operator<<( std::ostream & str, const PluginScript & obj )
550 { return str << *obj._pimpl; }
551
553} // namespace zypp
ExternalProgramWithStderr & _prog
const std::string & _buffer
struct _GPollFD GPollFD
Definition ZYppImpl.h:26
std::string asString() const
Definition ByteArray.h:24
Integral type with defined initial value when default constructed.
DefaultIntegral & reset()
Reset to the defined initial value.
Convenience errno wrapper.
Definition Errno.h:26
ExternalProgram extended to offer reading programs stderr.
Command frame for communication with PluginScript.
Definition PluginFrame.h:42
bool empty() const
Whether this is an empty frame.
const ByteArray & body() const
Return the frame body.
const std::string & command() const
Return the frame command.
const std::string & getHeaderNT(const std::string &key_r, const std::string &default_r=std::string()) const
Not throwing version returing one of the matching header values or default_r string.
bool isAckCommand() const
Convenience to identify an ACK command.
std::ostream & writeTo(std::ostream &stream_r) const
Write frame to stream.
Base class for PluginScript Exception.
Interface to plugin scripts using a Stomp inspired communication protocol.
PluginFrame receive() const
Receive a PluginFrame.
std::vector< std::string > Arguments
Commandline arguments passed to a script on open.
long sendTimeout() const
Local default timeout (sec.) when sending data.
void send(const PluginFrame &frame_r) const
Send a PluginFrame.
PluginScript()
Default ctor.
std::pair< int, int > Progress
RW_pointer< Impl > _pimpl
Pointer to implementation.
int lastReturn() const
Remembers a scripts return value after close until next open.
static long defaultReceiveTimeout()
Global default timeout (sec.) when receiving data.
static const pid_t NotConnected
pid_t(-1) constant indicating no connection.
int close()
Close any open connection.
const std::string & lastExecError() const
Remembers a scripts execError string after close until next open.
Progress progress() const
Send PLUGIN_PROGRESS frame and return /ref PluginScript::Progress.
pid_t getPid() const
Return a connected scripts pid or NotConnected.
void open()
Setup connection and execute script.
const Pathname & script() const
Return the script path if set.
static long defaultSendTimeout()
Global default timeout (sec.) when sending data.
bool isOpen() const
Whether we are connected to a script.
long receiveTimeout() const
Local default timeout (sec.) when receiving data.
const Arguments & args() const
Return the script arguments if set.
Exception safe signal handler save/restore.
Definition Signal.h:26
Wrapper class for stat/lstat.
Definition PathInfo.h:222
const std::string & asString() const
String representation.
Definition Pathname.h:93
Definition Arch.h:364
String related utilities and Regular expression matching.
std::ostream & copyIndent(std::istream &from_r, std::ostream &to_r, const std::string &indent_r="> ")
Copy istream to ostream, prefixing each line with indent_r (default "> " ).
Definition IOStream.h:65
SolvableSpec & operator=(const SolvableSpec &)=default
TInt strtonum(const C_Str &str)
Parsing numbers from string.
Easy-to use interface to the ZYPP dependency resolver.
std::ostream & dumpRangeLine(std::ostream &str, TIterator begin, TIterator end)
Print range defined by iterators (single line style).
Definition LogTools.h:143
std::ostream & operator<<(std::ostream &str, const SerialNumber &obj)
PluginScript implementation.
PluginFrame receive() const
Impl(Impl &&)=delete
Impl(const Impl &)=delete
DefaultIntegral< int, 0 > _lastReturn
Impl & operator=(const Impl &)=delete
const Pathname & script() const
scoped_ptr< ExternalProgramWithStderr > _cmd
void open(const Pathname &script_r=Pathname(), const Arguments &args_r=Arguments())
void send(const PluginFrame &frame_r) const
Impl & operator=(Impl &&)=delete
static long _defaultReceiveTimeout
const std::string & lastExecError() const
Impl(Pathname &&script_r=Pathname(), Arguments &&args_r=Arguments())
const Arguments & args() const
Progress progress() const
Convenient building of std::string via std::ostringstream Basically a std::ostringstream autoconverti...
Definition String.h:212
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition Exception.h:424
#define DBG
Definition Logger.h:99
#define ERR
Definition Logger.h:102
#define L_WAR(GROUP)
Definition Logger.h:110
#define WAR
Definition Logger.h:101
#define L_DBG(GROUP)
Definition Logger.h:108