diff --git a/README.md b/README.md index d2f34e90d..b559970c2 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

---------------- +----------------- # SKALED – SKALE C++ Client diff --git a/libbatched-io/batched_io.cpp b/libbatched-io/batched_io.cpp index 9051dda5c..e7edc1f72 100644 --- a/libbatched-io/batched_io.cpp +++ b/libbatched-io/batched_io.cpp @@ -13,9 +13,9 @@ std::string test_crash_at; namespace batched_io { void test_crash_before_commit( const std::string& id ) { if ( !test_crash_at.empty() ) { - cnote << "test_crash_before_commit: " << id << std::endl; + cnote << "test_crash_before_commit: " << id; if ( id == test_crash_at ) { - cerror << "test_crash_before_commit: crashing at " << test_crash_at << std::endl; + cerror << "test_crash_before_commit: crashing at " << test_crash_at; _exit( 33 ); } } // if 1 diff --git a/libdevcore/BMPBN_tests.h b/libdevcore/BMPBN_tests.h index fc513ab52..b7d1a66ea 100644 --- a/libdevcore/BMPBN_tests.h +++ b/libdevcore/BMPBN_tests.h @@ -50,18 +50,18 @@ inline bool test1( const std::string& s, bool bIsVerbose ) { ss << std::hex << std::setw( 2 ) << std::setfill( '0' ) << int( buffer[0] ); if ( bIsVerbose ) { while ( --length > 0 ) - ss << cc::debug( ":" ) << std::setw( 2 ) << std::setfill( '0' ) - << int( buffer[++index] ); + ss << ":" << std::setw( 2 ) << std::setfill( '0' ) << int( buffer[++index] ); } if ( bIsVerbose ) - ss << cc::debug( " = " ) << std::dec << std::setw( 1 ) << x << cc::debug( ", " ); + ss << " = " << std::dec << std::setw( 1 ) << x << ", "; if ( x != y ) { if ( bIsVerbose ) - std::cout << " " << ss.str() << cc::fatal( "FAILED" ) << "\n"; + std::cout << " " << ss.str() << "FAILED" + << "\n"; return false; } // if ( bIsVerbose ) - // std::cout << " " << cc::success( "OK for " ) << cc::info( s ) << "\n"; + // std::cout << " " << "OK for " ) << s ) << "\n"; return true; } // namespace rpc @@ -69,8 +69,8 @@ template < class T > inline bool test( bool bIncludeNegative, bool bIncludeHuge, bool bIsVerbose, const char* strTypeDescription ) { if ( bIsVerbose && strTypeDescription && strTypeDescription[0] ) - std::cout << cc::debug( "Testing conversion of " ) << cc::info( strTypeDescription ) - << cc::debug( "..." ) << "\n"; + std::cout << "Testing conversion of " << strTypeDescription << "..." + << "\n"; bool bOKay = true; // if ( !test1< T >( std::string( "0" ), bIsVerbose ) ) @@ -159,11 +159,12 @@ inline bool test( } if ( bIsVerbose && strTypeDescription && strTypeDescription[0] ) { if ( bOKay ) - std::cout << cc::success( "Successful conversion test of " ) - << cc::info( strTypeDescription ) << cc::success( "." ) << "\n"; + std::cout << "Successful conversion test of " << strTypeDescription << "." + << "\n"; else - std::cout << cc::fatal( "FAILED" ) << cc::error( " conversion test of " ) - << cc::warn( strTypeDescription ) << cc::error( "." ) << "\n"; + std::cout << "FAILED" + << " conversion test of " << strTypeDescription << "." + << "\n"; } return bOKay; } // namespace BMPBN @@ -172,8 +173,8 @@ template < class T > inline bool test_limit_limbs_and_halves( const char* strStartValue, size_t nBits, bool bIsVerbose ) { if ( bIsVerbose ) - std::cout << cc::debug( "Testing limit margin of " ) << cc::size10( nBits ) - << cc::debug( " bit values..." ) << "\n"; + std::cout << "Testing limit margin of " << nBits << " bit values..." + << "\n"; bool bOKay = true; if ( !test1< T >( std::string( strStartValue ), bIsVerbose ) ) bOKay = false; @@ -187,11 +188,12 @@ inline bool test_limit_limbs_and_halves( } if ( bIsVerbose ) { if ( bOKay ) - std::cout << cc::success( "Successful conversion test of " ) << cc::size10( nBits ) - << cc::success( " bit values." ) << "\n"; + std::cout << "Successful conversion test of " << nBits << " bit values." + << "\n"; else - std::cout << cc::fatal( "FAILED" ) << cc::error( " conversion test of " ) - << cc::size10( nBits ) << cc::debug( " bit values" ) << "\n"; + std::cout << "FAILED" + << " conversion test of " << nBits << " bit values" + << "\n"; } return bOKay; } diff --git a/libdevcore/Common.cpp b/libdevcore/Common.cpp index e15bb6ae7..689551cdf 100644 --- a/libdevcore/Common.cpp +++ b/libdevcore/Common.cpp @@ -58,7 +58,7 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { string( "\nInternal exit requested while already exiting. " ) : "\nInternal exit initiated. "; } - std::cerr << strMessagePrefix << skutils::signal::signal2str( nSignalNo ) << "\n\n"; + cerror << strMessagePrefix << skutils::signal::signal2str( nSignalNo ) << "\n\n"; switch ( nSignalNo ) { case SIGINT: @@ -85,10 +85,10 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { case SIGFPE: case SIGSEGV: // abort signals - std::cout << "\n" << skutils::signal::generate_stack_trace() << "\n"; - std::cout.flush(); - std::cout << skutils::signal::read_maps() << "\n"; - std::cout.flush(); + cerror << "\n" << skutils::signal::generate_stack_trace(); + cerror.flush(); + cerror << skutils::signal::read_maps(); + cerror.flush(); _exit( nSignalNo + 128 ); @@ -106,10 +106,9 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { auto start_time = std::chrono::steady_clock::now(); std::thread( [nSignalNo, start_time]() { - std::cerr << ( "\n" + string( "SELF-KILL:" ) + " " + "Will sleep " + - cc::size10( ExitHandler::KILL_TIMEOUT ) + - " seconds before force exit..." ) + - "\n\n"; + cerror << "\nSELF-KILL: " + << "Will sleep " << ExitHandler::KILL_TIMEOUT + << " seconds before force exit..."; clog( VerbosityInfo, "exit" ) << "THREADS timer started"; @@ -125,10 +124,9 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { threads = new_threads; if ( threads_diff.size() ) { - cerr << seconds << " THREADS " << threads.size() << ":"; + cerror << seconds << " THREADS " << threads.size() << ":"; for ( const string& t : threads_diff ) - cerr << " " << t; - cerr << endl; + cerror << " " << t; } } catch ( ... ) { // swallow it @@ -137,10 +135,9 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { std::this_thread::sleep_for( 100ms ); } - std::cerr << ( "\n" + string( "SELF-KILL:" ) + " " + - "Will force exit after sleeping " + - cc::size10( ExitHandler::KILL_TIMEOUT ) + cc::error( " second(s)" ) + - "\n\n" ); + cerror << "\nSELF-KILL: " + << "Will force exit after sleeping " << ExitHandler::KILL_TIMEOUT + << " second(s)"; // TODO deduplicate this with main() before return ExitHandler::exit_code_t ec = ExitHandler::requestedExitCode(); @@ -158,7 +155,7 @@ void ExitHandler::exitHandler( int nSignalNo, ExitHandler::exit_code_t ec ) { // TODO deduplicate with first if() if ( ExitHandler::shouldExit() && s_nStopSignal > 0 && nSignalNo > 0 ) { - std::cerr << ( "\n" + string( "SIGNAL-HANDLER:" ) + " " + "Will force exit now...\n\n" ); + cerror << "\nSIGNAL-HANDLER: Will force exit now..."; _exit( 13 ); } diff --git a/libdevcore/Exceptions.cpp b/libdevcore/Exceptions.cpp index 2ccd2d909..5df044d02 100644 --- a/libdevcore/Exceptions.cpp +++ b/libdevcore/Exceptions.cpp @@ -56,8 +56,6 @@ std::string innermost_exception_what( const std::exception& ex ) { } void rethrow_most_nested( const std::exception& ex ) { - // std::cerr << nested_exception_what(ex) << std::endl; - const std::nested_exception* nested_ptr = dynamic_cast< const std::nested_exception* >( &ex ); if ( nested_ptr == nullptr ) { throw; // TODO can we make this func to be called without arguments? what does it really diff --git a/libdevcore/Log.cpp b/libdevcore/Log.cpp index 4e0ca878e..a5d8a1d1f 100644 --- a/libdevcore/Log.cpp +++ b/libdevcore/Log.cpp @@ -123,12 +123,10 @@ void setupLogging( LoggingOptions const& _options ) { ss << channel; strChannel = ss.str(); } // block - sink->set_formatter( expr::stream - << timestamp << " " << cc::info( strThreadName ) << " " - << cc::warn( strChannel ) - << expr::if_( expr::has_attr( - context ) )[expr::stream << " " << cc::warn( strChannel )] - << " " << expr::smessage ); + sink->set_formatter( + expr::stream << timestamp << " " << strThreadName << " " << strChannel + << expr::if_( expr::has_attr( context ) )[expr::stream << " " << strChannel] + << " " << expr::smessage ); boost::log::core::get()->add_sink( sink ); boost::log::core::get()->add_global_attribute( diff --git a/libdevcore/Log.h b/libdevcore/Log.h index da18916f9..0cfd6f936 100644 --- a/libdevcore/Log.h +++ b/libdevcore/Log.h @@ -146,7 +146,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, bigint const& _value ) { std::stringstream ss; ss << _value; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -154,7 +154,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -162,7 +162,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, u256 const& _value ) { std::stringstream ss; ss << _value; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -170,7 +170,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -178,7 +178,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, u160 const& _value ) { std::stringstream ss; ss << _value; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -186,7 +186,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -195,7 +195,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, FixedHash< N > const& _value ) { std::stringstream ss; ss << _value.abridged(); - _strm.stream() << cc::warn( "#" ) << cc::info( ss.str() ); + _strm.stream() << "#" << ss.str(); return _strm; } template < unsigned N > @@ -204,7 +204,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -212,7 +212,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, h160 const& _value ) { std::stringstream ss; ss << _value.abridged(); - _strm.stream() << cc::warn( "#" ) << cc::error( ss.str() ); + _strm.stream() << "#" << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -220,7 +220,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::error( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -228,7 +228,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, h256 const& _value ) { std::stringstream ss; ss << _value.abridged(); - _strm.stream() << cc::warn( "#" ) << cc::info( ss.str() ); + _strm.stream() << "#" << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -236,7 +236,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -244,7 +244,7 @@ inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, h512 const& _value ) { std::stringstream ss; ss << _value.abridged(); - _strm.stream() << cc::warn( "##" ) << cc::info( ss.str() ); + _strm.stream() << "##" << ss.str(); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -252,7 +252,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } @@ -271,7 +271,7 @@ namespace boost { namespace log { inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, dev::bytes const& _value ) { - _strm.stream() << cc::warn( "%" ) << cc::c( dev::toHex( _value ) ); + _strm.stream() << "%" << dev::toHex( _value ); return _strm; } inline boost::log::formatting_ostream& operator<<( @@ -284,21 +284,21 @@ inline boost::log::formatting_ostream& operator<<( template < typename T > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::vector< T > const& _value ) { - _strm.stream() << cc::attention( "[" ); + _strm.stream() << "["; size_t idxWalk = 0; int n = 0; for ( T const& i : _value ) { - _strm.stream() << ( n++ ? ( cc::debug( ", " ) ) : std::string( "" ) ); + _strm.stream() << ( n++ ? ", " : "" ); std::stringstream ss; ss << i; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); if ( cc::_max_value_size_ != std::string::npos && idxWalk > cc::_max_value_size_ ) { _strm << cc::trimmed_str( _value.size() ); break; } ++idxWalk; } - _strm.stream() << cc::attention( "]" ); + _strm.stream() << "]"; return _strm; } template < typename T > @@ -307,28 +307,28 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } template < typename T > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::set< T > const& _value ) { - _strm.stream() << cc::attention( "{" ); + _strm.stream() << "{"; size_t idxWalk = 0; int n = 0; for ( T const& i : _value ) { - _strm.stream() << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm.stream() << n++ ? ", " : std::string( "" ); std::stringstream ss; ss << i; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); if ( cc::_max_value_size_ != std::string::npos && idxWalk > cc::_max_value_size_ ) { _strm << cc::trimmed_str( _value.size() ); break; } ++idxWalk; } - _strm.stream() << cc::attention( "}" ); + _strm.stream() << "}"; return _strm; } template < typename T > @@ -337,28 +337,28 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } template < typename T > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::unordered_set< T > const& _value ) { - _strm.stream() << cc::attention( "{" ); + _strm.stream() << "{"; size_t idxWalk = 0; int n = 0; for ( T const& i : _value ) { - _strm.stream() << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm.stream() << n++ ? ", " : std::string( "" ); std::stringstream ss; ss << i; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); if ( cc::_max_value_size_ != std::string::npos && idxWalk > cc::_max_value_size_ ) { _strm << cc::trimmed_str( _value.size() ); break; } ++idxWalk; } - _strm.stream() << cc::attention( "}" ); + _strm.stream() << "}"; return _strm; } template < typename T > @@ -367,30 +367,30 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } template < typename T, typename U > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::map< T, U > const& _value ) { - _strm.stream() << cc::attention( "{" ); + _strm.stream() << "{"; int n = 0; for ( auto const& i : _value ) { - _strm << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm << n++ ? ", " : std::string( "" ); { // block std::stringstream ss; ss << i.first; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); } // block - _strm << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm << n++ ? ", " : std::string( "" ); { // block std::stringstream ss; ss << i.second; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); } // block } - _strm.stream() << cc::attention( "}" ); + _strm.stream() << "}"; return _strm; } template < typename T, typename U > @@ -399,30 +399,30 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm << cc::info( ss.str() ); + _strm << ss.str(); return _strm; } template < typename T, typename U > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::unordered_map< T, U > const& _value ) { - _strm << cc::attention( "{" ); + _strm << "{"; int n = 0; for ( auto const& i : _value ) { - _strm.stream() << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm.stream() << n++ ? ", " : std::string( "" ); { // block std::stringstream ss; ss << i.first; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); } // block - _strm.stream() << ( n++ ? cc::debug( ", " ) : std::string( "" ) ); + _strm.stream() << n++ ? ", " : std::string( "" ); { // block std::stringstream ss; ss << i.second; - _strm << cc::notice( ss.str() ); + _strm << ss.str(); } // block } - _strm << cc::attention( "}" ); + _strm << "}"; return _strm; } template < typename T, typename U > @@ -431,18 +431,18 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } template < typename T, typename U > inline boost::log::formatting_ostream& operator<<( boost::log::formatting_ostream& _strm, std::pair< T, U > const& _value ) { - _strm.stream() << cc::attention( "(" ); + _strm.stream() << "("; _strm << _value.first; - _strm.stream() << cc::debug( ", " ); + _strm.stream() << ", "; _strm << _value.second; - _strm.stream() << cc::attention( ")" ); + _strm.stream() << ")"; return _strm; } template < typename T, typename U > @@ -451,7 +451,7 @@ inline boost::log::formatting_ostream& operator<<( auto const& constValue = _value; std::stringstream ss; ss << constValue; - _strm.stream() << cc::info( ss.str() ); + _strm.stream() << ss.str(); return _strm; } } // namespace log diff --git a/libdevcore/TrieDB.h b/libdevcore/TrieDB.h index 32f5bcbfc..42f980ae8 100644 --- a/libdevcore/TrieDB.h +++ b/libdevcore/TrieDB.h @@ -573,7 +573,7 @@ void GenericTrieDB< DB >::iterator::next( NibbleSlice _key ) { } if ( !rlp.isList() || ( rlp.itemCount() != 2 && rlp.itemCount() != 17 ) ) { #if ETH_PARANOIA - cwarn << "BIG FAT ERROR. STATE TRIE CORRUPTED!!!!!"; + cwarn << "ERROR. STATE TRIE CORRUPTED"; cwarn << b.rlp.size() << toHex( b.rlp ); cwarn << rlp; auto c = rlp.itemCount(); @@ -687,7 +687,7 @@ void GenericTrieDB< DB >::iterator::next() { } if ( !( rlp.isList() && ( rlp.itemCount() == 2 || rlp.itemCount() == 17 ) ) ) { #if ETH_PARANOIA - cwarn << "BIG FAT ERROR. STATE TRIE CORRUPTED!!!!!"; + cwarn << "ERROR. STATE TRIE CORRUPTED"; cwarn << b.rlp.size() << toHex( b.rlp ); cwarn << rlp; auto c = rlp.itemCount(); @@ -894,7 +894,7 @@ void GenericTrieDB< DB >::mergeAtAux( bool isRemovable = false; if ( !r.isList() && !r.isEmpty() ) { h256 h = _orig.toHash< h256 >(); - // std::cerr << "going down non-inline node " << h << "\n"; + s = node( h ); r = RLP( s ); assert( !r.isNull() ); diff --git a/libdevcore/Worker.cpp b/libdevcore/Worker.cpp index be3c6e4a1..f183d72c5 100644 --- a/libdevcore/Worker.cpp +++ b/libdevcore/Worker.cpp @@ -67,7 +67,7 @@ void Worker::startWorking() { cwarn << "Exception thrown in Worker thread: " << _e.what(); } catch ( ... ) { cerror << "CRITICAL unknown exception thrown in Worker thread"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + cerror << "\n" << skutils::signal::generate_stack_trace() << "\n"; } // ex = WorkerState::Stopping; diff --git a/libdevcore/microprofile.cpp b/libdevcore/microprofile.cpp index b54078a8b..18b9cebfd 100644 --- a/libdevcore/microprofile.cpp +++ b/libdevcore/microprofile.cpp @@ -6922,7 +6922,7 @@ void MicroProfileGpuShutdown() { #include "microprofile_xboxone.h" #endif -#endif //#if MICROPROFILE_ENABLED +#endif // #if MICROPROFILE_ENABLED #include "microprofile_html.h" diff --git a/libdevcore/system_usage.cpp b/libdevcore/system_usage.cpp index fb5c4318b..b22e10d21 100644 --- a/libdevcore/system_usage.cpp +++ b/libdevcore/system_usage.cpp @@ -5,7 +5,6 @@ #include #include "sys/times.h" -//#include "sys/vtimes.h" int parseLine( char* line ) { // This assumes that a digit will be found and the line ends in " Kb". diff --git a/libethcore/BlockHeader.cpp b/libethcore/BlockHeader.cpp index ecf76d5c3..433d32bb5 100644 --- a/libethcore/BlockHeader.cpp +++ b/libethcore/BlockHeader.cpp @@ -229,7 +229,7 @@ void BlockHeader::verify( Strictness _s, BlockHeader const& _parent, bytesConstR txList.itemCount(), [&]( unsigned i ) { return rlp( i ); }, [&]( unsigned i ) { return txList[i].data().toBytes(); } ); - LOG( m_logger ) << "Expected trie root: " << toString( expectedRoot ); + LOG( m_loggerDebug ) << "Expected trie root: " << toString( expectedRoot ); if ( m_transactionsRoot != expectedRoot ) { MemoryDB tm; GenericTrieDB< MemoryDB > transactionsTrie( &tm ); @@ -244,19 +244,19 @@ void BlockHeader::verify( Strictness _s, BlockHeader const& _parent, bytesConstR transactionsTrie.insert( &k.out(), txList[i].data() ); txs.push_back( txList[i].data() ); - cdebug << toHex( k.out() ) << toHex( txList[i].data() ); + LOG( m_loggerDebug ) << toHex( k.out() ) << toHex( txList[i].data() ); } - cdebug << "trieRootOver" << expectedRoot; - cdebug << "orderedTrieRoot" << orderedTrieRoot( txs ); - cdebug << "TrieDB" << transactionsTrie.root(); - cdebug << "Contents:"; + LOG( m_loggerDebug ) << "trieRootOver" << expectedRoot; + LOG( m_loggerDebug ) << "orderedTrieRoot" << orderedTrieRoot( txs ); + LOG( m_loggerDebug ) << "TrieDB" << transactionsTrie.root(); + LOG( m_loggerDebug ) << "Contents:"; for ( auto const& t : txs ) - cdebug << toHex( t ); + LOG( m_loggerDebug ) << toHex( t ); BOOST_THROW_EXCEPTION( InvalidTransactionsRoot() << Hash256RequirementError( expectedRoot, m_transactionsRoot ) ); } - LOG( m_logger ) << "Expected uncle hash: " << toString( sha3( root[2].data() ) ); + LOG( m_loggerDebug ) << "Expected uncle hash: " << toString( sha3( root[2].data() ) ); if ( m_sha3Uncles != sha3( root[2].data() ) ) BOOST_THROW_EXCEPTION( InvalidUnclesHash() << Hash256RequirementError( sha3( root[2].data() ), m_sha3Uncles ) ); diff --git a/libethcore/BlockHeader.h b/libethcore/BlockHeader.h index 749b53cae..1b21a7e03 100644 --- a/libethcore/BlockHeader.h +++ b/libethcore/BlockHeader.h @@ -246,7 +246,7 @@ class BlockHeader { mutable h256 m_hashWithout; ///< (Memoised) SHA3 hash of the block header without seal. mutable Mutex m_hashLock; ///< A lock for both m_hash and m_hashWithout. - mutable Logger m_logger{ createLogger( VerbosityDebug, "blockhdr" ) }; + mutable Logger m_loggerDebug{ createLogger( VerbosityDebug, "blockhdr" ) }; Counter< BlockHeader > c; diff --git a/libethcore/Common.cpp b/libethcore/Common.cpp index cb889a51a..65e9b38b9 100644 --- a/libethcore/Common.cpp +++ b/libethcore/Common.cpp @@ -134,9 +134,9 @@ bytes getMultitransactionCallData() { } static void badBlockInfo( BlockHeader const& _bi, string const& _err ) { - string const c_line = cc::debug( string( 80, ' ' ) ); - string const c_border = cc::debug( string( 2, ' ' ) ); - string const c_space = cc::debug( string( 76, ' ' ) ) + c_border; + string const c_line = string( 80, ' ' ); + string const c_border = string( 2, ' ' ); + string const c_space = string( 76, ' ' ) + c_border; stringstream ss; ss << c_line << "\n"; ss << c_space << "\n"; diff --git a/libethereum/Block.cpp b/libethereum/Block.cpp index 848acf2ee..da0048f19 100644 --- a/libethereum/Block.cpp +++ b/libethereum/Block.cpp @@ -86,7 +86,7 @@ Block::Block( const BlockChain& _bc, h256 const& _hash, const State& _state, Bas if ( !_bc.isKnown( _hash ) ) { // Might be worth throwing here. - cwarn << "Invalid block given for state population: " << _hash; + LOG( m_loggerWarning ) << "Invalid block given for state population: " << _hash; BOOST_THROW_EXCEPTION( BlockNotFound() << errinfo_target( _hash ) ); } @@ -207,7 +207,7 @@ PopulationStatistics Block::populateFromChain( if ( !_bc.isKnown( _h ) ) { // Might be worth throwing here. - cwarn << "Invalid block given for state population: " << _h; + LOG( m_loggerWarning ) << "Invalid block given for state population: " << _h; BOOST_THROW_EXCEPTION( BlockNotFound() << errinfo_target( _h ) ); } @@ -273,14 +273,14 @@ bool Block::sync( BlockChain const& _bc, h256 const& _block, BlockHeader const& break; } catch ( Exception const& _e ) { // TODO: Slightly nicer handling? :-) - cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." - << endl; - cerr << diagnostic_information( _e ) << endl; + LOG( m_loggerError ) + << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart."; + LOG( m_loggerError ) << diagnostic_information( _e ); } catch ( std::exception const& _e ) { // TODO: Slightly nicer handling? :-) - cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." - << endl; - cerr << _e.what() << endl; + LOG( m_loggerError ) + << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart."; + LOG( m_loggerError ) << _e.what(); } } #endif @@ -298,14 +298,6 @@ bool Block::sync( BlockChain const& _bc, h256 const& _block, BlockHeader const& // Find most recent state dump and replay what's left. // (Most recent state dump might end up being genesis.) - // if (m_state.db().lookup(bi.stateRoot()).empty()) // TODO: API in State for this? - // { - // cwarn << "Unable to sync to" << bi.hash() << "; state root" << bi.stateRoot() - // << "not found in database."; - // cwarn << "Database corrupt: contains block without stateRoot:" << bi; - // cwarn << "Try rescuing the database by running: eth --rescue"; - // BOOST_THROW_EXCEPTION(InvalidStateRoot() << errinfo_target(bi.stateRoot())); - // } m_previousBlock = bi; resetCurrent(); ret = true; @@ -337,8 +329,9 @@ bool Block::sync( BlockChain const& _bc, h256 const& _block, BlockHeader const& } } catch ( ... ) { // TODO: Slightly nicer handling? :-) - cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl; - cerr << boost::current_exception_diagnostic_information() << endl; + LOG( m_loggerError ) + << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart."; + LOG( m_loggerError ) << boost::current_exception_diagnostic_information(); exit( 1 ); } @@ -388,7 +381,7 @@ pair< TransactionReceipts, bool > Block::sync( ++goodTxs; // cnote << "TX took:" << t.elapsed() * 1000; } else if ( t.gasPrice() < _gp.ask( *this ) * 9 / 10 ) { - LOG( m_logger ) + LOG( m_loggerDebug ) << t.sha3() << " Dropping El Cheapo transaction (<90% of ask price)"; _tq.drop( t.sha3() ); } @@ -398,11 +391,12 @@ pair< TransactionReceipts, bool > Block::sync( if ( req > got ) { // too old - LOG( m_logger ) << t.sha3() << " Dropping old transaction (nonce too low)"; + LOG( m_loggerDebug ) + << t.sha3() << " Dropping old transaction (nonce too low)"; _tq.drop( t.sha3() ); } else if ( got > req + _tq.waiting( t.sender() ) ) { // too new - LOG( m_logger ) + LOG( m_loggerDebug ) << t.sha3() << " Dropping new transaction (too many nonces ahead)"; _tq.drop( t.sha3() ); } else @@ -410,16 +404,17 @@ pair< TransactionReceipts, bool > Block::sync( } catch ( BlockGasLimitReached const& e ) { bigint const& got = *boost::get_error_info< errinfo_got >( e ); if ( got > m_currentBlock.gasLimit() ) { - LOG( m_logger ) + LOG( m_loggerDebug ) << t.sha3() << " Dropping over-gassy transaction (gas > block's gas limit)"; - LOG( m_logger ) + LOG( m_loggerDebug ) << "got: " << got << " required: " << m_currentBlock.gasLimit(); _tq.drop( t.sha3() ); } else { - LOG( m_logger ) << t.sha3() - << " Temporarily no gas left in current block (txs gas > " - "block's gas limit)"; + LOG( m_loggerDebug ) + << t.sha3() + << " Temporarily no gas left in current block (txs gas > " + "block's gas limit)"; //_tq.drop(t.sha3()); // Temporarily no gas left in current block. // OPTIMISE: could note this and then we don't evaluate until a block that @@ -427,14 +422,15 @@ pair< TransactionReceipts, bool > Block::sync( } } catch ( Exception const& _e ) { // Something else went wrong - drop it. - LOG( m_logger ) + LOG( m_loggerDebug ) << t.sha3() << " Dropping invalid transaction: " << diagnostic_information( _e ); _tq.drop( t.sha3() ); } catch ( std::exception const& ) { // Something else went wrong - drop it. _tq.drop( t.sha3() ); - cwarn << t.sha3() << "Transaction caused low-level exception :("; + LOG( m_loggerWarning ) + << t.sha3() << "Transaction caused low-level exception :("; } } if ( chrono::steady_clock::now() > deadline ) { @@ -519,8 +515,9 @@ tuple< TransactionReceipts, unsigned > Block::syncEveryone( BlockChain const& _b if ( !tr.isInvalid() && !tr.hasExternalGas() && tr.gasPrice() < _gasPrice ) { - LOG( m_logger ) << "Transaction " << tr.sha3() << " WouldNotBeInBlock: gasPrice " - << tr.gasPrice() << " < " << _gasPrice; + LOG( m_loggerDebug ) + << "Transaction " << tr.sha3() << " WouldNotBeInBlock: gasPrice " + << tr.gasPrice() << " < " << _gasPrice; if ( SkipInvalidTransactionsPatch::isEnabledInWorkingBlock() ) { // Add to the user-originated transactions that we've executed. @@ -562,7 +559,7 @@ tuple< TransactionReceipts, unsigned > Block::syncEveryone( BlockChain const& _b ex << errinfo_transactionIndex( i ); // throw; // just ignore invalid transactions - clog( VerbosityError, "block" ) << "FAILED transaction after consensus! " << ex.what(); + LOG( m_loggerError ) << "FAILED transaction after consensus! " << ex.what(); } } @@ -637,8 +634,8 @@ u256 Block::enactOn( VerifiedBlockRef const& _block, BlockChain const& _bc ) { #if ETH_TIMED_ENACTMENTS enactment = t.elapsed(); if ( populateVerify + populateGrand + syncReset + enactment > 0.5 ) - LOG( m_logger ) << "popVer/popGrand/syncReset/enactment = " << populateVerify << " / " - << populateGrand << " / " << syncReset << " / " << enactment; + LOG( m_loggerDebug ) << "popVer/popGrand/syncReset/enactment = " << populateVerify << " / " + << populateGrand << " / " << syncReset << " / " << enactment; #endif return ret; } @@ -695,7 +692,7 @@ u256 Block::enact( VerifiedBlockRef const& _block, BlockChain const& _bc ) { // ex << errinfo_vmtrace(vmTrace(_block.block, _bc, ImportRequirements::None)); for ( auto const& receipt : m_receipts ) { if ( !receipt.hasStatusCode() ) { - cwarn << "Skale does not support state root in receipt"; + LOG( m_loggerWarning ) << "Skale does not support state root in receipt"; break; } } @@ -922,17 +919,17 @@ ExecutionResult Block::execute( LastBlockHashesFace const& _lh, Transaction cons // use fake receipt created above if execution throws!! } catch ( const TransactionException& ex ) { // shoul not happen as exception in execute() means that tx should not be in block - cerror << DETAILED_ERROR; + LOG( m_loggerError ) << DETAILED_ERROR; assert( false ); } catch ( const std::exception& ex ) { h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3( WithoutSignature ); - LOG( m_logger ) << "Transaction " << sha << " WouldNotBeInBlock: " << ex.what(); + LOG( m_loggerDebug ) << "Transaction " << sha << " WouldNotBeInBlock: " << ex.what(); if ( _p != Permanence::Reverted ) // if it is not call _p = Permanence::CommittedWithoutState; resultReceipt.first.excepted = TransactionException::WouldNotBeInBlock; } catch ( ... ) { h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3( WithoutSignature ); - LOG( m_logger ) << "Transaction " << sha << " WouldNotBeInBlock: ..."; + LOG( m_loggerDebug ) << "Transaction " << sha << " WouldNotBeInBlock: ..."; if ( _p != Permanence::Reverted ) // if it is not call _p = Permanence::CommittedWithoutState; resultReceipt.first.excepted = TransactionException::WouldNotBeInBlock; @@ -1085,9 +1082,9 @@ void Block::commitToSeal( // m_state.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : // State::CommitBehaviour::KeepEmptyAccounts); - LOG( m_loggerDetailed ) << cc::debug( "Post-reward stateRoot: " ) - << cc::notice( "is not calculated in Skale state" ); - LOG( m_loggerDetailed ) << m_state; + LOG( m_loggerTrace ) << "Post-reward stateRoot: " + << "is not calculated in Skale state"; + LOG( m_loggerTrace ) << m_state; m_currentBlock.setLogBloom( logBloom() ); m_currentBlock.setGasUsed( gasUsed() ); @@ -1160,30 +1157,15 @@ LogBloom Block::logBloom() const { void Block::cleanup() { MICROPROFILE_SCOPEI( "Block", "cleanup", MP_BEIGE ); - // Commit the new trie to disk. - // LOG(m_logger) << "Committing to disk: stateRoot " << m_currentBlock.stateRoot() << " = " - // << rootHash() << " = " << toHex(asBytes(db().lookup(globalRoot()))); - - // try - // { - // EnforceRefs er(db(), true); - // globalRoot(); - // } - // catch (BadRoot const&) - // { - // cwarn << "Trie corrupt! :-("; - // throw; - // } - m_state.commit(); // TODO: State API for this? - LOG( m_logger ) << "Committed: stateRoot is not calculated in Skale state"; + LOG( m_loggerDebug ) << "Committed: stateRoot is not calculated in Skale state"; m_previousBlock = m_currentBlock; sealEngine()->populateFromParent( m_currentBlock, m_previousBlock ); - LOG( m_logger ) << "finalising enactment. current -> previous, hash is " - << m_previousBlock.hash(); + LOG( m_loggerDebug ) << "finalising enactment. current -> previous, hash is " + << m_previousBlock.hash(); resetCurrent(); } diff --git a/libethereum/Block.h b/libethereum/Block.h index 249f9932d..d33a86b0b 100644 --- a/libethereum/Block.h +++ b/libethereum/Block.h @@ -353,8 +353,10 @@ class Block { SealEngineFace* m_sealEngine = nullptr; ///< The chain's seal engine. - Logger m_logger{ createLogger( VerbosityDebug, "block" ) }; - Logger m_loggerDetailed{ createLogger( VerbosityTrace, "block" ) }; + Logger m_loggerDebug{ createLogger( VerbosityDebug, "block" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "block" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "block" ) }; + Logger m_loggerError{ createLogger( VerbosityError, "block" ) }; Counter< Block > c; ; diff --git a/libethereum/BlockChain.cpp b/libethereum/BlockChain.cpp index 788c5454d..5b1d90ef1 100644 --- a/libethereum/BlockChain.cpp +++ b/libethereum/BlockChain.cpp @@ -82,7 +82,7 @@ std::ostream& dev::eth::operator<<( std::ostream& _out, BlockChain const& _bc ) try { BlockHeader d( bytesConstRef{ _value } ); _out << toHex( key ) << ": " << d.number() << " @ " << d.parentHash() - << ( cmp == key ? " BEST" : "" ) << std::endl; + << ( cmp == key ? " BEST" : "" ) << "\n"; } catch ( ... ) { cwarn << "Invalid DB entry:" << toHex( key ) << " -> " << toHex( bytesConstRef( _value ) ); @@ -227,7 +227,7 @@ void BlockChain::open( fs::path const& _path, bool _applyPatches, WithExisting _ DEV_IGNORE_EXCEPTIONS( fs::permissions( extrasPath, fs::owner_all ) ); if ( _we == WithExisting::Kill ) { - cnote << "Killing blockchain & extras database (WithExisting::Kill)."; + LOG( m_loggerInfo ) << "Killing blockchain & extras database (WithExisting::Kill)."; fs::remove_all( chainPath / fs::path( "blocks_and_extras" ) ); } @@ -251,14 +251,16 @@ void BlockChain::open( fs::path const& _path, bool _applyPatches, WithExisting _ throw; if ( fs::space( chainPath / fs::path( "blocks_and_extras" ) ).available < 1024 ) { - cwarn << "Not enough available space found on hard drive. Please free some up and then " - "re-run. Bailing."; + LOG( m_loggerWarning ) + << "Not enough available space found on hard drive. Please free some up and then " + "re-run. Bailing."; BOOST_THROW_EXCEPTION( NotEnoughAvailableSpace() ); } else { - cwarn << "Database " << ( chainPath / fs::path( "blocks_and_extras" ) ) << "or " - << ( extrasPath / fs::path( "extras" ) ) - << "already open. You appear to have another instance of ethereum running. " - "Bailing."; + LOG( m_loggerWarning ) + << "Database " << ( chainPath / fs::path( "blocks_and_extras" ) ) << "or " + << ( extrasPath / fs::path( "extras" ) ) + << "already open. You appear to have another instance of ethereum running. " + "Bailing."; BOOST_THROW_EXCEPTION( DatabaseAlreadyOpen() ); } } @@ -304,8 +306,8 @@ void BlockChain::open( fs::path const& _path, bool _applyPatches, WithExisting _ m_lastBlockNumber = number( m_lastBlockHash ); - cdebug << cc::info( "Opened blockchain DB. Latest: " ) << currentHash() << ' ' - << m_lastBlockNumber; + LOG( m_loggerDebug ) << "Opened blockchain DB. Latest: " << currentHash() << ' ' + << m_lastBlockNumber; // dump_blocks_and_extras_db( *this, 0 ); @@ -320,7 +322,7 @@ void BlockChain::reopen( ChainParams const& _p, bool _applyPatches, WithExisting } void BlockChain::close() { - ctrace << "Closing blockchain DB"; + LOG( m_loggerTrace ) << "Closing blockchain DB"; // Not thread safe... m_extrasDB = nullptr; m_blocksDB = nullptr; @@ -430,27 +432,29 @@ tuple< ImportRoute, bool, unsigned > BlockChain::sync( std::back_inserter( goodTransactions ) ); ++count; } catch ( dev::eth::AlreadyHaveBlock const& ) { - cwarn << "ODD: Import queue contains already imported block"; + LOG( m_loggerWarning ) << "ODD: Import queue contains already imported block"; continue; } catch ( dev::eth::UnknownParent const& ) { - cwarn << "ODD: Import queue contains block with unknown parent."; // << - // LogTag::Error + LOG( m_loggerWarning ) + << "ODD: Import queue contains block with unknown parent."; // << + // LogTag::Error // << // boost::current_exception_diagnostic_information(); // NOTE: don't reimport since the queue should guarantee everything in the right // order. Can't continue - chain bad. badBlocks.push_back( block.verified.info.hash() ); } catch ( dev::eth::FutureTime const& ) { - cwarn << "ODD: Import queue contains a block with future time."; + LOG( m_loggerWarning ) << "ODD: Import queue contains a block with future time."; this_thread::sleep_for( chrono::seconds( 1 ) ); continue; } catch ( dev::eth::TransientError const& ) { this_thread::sleep_for( chrono::milliseconds( 100 ) ); continue; } catch ( Exception& ex ) { - cerror << "Exception while importing block. Someone (Jeff? That you?) seems to be " - << "giving us dodgy blocks !"; - cerror << diagnostic_information( ex ); + LOG( m_loggerError ) + << "Exception while importing block. Someone (Jeff? That you?) seems to be " + << "giving us dodgy blocks !"; + LOG( m_loggerError ) << diagnostic_information( ex ); if ( m_onBad ) m_onBad( ex ); // NOTE: don't reimport since the queue should guarantee everything in the right @@ -486,8 +490,7 @@ ImportRoute BlockChain::import( bytes const& _block, State& _state, bool _mustBe // VERIFY: populates from the block and checks the block is internally coherent. VerifiedBlockRef const block = verifyBlock( &_block, m_onBad, ImportRequirements::OutOfOrderChecks ); - // cerr << "Import block #" << block.info.number() << " with hash = " << block.info.hash() << - // endl; + return import( block, _state, _mustBeNew ); } @@ -504,7 +507,8 @@ ImportRoute BlockChain::import( VerifiedBlockRef const& _block, State& _state, b // Work out its number as the parent's number + 1 if ( !isKnown( _block.info.parentHash(), false ) ) // doesn't have to be current. { - LOG( m_logger ) << _block.info.hash() << " : Unknown parent " << _block.info.parentHash(); + LOG( m_loggerDebug ) << _block.info.hash() << " : Unknown parent " + << _block.info.parentHash(); // We don't know the parent (yet) - discard for now. It'll get resent to us if we find out // about its ancestry later on. BOOST_THROW_EXCEPTION( UnknownParent() << errinfo_hash256( _block.info.parentHash() ) ); @@ -521,7 +525,7 @@ ImportRoute BlockChain::import( VerifiedBlockRef const& _block, State& _state, b LOG( m_loggerError ) << "Block: " << BlockHeader( &parentBlock ); LOG( m_loggerError ) << "RLP: " << RLP( parentBlock ); LOG( m_loggerError ) << "DATABASE CORRUPTION: CRITICAL FAILURE"; - cerror << DETAILED_ERROR; + LOG( m_loggerError ) << DETAILED_ERROR; exit( -1 ); } @@ -530,7 +534,7 @@ ImportRoute BlockChain::import( VerifiedBlockRef const& _block, State& _state, b // Verify parent-critical parts verifyBlock( _block.block, m_onBad, ImportRequirements::InOrderChecks ); - LOG( m_loggerDetail ) << "Attempting import of " << _block.info.hash() << " ..."; + LOG( m_loggerTrace ) << "Attempting import of " << _block.info.hash() << " ..."; performanceLogger.onStageFinished( "preliminaryChecks" ); @@ -559,9 +563,9 @@ ImportRoute BlockChain::import( VerifiedBlockRef const& _block, State& _state, b checkConsistency(); #endif // ETH_PARANOIA } catch ( BadRoot& ex ) { - cwarn << "*** BadRoot error! Trying to import" << _block.info.hash() << "needed root" - << *boost::get_error_info< errinfo_hash256 >( ex ); - cwarn << _block.info; + LOG( m_loggerWarning ) << "*** BadRoot error! Trying to import" << _block.info.hash() + << "needed root" << *boost::get_error_info< errinfo_hash256 >( ex ); + LOG( m_loggerWarning ) << _block.info; // Attempt in import later. BOOST_THROW_EXCEPTION( TransientError() ); } catch ( Exception& ex ) { @@ -625,7 +629,7 @@ ImportRoute BlockChain::import( const Block& _block ) { void BlockChain::checkBlockIsNew( VerifiedBlockRef const& _block ) const { if ( isKnown( _block.info.hash() ) ) { - LOG( m_logger ) << _block.info.hash() << " : Not new."; + LOG( m_loggerDebug ) << _block.info.hash() << " : Not new."; BOOST_THROW_EXCEPTION( AlreadyHaveBlock() << errinfo_block( _block.block.toBytes() ) ); } } @@ -633,8 +637,8 @@ void BlockChain::checkBlockIsNew( VerifiedBlockRef const& _block ) const { void BlockChain::checkBlockTimestamp( BlockHeader const& _header ) const { // Check it's not crazy if ( _header.timestamp() > utcTime() && !m_params.allowFutureBlocks ) { - LOG( m_loggerDetail ) << _header.hash() << " : Future time " << _header.timestamp() - << " (now at " << utcTime() << ")"; + LOG( m_loggerTrace ) << _header.hash() << " : Future time " << _header.timestamp() + << " (now at " << utcTime() << ")"; // Block has a timestamp in the future. This is no good. BOOST_THROW_EXCEPTION( FutureTime() ); } @@ -649,8 +653,7 @@ bool BlockChain::rotateDBIfNeeded( uint64_t pieceUsageBytes ) { true : false; if ( isRotate ) { - clog( VerbosityTrace, "BlockChain" ) - << ( cc::debug( "Will perform " ) + cc::notice( "storage-based block rotation" ) ); + LOG( m_loggerTrace ) << "Will perform storage-based block rotation"; } } if ( clockLastDbRotation_ == 0 ) @@ -660,8 +663,7 @@ bool BlockChain::rotateDBIfNeeded( uint64_t pieceUsageBytes ) { clock_t clockNow = clock(); if ( ( clockNow - clockLastDbRotation_ ) >= clockDbRotationPeriod_ ) { isRotate = true; - clog( VerbosityTrace, "BlockChain" ) - << ( cc::debug( "Will perform " ) + cc::notice( "timer-based block rotation" ) ); + LOG( m_loggerTrace ) << "Will perform timer-based block rotation"; } } if ( !isRotate ) @@ -839,7 +841,7 @@ void BlockChain::recomputeExistingOccupiedSpaceForBlockRotation() try { size_t blocksBatchSize = 0; size_t extrasBatchSize = 0; - LOG( m_logger ) << "Recomputing old blocks sizes..."; + LOG( m_loggerDebug ) << "Recomputing old blocks sizes..."; // HACK 34 is key size + extra size + db prefix (blocks or extras) for ( unsigned i = 1; i <= number; ++i ) { @@ -896,8 +898,8 @@ void BlockChain::recomputeExistingOccupiedSpaceForBlockRotation() try { // HACK Since blooms are often re-used, let's adjust size for them extrasBatchSize += ( 4147 + 34 ) / 16 + ( 4147 + 34 ) / 256 + 2; // 1+1/16th big bloom per block - LOG( m_loggerDetail ) << "Computed block " << i - << " DB usage = " << blocksBatchSize + extrasBatchSize; + LOG( m_loggerTrace ) << "Computed block " << i + << " DB usage = " << blocksBatchSize + extrasBatchSize; } // for block uint64_t pieceUsageBytes = 0; @@ -905,8 +907,8 @@ void BlockChain::recomputeExistingOccupiedSpaceForBlockRotation() try { pieceUsageBytes = std::stoull( this->m_db->lookup( ( db::Slice ) "pieceUsageBytes" ) ); } - LOG( m_logger ) << "pieceUsageBytes from DB = " << pieceUsageBytes - << " computed = " << blocksBatchSize + extrasBatchSize; + LOG( m_loggerDebug ) << "pieceUsageBytes from DB = " << pieceUsageBytes + << " computed = " << blocksBatchSize + extrasBatchSize; if ( pieceUsageBytes == 0 ) { pieceUsageBytes = blocksBatchSize + extrasBatchSize; @@ -967,11 +969,10 @@ ImportRoute BlockChain::insertBlockAndExtras( VerifiedBlockRef const& _block, newLastBlockHash = _block.info.hash(); newLastBlockNumber = ( unsigned ) _block.info.number(); - LOG( m_loggerDetail ) << cc::debug( " Imported and best " ) << _totalDifficulty - << cc::debug( " (" ) << cc::warn( "#" ) - << cc::num10( _block.info.number() ) << cc::debug( "). Has " ) - << ( details( _block.info.parentHash() ).children.size() - 1 ) - << cc::debug( " siblings." ); + LOG( m_loggerTrace ) << " Imported and best " << _totalDifficulty << " (" + << "#" << _block.info.number() << "). Has " + << ( details( _block.info.parentHash() ).children.size() - 1 ) + << " siblings."; #if ETH_PARANOIA if ( isKnown( _block.info.hash() ) && !details( _block.info.hash() ) ) { @@ -1009,12 +1010,13 @@ ImportRoute BlockChain::insertBlockAndExtras( VerifiedBlockRef const& _block, db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ); m_db->commit( "insertBlockAndExtras" ); } catch ( boost::exception const& ex ) { - cwarn << "Error writing to blocks_and_extras database: " - << boost::diagnostic_information( ex ); - cwarn << "Put" << toHex( bytesConstRef( db::Slice( "best" ) ) ) << "=>" - << toHex( bytesConstRef( db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ) ); - cwarn << "Fail writing to blocks_and_extras database. Bombing out."; - cerror << DETAILED_ERROR; + LOG( m_loggerWarning ) << "Error writing to blocks_and_extras database: " + << boost::diagnostic_information( ex ); + LOG( m_loggerWarning ) + << "Put" << toHex( bytesConstRef( db::Slice( "best" ) ) ) << "=>" + << toHex( bytesConstRef( db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ) ); + LOG( m_loggerWarning ) << "Fail writing to blocks_and_extras database. Bombing out."; + LOG( m_loggerError ) << DETAILED_ERROR; exit( -1 ); } } @@ -1042,9 +1044,8 @@ ImportRoute BlockChain::insertBlockAndExtras( VerifiedBlockRef const& _block, h256s fresh; fresh.push_back( tbi.hash() ); - clog( VerbosityTrace, "BlockChain" ) - << cc::debug( "Insterted block with " ) << _block.transactions.size() - << cc::debug( " transactions" ); + LOG( m_loggerTrace ) << "Insterted block with " << _block.transactions.size() + << " transactions"; return ImportRoute{ dead, fresh, _block.transactions }; } @@ -1089,7 +1090,7 @@ void BlockChain::clearBlockBlooms( unsigned _begin, unsigned _end ) { } void BlockChain::rescue( State const& /*_state*/ ) { - clog( VerbosityInfo, "BlockChain" ) << "Rescuing database..."; + LOG( m_loggerInfo ) << "Rescuing database..."; throw std::logic_error( "Rescueing is not implemented" ); unsigned u = 1; @@ -1104,35 +1105,32 @@ void BlockChain::rescue( State const& /*_state*/ ) { } } unsigned l = u / 2; - clog( VerbosityInfo, "BlockChain" ) << cc::debug( "Finding last likely block number..." ); + LOG( m_loggerTrace ) << "Finding last likely block number..."; while ( u - l > 1 ) { unsigned m = ( u + l ) / 2; - clog( VerbosityInfo, "BlockChain" ) << " " << m << flush; + LOG( m_loggerTrace ) << " " << m << flush; if ( isKnown( numberHash( m ) ) ) l = m; else u = m; } - clog( VerbosityInfo, "BlockChain" ) << " lowest is " << l; + LOG( m_loggerTrace ) << " lowest is " << l; for ( ; l > 0; --l ) { h256 h = numberHash( l ); - clog( VerbosityInfo, "BlockChain" ) - << cc::debug( "Checking validity of " ) << l << cc::debug( " (" ) << h - << cc::debug( ")..." ) << flush; + LOG( m_loggerTrace ) << "Checking validity of " << l << " (" << h << ")..." << flush; try { - clog( VerbosityInfo, "BlockChain" ) << cc::debug( "block..." ) << flush; + LOG( m_loggerTrace ) << "block..." << flush; BlockHeader bi( block( h ) ); - clog( VerbosityInfo, "BlockChain" ) << cc::debug( "extras..." ) << flush; + LOG( m_loggerTrace ) << "extras..." << flush; details( h ); - clog( VerbosityInfo, "BlockChain" ) << cc::debug( "state..." ) << flush; - clog( VerbosityInfo, "BlockChain" ) - << cc::warn( "STATE VALIDITY CHECK IS NOT SUPPORTED" ) << flush; + LOG( m_loggerTrace ) << "state..." << flush; + LOG( m_loggerTrace ) << "STATE VALIDITY CHECK IS NOT SUPPORTED" << flush; // if (_db.exists(bi.stateRoot())) // break; } catch ( ... ) { } } - clog( VerbosityInfo, "BlockChain" ) << "OK."; + LOG( m_loggerTrace ) << "OK."; rewind( l ); } @@ -1147,11 +1145,13 @@ void BlockChain::rewind( unsigned _newHead ) { m_extrasDB->insert( db::Slice( "best" ), db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ); } catch ( boost::exception const& ex ) { - cwarn << "Error writing to extras database: " << boost::diagnostic_information( ex ); - cwarn << "Put" << toHex( bytesConstRef( db::Slice( "best" ) ) ) << "=>" - << toHex( bytesConstRef( db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ) ); - cwarn << "Fail writing to extras database. Bombing out."; - cerror << DETAILED_ERROR; + LOG( m_loggerWarning ) + << "Error writing to extras database: " << boost::diagnostic_information( ex ); + LOG( m_loggerWarning ) + << "Put" << toHex( bytesConstRef( db::Slice( "best" ) ) ) << "=>" + << toHex( bytesConstRef( db::Slice( ( char const* ) &m_lastBlockHash, 32 ) ) ); + LOG( m_loggerWarning ) << "Fail writing to extras database. Bombing out."; + LOG( m_loggerError ) << DETAILED_ERROR; exit( -1 ); } noteCanonChanged(); @@ -1332,7 +1332,7 @@ void BlockChain::garbageCollect( bool _force ) { case ExtraBlockHash: { // m_cacheUsage should not contain ExtraBlockHash elements currently. See the // second noteUsed() in BlockChain.h, which is a no-op. - cerror << DETAILED_ERROR; + LOG( m_loggerError ) << DETAILED_ERROR; assert( false ); break; } @@ -1438,11 +1438,13 @@ void BlockChain::checkConsistency() { { auto dp = details( p ); if ( asserts( contains( dp.children, h ) ) ) - cnote << "Apparently the database is corrupt. Not much we can do at this " - "stage..."; + LOG( m_loggerInfo ) + << "Apparently the database is corrupt. Not much we can do at this " + "stage..."; if ( assertsEqual( dp.number, dh.number - 1 ) ) - cnote << "Apparently the database is corrupt. Not much we can do at this " - "stage..."; + LOG( m_loggerInfo ) + << "Apparently the database is corrupt. Not much we can do at this " + "stage..."; } } return true; @@ -1590,7 +1592,7 @@ bytes BlockChain::block( h256 const& _hash ) const { string d = m_blocksDB->lookup( toSlice( _hash ) ); if ( d.empty() ) { - cwarn << "Couldn't find requested block:" << _hash; + LOG( m_loggerWarning ) << "Couldn't find requested block:" << _hash; return bytes(); } @@ -1616,7 +1618,7 @@ bytes BlockChain::headerData( h256 const& _hash ) const { string d = m_blocksDB->lookup( toSlice( _hash ) ); if ( d.empty() ) { - cwarn << "Couldn't find requested block:" << _hash; + LOG( m_loggerWarning ) << "Couldn't find requested block:" << _hash; return bytes(); } diff --git a/libethereum/BlockChain.h b/libethereum/BlockChain.h index 7a7ae5f5a..9d3345f42 100644 --- a/libethereum/BlockChain.h +++ b/libethereum/BlockChain.h @@ -281,9 +281,6 @@ class BlockChain { BlocksBlooms blocksBlooms( h256 const& _chunkId ) const { auto res = queryExtras< BlocksBlooms, ExtraBlocksBlooms >( _chunkId, m_blocksBlooms, x_blocksBlooms, NullBlocksBlooms ); - // std::cerr << "Queried " << _chunkId.hex() << "->" << std::endl; - // for ( size_t i = 0; i < 16; ++i ) - // std::cerr << "\t" << i << " = " << res.blooms[i].hex() << std::endl; return res; } LogBloom blockBloom( unsigned _number ) const { @@ -617,10 +614,11 @@ class BlockChain { boost::filesystem::path m_dbPath; - mutable Logger m_loggerInfo{ createLogger( VerbosityInfo, "chain" ) }; - mutable Logger m_logger{ createLogger( VerbosityDebug, "chain" ) }; - mutable Logger m_loggerDetail{ createLogger( VerbosityTrace, "chain" ) }; - mutable Logger m_loggerError{ createLogger( VerbosityError, "chain" ) }; + mutable Logger m_loggerInfo{ createLogger( VerbosityInfo, "Blockchain" ) }; + mutable Logger m_loggerDebug{ createLogger( VerbosityDebug, "Blockchain" ) }; + mutable Logger m_loggerTrace{ createLogger( VerbosityTrace, "Blockchain" ) }; + mutable Logger m_loggerError{ createLogger( VerbosityError, "Blockchain" ) }; + mutable Logger m_loggerWarning{ createLogger( VerbosityWarning, "Blockchain" ) }; friend std::ostream& operator<<( std::ostream& _out, BlockChain const& _bc ); }; diff --git a/libethereum/BlockQueue.cpp b/libethereum/BlockQueue.cpp index 5c69b0505..dbb74d929 100644 --- a/libethereum/BlockQueue.cpp +++ b/libethereum/BlockQueue.cpp @@ -135,7 +135,8 @@ void BlockQueue::verifierBody() try { m_readySet.erase( work.hash ); m_knownBad.insert( work.hash ); if ( !m_verifying.remove( work.hash ) ) - cwarn << "Unexpected exception when verifying block: " << _ex.what(); + LOG( m_loggerWarning ) + << "Unexpected exception when verifying block: " << _ex.what(); drainVerified_WITH_BOTH_LOCKS(); continue; } @@ -158,18 +159,18 @@ void BlockQueue::verifierBody() try { ready = true; } else { if ( !m_verifying.replace( work.hash, move( res ) ) ) - cwarn << "BlockQueue missing our job: was there a GM?"; + LOG( m_loggerWarning ) << "BlockQueue missing our job: was there a GM?"; } } if ( ready ) m_onReady(); } } catch ( const std::exception& ex ) { - cerror << "CRITICAL " << ex.what(); - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL " << ex.what(); + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; } catch ( ... ) { - cerror << "CRITICAL unknown exception"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL unknown exception"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; } void BlockQueue::drainVerified_WITH_BOTH_LOCKS() { @@ -189,14 +190,14 @@ ImportResult BlockQueue::import( bytesConstRef _block, bool _isOurs ) { // Check if we already know this block. h256 h = BlockHeader::headerHashFromBlock( _block ); - LOG( m_loggerDetail ) << "Queuing block " << h << " for import..."; + LOG( m_loggerTrace ) << "Queuing block " << h << " for import..."; UpgradableGuard l( m_lock ); if ( contains( m_readySet, h ) || contains( m_drainingSet, h ) || contains( m_unknownSet, h ) || contains( m_knownBad, h ) || contains( m_futureSet, h ) ) { // Already know about this one. - LOG( m_loggerDetail ) << "Already known."; + LOG( m_loggerTrace ) << "Already known."; return ImportResult::AlreadyKnown; } @@ -206,16 +207,16 @@ ImportResult BlockQueue::import( bytesConstRef _block, bool _isOurs ) { // VERIFY: populates from the block and checks the block is internally coherent. bi = m_bc->verifyBlock( _block, m_onBad, ImportRequirements::PostGenesis ).info; } catch ( Exception const& _e ) { - cwarn << "Ignoring malformed block: " << diagnostic_information( _e ); + LOG( m_loggerWarning ) << "Ignoring malformed block: " << diagnostic_information( _e ); return ImportResult::Malformed; } - LOG( m_loggerDetail ) << "Block " << h << " is " << bi.number() << " parent is " - << bi.parentHash(); + LOG( m_loggerTrace ) << "Block " << h << " is " << bi.number() << " parent is " + << bi.parentHash(); // Check block doesn't already exist first! if ( m_bc->isKnown( h ) ) { - LOG( m_logger ) << "Already known in chain."; + LOG( m_loggerDebug ) << "Already known in chain."; return ImportResult::AlreadyInChain; } @@ -230,8 +231,8 @@ ImportResult BlockQueue::import( bytesConstRef _block, bool _isOurs ) { time_t bit = static_cast< time_t >( bi.timestamp() ); if ( strftime( buf, 24, "%X", localtime( &bit ) ) == 0 ) buf[0] = '\0'; // empty if case strftime fails - LOG( m_loggerDetail ) << "OK - queued for future [" << bi.timestamp() << " vs " << utcTime() - << "] - will wait until " << buf; + LOG( m_loggerTrace ) << "OK - queued for future [" << bi.timestamp() << " vs " << utcTime() + << "] - will wait until " << buf; m_difficulty += bi.difficulty(); h256 const parentHash = bi.parentHash(); bool const unknown = !contains( m_readySet, parentHash ) && @@ -249,7 +250,7 @@ ImportResult BlockQueue::import( bytesConstRef _block, bool _isOurs ) { !m_drainingSet.count( bi.parentHash() ) && !m_bc->isKnown( bi.parentHash() ) ) { // We don't know the parent (yet) - queue it up for later. It'll get resent to us if we // find out about its ancestry later on. - LOG( m_loggerDetail ) << "OK - queued as unknown parent: " << bi.parentHash(); + LOG( m_loggerTrace ) << "OK - queued as unknown parent: " << bi.parentHash(); m_unknown.insert( bi.parentHash(), h, _block.toBytes() ); m_unknownSet.insert( h ); m_difficulty += bi.difficulty(); @@ -257,7 +258,7 @@ ImportResult BlockQueue::import( bytesConstRef _block, bool _isOurs ) { return ImportResult::UnknownParent; } else { // If valid, append to blocks. - LOG( m_loggerDetail ) << "OK - ready for chain insertion."; + LOG( m_loggerTrace ) << "OK - ready for chain insertion."; DEV_GUARDED( m_verification ) m_unverified.enqueue( UnverifiedBlock{ h, bi.parentHash(), _block.toBytes() } ); m_moreToVerify.notify_one(); @@ -354,13 +355,13 @@ void BlockQueue::tick() { if ( m_future.isEmpty() ) return; - LOG( m_logger ) << cc::debug( "Checking past-future blocks..." ); + LOG( m_loggerDebug ) << "Checking past-future blocks..."; time_t t = utcTime(); if ( t < m_future.firstKey() ) return; - LOG( m_logger ) << cc::debug( "Past-future blocks ready." ); + LOG( m_loggerDebug ) << "Past-future blocks ready."; { UpgradeGuard l2( l ); @@ -370,8 +371,7 @@ void BlockQueue::tick() { m_futureSet.erase( hash.first ); } } - LOG( m_logger ) << cc::debug( "Importing " ) << todo.size() - << cc::debug( " past-future blocks." ); + LOG( m_loggerDebug ) << "Importing " << todo.size() << " past-future blocks."; for ( auto const& b : todo ) import( &b.second ); diff --git a/libethereum/BlockQueue.h b/libethereum/BlockQueue.h index 41d0feadb..a62dec7c2 100644 --- a/libethereum/BlockQueue.h +++ b/libethereum/BlockQueue.h @@ -329,8 +329,10 @@ class BlockQueue : HasInvariants { u256 m_difficulty; ///< Total difficulty of blocks in the queue u256 m_drainingDifficulty; ///< Total difficulty of blocks in draining - Logger m_logger{ createLogger( VerbosityDebug, "bq" ) }; - Logger m_loggerDetail{ createLogger( VerbosityTrace, "bq" ) }; + Logger m_loggerDebug{ createLogger( VerbosityDebug, "bq" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "bq" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "bq" ) }; + Logger m_loggerError{ createLogger( VerbosityError, "bq" ) }; Counter< BlockQueue > c; diff --git a/libethereum/ChainParams.cpp b/libethereum/ChainParams.cpp index 4b2be0789..c90b629dc 100644 --- a/libethereum/ChainParams.cpp +++ b/libethereum/ChainParams.cpp @@ -483,10 +483,10 @@ void ChainParams::populateFromGenesis( bytes const& _genesisRLP, AccountMap cons auto b = genesisBlock(); if ( b != _genesisRLP ) { - cdebug << "Block passed:" << bi.hash() << bi.hash( WithoutSeal ); - cdebug << "Genesis now:" << BlockHeader::headerHashFromBlock( b ); - cdebug << RLP( b ); - cdebug << RLP( _genesisRLP ); + LOG( m_loggerDebug ) << "Block passed:" << bi.hash() << bi.hash( WithoutSeal ); + LOG( m_loggerDebug ) << "Genesis now:" << BlockHeader::headerHashFromBlock( b ); + LOG( m_loggerDebug ) << RLP( b ); + LOG( m_loggerDebug ) << RLP( _genesisRLP ); throw 0; } } diff --git a/libethereum/ChainParams.h b/libethereum/ChainParams.h index 60c763398..c5b9c2665 100644 --- a/libethereum/ChainParams.h +++ b/libethereum/ChainParams.h @@ -84,6 +84,8 @@ struct ChainParams : public ChainOperationParams { ChainParams loadGenesis( std::string const& _json ) const; mutable std::string originalJSON; + + Logger m_loggerDebug{ createLogger( VerbosityDebug, "ChainParams" ) }; }; } // namespace dev::eth diff --git a/libethereum/Client.cpp b/libethereum/Client.cpp index b266145df..902cd8ce3 100644 --- a/libethereum/Client.cpp +++ b/libethereum/Client.cpp @@ -145,8 +145,8 @@ Client::Client( ChainParams const& _params, int _networkID, #endif /// (defined __HAVE_SKALED_LOCK_FILE_INDICATING_CRITICAL_STOP__) m_debugTracer.call_on_tracepoint( [this]( const std::string& name ) { - clog( VerbosityTrace, "client" ) - << "TRACEPOINT " << name << " " << m_debugTracer.get_tracepoint_count( name ); + LOG( m_loggerTrace ) << "TRACEPOINT " << name << " " + << m_debugTracer.get_tracepoint_count( name ); } ); m_debugHandler = [this]( const std::string& arg ) -> std::string { @@ -172,7 +172,7 @@ void Client::stopWorking() { m_skaleHost->stopWorking(); // TODO Find and document a systematic way to start/stop all // workers else - cerror << "Instance of SkaleHost was not properly created."; + LOG( m_loggerError ) << "Instance of SkaleHost was not properly created."; m_snapshotAgent->terminate(); @@ -185,23 +185,25 @@ void Client::stopWorking() { m_bq.stop(); // l_sergiy: added to stop block queue processing m_bc.close(); - LOG( m_logger ) << cc::success( "Blockchain is closed" ); + LOG( m_loggerInfo ) << "Blockchain is closed"; #if ( defined __HAVE_SKALED_LOCK_FILE_INDICATING_CRITICAL_STOP__ ) bool isForcefulExit = ( !m_skaleHost || m_skaleHost->exitedForcefully() == false ) ? false : true; if ( !isForcefulExit ) { delete_lock_file( m_dbPath ); - LOG( m_logger ) << cc::success( "Deleted lock file " ) - << cc::p( boost::filesystem::canonical( m_dbPath ).string() + - std::string( "/skaled.lock" ) ); + LOG( m_loggerInfo ) << "Deleted lock file " + << boost::filesystem::canonical( m_dbPath ).string() + + std::string( "/skaled.lock" ); } else { - LOG( m_logger ) << cc::fatal( "ATTENTION:" ) << " " << cc::error( "Deleted lock file " ) - << cc::p( boost::filesystem::canonical( m_dbPath ).string() + - std::string( "/skaled.lock" ) ) - << cc::error( " after forceful exit" ); + LOG( m_loggerInfo ) << "ATTENTION:" + << " " + << "Deleted lock file " + << boost::filesystem::canonical( m_dbPath ).string() + + std::string( "/skaled.lock" ) + << " after forceful exit"; } - LOG( m_logger ).flush(); + LOG( m_loggerInfo ).flush(); #endif /// (defined __HAVE_SKALED_LOCK_FILE_INDICATING_CRITICAL_STOP__) terminate(); @@ -306,8 +308,8 @@ void Client::init( WithExisting _forceAction, u256 _networkId ) { if ( chainParams().sChain.nodeGroups.size() > 0 ) { initHistoricGroupIndex(); } else { - LOG( m_logger ) << "Empty node groups in config. " - "This is OK in tests but not OK in production"; + LOG( m_loggerInfo ) << "Empty node groups in config. " + "This is OK in tests but not OK in production"; } // init snapshots for not newly created chains @@ -346,11 +348,12 @@ tuple< ImportRoute, bool, unsigned > Client::syncQueue( unsigned _max ) { } void Client::onBadBlock( Exception& _ex ) const { - // BAD BLOCK!!! + // BAD BLOCK bytes const* block = boost::get_error_info< errinfo_block >( _ex ); if ( !block ) { - cwarn << "ODD: onBadBlock called but exception (" << _ex.what() << ") has no block in it."; - cwarn << boost::diagnostic_information( _ex ); + LOG( m_loggerWarning ) << "ODD: onBadBlock called but exception (" << _ex.what() + << ") has no block in it."; + LOG( m_loggerWarning ) << boost::diagnostic_information( _ex ); return; } @@ -395,7 +398,7 @@ bool Client::isMajorSyncing() const { void Client::startedWorking() { // Synchronise the state according to the head of the block chain. // TODO: currently it contains keys for *all* blocks. Make it remove old ones. - LOG( m_loggerDetail ) << cc::debug( "startedWorking()" ); + LOG( m_loggerTrace ) << "startedWorking()"; DEV_GUARDED( m_blockImportMutex ) { DEV_WRITE_GUARDED( x_preSeal ) @@ -500,8 +503,8 @@ void Client::syncBlockQueue() { double elapsed = t.elapsed(); if ( count ) { - LOG( m_logger ) << count << " blocks imported in " << unsigned( elapsed * 1000 ) << " ms (" - << ( count / elapsed ) << " blocks/s) in #" << bc().number(); + LOG( m_loggerInfo ) << count << " blocks imported in " << unsigned( elapsed * 1000 ) + << " ms (" << ( count / elapsed ) << " blocks/s) in #" << bc().number(); } if ( elapsed > c_targetDuration * 1.1 && count > c_syncMin ) @@ -514,7 +517,6 @@ void Client::syncBlockQueue() { onChainChanged( ir ); } - size_t Client::importTransactionsAsBlock( const Transactions& _transactions, u256 _gasPrice, uint64_t _timestamp ) { // on schain creation, SnapshotAgent needs timestamp of block 1 @@ -534,14 +536,13 @@ size_t Client::importTransactionsAsBlock( SchainPatch::useLatestBlockTimestamp( blockChain().info().timestamp() ); if ( !UnsafeRegion::isActive() ) { - LOG( m_loggerDetail ) << "Total unsafe time so far = " - << std::chrono::duration_cast< std::chrono::seconds >( - UnsafeRegion::getTotalTime() ) - .count() - << " seconds"; + LOG( m_loggerTrace ) << "Total unsafe time so far = " + << std::chrono::duration_cast< std::chrono::seconds >( + UnsafeRegion::getTotalTime() ) + .count() + << " seconds"; } else - cwarn << "Warning: UnsafeRegion still active!"; - + LOG( m_loggerWarning ) << "Warning: UnsafeRegion still active!"; if ( chainParams().sChain.nodeGroups.size() > 0 ) updateHistoricGroupIndex(); @@ -558,7 +559,7 @@ size_t Client::syncTransactions( assert( m_skaleHost ); while ( m_working.isSealed() ) { - cnote << "m_working.isSealed. sleeping"; + LOG( m_loggerInfo ) << "m_working.isSealed. sleeping"; usleep( 1000 ); } @@ -591,12 +592,12 @@ size_t Client::syncTransactions( // Tell network about the new transactions. m_skaleHost->noteNewTransactions(); - ctrace << "Processed " << newPendingReceipts.size() << " transactions in " - << timer.elapsed() * 1000 << "(" << ( bool ) m_syncTransactionQueue << ")"; + LOG( m_loggerTrace ) << "Processed " << newPendingReceipts.size() << " transactions in " + << timer.elapsed() * 1000 << "(" << ( bool ) m_syncTransactionQueue << ")"; #ifdef HISTORIC_STATE - LOG( m_logger ) << "HSCT: " - << m_working.mutableState().mutableHistoricState().getAndResetBlockCommitTime(); + LOG( m_loggerInfo ) + << "HSCT: " << m_working.mutableState().mutableHistoricState().getAndResetBlockCommitTime(); #endif return goodReceipts; } @@ -604,12 +605,12 @@ size_t Client::syncTransactions( void Client::onDeadBlocks( h256s const& _blocks, h256Hash& io_changed ) { // insert transactions that we are declaring the dead part of the chain for ( auto const& h : _blocks ) { - LOG( m_loggerDetail ) << cc::warn( "Dead block: " ) << h; + LOG( m_loggerTrace ) << "Dead block: " << h; for ( auto const& t : bc().transactions( h ) ) { - LOG( m_loggerDetail ) << cc::debug( "Resubmitting dead-block transaction " ) - << Transaction( t, CheckTransaction::None ); - ctrace << cc::debug( "Resubmitting dead-block transaction " ) - << Transaction( t, CheckTransaction::None ); + LOG( m_loggerTrace ) << "Resubmitting dead-block transaction " + << Transaction( t, CheckTransaction::None ); + LOG( m_loggerTrace ) << "Resubmitting dead-block transaction " + << Transaction( t, CheckTransaction::None ); m_tq.import( t, IfDropped::Retry ); } } @@ -652,7 +653,7 @@ void Client::restartMining() { DEV_READ_GUARDED( x_postSeal ) if ( !m_postSeal.isSealed() || m_postSeal.info().hash() != newPreMine.info().parentHash() ) for ( auto const& t : m_postSeal.pending() ) { - LOG( m_loggerDetail ) << "Resubmitting post-seal transaction " << t; + LOG( m_loggerTrace ) << "Resubmitting post-seal transaction " << t; // ctrace << "Resubmitting post-seal transaction " << t; auto ir = m_tq.import( t, IfDropped::Retry ); if ( ir != ImportResult::Success ) @@ -700,7 +701,7 @@ bool Client::remoteActive() const { } void Client::onPostStateChanged() { - LOG( m_loggerDetail ) << cc::notice( "Post state changed." ); + LOG( m_loggerTrace ) << "Post state changed."; m_signalled.notify_all(); m_remoteWorking = false; } @@ -708,12 +709,12 @@ void Client::onPostStateChanged() { void Client::startSealing() { if ( m_wouldSeal == true ) return; - LOG( m_logger ) << "Client::startSealing: " << author(); + LOG( m_loggerInfo ) << "Client::startSealing: " << author(); if ( author() ) { m_wouldSeal = true; m_signalled.notify_all(); } else - LOG( m_logger ) << "You need to set an author in order to seal!"; + LOG( m_loggerInfo ) << "You need to set an author in order to seal!"; } void Client::rejigSealing() { @@ -721,15 +722,15 @@ void Client::rejigSealing() { if ( sealEngine()->shouldSeal( this ) ) { m_wouldButShouldnot = false; - LOG( m_loggerDetail ) << "Rejigging seal engine..."; + LOG( m_loggerTrace ) << "Rejigging seal engine..."; DEV_WRITE_GUARDED( x_working ) { if ( m_working.isSealed() ) { - LOG( m_logger ) << "Tried to seal sealed block..."; + LOG( m_loggerInfo ) << "Tried to seal sealed block..."; return; } // TODO is that needed? we have "Generating seal on" below - LOG( m_loggerDetail ) << "Starting to seal block" - << " #" << m_working.info().number(); + LOG( m_loggerTrace ) << "Starting to seal block" + << " #" << m_working.info().number(); // TODO Deduplicate code dev::h256 stateRootToSet; @@ -756,15 +757,15 @@ void Client::rejigSealing() { if ( wouldSeal() ) { sealEngine()->onSealGenerated( [=]( bytes const& _header ) { - LOG( m_logger ) << "Block sealed" - << " #" << BlockHeader( _header, HeaderData ).number(); + LOG( m_loggerInfo ) << "Block sealed" + << " #" << BlockHeader( _header, HeaderData ).number(); if ( this->submitSealed( _header ) ) m_onBlockSealed( _header ); else - LOG( m_logger ) << "Submitting block failed..."; + LOG( m_loggerInfo ) << "Submitting block failed..."; } ); - ctrace << "Generating seal on " << m_sealingInfo.hash( WithoutSeal ) << " #" - << m_sealingInfo.number(); + LOG( m_loggerTrace ) << "Generating seal on " << m_sealingInfo.hash( WithoutSeal ) + << " #" << m_sealingInfo.number(); sealEngine()->generateSeal( m_sealingInfo ); } } else @@ -777,15 +778,15 @@ void Client::rejigSealing() { void Client::sealUnconditionally( bool submitToBlockChain ) { m_wouldButShouldnot = false; - LOG( m_loggerDetail ) << "Rejigging seal engine..."; + LOG( m_loggerTrace ) << "Rejigging seal engine..."; DEV_WRITE_GUARDED( x_working ) { if ( m_working.isSealed() ) { - LOG( m_logger ) << "Tried to seal sealed block..."; + LOG( m_loggerInfo ) << "Tried to seal sealed block..."; return; } // TODO is that needed? we have "Generating seal on" below - LOG( m_loggerDetail ) << "Starting to seal block" - << " #" << m_working.info().number(); + LOG( m_loggerTrace ) << "Starting to seal block" + << " #" << m_working.info().number(); // latest hash is really updated after NEXT snapshot already started hash computation // TODO Deduplicate code dev::h256 stateRootToSet; @@ -819,13 +820,13 @@ void Client::sealUnconditionally( bool submitToBlockChain ) { m_sealingInfo.streamRLP( headerRlp ); const bytes& header = headerRlp.out(); BlockHeader header_struct( header, HeaderData ); - LOG( m_logger ) << cc::success( "Block sealed" ) << " #" << cc::num10( header_struct.number() ) - << " (" << header_struct.hash() << ")"; + LOG( m_loggerInfo ) << "Block sealed" + << " #" << header_struct.number() << " (" << header_struct.hash() << ")"; std::stringstream ssBlockStats; - ssBlockStats << cc::success( "Block stats:" ) << "BN:" << number() - << ":BTS:" << bc().info().timestamp() << ":TXS:" << TransactionBase::howMany() - << ":HDRS:" << BlockHeader::howMany() << ":LOGS:" << LogEntry::howMany() - << ":SENGS:" << SealEngineBase::howMany() + ssBlockStats << "Block stats:" + << "BN:" << number() << ":BTS:" << bc().info().timestamp() + << ":TXS:" << TransactionBase::howMany() << ":HDRS:" << BlockHeader::howMany() + << ":LOGS:" << LogEntry::howMany() << ":SENGS:" << SealEngineBase::howMany() << ":TXRS:" << TransactionReceipt::howMany() << ":BLCKS:" << Block::howMany() << ":ACCS:" << Account::howMany() << ":BQS:" << BlockQueue::howMany() << ":BDS:" << BlockDetails::howMany() << ":TSS:" << TransactionSkeleton::howMany() @@ -837,14 +838,14 @@ void Client::sealUnconditionally( bool submitToBlockChain ) { ssBlockStats << ":RAM:" << getRAMUsage(); ssBlockStats << ":CPU:" << getCPUUsage(); } - LOG( m_logger ) << ssBlockStats.str(); + LOG( m_loggerInfo ) << ssBlockStats.str(); if ( submitToBlockChain ) { if ( this->submitSealed( header ) ) m_onBlockSealed( header ); else - LOG( m_logger ) << cc::error( "Submitting block failed..." ); + LOG( m_loggerInfo ) << "Submitting block failed..."; } else { UpgradableGuard l( x_working ); { @@ -852,7 +853,7 @@ void Client::sealUnconditionally( bool submitToBlockChain ) { if ( m_working.sealBlock( header ) ) { m_onBlockSealed( header ); } else { - LOG( m_logger ) << cc::error( "Sealing block failed..." ); + LOG( m_loggerInfo ) << "Sealing block failed..."; } } DEV_WRITE_GUARDED( x_postSeal ) @@ -870,16 +871,16 @@ void Client::importWorkingBlock() { void Client::noteChanged( h256Hash const& _filters ) { Guard l( x_filtersWatches ); if ( _filters.size() ) - LOG( m_loggerWatch ) << cc::notice( "noteChanged: " ) << filtersToString( _filters ); + LOG( m_loggerWatch ) << "noteChanged: " << filtersToString( _filters ); // accrue all changes left in each filter into the watches. for ( auto& w : m_watches ) if ( _filters.count( w.second.id ) ) { if ( m_filters.count( w.second.id ) ) { - LOG( m_loggerWatch ) << "!!! " << w.first << " " << w.second.id.abridged(); + LOG( m_loggerWatch ) << w.first << " " << w.second.id.abridged(); w.second.append_changes( m_filters.at( w.second.id ).changes_ ); } else if ( m_specialFilters.count( w.second.id ) ) for ( h256 const& hash : m_specialFilters.at( w.second.id ) ) { - LOG( m_loggerWatch ) << "!!! " << w.first << " " + LOG( m_loggerWatch ) << w.first << " " << ( w.second.id == PendingChangedFilter ? "pending" : w.second.id == ChainChangedFilter ? "chain" : "???" ); @@ -938,7 +939,7 @@ void Client::tick() { m_bq.tick(); m_lastTick = chrono::system_clock::now(); if ( m_report.ticks == 15 ) - LOG( m_loggerDetail ) << activityReport(); + LOG( m_loggerTrace ) << activityReport(); } } @@ -954,11 +955,11 @@ void Client::checkWatchGarbage() { chrono::seconds( 20 ) ) // NB Was 200 for debugging. Normal value is 20! { toUninstall.push_back( key ); - LOG( m_loggerDetail ) << "GC: Uninstall " << key << " (" - << chrono::duration_cast< chrono::seconds >( - chrono::system_clock::now() - m_watches[key].lastPoll ) - .count() - << " s old)"; + LOG( m_loggerTrace ) << "GC: Uninstall " << key << " (" + << chrono::duration_cast< chrono::seconds >( + chrono::system_clock::now() - m_watches[key].lastPoll ) + .count() + << " s old)"; } for ( auto i : toUninstall ) uninstallWatch( i ); @@ -1176,12 +1177,12 @@ ExecutionResult Client::call( Address const& _from, u256 _value, Address _dest, temp.mutableState().addBalance( _from, ( u256 )( t.gas() * t.gasPrice() + t.value() ) ); ret = temp.execute( bc().lastBlockHashes(), t, skale::Permanence::Reverted ); } catch ( InvalidNonce const& in ) { - LOG( m_logger ) << "exception in client call(1):" - << boost::current_exception_diagnostic_information() << std::endl; + LOG( m_loggerInfo ) << "exception in client call(1):" + << boost::current_exception_diagnostic_information(); throw std::runtime_error( "call with invalid nonce" ); } catch ( ... ) { - LOG( m_logger ) << "exception in client call(2):" - << boost::current_exception_diagnostic_information() << std::endl; + LOG( m_loggerInfo ) << "exception in client call(2):" + << boost::current_exception_diagnostic_information(); throw; } return ret; diff --git a/libethereum/Client.h b/libethereum/Client.h index e9f423bbc..89f6c2dcd 100644 --- a/libethereum/Client.h +++ b/libethereum/Client.h @@ -563,8 +563,10 @@ class Client : public ClientBase, protected Worker { ///< the DB Signal< bytes const& > m_onBlockSealed; ///< Called if we have sealed a new block - Logger m_logger{ createLogger( VerbosityInfo, "client" ) }; - Logger m_loggerDetail{ createLogger( VerbosityTrace, "client" ) }; + mutable Logger m_loggerInfo{ createLogger( VerbosityInfo, "client" ) }; + mutable Logger m_loggerTrace{ createLogger( VerbosityTrace, "client" ) }; + mutable Logger m_loggerWarning{ createLogger( VerbosityWarning, "client" ) }; + mutable Logger m_loggerError{ createLogger( VerbosityError, "client" ) }; SkaleDebugTracer m_debugTracer; SkaleDebugInterface::handler m_debugHandler; diff --git a/libethereum/ClientTest.cpp b/libethereum/ClientTest.cpp index 85e9ebe58..1a44813f5 100644 --- a/libethereum/ClientTest.cpp +++ b/libethereum/ClientTest.cpp @@ -81,7 +81,7 @@ void ClientTest::modifyTimestamp( int64_t _timestamp ) { } bool ClientTest::mineBlocks( unsigned _count ) noexcept { - std::cout << "mineBlocks begin " << _count << std::endl; + LOG( m_loggerDebug ) << "mineBlocks begin " << _count << "\n"; if ( wouldSeal() ) return false; try { @@ -97,10 +97,10 @@ bool ClientTest::mineBlocks( unsigned _count ) noexcept { startSealing(); future_status ret = allBlocksImported.get_future().wait_for( std::chrono::seconds( m_singleBlockMaxMiningTimeInSeconds * _count ) ); - std::cout << "mineBlocks end 0 is OK:" << ( int ) ret << std::endl; + LOG( m_loggerDebug ) << "mineBlocks end 0 is OK:" << ( int ) ret << "\n"; return ( ret == future_status::ready ); } catch ( std::exception const& ) { - LOG( m_logger ) << boost::current_exception_diagnostic_information(); + LOG( m_loggerDebug ) << boost::current_exception_diagnostic_information(); return false; } } diff --git a/libethereum/ClientTest.h b/libethereum/ClientTest.h index c58aeb76f..9dace0311 100644 --- a/libethereum/ClientTest.h +++ b/libethereum/ClientTest.h @@ -51,6 +51,9 @@ class ClientTest : public Client { void rewindToBlock( unsigned _number ); h256 importRawBlock( std::string const& _blockRLP ); +private: + Logger m_loggerDebug{ createLogger( VerbosityDebug, "ClientTest" ) }; + protected: unsigned const m_singleBlockMaxMiningTimeInSeconds = 10; }; diff --git a/libethereum/ConsensusStub.cpp b/libethereum/ConsensusStub.cpp index 23215a836..d08a786e5 100644 --- a/libethereum/ConsensusStub.cpp +++ b/libethereum/ConsensusStub.cpp @@ -88,8 +88,8 @@ void ConsensusStub::doWork() { if ( txns.size() == 0 ) // check for exit return; - std::cout << cc::debug( "Taken " ) << txns.size() << cc::debug( " transactions for consensus" ) - << std::endl; + LOG( m_loggerDebug ) << "Taken " << txns.size() << " transactions for consensus" + << "\n"; size_t txns_in_block = txns.size(); // rand()%txns.size(); // any subset but not zero @@ -109,9 +109,10 @@ void ConsensusStub::doWork() { ++blockCounter; m_extFace.createBlock( out_vector, time( NULL ), 0, blockCounter, getPriceForBlockId( blockCounter ), stateRoot, -1 ); - std::cout << cc::debug( "createBlock" ) << std::endl; + LOG( m_loggerDebug ) << "createBlock" + << "\n"; } catch ( const dev::Exception& x ) { - std::cout << x.what() << std::endl; + LOG( m_loggerDebug ) << x.what() << "\n"; } // catch } diff --git a/libethereum/ConsensusStub.h b/libethereum/ConsensusStub.h index d102b78fc..a72c5953b 100644 --- a/libethereum/ConsensusStub.h +++ b/libethereum/ConsensusStub.h @@ -29,6 +29,7 @@ using namespace std; #include #include #include +#include #include #include #include @@ -63,6 +64,8 @@ class ConsensusStub : private dev::Worker, public ConsensusInterface { ConsensusExtFace& m_extFace; int64_t blockCounter = 0; u256 stateRoot = 0; + + dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "ConsensusStub" ) }; }; #endif /* LIBETHEREUM_CONSENSUSSTUB_H_ */ diff --git a/libethereum/Executive.cpp b/libethereum/Executive.cpp index 4de49515d..944b796ec 100644 --- a/libethereum/Executive.cpp +++ b/libethereum/Executive.cpp @@ -116,8 +116,9 @@ void StandardTrace::operator()( uint64_t _steps, uint64_t PC, Instruction inst, lastInst = m_lastInst.back(); m_lastInst.back() = inst; } else { - cwarn << "GAA!!! Tracing VM and more than one new/deleted stack frame between steps!"; - cwarn << "Attmepting naive recovery..."; + LOG( m_loggerWarning ) + << "Tracing VM and more than one new/deleted stack frame between steps!"; + LOG( m_loggerWarning ) << "Attmepting naive recovery..."; m_lastInst.resize( ext.depth + 1 ); } @@ -269,9 +270,8 @@ bool Executive::execute() { if ( !m_t.hasExternalGas() ) { // Pay... - LOG( m_detailsLogger ) << "Paying " << formatBalance( m_gasCost ) - << " from sender for gas (" << m_t.gas() << " gas at " - << formatBalance( m_t.gasPrice() ) << ")"; + LOG( m_loggerTrace ) << "Paying " << formatBalance( m_gasCost ) << " from sender for gas (" + << m_t.gas() << " gas at " << formatBalance( m_t.gasPrice() ) << ")"; m_s.subBalance( m_t.sender(), m_gasCost ); } @@ -405,7 +405,7 @@ bool Executive::executeCreate( Address const& _sender, u256 const& _endowment, bool accountAlreadyExist = ( m_s.addressHasCode( m_newAddress ) || m_s.getNonce( m_newAddress ) > 0 ); if ( accountAlreadyExist ) { - LOG( m_detailsLogger ) << "Address already used: " << m_newAddress; + LOG( m_loggerTrace ) << "Address already used: " << m_newAddress; m_gas = 0; m_excepted = TransactionException::AddressAlreadyUsed; revert(); @@ -437,7 +437,7 @@ bool Executive::executeCreate( Address const& _sender, u256 const& _endowment, } OnOpFunc Executive::simpleTrace() { - Logger& traceLogger = m_vmTraceLogger; + Logger& traceLogger = m_loggerTrace; return [&traceLogger]( uint64_t steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, VMFace const* _vm, ExtVMFace const* voidExt ) { @@ -514,30 +514,33 @@ bool Executive::go( OnOpFunc const& _onOp ) { m_output = _e.output(); m_excepted = TransactionException::RevertInstruction; } catch ( VMException const& _e ) { - LOG( m_detailsLogger ) << "Safe VM Exception. " << diagnostic_information( _e ); + LOG( m_loggerTrace ) << "Safe VM Exception. " << diagnostic_information( _e ); m_gas = 0; m_excepted = toTransactionException( _e ); revert(); } catch ( InternalVMError const& _e ) { - cwarn << "Internal VM Error (" << *boost::get_error_info< errinfo_evmcStatusCode >( _e ) - << ")\n" - << diagnostic_information( _e ); + LOG( m_loggerWarning ) + << "Internal VM Error (" << *boost::get_error_info< errinfo_evmcStatusCode >( _e ) + << ")\n" + << diagnostic_information( _e ); revert(); throw; } catch ( Exception const& _e ) { // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it // does. - cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " - << diagnostic_information( _e ); - cwarn << DETAILED_ERROR; + LOG( m_loggerWarning ) + << "Unexpected exception in VM. There may be a bug in this implementation. " + << diagnostic_information( _e ); + LOG( m_loggerWarning ) << DETAILED_ERROR; exit( 1 ); // Another solution would be to reject this transaction, but that also // has drawbacks. Essentially, the amount of ram has to be increased here. } catch ( std::exception const& _e ) { // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it // does. - cwarn << "Unexpected std::exception in VM. Not enough RAM? " << _e.what(); - cwarn << DETAILED_ERROR; + LOG( m_loggerWarning ) + << "Unexpected std::exception in VM. Not enough RAM? " << _e.what(); + LOG( m_loggerWarning ) << DETAILED_ERROR; exit( 1 ); // Another solution would be to reject this transaction, but that also // has drawbacks. Essentially, the amount of ram has to be increased here. diff --git a/libethereum/Executive.h b/libethereum/Executive.h index cf1b2715c..6828d1f61 100644 --- a/libethereum/Executive.h +++ b/libethereum/Executive.h @@ -77,6 +77,9 @@ class StandardTrace { std::vector< Instruction > m_lastInst; Json::Value m_trace; DebugOptions m_options; + + Logger m_loggerDebug{ createLogger( VerbosityDebug, "StandardTrace" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "StandardTrace" ) }; }; /** @@ -243,9 +246,9 @@ class Executive { Address m_newAddress; size_t m_savepoint = 0; - Logger m_execLogger{ createLogger( VerbosityDebug, "exec" ) }; - Logger m_detailsLogger{ createLogger( VerbosityTrace, "exec" ) }; - Logger m_vmTraceLogger{ createLogger( VerbosityTrace, "vmtrace" ) }; + Logger m_loggerDebug{ createLogger( VerbosityDebug, "Executive" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "Executive" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "Executive" ) }; }; } // namespace eth diff --git a/libethereum/InstanceMonitor.cpp b/libethereum/InstanceMonitor.cpp index ed180f6fc..baa219b21 100644 --- a/libethereum/InstanceMonitor.cpp +++ b/libethereum/InstanceMonitor.cpp @@ -47,9 +47,9 @@ void InstanceMonitor::initRotationParams( uint64_t _finishTimestamp ) { std::ofstream rotationInfoFile( m_rotationInfoFilePath.string() ); rotationInfoFile << rotationJson; - LOG( m_infoLogger ) << "Set rotation time to " << _finishTimestamp; + LOG( m_loggerInfo ) << "Set rotation time to " << _finishTimestamp; } catch ( ... ) { - LOG( m_errorLogger ) << "Setting rotation timestamp failed"; + LOG( m_loggerError ) << "Setting rotation timestamp failed"; throw_with_nested( std::runtime_error( "cannot save rotation timestamp" ) ); } } @@ -71,18 +71,18 @@ uint64_t InstanceMonitor::rotationTimestamp() const { try { auto rotationJson = nlohmann::json::parse( rotationInfoFile ); auto timestamp = rotationJson["timestamp"].get< uint64_t >(); - LOG( m_infoLogger ) << "Rotation scheduled for " << timestamp; + LOG( m_loggerInfo ) << "Rotation scheduled for " << timestamp; return timestamp; } catch ( ... ) { - LOG( m_errorLogger ) << "Rotation file is malformed or missing"; + LOG( m_loggerError ) << "Rotation file is malformed or missing"; throw InvalidRotationInfoFileException( m_rotationInfoFilePath ); } } void InstanceMonitor::reportExitTimeReached( bool _reached ) { if ( m_statusAndControl ) { - LOG( m_infoLogger ) << "Setting ExitTimeReached = " << _reached; + LOG( m_loggerInfo ) << "Setting ExitTimeReached = " << _reached; m_statusAndControl->setExitState( StatusAndControl::ExitTimeReached, _reached ); } else - LOG( m_infoLogger ) << "Simulating setting ExitTimeReached = " << _reached; + LOG( m_loggerInfo ) << "Simulating setting ExitTimeReached = " << _reached; } diff --git a/libethereum/InstanceMonitor.h b/libethereum/InstanceMonitor.h index 688fddcbd..acdd8f099 100644 --- a/libethereum/InstanceMonitor.h +++ b/libethereum/InstanceMonitor.h @@ -70,6 +70,6 @@ class InstanceMonitor { private: - mutable dev::Logger m_infoLogger{ createLogger( dev::VerbosityInfo, "instance-monitor" ) }; - mutable dev::Logger m_errorLogger{ createLogger( dev::VerbosityError, "instance-monitor" ) }; + mutable dev::Logger m_loggerInfo{ createLogger( dev::VerbosityInfo, "instance-monitor" ) }; + mutable dev::Logger m_loggerError{ createLogger( dev::VerbosityError, "instance-monitor" ) }; }; diff --git a/libethereum/Precompiled.cpp b/libethereum/Precompiled.cpp index bfcff6b7c..2534c4976 100644 --- a/libethereum/Precompiled.cpp +++ b/libethereum/Precompiled.cpp @@ -620,12 +620,8 @@ ETH_REGISTER_PRECOMPILED( logTextMessage )( bytesConstRef _in ) { convertBytesToString( _in, 64, rawString, lengthString ); typedef std::function< std::string( const std::string& s ) > fnColorizer_t; - fnColorizer_t fnHeader = []( const std::string& s ) -> std::string { - return cc::info( s ); - }; - fnColorizer_t fnText = []( const std::string& s ) -> std::string { - return cc::normal( s ); - }; + fnColorizer_t fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnColorizer_t fnText = []( const std::string& s ) -> std::string { return s; }; std::string strMessageTypeDesc = ""; switch ( nMessageType ) { @@ -634,28 +630,28 @@ ETH_REGISTER_PRECOMPILED( logTextMessage )( bytesConstRef _in ) { strMessageTypeDesc = "normal"; break; case 1: // debug message - fnHeader = []( const std::string& s ) -> std::string { return cc::normal( s ); }; - fnText = []( const std::string& s ) -> std::string { return cc::debug( s ); }; + fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnText = []( const std::string& s ) -> std::string { return s; }; strMessageTypeDesc = "debug"; break; case 2: // trace message - fnHeader = []( const std::string& s ) -> std::string { return cc::debug( s ); }; - fnText = []( const std::string& s ) -> std::string { return cc::debug( s ); }; + fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnText = []( const std::string& s ) -> std::string { return s; }; strMessageTypeDesc = "trace"; break; case 3: // warning message - fnHeader = []( const std::string& s ) -> std::string { return cc::warn( s ); }; - fnText = []( const std::string& s ) -> std::string { return cc::warn( s ); }; + fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnText = []( const std::string& s ) -> std::string { return s; }; strMessageTypeDesc = "warning"; break; case 4: // error message - fnHeader = []( const std::string& s ) -> std::string { return cc::error( s ); }; - fnText = []( const std::string& s ) -> std::string { return cc::error( s ); }; + fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnText = []( const std::string& s ) -> std::string { return s; }; strMessageTypeDesc = "error"; break; case 5: // fatal message - fnHeader = []( const std::string& s ) -> std::string { return cc::fatal( s ); }; - fnText = []( const std::string& s ) -> std::string { return cc::error( s ); }; + fnHeader = []( const std::string& s ) -> std::string { return s; }; + fnText = []( const std::string& s ) -> std::string { return s; }; strMessageTypeDesc = "FATAL"; break; } diff --git a/libethereum/Precompiled.h b/libethereum/Precompiled.h index cc0219dc3..399499f60 100644 --- a/libethereum/Precompiled.h +++ b/libethereum/Precompiled.h @@ -30,7 +30,6 @@ #include #include -//#include #include #include diff --git a/libethereum/SkaleHost.cpp b/libethereum/SkaleHost.cpp index b66d70bac..c098c7d79 100644 --- a/libethereum/SkaleHost.cpp +++ b/libethereum/SkaleHost.cpp @@ -71,8 +71,7 @@ std::unique_ptr< ConsensusInterface > DefaultConsensusFactory::create( #if CONSENSUS const auto& nfo = static_cast< const Interface& >( m_client ).blockInfo( LatestBlock ); // - clog( VerbosityInfo, "skale-host" ) - << cc::note( "NOTE: Block number at startup is " ) << cc::size10( nfo.number() ) << "\n"; + LOG( m_loggerInfo ) << "NOTE: Block number at startup is " << nfo.number(); // auto ts = nfo.timestamp(); @@ -275,7 +274,7 @@ SkaleHost::SkaleHost( dev::eth::Client& _client, const ConsensusFactory* _consFa last_block_when_log = current_block; } - LOG( m_traceLogger ) << "TRACEPOINT " << name << " " + LOG( m_loggerTrace ) << "TRACEPOINT " << name << " " << m_debugTracer.get_tracepoint_count( name ); } ); @@ -285,7 +284,7 @@ SkaleHost::SkaleHost( dev::eth::Client& _client, const ConsensusFactory* _consFa m_extFace.reset( new ConsensusExtImpl( *this ) ); } catch ( const std::exception& e ) { - clog( Verbosity::VerbosityError, "main" ) << "Could not init SkaleHost" << e.what(); + LOG( m_loggerError ) << "Could not init SkaleHost" << e.what(); std::throw_with_nested( CreationException() ); } @@ -298,8 +297,7 @@ SkaleHost::SkaleHost( dev::eth::Client& _client, const ConsensusFactory* _consFa m_consensus = _consFactory->create( *m_extFace ); } catch ( const std::exception& e ) { - clog( Verbosity::VerbosityError, "main" ) - << "Could not create consensus in SkaleHost" << e.what(); + LOG( m_loggerError ) << "Could not create consensus in SkaleHost" << e.what(); std::throw_with_nested( CreationException() ); } @@ -307,8 +305,7 @@ SkaleHost::SkaleHost( dev::eth::Client& _client, const ConsensusFactory* _consFa m_consensus->parseFullConfigAndCreateNode( m_client.chainParams().getOriginalJson(), _gethURL ); } catch ( const std::exception& e ) { - clog( Verbosity::VerbosityError, "main" ) - << "Could not create parse consensus config in SkaleHost" << e.what(); + LOG( m_loggerError ) << "Could not create parse consensus config in SkaleHost" << e.what(); std::throw_with_nested( CreationException() ); } } @@ -316,10 +313,10 @@ SkaleHost::SkaleHost( dev::eth::Client& _client, const ConsensusFactory* _consFa SkaleHost::~SkaleHost() {} void SkaleHost::logState() { - LOG( m_traceLogger ) << cc::debug( " sent_to_consensus = " ) << total_sent - << cc::debug( " got_from_consensus = " ) << total_arrived - << cc::debug( " m_tq = " ) << m_tq.status().current - << cc::debug( " m_bcast_counter = " ) << m_bcast_counter; + LOG( m_loggerTrace ) << " sent_to_consensus = " << total_sent + << " got_from_consensus = " << total_arrived + << " m_tq = " << m_tq.status().current + << " m_bcast_counter = " << m_bcast_counter; } constexpr uint64_t MAX_BROADCAST_QUEUE_SIZE = 2048; @@ -344,7 +341,7 @@ h256 SkaleHost::receiveTransaction( std::string _rlp ) { // drop incoming transactions if skaled has an outdated state if ( m_client.bc().info().timestamp() + REJECT_OLD_TRANSACTION_THROUGH_BROADCAST_INTERVAL_SEC < std::time( NULL ) ) { - LOG( m_debugLogger ) << "Dropped the transaction received through broadcast"; + LOG( m_loggerDebug ) << "Dropped the transaction received through broadcast"; return h256(); } @@ -355,7 +352,6 @@ h256 SkaleHost::receiveTransaction( std::string _rlp ) { // m_debugTracer.tracepoint( "receive_transaction" ); - #if ( defined _DEBUG ) h256 sha2 = #endif @@ -365,7 +361,7 @@ h256 SkaleHost::receiveTransaction( std::string _rlp ) { #endif m_debugTracer.tracepoint( "receive_transaction_success" ); - LOG( m_debugLogger ) << "Successfully received through broadcast " << sha; + LOG( m_loggerDebug ) << "Successfully received through broadcast " << sha; return sha; @@ -439,13 +435,11 @@ ConsensusExtFace::transactions_vector SkaleHost::pendingTransactions( getGasPrice(), isMtmEnabled ); } catch ( const exception& ex ) { if ( to_delete.count( tx.sha3() ) == 0 ) - clog( VerbosityInfo, "skale-host" ) - << "Dropped now-invalid transaction in pending queue " << tx.sha3() << ":" - << ex.what(); + LOG( m_loggerInfo ) << "Dropped now-invalid transaction in pending queue " + << tx.sha3() << ":" << ex.what(); to_delete.insert( tx.sha3() ); return false; } - return true; } ); @@ -486,11 +480,11 @@ ConsensusExtFace::transactions_vector SkaleHost::pendingTransactions( #ifdef DEBUG_TX_BALANCE if ( sent.count( sha ) != 0 ) { int prev = sent[sha]; - std::cerr << "Prev no = " << prev << std::endl; + LOG( m_loggerError ) << "Prev no = " << prev; if ( sent.count( sha ) != 0 ) { // TODO fix this!!? - clog( VerbosityWarning, "skale-host" ) + LOG( m_loggerWarning ) << "Sending to consensus duplicate transaction (sent before!)"; } } @@ -498,10 +492,10 @@ ConsensusExtFace::transactions_vector SkaleHost::pendingTransactions( #endif m_debugTracer.tracepoint( "sent_txn" ); - LOG( m_traceLogger ) << "Sent txn: " << sha << std::endl; + LOG( m_loggerTrace ) << "Sent txn: " << sha; } } catch ( ... ) { - clog( VerbosityError, "skale-host" ) << "BAD exception in pendingTransactions!"; + LOG( m_loggerError ) << "BAD exception in pendingTransactions!"; } logState(); @@ -520,12 +514,12 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro std::lock_guard< std::recursive_mutex > lock( m_pending_createMutex ); if ( m_ignoreNewBlocks ) { - LOG( m_warningLogger ) << "WARNING: skaled got new block #" << _blockID + LOG( m_loggerWarning ) << "WARNING: skaled got new block #" << _blockID << " after timestamp-related exit initiated!"; return; } - LOG( m_debugLogger ) << "createBlock ID = #" << _blockID; + LOG( m_loggerDebug ) << "createBlock ID = #" << _blockID; m_debugTracer.tracepoint( "create_block" ); // convert bytes back to transactions (using caching), delete them from q and push results into @@ -535,12 +529,12 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro dev::h256 stCurrent = this->m_client.blockInfo( this->m_client.hashFromNumber( _blockID - 1 ) ).stateRoot(); - LOG( m_traceLogger ) << "STATE ROOT FOR BLOCK: " << std::to_string( _blockID - 1 ) << " " + LOG( m_loggerTrace ) << "STATE ROOT FOR BLOCK: " << std::to_string( _blockID - 1 ) << " " << stCurrent.hex(); // FATAL if mismatch in non-default if ( _winningNodeIndex != 0 && dev::h256::Arith( stCurrent ) != _stateRoot ) { - LOG( m_errorLogger ) << "FATAL STATE ROOT MISMATCH ERROR: current state root " + LOG( m_loggerError ) << "FATAL STATE ROOT MISMATCH ERROR: current state root " << dev::h256::Arith( stCurrent ).str() << " is not equal to arrived state root " << _stateRoot.str() << " with block ID #" << _blockID @@ -555,7 +549,7 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro // WARN if default but non-zero if ( _winningNodeIndex == 0 && _stateRoot != u256() ) - LOG( m_warningLogger ) << "WARNING: STATE ROOT MISMATCH!" + LOG( m_loggerWarning ) << "WARNING: STATE ROOT MISMATCH!" << "Current block is DEFAULT BUT arrived state root is " << _stateRoot.str() << " with block ID #" << _blockID; } @@ -573,7 +567,7 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro for ( auto it = _approvedTransactions.begin(); it != _approvedTransactions.end(); ++it ) { const bytes& data = *it; h256 sha = sha3( data ); - LOG( m_traceLogger ) << "Arrived txn: " << sha; + LOG( m_loggerTrace ) << "Arrived txn: " << sha; Transaction t( data, CheckTransaction::Everything, true, @@ -600,7 +594,7 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro total_arrived += out_txns.size(); if ( _blockID != m_client.number() + 1 ) { - LOG( m_errorLogger ) << "Mismatch in block number:SKALED_NUMBER:" << m_client.number() + LOG( m_loggerError ) << "Mismatch in block number:SKALED_NUMBER:" << m_client.number() << ":CONSENSUS_NUMBER:" << _blockID; assert( false ); } @@ -616,7 +610,7 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro boost::chrono::high_resolution_clock::time_point skaledTimeFinish = boost::chrono::high_resolution_clock::now(); if ( latestBlockTime != boost::chrono::high_resolution_clock::time_point() ) { - LOG( m_infoLogger ) << "SWT:" + LOG( m_loggerInfo ) << "SWT:" << boost::chrono::duration_cast< boost::chrono::milliseconds >( skaledTimeFinish - skaledTimeStart ) .count() @@ -625,19 +619,19 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro skaledTimeFinish - latestBlockTime ) .count(); } else { - LOG( m_infoLogger ) << "SWT:" + LOG( m_loggerInfo ) << "SWT:" << boost::chrono::duration_cast< boost::chrono::milliseconds >( skaledTimeFinish - skaledTimeStart ) .count(); } latestBlockTime = skaledTimeFinish; - LOG( m_debugLogger ) << "Successfully imported " << n_succeeded << " of " << out_txns.size() + LOG( m_loggerDebug ) << "Successfully imported " << n_succeeded << " of " << out_txns.size() << " transactions"; logState(); - LOG( m_infoLogger ) << "TQBYTES:CTQ:" << m_tq.status().currentBytes + LOG( m_loggerInfo ) << "TQBYTES:CTQ:" << m_tq.status().currentBytes << ":FTQ:" << m_tq.status().futureBytes << ":TQSIZE:CTQ:" << m_tq.status().current << ":FTQ:" << m_tq.status().future; @@ -648,17 +642,17 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro m_ignoreNewBlocks = true; m_consensus->exitGracefully(); ExitHandler::exitHandler( -1, ExitHandler::ec_rotation_complete ); - LOG( m_infoLogger ) << "Rotation is completed. Instance is exiting"; + LOG( m_loggerInfo ) << "Rotation is completed. Instance is exiting"; } } } catch ( const std::exception& ex ) { - LOG( m_errorLogger ) << "CRITICAL " << ex.what() << " (in createBlock)"; - LOG( m_errorLogger ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; + LOG( m_loggerError ) << "CRITICAL " << ex.what() << " (in createBlock)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace(); } catch ( ... ) { - LOG( m_errorLogger ) << "CRITICAL unknown exception (in createBlock)"; - LOG( m_errorLogger ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; + LOG( m_loggerError ) << "CRITICAL unknown exception (in createBlock)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace(); } void SkaleHost::startWorking() { @@ -682,42 +676,40 @@ void SkaleHost::startWorking() { auto broadcastFunction = std::bind( &SkaleHost::broadcastFunc, this ); m_broadcastThread = std::thread( broadcastFunction ); - auto consensusFunction = [&]() { - try { - m_consensus->startAll(); - } catch ( ... ) { - // cleanup - m_exitNeeded = true; - m_broadcastThread.join(); - ExitHandler::exitHandler( -1, ExitHandler::ec_termninated_by_signal ); - return; - } - - // comment out as this hack is in consensus now - // HACK Prevent consensus from hanging up for emptyBlockIntervalMs at bootstrapAll()! - // uint64_t tmp_interval = m_consensus->getEmptyBlockIntervalMs(); - // m_consensus->setEmptyBlockIntervalMs( 50 ); - try { - static const char g_strThreadName[] = "bootStrapAll"; - dev::setThreadName( g_strThreadName ); - clog( VerbosityInfo, "skale-host" ) << "Thread " << g_strThreadName << " started\n"; - m_consensus->bootStrapAll(); - clog( VerbosityInfo, "skale-host" ) << "Thread " << g_strThreadName << " will exit\n"; - } catch ( std::exception& ex ) { - std::string s = ex.what(); - if ( s.empty() ) - s = "no description"; - clog( VerbosityError, "skale-host" ) - << "Consensus thread in skale host will exit with exception: " << s << "\n"; - } catch ( ... ) { - clog( VerbosityError, "skale-host" ) - << "Consensus thread in skale host will exit with unknown exception\n" - << skutils::signal::generate_stack_trace() << "\n"; - } + auto consensusFunction = + [&]() { + try { + m_consensus->startAll(); + } catch ( ... ) { + // cleanup + m_exitNeeded = true; + m_broadcastThread.join(); + ExitHandler::exitHandler( -1, ExitHandler::ec_termninated_by_signal ); + return; + } - // comment out as this hack is in consensus now - // m_consensus->setEmptyBlockIntervalMs( tmp_interval ); - }; // func + // comment out as this hack is in consensus now + // HACK Prevent consensus from hanging up for emptyBlockIntervalMs at bootstrapAll()! + // uint64_t tmp_interval = m_consensus->getEmptyBlockIntervalMs(); + // m_consensus->setEmptyBlockIntervalMs( 50 ); + try { + static const char g_strThreadName[] = "bootStrapAll"; + dev::setThreadName( g_strThreadName ); + LOG( m_loggerInfo ) << "Thread " << g_strThreadName << " started"; + m_consensus->bootStrapAll(); + LOG( m_loggerInfo ) << "Thread " << g_strThreadName << " will exit"; + } catch ( std::exception& ex ) { + std::string s = ex.what(); + if ( s.empty() ) + s = "no description"; + LOG( m_loggerError ) + << "Consensus thread in skale host will exit with exception: " << s; + } catch ( ... ) { + LOG( m_loggerError ) + << "Consensus thread in skale host will exit with unknown exception\n" + << skutils::signal::generate_stack_trace(); + } + }; // func m_consensusThread = std::thread( consensusFunction ); } @@ -730,32 +722,31 @@ void SkaleHost::stopWorking() { m_exitNeeded = true; pauseConsensus( false ); - cnote << "1 before exitGracefully()"; + LOG( m_loggerInfo ) << "1 before exitGracefully()"; if ( ExitHandler::shouldExit() ) { // requested exit int signal = ExitHandler::getSignal(); int exitCode = ExitHandler::requestedExitCode(); if ( signal > 0 ) - clog( VerbosityInfo, "skale-host" ) << cc::info( "Exit requested with signal " ) - << signal << " and exit code " << exitCode; + LOG( m_loggerInfo ) << "Exit requested with signal " << signal << " and exit code " + << exitCode; else - clog( VerbosityInfo, "skale-host" ) - << cc::info( "Exit requested internally with exit code " ) << exitCode; + LOG( m_loggerInfo ) << "Exit requested internally with exit code " << exitCode; } else { - clog( VerbosityInfo, "skale-host" ) << cc::info( "Exiting without request" ); + LOG( m_loggerInfo ) << "Exiting without request"; } m_consensus->exitGracefully(); - cnote << "2 after exitGracefully()"; + LOG( m_loggerInfo ) << "2 after exitGracefully()"; while ( m_consensus->getStatus() != CONSENSUS_EXITED ) { timespec ms100{ 0, 100000000 }; nanosleep( &ms100, nullptr ); } - cnote << "3 after wait loop"; + LOG( m_loggerInfo ) << "3 after wait loop"; if ( m_consensusThread.joinable() ) m_consensusThread.join(); @@ -765,7 +756,7 @@ void SkaleHost::stopWorking() { working = false; - cnote << "4 before dtor"; + LOG( m_loggerInfo ) << "4 before dtor"; } void SkaleHost::broadcastFunc() { @@ -808,8 +799,8 @@ void SkaleHost::broadcastFunc() { m_debugTracer.tracepoint( "broadcast" ); m_broadcaster->broadcast( rlp ); } catch ( const std::exception& ex ) { - cwarn << "BROADCAST EXCEPTION CAUGHT"; - cwarn << ex.what(); + LOG( m_loggerWarning ) << "BROADCAST EXCEPTION CAUGHT"; + LOG( m_loggerWarning ) << ex.what(); } // catch } @@ -817,12 +808,12 @@ void SkaleHost::broadcastFunc() { logState(); } catch ( const std::exception& ex ) { - cerror << "CRITICAL " << ex.what() << " (restarting broadcastFunc)"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL " << ex.what() << " (restarting broadcastFunc)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace(); sleep( 2 ); } catch ( ... ) { - cerror << "CRITICAL unknown exception (restarting broadcastFunc)"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL unknown exception (restarting broadcastFunc)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace(); sleep( 2 ); } } // while diff --git a/libethereum/SkaleHost.h b/libethereum/SkaleHost.h index f99e70294..10293dbff 100644 --- a/libethereum/SkaleHost.h +++ b/libethereum/SkaleHost.h @@ -80,6 +80,10 @@ class DefaultConsensusFactory : public ConsensusFactory { private: const dev::eth::Client& m_client; + + /// Loggers + mutable dev::Logger m_loggerInfo{ dev::createLogger( + dev::VerbosityInfo, "DefaultConsensusFactory" ) }; #if CONSENSUS void fillSgxInfo( ConsensusEngine& consensus ) const; void fillPublicKeyInfo( ConsensusEngine& consensus ) const; @@ -205,11 +209,11 @@ class SkaleHost { bool m_broadcastEnabled; - dev::Logger m_errorLogger{ dev::createLogger( dev::VerbosityError, "skale-host" ) }; - dev::Logger m_warningLogger{ dev::createLogger( dev::VerbosityWarning, "skale-host" ) }; - dev::Logger m_infoLogger{ dev::createLogger( dev::VerbosityInfo, "skale-host" ) }; - dev::Logger m_debugLogger{ dev::createLogger( dev::VerbosityDebug, "skale-host" ) }; - dev::Logger m_traceLogger{ dev::createLogger( dev::VerbosityTrace, "skale-host" ) }; + dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "skale-host" ) }; + dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "skale-host" ) }; + dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "skale-host" ) }; + dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "skale-host" ) }; + dev::Logger m_loggerTrace{ dev::createLogger( dev::VerbosityTrace, "skale-host" ) }; void logState(); std::unique_ptr< ConsensusExtFace > m_extFace; diff --git a/libethereum/SnapshotAgent.cpp b/libethereum/SnapshotAgent.cpp index 68e055147..a5701de88 100644 --- a/libethereum/SnapshotAgent.cpp +++ b/libethereum/SnapshotAgent.cpp @@ -14,7 +14,8 @@ SnapshotAgent::SnapshotAgent( int64_t _snapshotIntervalSec, m_snapshotManager( _snapshotManager ), m_debugTracer( _debugTracer ) { if ( m_snapshotIntervalSec > 0 ) { - LOG( m_logger ) << "Snapshots enabled, snapshotIntervalSec is: " << m_snapshotIntervalSec; + LOG( m_loggerInfo ) << "Snapshots enabled, snapshotIntervalSec is: " + << m_snapshotIntervalSec; } } @@ -71,15 +72,17 @@ void SnapshotAgent::init( unsigned _currentBlockNumber, int64_t _timestampOfBloc last_snapshot_creation_time = _timestampOfBlock1; } - LOG( m_logger ) << "Latest snapshots init: " << latest_snapshots.first << " " - << latest_snapshots.second << " -> " << this->last_snapshoted_block_with_hash; + LOG( m_loggerInfo ) << "Latest snapshots init: " << latest_snapshots.first << " " + << latest_snapshots.second << " -> " + << this->last_snapshoted_block_with_hash; - LOG( m_logger ) << "Init last snapshot creation time: " << this->last_snapshot_creation_time; + LOG( m_loggerInfo ) << "Init last snapshot creation time: " + << this->last_snapshot_creation_time; } void SnapshotAgent::finishHashComputingAndUpdateHashesIfNeeded( int64_t _timestamp ) { if ( m_snapshotIntervalSec > 0 && this->isTimeToDoSnapshot( _timestamp ) ) { - LOG( m_logger ) << "Last snapshot creation time: " << this->last_snapshot_creation_time; + LOG( m_loggerInfo ) << "Last snapshot creation time: " << this->last_snapshot_creation_time; if ( m_snapshotHashComputing != nullptr && m_snapshotHashComputing->joinable() ) m_snapshotHashComputing->join(); @@ -101,13 +104,13 @@ void SnapshotAgent::doSnapshotIfNeeded( unsigned _currentBlockNumber, int64_t _t if ( m_snapshotIntervalSec <= 0 ) return; - LOG( m_loggerDetail ) << "Block timestamp: " << _timestamp; + LOG( m_loggerTrace ) << "Block timestamp: " << _timestamp; if ( this->isTimeToDoSnapshot( _timestamp ) ) { try { boost::chrono::high_resolution_clock::time_point t1; boost::chrono::high_resolution_clock::time_point t2; - LOG( m_logger ) << "DOING SNAPSHOT: " << _currentBlockNumber; + LOG( m_loggerInfo ) << "DOING SNAPSHOT: " << _currentBlockNumber; m_debugTracer.tracepoint( "doing_snapshot" ); t1 = boost::chrono::high_resolution_clock::now(); @@ -116,12 +119,12 @@ void SnapshotAgent::doSnapshotIfNeeded( unsigned _currentBlockNumber, int64_t _t this->snapshot_calculation_time_ms = boost::chrono::duration_cast< boost::chrono::milliseconds >( t2 - t1 ).count(); } catch ( SnapshotManager::SnapshotPresent& ex ) { - cerror << "WARNING " << dev::nested_exception_what( ex ); + LOG( m_loggerError ) << "WARNING " << dev::nested_exception_what( ex ); } this->last_snapshot_creation_time = _timestamp; - LOG( m_logger ) << "New snapshot creation time: " << this->last_snapshot_creation_time; + LOG( m_loggerInfo ) << "New snapshot creation time: " << this->last_snapshot_creation_time; } // snapshots without hash can appear either from start, from downloading or from just @@ -193,39 +196,39 @@ void SnapshotAgent::startHashComputingThread() { t2 = boost::chrono::high_resolution_clock::now(); this->snapshot_hash_calculation_time_ms = boost::chrono::duration_cast< boost::chrono::milliseconds >( t2 - t1 ).count(); - LOG( m_logger ) << "Computed hash for snapshot " << latest_snapshots.second << ": " - << m_snapshotManager->getSnapshotHash( latest_snapshots.second ); + LOG( m_loggerInfo ) << "Computed hash for snapshot " << latest_snapshots.second << ": " + << m_snapshotManager->getSnapshotHash( latest_snapshots.second ); m_debugTracer.tracepoint( "computeSnapshotHash_end" ); } catch ( const std::exception& ex ) { - cerror << cc::fatal( "CRITICAL" ) << " " << cc::warn( dev::nested_exception_what( ex ) ) - << cc::error( " in computeSnapshotHash(). Exiting..." ); - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL" + << " " << dev::nested_exception_what( ex ) + << " in computeSnapshotHash(). Exiting..."; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; ExitHandler::exitHandler( -1, ExitHandler::ec_compute_snapshot_error ); } catch ( ... ) { - cerror << cc::fatal( "CRITICAL" ) - << cc::error( - " unknown exception in computeSnapshotHash(). " - "Exiting..." ); - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL" + << " unknown exception in computeSnapshotHash(). " + "Exiting..."; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; ExitHandler::exitHandler( -1, ExitHandler::ec_compute_snapshot_error ); } } ) ); } void SnapshotAgent::doSnapshotAndComputeHash( unsigned _blockNumber ) { - LOG( m_logger ) << "DOING SNAPSHOT: " << _blockNumber; + LOG( m_loggerInfo ) << "DOING SNAPSHOT: " << _blockNumber; m_debugTracer.tracepoint( "doing_snapshot" ); try { m_snapshotManager->doSnapshot( _blockNumber ); } catch ( SnapshotManager::SnapshotPresent& ex ) { - LOG( m_logger ) << "0 block snapshot is already present. Skipping."; + LOG( m_loggerInfo ) << "0 block snapshot is already present. Skipping."; return; } m_snapshotManager->computeSnapshotHash( _blockNumber ); - LOG( m_logger ) << "Computed hash for snapshot " << _blockNumber << ": " - << m_snapshotManager->getSnapshotHash( _blockNumber ); + LOG( m_loggerInfo ) << "Computed hash for snapshot " << _blockNumber << ": " + << m_snapshotManager->getSnapshotHash( _blockNumber ); m_debugTracer.tracepoint( "computeSnapshotHash_end" ); } diff --git a/libethereum/SnapshotAgent.h b/libethereum/SnapshotAgent.h index 140e0c4cd..ac112e2b4 100644 --- a/libethereum/SnapshotAgent.h +++ b/libethereum/SnapshotAgent.h @@ -56,8 +56,9 @@ class SnapshotAgent { uint64_t snapshot_calculation_time_ms; uint64_t snapshot_hash_calculation_time_ms; - dev::Logger m_logger{ createLogger( dev::VerbosityInfo, "SnapshotAgent" ) }; - dev::Logger m_loggerDetail{ createLogger( dev::VerbosityTrace, "SnapshotAgent" ) }; + dev::Logger m_loggerInfo{ createLogger( dev::VerbosityInfo, "SnapshotAgent" ) }; + dev::Logger m_loggerTrace{ createLogger( dev::VerbosityTrace, "SnapshotAgent" ) }; + dev::Logger m_loggerError{ createLogger( dev::VerbosityError, "SnapshotAgent" ) }; SkaleDebugTracer& m_debugTracer; }; diff --git a/libethereum/Transaction.cpp b/libethereum/Transaction.cpp index eee35a457..42c4d05a4 100644 --- a/libethereum/Transaction.cpp +++ b/libethereum/Transaction.cpp @@ -217,7 +217,7 @@ void Transaction::checkOutExternalGas( } u256 externalGas = ~u256( 0 ) / u256( hash ) / difficulty; if ( externalGas > 0 ) - ctrace << "Mined gas: " << externalGas; + LOG( m_loggerTrace ) << "Mined gas: " << externalGas; EVMSchedule scheduleForUse = ConstantinopleSchedule; if ( CorrectForkInPowPatch::isEnabledWhen( _committedBlockTimestamp ) ) diff --git a/libethereum/Transaction.h b/libethereum/Transaction.h index 1aecefaaa..dc41242bb 100644 --- a/libethereum/Transaction.h +++ b/libethereum/Transaction.h @@ -133,6 +133,9 @@ class Transaction : public TransactionBase { private: bool m_externalGasIsChecked = false; std::optional< u256 > m_externalGas; + + dev::Logger m_loggerInfo{ createLogger( dev::VerbosityInfo, "Transaction" ) }; + dev::Logger m_loggerTrace{ createLogger( dev::VerbosityTrace, "Transaction" ) }; }; /// Nice name for vector of Transaction. diff --git a/libethereum/TransactionQueue.cpp b/libethereum/TransactionQueue.cpp index a88c69fa4..b9f37395f 100644 --- a/libethereum/TransactionQueue.cpp +++ b/libethereum/TransactionQueue.cpp @@ -137,7 +137,7 @@ ImportResult TransactionQueue::import( --m_futureSize; m_futureSizeBytes -= t->second.transaction.toBytes().size(); auto erasedHash = t->second.transaction.sha3(); - LOG( m_loggerDetail ) << "Re-inserting future transaction " << erasedHash; + LOG( m_loggerTrace ) << "Re-inserting future transaction " << erasedHash; m_known.erase( erasedHash ); fs->second.erase( t->second.transaction.nonce() ); if ( fs->second.empty() ) @@ -207,12 +207,12 @@ Transactions TransactionQueue::topTransactions_WITH_LOCK( unsigned _limit ) { found_difference = true; } if ( found_difference ) { - clog( VerbosityError, "skale-host" ) << "IS-348 bug detected. Wrong transaction order in " - "block proposal was fixed by workaround :("; - clog( VerbosityTrace, "skale-host" ) << " "; + LOG( m_loggerError ) << "IS-348 bug detected. Wrong transaction order in " + "block proposal was fixed by workaround :("; + LOG( m_loggerTrace ) << " "; for ( size_t i = 0; i < top_transactions.size(); ++i ) { - clog( VerbosityTrace, "skale-host" ) - << i << " " << saved_txns[i].sha3() << " " << top_transactions[i].sha3(); + LOG( m_loggerTrace ) << i << " " << saved_txns[i].sha3() << " " + << top_transactions[i].sha3(); } } @@ -263,19 +263,19 @@ ImportResult TransactionQueue::manageImport_WITH_LOCK( // If valid, append to transactions. insertCurrent_WITH_LOCK( make_pair( _h, _transaction ) ); - LOG( m_loggerDetail ) << "Queued vaguely legit-looking transaction " << _h; + LOG( m_loggerTrace ) << "Queued vaguely legit-looking transaction " << _h; while ( m_current.size() > m_limit || m_currentSizeBytes > m_currentSizeBytesLimit ) { - LOG( m_loggerDetail ) << "Dropping out of bounds transaction " << _h; + LOG( m_loggerTrace ) << "Dropping out of bounds transaction " << _h; remove_WITH_LOCK( m_current.rbegin()->transaction.sha3() ); } m_onReady(); } catch ( Exception const& _e ) { - LOG( m_loggerDetail ) << "Ignoring invalid transaction: " << diagnostic_information( _e ); + LOG( m_loggerTrace ) << "Ignoring invalid transaction: " << diagnostic_information( _e ); return ImportResult::Malformed; } catch ( std::exception const& _e ) { - LOG( m_loggerDetail ) << "Ignoring invalid transaction: " << _e.what(); + LOG( m_loggerTrace ) << "Ignoring invalid transaction: " << _e.what(); return ImportResult::Malformed; } @@ -313,7 +313,7 @@ u256 TransactionQueue::maxCurrentNonce_WITH_LOCK( Address const& _a ) const { void TransactionQueue::insertCurrent_WITH_LOCK( std::pair< h256, Transaction > const& _p ) { if ( m_currentByHash.count( _p.first ) ) { - cwarn << "Transaction hash" << _p.first << "already in current"; + LOG( m_loggerWarning ) << "Transaction hash" << _p.first << "already in current"; return; } @@ -398,7 +398,7 @@ void TransactionQueue::setFuture_WITH_LOCK( h256 const& _txHash ) { --m_futureSize; m_futureSizeBytes -= m_future.begin()->second.rbegin()->second.transaction.toBytes().size(); auto erasedHash = m_future.begin()->second.rbegin()->second.transaction.sha3(); - LOG( m_loggerDetail ) << "Dropping out of bounds future transaction " << erasedHash; + LOG( m_loggerTrace ) << "Dropping out of bounds future transaction " << erasedHash; m_known.erase( erasedHash ); m_future.begin()->second.erase( --m_future.begin()->second.end() ); if ( m_future.begin()->second.empty() ) @@ -494,8 +494,8 @@ void TransactionQueue::enqueue( RLP const& _data, h512 const& _nodeId ) { unsigned itemCount = _data.itemCount(); for ( unsigned i = 0; i < itemCount; ++i ) { if ( m_unverified.size() >= c_maxVerificationQueueSize ) { - LOG( m_logger ) << "Transaction verification queue is full. Dropping " - << itemCount - i << " transactions"; + LOG( m_loggerInfo ) << "Transaction verification queue is full. Dropping " + << itemCount - i << " transactions"; break; } m_unverified.emplace_back( UnverifiedTransaction( _data[i].data(), _nodeId ) ); @@ -534,7 +534,8 @@ void TransactionQueue::verifierBody() { m_onImport( ir, t.sha3(), work.nodeId ); } catch ( ... ) { // should not happen as exceptions are handled in import. - cwarn << "Bad transaction:" << boost::current_exception_diagnostic_information(); + LOG( m_loggerWarning ) + << "Bad transaction:" << boost::current_exception_diagnostic_information(); } MICROPROFILE_LEAVE(); } diff --git a/libethereum/TransactionQueue.h b/libethereum/TransactionQueue.h index 827935f37..1d4303437 100644 --- a/libethereum/TransactionQueue.h +++ b/libethereum/TransactionQueue.h @@ -345,8 +345,11 @@ class TransactionQueue { mutable Mutex x_queue; ///< Verification queue mutex std::atomic_bool m_aborting; ///< Exit condition for verifier. - Logger m_logger{ createLogger( VerbosityInfo, "tq" ) }; - Logger m_loggerDetail{ createLogger( VerbosityDebug, "tq" ) }; + Logger m_loggerInfo{ createLogger( VerbosityInfo, "TransactionQueue" ) }; + Logger m_loggerDebug{ createLogger( VerbosityDebug, "TransactionQueue" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "TransactionQueue" ) }; + Logger m_loggerError{ createLogger( VerbosityError, "TransactionQueue" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "TransactionQueue" ) }; }; template < class... Args > diff --git a/libethereum/TransactionReceipt.cpp b/libethereum/TransactionReceipt.cpp index f66a8457a..d154ad6dc 100644 --- a/libethereum/TransactionReceipt.cpp +++ b/libethereum/TransactionReceipt.cpp @@ -122,17 +122,19 @@ h256 const& TransactionReceipt::stateRoot() const { std::ostream& dev::eth::operator<<( std::ostream& _out, TransactionReceipt const& _r ) { if ( _r.hasStatusCode() ) - _out << "Status: " << _r.statusCode() << std::endl; + _out << "Status: " << _r.statusCode() << "\n"; else - _out << "Root: " << _r.stateRoot() << std::endl; - _out << "Gas used: " << _r.cumulativeGasUsed() << std::endl; - _out << "Logs: " << _r.log().size() << " entries:" << std::endl; + _out << "Root: " << _r.stateRoot() << "\n"; + _out << "Gas used: " << _r.cumulativeGasUsed() << "\n"; + _out << "Logs: " << _r.log().size() << " entries:" + << "\n"; for ( LogEntry const& i : _r.log() ) { - _out << "Address " << i.address << ". Topics:" << std::endl; + _out << "Address " << i.address << ". Topics:" + << "\n"; for ( auto const& j : i.topics ) - _out << " " << j << std::endl; - _out << " Data: " << toHex( i.data ) << std::endl; + _out << " " << j << "\n"; + _out << " Data: " << toHex( i.data ) << "\n"; } - _out << "Bloom: " << _r.bloom() << std::endl; + _out << "Bloom: " << _r.bloom() << "\n"; return _out; } diff --git a/libethereum/db_repair.cpp b/libethereum/db_repair.cpp index ffccc5660..ca51bddfb 100644 --- a/libethereum/db_repair.cpp +++ b/libethereum/db_repair.cpp @@ -35,21 +35,20 @@ void dump_blocks_and_extras_db( const BlockChain& _bc, size_t _startBlock ) { // block_json["parentHash"] = "suppressed"; // block_json["stateRoot"] = "suppressed"; - cout << "Block " << bn << "\n"; + cdebug << "Block " << bn << "\n"; if ( transaction_hashes.size() || header.timestamp() == prev_ts ) { - cout << block_json << "\n"; - cout << "Transactions: " - << "\n"; + cdebug << block_json << "\n"; + cdebug << "Transactions: " + << "\n"; for ( size_t i = 0; i < transaction_hashes.size(); ++i ) { h256 tx_hash = transaction_hashes[i]; pair< h256, int > loc = _bc.transactionLocation( tx_hash ); - cout << tx_hash << " -> " - << ( loc.first == header.hash() ? "block hash ok" : "block hash error!" ) - << " " << loc.second << "\n"; + cdebug << tx_hash << " -> " + << ( loc.first == header.hash() ? "block hash ok" : "block hash error!" ) + << " " << loc.second; } // for t - cout << "Bloom:" - << "\n"; - cout << bloom.hex() << endl; + cdebug << "Bloom:"; + cdebug << bloom.hex(); } // if prev_ts = header.timestamp(); diff --git a/libevm/EVMC.cpp b/libevm/EVMC.cpp index 95bdbb4e5..24554a549 100644 --- a/libevm/EVMC.cpp +++ b/libevm/EVMC.cpp @@ -39,13 +39,15 @@ EVMC::EVMC( evmc_instance* _instance ) noexcept : evmc::vm( _instance ) { case EVMC_SET_OPTION_SUCCESS: break; case EVMC_SET_OPTION_INVALID_NAME: - cwarn << "Unknown EVMC option '" << pair.first << "'"; + LOG( m_loggerWarning ) << "Unknown EVMC option '" << pair.first << "'"; break; case EVMC_SET_OPTION_INVALID_VALUE: - cwarn << "Invalid value '" << pair.second << "' for EVMC option '" << pair.first << "'"; + LOG( m_loggerWarning ) + << "Invalid value '" << pair.second << "' for EVMC option '" << pair.first << "'"; break; default: - cwarn << "Unknown error when setting EVMC option '" << pair.first << "'"; + LOG( m_loggerWarning ) + << "Unknown error when setting EVMC option '" << pair.first << "'"; } } } @@ -111,7 +113,8 @@ owning_bytes_ref EVMC::exec( u256& io_gas, ExtVMFace& _ext, const OnOpFunc& _onO BOOST_THROW_EXCEPTION( DisallowedStateChange() ); case EVMC_REJECTED: - cwarn << "Execution rejected by EVMC, executing with default VM implementation"; + LOG( m_loggerWarning ) + << "Execution rejected by EVMC, executing with default VM implementation"; return VMFactory::create( VMKind::Legacy )->exec( io_gas, _ext, _onOp ); case EVMC_INTERNAL_ERROR: diff --git a/libevm/EVMC.h b/libevm/EVMC.h index 1ed44fff7..7c3084c14 100644 --- a/libevm/EVMC.h +++ b/libevm/EVMC.h @@ -14,6 +14,9 @@ class EVMC : public evmc::vm, public VMFace { explicit EVMC( evmc_instance* _instance ) noexcept; owning_bytes_ref exec( u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp ) final; + +private: + dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "EVMC" ) }; }; } // namespace eth } // namespace dev diff --git a/libevm/LegacyVMConfig.h b/libevm/LegacyVMConfig.h index 596433270..de2a0de4b 100644 --- a/libevm/LegacyVMConfig.h +++ b/libevm/LegacyVMConfig.h @@ -86,29 +86,29 @@ namespace eth { #undef ON_OP #if EVM_TRACE > 2 #define ON_OP() \ - ( cerr << "### " << ++m_nSteps << ": " << m_PC << " " << instructionInfo( m_OP ).name << endl ) + cerr << "### " << ++m_nSteps << ": " << m_PC << " " << instructionInfo( m_OP ).name << "\n" #else #define ON_OP() onOperation() #endif #define TRACE_STR( level, str ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "$$$ " << ( str ) << endl; + cerr << "$$$ " << ( str ) << "\n"; #define TRACE_VAL( level, name, val ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "=== " << ( name ) << " " << hex << ( val ) << endl; + cerr << "=== " << ( name ) << " " << hex << ( val ) << "\n"; #define TRACE_OP( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "*** " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << "*** " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #define TRACE_PRE_OPT( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "<<< " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << "<<< " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #define TRACE_POST_OPT( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << ">>> " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << ">>> " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #else #define TRACE_STR( level, str ) #define TRACE_VAL( level, name, val ) @@ -120,11 +120,11 @@ namespace eth { // Executive swallows exceptions in some circumstances #if 0 -#define THROW_EXCEPTION( X ) ( ( cerr << "!!! EVM EXCEPTION " << ( X ).what() << endl ), abort() ) +#define THROW_EXCEPTION( X ) ( ( cerr << "EVM EXCEPTION " << ( X ).what() << "\n" ), abort() ) #else #if EVM_TRACE > 0 #define THROW_EXCEPTION( X ) \ - ( ( cerr << "!!! EVM EXCEPTION " << ( X ).what() << endl ), BOOST_THROW_EXCEPTION( X ) ) + ( ( cerr << "EVM EXCEPTION " << ( X ).what() << "\n" ), BOOST_THROW_EXCEPTION( X ) ) #else #define THROW_EXCEPTION( X ) BOOST_THROW_EXCEPTION( X ) #endif diff --git a/libhistoric/AlethExecutive.cpp b/libhistoric/AlethExecutive.cpp index b5c6cc372..ef4de562d 100644 --- a/libhistoric/AlethExecutive.cpp +++ b/libhistoric/AlethExecutive.cpp @@ -92,13 +92,13 @@ void AlethExecutive::initialize( Transaction const& _transaction ) { try { nonceReq = m_s.getNonce( m_t.sender() ); } catch ( InvalidSignature const& ) { - LOG( m_execLogger ) << "Invalid Signature"; + LOG( m_loggerDebug ) << "Invalid Signature"; m_excepted = TransactionException::InvalidSignature; throw; } if ( m_t.nonce() != nonceReq ) { - LOG( m_execLogger ) << "Sender: " << m_t.sender().hex() << " Invalid Nonce: Required " - << nonceReq << ", received " << m_t.nonce(); + LOG( m_loggerDebug ) << "Sender: " << m_t.sender().hex() << " Invalid Nonce: Required " + << nonceReq << ", received " << m_t.nonce(); m_excepted = TransactionException::InvalidNonce; BOOST_THROW_EXCEPTION( InvalidNonce() << RequirementError( ( bigint ) nonceReq, ( bigint ) m_t.nonce() ) ); @@ -108,9 +108,9 @@ void AlethExecutive::initialize( Transaction const& _transaction ) { bigint gasCost = ( bigint ) m_t.gas() * m_t.gasPrice(); bigint totalCost = m_t.value() + gasCost; if ( m_s.balance( m_t.sender() ) < totalCost ) { - LOG( m_execLogger ) << "Not enough cash: Require > " << totalCost << " = " << m_t.gas() - << " * " << m_t.gasPrice() << " + " << m_t.value() << " Got" - << m_s.balance( m_t.sender() ) << " for sender: " << m_t.sender(); + LOG( m_loggerDebug ) << "Not enough cash: Require > " << totalCost << " = " << m_t.gas() + << " * " << m_t.gasPrice() << " + " << m_t.value() << " Got" + << m_s.balance( m_t.sender() ) << " for sender: " << m_t.sender(); m_excepted = TransactionException::NotEnoughCash; BOOST_THROW_EXCEPTION( NotEnoughCash() << RequirementError( totalCost, ( bigint ) m_s.balance( m_t.sender() ) ) @@ -124,8 +124,8 @@ bool AlethExecutive::execute() { // Entry point for a user-executed transaction. // Pay... - LOG( m_detailsLogger ) << "Paying " << formatBalance( m_gasCost ) << " from sender for gas (" - << m_t.gas() << " gas at " << formatBalance( m_t.gasPrice() ) << ")"; + LOG( m_loggerTrace ) << "Paying " << formatBalance( m_gasCost ) << " from sender for gas (" + << m_t.gas() << " gas at " << formatBalance( m_t.gasPrice() ) << ")"; m_s.subBalance( m_t.sender(), m_gasCost ); assert( m_t.gas() >= ( u256 ) m_baseGasRequired ); @@ -262,7 +262,7 @@ bool AlethExecutive::executeCreate( Address const& _sender, u256 const& _endowme bool accountAlreadyExist = ( m_s.addressHasCode( m_newAddress ) || m_s.getNonce( m_newAddress ) > 0 ); if ( accountAlreadyExist ) { - LOG( m_detailsLogger ) << "Address already used: " << m_newAddress; + LOG( m_loggerTrace ) << "Address already used: " << m_newAddress; m_gas = 0; m_excepted = TransactionException::AddressAlreadyUsed; revert(); @@ -294,21 +294,19 @@ bool AlethExecutive::executeCreate( Address const& _sender, u256 const& _endowme } OnOpFunc AlethExecutive::simpleTrace() { - Logger& traceLogger = m_vmTraceLogger; - - return [&traceLogger]( uint64_t steps, uint64_t PC, Instruction inst, bigint newMemSize, - bigint gasCost, bigint gas, VMFace const* _vm, ExtVMFace const* voidExt ) { + return [this]( uint64_t steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, + bigint gas, VMFace const* _vm, ExtVMFace const* voidExt ) { AlethExtVM const& ext = *static_cast< AlethExtVM const* >( voidExt ); auto vm = dynamic_cast< LegacyVM const* >( _vm ); if ( vm ) - LOG( traceLogger ) << dumpStackAndMemory( *vm ); - LOG( traceLogger ) << dumpStorage( ext ); - LOG( traceLogger ) << " < " << dec << ext.depth << " : " << ext.myAddress << " : #" << steps - << " : " << hex << setw( 4 ) << setfill( '0' ) << PC << " : " - << instructionInfo( inst ).name << " : " << dec << gas << " : -" << dec - << gasCost << " : " << newMemSize << "x32" - << " >"; + LOG( m_loggerTrace ) << dumpStackAndMemory( *vm ); + LOG( m_loggerTrace ) << dumpStorage( ext ); + LOG( m_loggerTrace ) << " < " << dec << ext.depth << " : " << ext.myAddress << " : #" + << steps << " : " << hex << setw( 4 ) << setfill( '0' ) << PC << " : " + << instructionInfo( inst ).name << " : " << dec << gas << " : -" << dec + << gasCost << " : " << newMemSize << "x32" + << " >"; }; } @@ -351,13 +349,13 @@ bool AlethExecutive::go( OnOpFunc const& _onOp ) { m_output = _e.output(); m_excepted = TransactionException::RevertInstruction; } catch ( VMException const& _e ) { - LOG( m_detailsLogger ) << "Safe VM Exception. " << diagnostic_information( _e ); + LOG( m_loggerTrace ) << "Safe VM Exception. " << diagnostic_information( _e ); m_gas = 0; m_excepted = toTransactionException( _e ); revert(); } catch ( InternalVMError const& _e ) { - cerror << "Internal VM Error (EVMC status code: " - << *boost::get_error_info< errinfo_evmcStatusCode >( _e ) << ")"; + LOG( m_loggerError ) << "Internal VM Error (EVMC status code: " + << *boost::get_error_info< errinfo_evmcStatusCode >( _e ) << ")"; revert(); throw; #ifdef HISTORIC_STATE @@ -369,15 +367,17 @@ bool AlethExecutive::go( OnOpFunc const& _onOp ) { } catch ( Exception const& _e ) { // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it // does. - cerror << "Unexpected exception in VM. There may be a bug in this implementation. " - << diagnostic_information( _e ); + LOG( m_loggerError ) + << "Unexpected exception in VM. There may be a bug in this implementation. " + << diagnostic_information( _e ); exit( 1 ); // Another solution would be to reject this transaction, but that also // has drawbacks. Essentially, the amount of ram has to be increased here. } catch ( std::exception const& _e ) { // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it // does. - cerror << "Unexpected std::exception in VM. Not enough RAM? " << _e.what(); + LOG( m_loggerError ) << "Unexpected std::exception in VM. Not enough RAM? " + << _e.what(); exit( 1 ); // Another solution would be to reject this transaction, but that also // has drawbacks. Essentially, the amount of ram has to be increased here. @@ -388,7 +388,7 @@ bool AlethExecutive::go( OnOpFunc const& _onOp ) { m_res->output = m_output.toVector(); #if ETH_TIMED_EXECUTIONS - cnote << "VM took:" << t.elapsed() << "; gas used: " << ( sgas - m_endGas ); + LOG( m_loggerInfo ) << "VM took:" << t.elapsed() << "; gas used: " << ( sgas - m_endGas ); #endif } return true; diff --git a/libhistoric/AlethExecutive.h b/libhistoric/AlethExecutive.h index eb61ea2d1..fb42fbb49 100644 --- a/libhistoric/AlethExecutive.h +++ b/libhistoric/AlethExecutive.h @@ -173,9 +173,10 @@ class AlethExecutive { Address m_newAddress; size_t m_savepoint = 0; - Logger m_execLogger{ createLogger( VerbosityDebug, "exec" ) }; - Logger m_detailsLogger{ createLogger( VerbosityTrace, "exec" ) }; - Logger m_vmTraceLogger{ createLogger( VerbosityTrace, "vmtrace" ) }; + Logger m_loggerDebug{ createLogger( VerbosityDebug, "AlethExecutive" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "AlethExecutive" ) }; + Logger m_loggerError{ createLogger( VerbosityError, "AlethExecutive" ) }; + Logger m_loggerInfo{ createLogger( VerbosityInfo, "AlethExecutive" ) }; }; } // namespace eth diff --git a/libhistoric/HistoricState.cpp b/libhistoric/HistoricState.cpp index 9f3938a71..74a4aab7b 100644 --- a/libhistoric/HistoricState.cpp +++ b/libhistoric/HistoricState.cpp @@ -52,47 +52,45 @@ OverlayDB HistoricState::openDB( DatabasePaths const dbPaths{ _basePath, _genesisHash }; if ( db::isDiskDatabase() ) { if ( _we == WithExisting::Kill ) { - clog( VerbosityInfo, "statedb" ) << "Deleting state database: " << dbPaths.statePath(); + LOG( m_loggerInfo ) << "Deleting state database: " << dbPaths.statePath(); fs::remove_all( dbPaths.statePath() ); } - clog( VerbosityDebug, "statedb" ) - << "Verifying path exists (and creating if not present): " << dbPaths.chainPath(); + LOG( m_loggerDebug ) << "Verifying path exists (and creating if not present): " + << dbPaths.chainPath(); fs::create_directories( dbPaths.chainPath() ); - clog( VerbosityDebug, "statedb" ) - << "Ensuring permissions are set for path: " << dbPaths.chainPath(); + LOG( m_loggerDebug ) << "Ensuring permissions are set for path: " << dbPaths.chainPath(); DEV_IGNORE_EXCEPTIONS( fs::permissions( dbPaths.chainPath(), fs::owner_all ) ); } try { - clog( VerbosityTrace, "statedb" ) << "Opening state database"; + LOG( m_loggerTrace ) << "Opening state database"; std::unique_ptr< db::DatabaseFace > db = db::DBFactory::createHistoric( db::DatabaseKind::LevelDB, dbPaths.statePath() ); return OverlayDB( std::move( db ) ); } catch ( boost::exception const& ex ) { if ( db::isDiskDatabase() ) { - clog( VerbosityError, "statedb" ) - << "Error opening state database: " << dbPaths.statePath(); + LOG( m_loggerError ) << "Error opening state database: " << dbPaths.statePath(); db::DatabaseStatus const dbStatus = *boost::get_error_info< db::errinfo_dbStatusCode >( ex ); if ( fs::space( dbPaths.statePath() ).available < 1024 ) { - clog( VerbosityError, "statedb" ) + LOG( m_loggerError ) << "Not enough available space found on hard drive. Please free some up and " "then re-run. Bailing."; BOOST_THROW_EXCEPTION( NotEnoughAvailableSpace() ); } else if ( dbStatus == db::DatabaseStatus::Corruption ) { - clog( VerbosityError, "statedb" ) + LOG( m_loggerError ) << "Database corruption detected. Please see the exception for corruption " "details. Exception: " << boost::diagnostic_information( ex ); BOOST_THROW_EXCEPTION( DatabaseCorruption() ); } else if ( dbStatus == db::DatabaseStatus::IOError ) { - clog( VerbosityError, "statedb" ) << "Database already open. You appear to have " - "another instance of Aleth running."; + LOG( m_loggerError ) << "Database already open. You appear to have " + "another instance of Aleth running."; BOOST_THROW_EXCEPTION( DatabaseAlreadyOpen() ); } } - clog( VerbosityError, "statedb" ) + LOG( m_loggerError ) << "Unknown error encountered when opening state database. Exception details: " << boost::diagnostic_information( ex ); throw; @@ -657,7 +655,7 @@ bool HistoricState::executeTransaction( } std::ostream& dev::eth::operator<<( std::ostream& _out, HistoricState const& _s ) { - _out << "--- " << _s.globalRoot() << std::endl; + _out << "--- " << _s.globalRoot() << "\n"; std::set< Address > d; std::set< Address > dtr; auto trie = @@ -675,7 +673,7 @@ std::ostream& dev::eth::operator<<( std::ostream& _out, HistoricState const& _s assert( cache || r ); if ( cache && !cache->isAlive() ) - _out << "XXX " << i << std::endl; + _out << "XXX " << i << "\n"; else { string lead = ( cache ? r ? " * " : " + " : " " ); if ( cache && r && cache->nonce() == r[0].toInt< u256 >() && @@ -719,7 +717,7 @@ std::ostream& dev::eth::operator<<( std::ostream& _out, HistoricState const& _s for ( auto const& j : mem ) if ( j.second ) - contout << std::endl + contout << "\n" << ( delta.count( j.first ) ? back.count( j.first ) ? " * " : " + " : cached.count( j.first ) ? " . " : @@ -727,7 +725,7 @@ std::ostream& dev::eth::operator<<( std::ostream& _out, HistoricState const& _s << std::hex << nouppercase << std::setw( 64 ) << j.first << ": " << std::setw( 0 ) << j.second; else - contout << std::endl + contout << "\n" << "XXX " << std::hex << nouppercase << std::setw( 64 ) << j.first << ""; } else @@ -735,7 +733,7 @@ std::ostream& dev::eth::operator<<( std::ostream& _out, HistoricState const& _s _out << lead << i << ": " << std::dec << ( cache ? cache->nonce() : r[0].toInt< u256 >() ) << " #:" << ( cache ? cache->balance() : r[1].toInt< u256 >() ) << contout.str() - << std::endl; + << "\n"; } } return _out; diff --git a/libhistoric/HistoricState.h b/libhistoric/HistoricState.h index 8c3a8cb4a..b90a1a776 100644 --- a/libhistoric/HistoricState.h +++ b/libhistoric/HistoricState.h @@ -349,6 +349,12 @@ class HistoricState { AccountMap const& _cache, SecureTrieDB< Address, OverlayDB >& _state ); uint64_t m_totalTimeSpentInStateCommitsPerBlock = 0; + + /// Loggers + static inline Logger m_loggerInfo{ createLogger( VerbosityInfo, "HistoricState" ) }; + static inline Logger m_loggerTrace{ createLogger( VerbosityTrace, "HistoricState" ) }; + static inline Logger m_loggerDebug{ createLogger( VerbosityDebug, "HistoricState" ) }; + static inline Logger m_loggerError{ createLogger( VerbosityError, "HistoricState" ) }; }; std::ostream& operator<<( std::ostream& _out, HistoricState const& _s ); diff --git a/libskale-interpreter/VMConfig.h b/libskale-interpreter/VMConfig.h index 48bf5a85d..763a07291 100644 --- a/libskale-interpreter/VMConfig.h +++ b/libskale-interpreter/VMConfig.h @@ -75,29 +75,29 @@ namespace eth { #undef ON_OP #if EVM_TRACE > 2 #define ON_OP() \ - ( cerr << "### " << ++m_nSteps << ": " << m_PC << " " << instructionInfo( m_OP ).name << endl ) + ( cerr << "### " << ++m_nSteps << ": " << m_PC << " " << instructionInfo( m_OP ).name << "\n" ) #else #define ON_OP() onOperation() #endif #define TRACE_STR( level, str ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "$$$ " << ( str ) << endl; + cerr << "$$$ " << ( str ) << "\n"; #define TRACE_VAL( level, name, val ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "=== " << ( name ) << " " << hex << ( val ) << endl; + cerr << "=== " << ( name ) << " " << hex << ( val ) << "\n"; #define TRACE_OP( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "*** " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << "*** " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #define TRACE_PRE_OPT( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << "<<< " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << "<<< " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #define TRACE_POST_OPT( level, pc, op ) \ if ( ( level ) <= EVM_TRACE ) \ - cerr << ">>> " << ( pc ) << " " << instructionInfo( op ).name << endl; + cerr << ">>> " << ( pc ) << " " << instructionInfo( op ).name << "\n"; #else #define TRACE_STR( level, str ) #define TRACE_VAL( level, name, val ) @@ -109,11 +109,11 @@ namespace eth { // Executive swallows exceptions in some circumstances #if 0 -#define THROW_EXCEPTION( X ) ( ( cerr << "!!! EVM EXCEPTION " << ( X ).what() << endl ), abort() ) +#define THROW_EXCEPTION( X ) ( ( cerr << "EVM EXCEPTION " << ( X ).what() << "\n" ), abort() ) #else #if EVM_TRACE > 0 #define THROW_EXCEPTION( X ) \ - ( ( cerr << "!!! EVM EXCEPTION " << ( X ).what() << endl ), BOOST_THROW_EXCEPTION( X ) ) + ( ( cerr << "EVM EXCEPTION " << ( X ).what() << "\n" ), BOOST_THROW_EXCEPTION( X ) ) #else #define THROW_EXCEPTION( X ) BOOST_THROW_EXCEPTION( X ) #endif diff --git a/libskale/AmsterdamFixPatch.cpp b/libskale/AmsterdamFixPatch.cpp index 8d7422aff..c5a47fa8e 100644 --- a/libskale/AmsterdamFixPatch.cpp +++ b/libskale/AmsterdamFixPatch.cpp @@ -62,8 +62,8 @@ bool AmsterdamFixPatch::isInitOnChainNeeded( totalStorageUsed = std::stoull( totalStorageUsedStr ); if ( totalStorageUsed != best_number * 32 ) - clog( VerbosityInfo, "AmsterdamFixPatch" ) - << "Will fix old stateRoots because totalStorageUsed = " << totalStorageUsed; + LOG( m_loggerInfo ) << "Will fix old stateRoots because totalStorageUsed = " + << totalStorageUsed; return totalStorageUsed != best_number * 32; } catch ( ... ) { @@ -126,8 +126,7 @@ void AmsterdamFixPatch::initOnChain( batched_io::db_operations_face& _blocksDB, h256 prev_hash; BlockDetails prev_details; - clog( VerbosityInfo, "AmsterdamFixPatch" ) - << "Repairing stateRoots using base block " << start_block; + LOG( m_loggerInfo ) << "Repairing stateRoots using base block " << start_block; for ( size_t bn = start_block;; ++bn ) { // read block @@ -200,7 +199,8 @@ void AmsterdamFixPatch::initOnChain( batched_io::db_operations_face& _blocksDB, if ( bn == start_block + 1 || old_hash == best_hash || transactions.size() || bn % 1000 == 0 ) - cout << "Repairing block " << bn << " " << old_hash << " -> " << new_hash << endl; + LOG( m_loggerInfo ) << "Repairing block " << bn << " " << old_hash << " -> " + << new_hash; TransactionAddress ta; ta.blockHash = new_hash; @@ -209,8 +209,8 @@ void AmsterdamFixPatch::initOnChain( batched_io::db_operations_face& _blocksDB, for ( size_t i = 0; i < transactions.size(); ++i ) { h256 hash = sha3( transactions[i].data() ); ta.index = i; - cout << "Updating transaction " << hash << " location " << old_hash << " -> " - << new_hash << " " << ta.index << endl; + LOG( m_loggerInfo ) << "Updating transaction " << hash << " location " << old_hash + << " -> " << new_hash << " " << ta.index; _extrasDB.insert( toSlice( hash, ExtraTransactionAddress ), ( db::Slice ) dev::ref( ta.rlp() ) ); } // for @@ -225,7 +225,7 @@ void AmsterdamFixPatch::initOnChain( batched_io::db_operations_face& _blocksDB, _extrasDB.insert( db::Slice( "best" ), db::Slice( ( const char* ) new_hash.data(), 32 ) ); _db.commit( "repair_best" ); - clog( VerbosityInfo, "AmsterdamFixPatch" ) << "Repaired till block " << bn; + LOG( m_loggerInfo ) << "Repaired till block " << bn; break; } diff --git a/libskale/AmsterdamFixPatch.h b/libskale/AmsterdamFixPatch.h index c7f08771a..80caf0c7e 100644 --- a/libskale/AmsterdamFixPatch.h +++ b/libskale/AmsterdamFixPatch.h @@ -32,6 +32,10 @@ class AmsterdamFixPatch : public SchainPatch { static dev::h256 newStateRootForAll; static size_t lastBlockToModify; static std::vector< size_t > majorityNodesIds(); + +private: + static inline dev::Logger m_loggerInfo{ dev::createLogger( + dev::VerbosityInfo, "AmsterdamFixPatch" ) }; }; #endif // AMSTERDAMFIXPATCH_H diff --git a/libskale/OverlayDB.cpp b/libskale/OverlayDB.cpp index 766ab028b..d9fe1199e 100644 --- a/libskale/OverlayDB.cpp +++ b/libskale/OverlayDB.cpp @@ -72,12 +72,7 @@ dev::db::Slice toSlice( std::string const& _s ) { }; // namespace slicing OverlayDB::OverlayDB( std::unique_ptr< batched_io::db_face > _db_face ) - : m_db_face( _db_face.release(), []( batched_io::db_face* db ) { - // clog(dev::VerbosityDebug, "overlaydb") << "Closing state DB"; - // std::cerr << "!!! Closing state DB !!!" << std::endl; - // std::cerr.flush(); - delete db; - } ) {} + : m_db_face( _db_face.release(), []( batched_io::db_face* db ) { delete db; } ) {} dev::h256 OverlayDB::getLastExecutedTransactionHash() const { if ( lastExecutedTransactionHash.has_value() ) @@ -234,24 +229,28 @@ void OverlayDB::commit() { break; } catch ( boost::exception const& ex ) { if ( commitTry == 9 ) { - cwarn << "Fail(1) writing to state database. Bombing out. "; - cwarn << DETAILED_ERROR; + LOG( m_loggerWarning ) << "Fail(1) writing to state database. Bombing out. "; + LOG( m_loggerWarning ) << DETAILED_ERROR; exit( -1 ); } cerror << "Error(2) writing to state database (during DB commit): " << boost::diagnostic_information( ex ); - cwarn << "Error writing to state database: " << boost::diagnostic_information( ex ); - cwarn << "Sleeping for" << ( commitTry + 1 ) << "seconds, then retrying."; + LOG( m_loggerWarning ) + << "Error writing to state database: " << boost::diagnostic_information( ex ); + LOG( m_loggerWarning ) + << "Sleeping for" << ( commitTry + 1 ) << "seconds, then retrying."; std::this_thread::sleep_for( std::chrono::seconds( commitTry + 1 ) ); } catch ( std::exception const& ex ) { if ( commitTry == 9 ) { - cwarn << "Fail(2) writing to state database. Bombing out. "; - cwarn << DETAILED_ERROR; + LOG( m_loggerWarning ) << "Fail(2) writing to state database. Bombing out. "; + LOG( m_loggerWarning ) << DETAILED_ERROR; exit( -1 ); } - cerror << "Error(2) writing to state database (during DB commit): " << ex.what(); - cwarn << "Error(2) writing to state database: " << ex.what(); - cwarn << "Sleeping for" << ( commitTry + 1 ) << "seconds, then retrying."; + LOG( m_loggerError ) + << "Error(2) writing to state database (during DB commit): " << ex.what(); + LOG( m_loggerWarning ) << "Error(2) writing to state database: " << ex.what(); + LOG( m_loggerWarning ) + << "Sleeping for" << ( commitTry + 1 ) << "seconds, then retrying."; std::this_thread::sleep_for( std::chrono::seconds( commitTry + 1 ) ); } } @@ -265,7 +264,7 @@ void OverlayDB::commit() { m_db_face->revert(); } } else { - cnote << "Try to commit into closed or not initialized DB"; + LOG( m_loggerInfo ) << "Try to commit into closed or not initialized DB"; } } @@ -284,7 +283,7 @@ string OverlayDB::lookupAuxiliary( h160 const& _address, _byte_ _space ) const { std::string const loadedValue = m_db_face->lookup( skale::slicing::toSlice( getAuxiliaryKey( _address, _space ) ) ); if ( loadedValue.empty() ) - cwarn << "Aux not found: " << _address; + LOG( m_loggerWarning ) << "Aux not found: " << _address; return loadedValue; } @@ -309,7 +308,8 @@ void OverlayDB::killAuxiliary( const dev::h160& _address, _byte_ _space ) { // NB! This is not committed! So, this can be reverted m_db_face->kill( skale::slicing::toSlice( key ) ); } else { - ctrace << "Try to delete non existing key " << _address << "(" << _space << ")"; + LOG( m_loggerTrace ) + << "Try to delete non existing key " << _address << "(" << _space << ")"; } } } @@ -331,7 +331,7 @@ void OverlayDB::insertAuxiliary( } std::unordered_map< h160, string > OverlayDB::accounts() const { - cnote << "Iterating over all accounts in state"; + LOG( m_loggerInfo ) << "Iterating over all accounts in state"; unordered_map< h160, string > accounts; if ( m_db_face ) { m_db_face->forEach( [&accounts]( Slice key, Slice value ) { @@ -354,24 +354,25 @@ std::unordered_map< u256, u256 > OverlayDB::storage( const dev::h160& _address ) if ( m_db_face ) { // iterate of a keys that start with the given substring string prefix( ( const char* ) _address.data(), _address.size ); - m_db_face->forEachWithPrefix( prefix, [&storage, &_address]( Slice key, Slice value ) { - if ( key.size() == h160::size + h256::size ) { - // key is storage address - string keyString( key.begin(), key.end() ); - h160 address = h160( - keyString.substr( 0, h160::size ), h160::ConstructFromStringType::FromBinary ); - if ( address == _address ) { - h256 memoryAddress = h256( - keyString.substr( h160::size ), h256::ConstructFromStringType::FromBinary ); - u256 memoryValue = h256( string( value.begin(), value.end() ), - h256::ConstructFromStringType::FromBinary ); - storage[memoryAddress] = memoryValue; - } else { - cerror << "Address mismatch in:" << __FUNCTION__; + m_db_face->forEachWithPrefix( + prefix, [this, &storage, &_address]( Slice key, Slice value ) { + if ( key.size() == h160::size + h256::size ) { + // key is storage address + string keyString( key.begin(), key.end() ); + h160 address = h160( keyString.substr( 0, h160::size ), + h160::ConstructFromStringType::FromBinary ); + if ( address == _address ) { + h256 memoryAddress = h256( keyString.substr( h160::size ), + h256::ConstructFromStringType::FromBinary ); + u256 memoryValue = h256( string( value.begin(), value.end() ), + h256::ConstructFromStringType::FromBinary ); + storage[memoryAddress] = memoryValue; + } else { + LOG( m_loggerError ) << "Address mismatch in:" << __FUNCTION__; + } } - } - return true; - } ); + return true; + } ); } else { cerror << "Try to load account's storage but connection to database is not established"; } @@ -382,7 +383,7 @@ void OverlayDB::copyStorageIntoAccountMap( dev::eth::AccountMap& _map ) const { static uint64_t counter = 0; if ( m_db_face ) { - m_db_face->forEach( [&_map]( Slice key, Slice value ) { + m_db_face->forEach( [this, &_map]( Slice key, Slice value ) { if ( key.size() == h160::size + h256::size ) { // key is storage address string keyString( key.begin(), key.end() ); @@ -397,18 +398,17 @@ void OverlayDB::copyStorageIntoAccountMap( dev::eth::AccountMap& _map ) const { [[maybe_unused]] u256 memoryValue = h256( string( value.begin(), value.end() ), h256::ConstructFromStringType::FromBinary ); - _map.at( address ).setStorage( memoryAddress, memoryValue ); counter++; if ( counter % 1000000 == 0 ) { - std::cout << "."; - std::cout.flush(); + LOG( m_loggerDebug ) << "."; + LOG( m_loggerDebug ).flush(); } } return true; } ); - std::cout << std::endl; + LOG( m_loggerInfo ) << "\n"; } else { cerror << "Try to load account's storage but connection to database is not established"; } @@ -497,7 +497,7 @@ void OverlayDB::kill( h160 const& _h ) { // NB! This is not committed! So, this can be reverted m_db_face->kill( skale::slicing::toSlice( _h ) ); } else { - ctrace << "Try to delete non existing key " << _h; + LOG( m_loggerTrace ) << "Try to delete non existing key " << _h; } } } diff --git a/libskale/OverlayDB.h b/libskale/OverlayDB.h index 2c504a7d1..cddbf6e4a 100644 --- a/libskale/OverlayDB.h +++ b/libskale/OverlayDB.h @@ -124,6 +124,13 @@ class OverlayDB { mutable std::optional< dev::h256 > lastExecutedTransactionHash; + /// Loggers + mutable dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "OverlayDB" ) }; + mutable dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "OverlayDB" ) }; + mutable dev::Logger m_loggerTrace{ dev::createLogger( dev::VerbosityTrace, "OverlayDB" ) }; + mutable dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "OverlayDB" ) }; + mutable dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "OverlayDB" ) }; + public: std::shared_ptr< batched_io::db_face > db() { return m_db_face; } void copyStorageIntoAccountMap( dev::eth::AccountMap& _map ) const; diff --git a/libskale/OverlayFS.cpp b/libskale/OverlayFS.cpp index d9867249e..b1d1b314d 100644 --- a/libskale/OverlayFS.cpp +++ b/libskale/OverlayFS.cpp @@ -45,9 +45,9 @@ bool CreateFileOp::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in CreateFileOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in CreateFileOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in CreateFileOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in CreateFileOp\n"; } return false; } @@ -64,9 +64,9 @@ bool CreateDirectoryOp::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in createDirectoryOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in createDirectoryOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in createDirectoryOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in createDirectoryOp\n"; } return false; } @@ -82,9 +82,9 @@ bool DeleteFileOp::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in DeleteFileOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in DeleteFileOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in DeleteFileOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in DeleteFileOp\n"; } return false; } @@ -100,9 +100,9 @@ bool DeleteDirectoryOp::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in DeleteDirectoryOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in DeleteDirectoryOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in DeleteDirectoryOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in DeleteDirectoryOp\n"; } return false; } @@ -118,9 +118,9 @@ bool WriteChunkOp::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in WriteChunkOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in WriteChunkOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in WriteChunkOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in WriteChunkOp\n"; } return false; } @@ -160,9 +160,9 @@ bool CalculateFileHash::execute() { std::string strError = ex.what(); if ( strError.empty() ) strError = "exception without description"; - LOG( m_logger ) << "Exception in WriteHashFileOp: " << strError << "\n"; + LOG( m_loggerDebug ) << "Exception in WriteHashFileOp: " << strError << "\n"; } catch ( ... ) { - LOG( m_logger ) << "Unknown exception in WriteHashFileOp\n"; + LOG( m_loggerDebug ) << "Unknown exception in WriteHashFileOp\n"; } return false; } diff --git a/libskale/OverlayFS.h b/libskale/OverlayFS.h index 317282d7a..db2750f1d 100644 --- a/libskale/OverlayFS.h +++ b/libskale/OverlayFS.h @@ -35,7 +35,7 @@ namespace skale { class BaseOp { public: virtual bool execute() = 0; - dev::Logger m_logger{ createLogger( dev::VerbosityDebug, "fs" ) }; + dev::Logger m_loggerDebug{ createLogger( dev::VerbosityDebug, "fs" ) }; }; class CreateFileOp : public BaseOp { diff --git a/libskale/SnapshotHashAgent.cpp b/libskale/SnapshotHashAgent.cpp index d4c504689..f33986824 100644 --- a/libskale/SnapshotHashAgent.cpp +++ b/libskale/SnapshotHashAgent.cpp @@ -89,7 +89,7 @@ size_t SnapshotHashAgent::verifyAllData() const { this->hashes_.at( i ).asArray() ), this->signatures_.at( i ), this->public_keys_.at( i ) ); } catch ( std::exception& ex ) { - cerror << ex.what(); + LOG( m_loggerError ) << ex.what(); } verified += is_verified; @@ -125,7 +125,7 @@ bool SnapshotHashAgent::voteForHash() { std::map< dev::h256, size_t >::iterator it; it = std::find_if( map_hash.begin(), map_hash.end(), [this]( const std::pair< dev::h256, size_t > p ) { return 3 * p.second > 2 * this->n_; } ); - cnote << "Snapshot hash is: " << ( *it ).first << ". Verifying it..."; + LOG( m_loggerInfo ) << "Snapshot hash is: " << ( *it ).first << ". Verifying it..."; if ( it == map_hash.end() ) { throw NotEnoughVotesException( "note enough votes to choose hash" ); @@ -152,11 +152,11 @@ bool SnapshotHashAgent::voteForHash() { libBLS::ThresholdUtils::LagrangeCoeffs( idx, ( 2 * this->n_ + 1 ) / 3 ); common_signature = this->bls_->SignatureRecover( signatures, lagrange_coeffs ); } catch ( libBLS::ThresholdUtils::IncorrectInput& ex ) { - cerror << "Exception while recovering common signature from other skaleds: " - << ex.what(); + LOG( m_loggerError ) + << "Exception while recovering common signature from other skaleds: " << ex.what(); } catch ( libBLS::ThresholdUtils::IsNotWellFormed& ex ) { - cerror << "Exception while recovering common signature from other skaleds: " - << ex.what(); + LOG( m_loggerError ) + << "Exception while recovering common signature from other skaleds: " << ex.what(); } bool is_verified = false; @@ -167,14 +167,15 @@ bool SnapshotHashAgent::voteForHash() { std::make_shared< std::array< uint8_t, 32 > >( ( *it ).first.asArray() ), common_signature, this->commonPublicKey_ ); } catch ( libBLS::ThresholdUtils::IsNotWellFormed& ex ) { - cerror << "Exception while verifying common signature from other skaleds: " - << ex.what(); + LOG( m_loggerError ) + << "Exception while verifying common signature from other skaleds: " << ex.what(); } if ( !is_verified ) { - cerror << "Common BLS signature wasn't verified, probably using incorrect " - "common public key specified in command line. Trying again with " - "common public key from config"; + LOG( m_loggerError ) + << "Common BLS signature wasn't verified, probably using incorrect " + "common public key specified in command line. Trying again with " + "common public key from config"; libff::alt_bn128_G2 commonPublicKey_from_config; commonPublicKey_from_config.X.c0 = @@ -186,24 +187,26 @@ bool SnapshotHashAgent::voteForHash() { commonPublicKey_from_config.Y.c1 = libff::alt_bn128_Fq( this->chainParams_.nodeInfo.commonBLSPublicKeys[3].c_str() ); commonPublicKey_from_config.Z = libff::alt_bn128_Fq2::one(); - std::cout << "NEW BLS COMMON PUBLIC KEY:\n"; + LOG( m_loggerDebug ) << "NEW BLS COMMON PUBLIC KEY:"; commonPublicKey_from_config.print_coordinates(); try { is_verified = this->bls_->Verification( std::make_shared< std::array< uint8_t, 32 > >( ( *it ).first.asArray() ), common_signature, commonPublicKey_from_config ); } catch ( libBLS::ThresholdUtils::IsNotWellFormed& ex ) { - cerror << "Exception while verifying common signature from other skaleds: " - << ex.what(); + LOG( m_loggerError ) + << "Exception while verifying common signature from other skaleds: " + << ex.what(); } if ( !is_verified ) { - cerror << "Common BLS signature wasn't verified, snapshot will not be " - "downloaded. Try to backup node manually using skale-node-cli."; + LOG( m_loggerError ) + << "Common BLS signature wasn't verified, snapshot will not be " + "downloaded. Try to backup node manually using skale-node-cli."; return false; } else { - cnote << "Common BLS signature was verified with common public key " - "from config."; + LOG( m_loggerInfo ) << "Common BLS signature was verified with common public key " + "from config."; this->commonPublicKey_ = commonPublicKey_from_config; } } @@ -226,24 +229,25 @@ std::tuple< dev::h256, libff::alt_bn128_G1, libff::alt_bn128_G2 > SnapshotHashAg try { joSignatureResponse = skaleClient.skale_getSnapshotSignature( blockNumber ); } catch ( jsonrpc::JsonRpcException& ex ) { - cerror << "WARNING " - << "Error while trying to get snapshot signature from " << url << " : " << ex.what(); + LOG( m_loggerError ) << "WARNING " + << "Error while trying to get snapshot signature from " << url << " : " + << ex.what(); delete jsonRpcClient; return {}; } if ( !joSignatureResponse.get( "hash", 0 ) || !joSignatureResponse.get( "X", 0 ) || !joSignatureResponse.get( "Y", 0 ) ) { - cerror << "WARNING " - << " Signature from " + url + - "-th node was not received during " - "getNodesToDownloadSnapshotFrom "; + LOG( m_loggerError ) << "WARNING " + << " Signature from " + url + + "-th node was not received during " + "getNodesToDownloadSnapshotFrom "; delete jsonRpcClient; return {}; } else { std::string strHash = joSignatureResponse["hash"].asString(); - cnote << "Received snapshot hash from " << url << " : " << strHash << '\n'; + LOG( m_loggerInfo ) << "Received snapshot hash from " << url << " : " << strHash; libff::alt_bn128_G1 signature = libff::alt_bn128_G1( libff::alt_bn128_Fq( joSignatureResponse["X"].asCString() ), @@ -301,8 +305,9 @@ std::vector< std::string > SnapshotHashAgent::getNodesToDownloadSnapshotFrom( this->public_keys_.at( i ) = std::get< 2 >( snapshotData ); } } catch ( std::exception& ex ) { - cerror << "Exception while collecting snapshot signatures from other skaleds: " - << ex.what(); + LOG( m_loggerError ) + << "Exception while collecting snapshot signatures from other skaleds: " + << ex.what(); } } ) ); } @@ -349,13 +354,15 @@ std::vector< std::string > SnapshotHashAgent::getNodesToDownloadSnapshotFrom( try { result = this->voteForHash(); } catch ( SnapshotHashAgentException& ex ) { - cerror << "Exception while voting for snapshot hash from other skaleds: " << ex.what(); + LOG( m_loggerError ) << "Exception while voting for snapshot hash from other skaleds: " + << ex.what(); } catch ( std::exception& ex ) { - cerror << "Exception while voting for snapshot hash from other skaleds: " << ex.what(); + LOG( m_loggerError ) << "Exception while voting for snapshot hash from other skaleds: " + << ex.what(); } // catch if ( !result ) { - cnote << "Not enough nodes to choose snapshot hash for block " << blockNumber; + LOG( m_loggerInfo ) << "Not enough nodes to choose snapshot hash for block " << blockNumber; return {}; } diff --git a/libskale/SnapshotHashAgent.h b/libskale/SnapshotHashAgent.h index 23a8b5861..ba4d50d4e 100644 --- a/libskale/SnapshotHashAgent.h +++ b/libskale/SnapshotHashAgent.h @@ -96,6 +96,14 @@ class SnapshotHashAgent { std::pair< dev::h256, libff::alt_bn128_G1 > votedHash_; size_t verifyAllData() const; + + /// Loggers + mutable dev::Logger m_loggerDebug{ dev::createLogger( + dev::VerbosityDebug, "SnapshotHashAgent" ) }; + mutable dev::Logger m_loggerInfo{ dev::createLogger( + dev::VerbosityInfo, "SnapshotHashAgent" ) }; + mutable dev::Logger m_loggerError{ dev::createLogger( + dev::VerbosityError, "SnapshotHashAgent" ) }; }; #endif // SNAPSHOTHASHAGENT_H diff --git a/libskale/SnapshotManager.cpp b/libskale/SnapshotManager.cpp index 1101b52e7..63ca95852 100644 --- a/libskale/SnapshotManager.cpp +++ b/libskale/SnapshotManager.cpp @@ -505,7 +505,8 @@ void SnapshotManager::computeDatabaseHash( dev::h256 dbHash; secp256k1_sha256_finalize( &dbCtx, dbHash.data() ); - cnote << _dbDir << " hash is: " << dbHash << std::endl; + + LOG( m_loggerInfo ) << _dbDir << " hash is: " << dbHash; secp256k1_sha256_write( ctx, dbHash.data(), dbHash.size ); } catch ( const fs::filesystem_error& ex ) { @@ -543,7 +544,8 @@ void SnapshotManager::addLastPriceToHash( unsigned _blockNumber, secp256k1_sha25 } dev::h256 last_price_hash = dev::sha256( last_price.str() ); - cnote << "Latest price hash is: " << last_price_hash << std::endl; + + LOG( m_loggerInfo ) << "Latest price hash is: " << last_price_hash; secp256k1_sha256_write( ctx, last_price_hash.data(), last_price_hash.size ); } @@ -732,19 +734,19 @@ void SnapshotManager::computeAllVolumesHash( // this->computeDatabaseHash( content, ctx ); // } - //#ifdef HISTORIC_STATE - // // historic dbs - // this->computeDatabaseHash( - // this->snapshotsDir / std::to_string( _blockNumber ) / archiveVolumes[0] / - // dev::eth::BlockChain::getChainDirName( chainParams ) / "state", - // ctx ); - // this->computeDatabaseHash( - // this->snapshotsDir / std::to_string( _blockNumber ) / archiveVolumes[1] / - // dev::eth::BlockChain::getChainDirName( chainParams ) / "state", - // ctx ); - //#endif - // } - // } + // #ifdef HISTORIC_STATE + // // historic dbs + // this->computeDatabaseHash( + // this->snapshotsDir / std::to_string( _blockNumber ) / archiveVolumes[0] / + // dev::eth::BlockChain::getChainDirName( chainParams ) / "state", + // ctx ); + // this->computeDatabaseHash( + // this->snapshotsDir / std::to_string( _blockNumber ) / archiveVolumes[1] / + // dev::eth::BlockChain::getChainDirName( chainParams ) / "state", + // ctx ); + // #endif + // } + // } } void SnapshotManager::computeSnapshotHash( unsigned _blockNumber, bool is_checking ) { diff --git a/libskale/SnapshotManager.h b/libskale/SnapshotManager.h index 4a5ca58d8..175df7a54 100644 --- a/libskale/SnapshotManager.h +++ b/libskale/SnapshotManager.h @@ -204,6 +204,9 @@ class SnapshotManager { void computeDatabaseHash( const boost::filesystem::path& _dbDir, secp256k1_sha256_t* ctx ) const; void addLastPriceToHash( unsigned _blockNumber, secp256k1_sha256_t* ctx ) const; + + /// Loggers + mutable dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "SnapshotManager" ) }; }; #endif // SNAPSHOTMANAGER_H diff --git a/libskale/State.cpp b/libskale/State.cpp index 384e5b179..0a59d89ce 100644 --- a/libskale/State.cpp +++ b/libskale/State.cpp @@ -106,7 +106,7 @@ State::State( dev::u256 const& _accountStartNonce, boost::filesystem::path const #endif m_fs_ptr = state.fs(); if ( _bs == BaseState::PreExisting ) { - clog( VerbosityDebug, "statedb" ) << cc::debug( "Using existing database" ); + LOG( m_loggerDebug ) << "Using existing database"; } else if ( _bs == BaseState::Empty ) { // Initialise to the state entailed by the genesis block; this guarantees the trie is built // correctly. @@ -138,7 +138,7 @@ State::State( u256 const& _accountStartNonce, OverlayDB const& _db, #endif m_fs_ptr = state.fs(); if ( _bs == BaseState::PreExisting ) { - clog( VerbosityDebug, "statedb" ) << cc::debug( "Using existing database" ); + LOG( m_loggerDebug ) << "Using existing database"; } else if ( _bs == BaseState::Empty ) { // Initialise to the state entailed by the genesis block; this guarantees the trie is built // correctly. @@ -156,9 +156,9 @@ const uint64_t STATE_IMPORT_BATCH_COUNT = 16; void State::populateHistoricStateFromSkaleState() { auto allAccountAddresses = this->addresses(); - cout << "Number of addresses in statedb:" << allAccountAddresses.size() << endl; - cout << "Historic state does not yet exist. Populating historic state ..." << endl; - cout << "Please be patient as it may take up to several hours for a large state" << endl; + LOG( m_loggerInfo ) << "Number of addresses in statedb:" << allAccountAddresses.size(); + LOG( m_loggerInfo ) << "Historic state does not yet exist. Populating historic state ..."; + LOG( m_loggerInfo ) << "Please be patient as it may take up to several hours for a large state"; // this is done to save memory, otherwise OverlayDB will frow @@ -166,7 +166,7 @@ void State::populateHistoricStateFromSkaleState() { populateHistoricStateBatchFromSkaleState( allAccountAddresses, i ); } - cout << "Completed state import" << endl; + LOG( m_loggerInfo ) << "Completed state import"; } @@ -200,7 +200,8 @@ dev::eth::AccountMap State::getBatchOfAccounts( void State::populateHistoricStateBatchFromSkaleState( std::unordered_map< Address, u256 >& _allAccountAddresses, uint64_t _batchNumber ) { - cout << "Now running batch " << _batchNumber << " out of " << STATE_IMPORT_BATCH_COUNT << endl; + LOG( m_loggerInfo ) << "Now running batch " << _batchNumber << " out of " + << STATE_IMPORT_BATCH_COUNT; dev::eth::AccountMap accountMap = getBatchOfAccounts( _allAccountAddresses, _batchNumber ); @@ -215,7 +216,7 @@ skale::OverlayDB State::openDB( fs::path path = _basePath.empty() ? eth::Defaults::dbPath() : _basePath; if ( _we == WithExisting::Kill ) { - clog( VerbosityDebug, "statedb" ) << "Killing state database (WithExisting::Kill)."; + LOG( m_loggerDebug ) << "Killing state database (WithExisting::Kill)."; fs::remove_all( path / fs::path( "state" ) ); } @@ -230,19 +231,21 @@ skale::OverlayDB State::openDB( std::unique_ptr< batched_io::batched_db > bdb = make_unique< batched_io::batched_db >(); bdb->open( m_orig_db ); assert( bdb->is_open() ); - clog( VerbosityDebug, "statedb" ) << cc::success( "Opened state DB." ); + LOG( m_loggerDebug ) << "Opened state DB."; return OverlayDB( std::move( bdb ) ); } catch ( boost::exception const& ex ) { - cwarn << boost::diagnostic_information( ex ) << '\n'; + LOG( m_loggerWarning ) << boost::diagnostic_information( ex ); if ( fs::space( path / fs::path( "state" ) ).available < 1024 ) { - cwarn << "Not enough available space found on hard drive. Please free some up and " - "then " - "re-run. Bailing."; + LOG( m_loggerWarning ) + << "Not enough available space found on hard drive. Please free some up and " + "then " + "re-run. Bailing."; BOOST_THROW_EXCEPTION( eth::NotEnoughAvailableSpace() ); } else { - cwarn << "Database " << ( path / fs::path( "state" ) ) - << "already open. You appear to have another instance of ethereum running. " - "Bailing."; + LOG( m_loggerWarning ) + << "Database " << ( path / fs::path( "state" ) ) + << "already open. You appear to have another instance of ethereum running. " + "Bailing."; BOOST_THROW_EXCEPTION( eth::DatabaseAlreadyOpen() ); } } @@ -1032,8 +1035,7 @@ std::pair< ExecutionResult, TransactionReceipt > State::execute( EnvInfo const& h256 shaLastTx = _t.sha3(); // _t.hasSignature() ? _t.sha3() : _t.sha3( // dev::eth::WithoutSignature ); this->m_db_ptr->setLastExecutedTransactionHash( shaLastTx ); - // std::cout << "--- saving \"safeLastExecutedTransactionHash\" = " << - // shaLastTx.hex() << "\n"; + TransactionReceipt receipt = TransactionReceipt( statusCode, startGasUsed + e.gasUsed(), e.logs() ); @@ -1156,7 +1158,8 @@ dev::s256 State::storageUsed( const dev::Address& _addr ) const { std::ostream& skale::operator<<( std::ostream& _out, State const& _s ) { - _out << cc::debug( "--- Cache ---" ) << std::endl; + _out << "--- Cache ---" + << "\n"; std::set< Address > d; for ( auto i : _s.m_cache ) d.insert( i.first ); @@ -1167,11 +1170,11 @@ std::ostream& skale::operator<<( std::ostream& _out, State const& _s ) { assert( cache ); if ( cache && !cache->isAlive() ) - _out << cc::debug( "XXX " ) << i << std::endl; + _out << "XXX " << i << "\n"; else { - string lead = cc::debug( " + " ); + string lead = " + "; if ( cache ) - lead = cc::debug( " . " ); + lead = " . "; stringstream contout; @@ -1194,13 +1197,13 @@ std::ostream& skale::operator<<( std::ostream& _out, State const& _s ) { contout << " @:"; if ( cache && cache->hasNewCode() ) - contout << cc::debug( " $" ) << toHex( cache->code() ); + contout << " $" << toHex( cache->code() ); else - contout << cc::debug( " $" ) << ( cache ? cache->codeHash() : dev::h256( 0 ) ); + contout << " $" << ( cache ? cache->codeHash() : dev::h256( 0 ) ); for ( auto const& j : mem ) if ( j.second ) - contout << std::endl + contout << "\n" << ( delta.count( j.first ) ? back.count( j.first ) ? " * " : " + " : cached.count( j.first ) ? " . " : @@ -1208,14 +1211,13 @@ std::ostream& skale::operator<<( std::ostream& _out, State const& _s ) { << std::hex << nouppercase << std::setw( 64 ) << j.first << ": " << std::setw( 0 ) << j.second; else - contout << std::endl - << cc::debug( "XXX " ) << std::hex << nouppercase - << std::setw( 64 ) << j.first << ""; + contout << "\n" + << "XXX " << std::hex << nouppercase << std::setw( 64 ) + << j.first << ""; } else - contout << cc::debug( " [SIMPLE]" ); - _out << lead << i << cc::debug( ": " ) << std::dec - << ( cache ? cache->nonce() : u256( 0 ) ) << cc::debug( " #:" ) - << ( cache ? cache->balance() : u256( 0 ) ) << contout.str() << std::endl; + contout << " [SIMPLE]"; + _out << lead << i << ": " << std::dec << ( cache ? cache->nonce() : u256( 0 ) ) + << " #:" << ( cache ? cache->balance() : u256( 0 ) ) << contout.str() << "\n"; } } return _out; diff --git a/libskale/State.h b/libskale/State.h index e6a81ed92..bebd25325 100644 --- a/libskale/State.h +++ b/libskale/State.h @@ -518,6 +518,12 @@ class State { std::shared_ptr< dev::db::LevelDBSnap > m_snap = nullptr; bool m_isReadOnlySnapBasedState = false; + /// Loggers + mutable dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "State" ) }; + mutable dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "State" ) }; + mutable dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "State" ) }; + mutable dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "State" ) }; + #ifdef HISTORIC_STATE dev::eth::HistoricState m_historicState; diff --git a/libskale/broadcaster.cpp b/libskale/broadcaster.cpp index e264ebbbc..6dd3f0bdf 100644 --- a/libskale/broadcaster.cpp +++ b/libskale/broadcaster.cpp @@ -56,7 +56,7 @@ void HttpBroadcaster::initClients( dev::eth::SChain sChain, dev::eth::NodeInfo n std::string HttpBroadcaster::getHttpUrl( const dev::eth::sChainNode& node ) { std::string url = "http://" + node.ip + ":" + ( node.port + 3 ).str(); // HACK +0 +1 +2 are used by consensus - clog( dev::VerbosityInfo, "broadcaster" ) << url; // todo + LOG( m_loggerInfo ) << url; // todo return url; } @@ -82,7 +82,7 @@ ZmqBroadcaster::ZmqBroadcaster( dev::eth::Client& _client, SkaleHost& _skaleHost std::string ZmqBroadcaster::getZmqUrl( const dev::eth::sChainNode& node ) const { std::string url = "tcp://" + node.ip + ":" + ( node.port + 5 ).str(); // HACK +5 - clog( dev::VerbosityInfo, "broadcaster" ) << url; // todo + LOG( m_loggerInfo ) << url; return url; } @@ -192,7 +192,7 @@ void ZmqBroadcaster::startService() { } if ( res < 0 ) { - clog( dev::VerbosityWarning, "skale-host" ) + LOG( m_loggerWarning ) << "Received bad message on ZmqBroadcaster port. errno = " << errno; continue; } @@ -205,17 +205,17 @@ void ZmqBroadcaster::startService() { try { m_skaleHost.receiveTransaction( str ); } catch ( const std::exception& ex ) { - clog( dev::VerbosityDebug, "skale-host" ) + LOG( m_loggerDebug ) << "Received bad transaction through broadcast: " << ex.what(); } } catch ( const std::exception& ex ) { - cerror << "CRITICAL " << ex.what() << " (restarting ZmqBroadcaster)"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL " << ex.what() << " (restarting ZmqBroadcaster)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; sleep( 2 ); } catch ( ... ) { - cerror << "CRITICAL unknown exception (restarting ZmqBroadcaster)"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL unknown exception (restarting ZmqBroadcaster)"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; sleep( 2 ); } @@ -249,8 +249,7 @@ void ZmqBroadcaster::initSocket() { void ZmqBroadcaster::broadcast( const std::string& _rlp ) { int res = zmq_send( server_socket(), const_cast< char* >( _rlp.c_str() ), _rlp.size(), 0 ); if ( res <= 0 ) { - clog( dev::VerbosityWarning, "zmq-broadcaster" ) - << "Got error " << res << " in zmq_send: " << zmq_strerror( res ); + LOG( m_loggerWarning ) << "Got error " << res << " in zmq_send: " << zmq_strerror( res ); throw std::runtime_error( "Zmq can't send data" ); } } diff --git a/libskale/broadcaster.h b/libskale/broadcaster.h index bb4381de3..34d9b8562 100644 --- a/libskale/broadcaster.h +++ b/libskale/broadcaster.h @@ -74,6 +74,8 @@ class HttpBroadcaster : public Broadcaster { void initClients( dev::eth::SChain, dev::eth::NodeInfo ); std::string getHttpUrl( const dev::eth::sChainNode& ); + + dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "HttpBroadcaster" ) }; }; class ZmqBroadcaster : public Broadcaster { @@ -102,6 +104,13 @@ class ZmqBroadcaster : public Broadcaster { // threading std::atomic_bool m_need_exit; std::thread m_thread; + + /// Logger + mutable dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "ZmqBroadcaster" ) }; + mutable dev::Logger m_loggerWarning{ dev::createLogger( + dev::VerbosityWarning, "ZmqBroadcaster" ) }; + mutable dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "ZmqBroadcaster" ) }; + mutable dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "ZmqBroadcaster" ) }; }; #endif // BROADCASTER_H diff --git a/libskale/httpserveroverride.cpp b/libskale/httpserveroverride.cpp index 8fb415058..e21733883 100644 --- a/libskale/httpserveroverride.cpp +++ b/libskale/httpserveroverride.cpp @@ -99,28 +99,6 @@ namespace skale { namespace server { namespace helper { -dev::Verbosity dv_from_ws_msg_type( skutils::ws::e_ws_log_message_type_t eWSLMT ) { - dev::Verbosity dv = dev::Verbosity::VerbosityTrace; - switch ( eWSLMT ) { - case skutils::ws::e_ws_log_message_type_t::eWSLMT_debug: - dv = dev::Verbosity::VerbosityDebug; - break; - case skutils::ws::e_ws_log_message_type_t::eWSLMT_info: - dv = dev::Verbosity::VerbosityDebug; // VerbosityInfo - break; - case skutils::ws::e_ws_log_message_type_t::eWSLMT_warning: - dv = dev::Verbosity::VerbosityWarning; - break; - case skutils::ws::e_ws_log_message_type_t::eWSLMT_error: - dv = dev::Verbosity::VerbosityWarning; - break; - default: - dv = dev::Verbosity::VerbosityError; - break; - } - return dv; -} - dev::eth::LogFilter toLogFilter( const nlohmann::json& jo ) { dev::eth::LogFilter filter; if ( ( !jo.is_object() ) || jo.size() == 0 ) @@ -562,14 +540,11 @@ bool SkaleStatsSubscriptionManager::subscribe( joNotification["params"] = joParams; std::string strNotification = joNotification.dump(); if ( getSSO().opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, - cc::info( subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() ) ) - << ( cc::ws_tx_inv( " <<< " + - subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() + - "/TX <<< " ) + - subscriptionData.m_pPeer->desc() + cc::ws_tx( " <<< " ) + + LOG( m_loggerDebug ) + << " <<< " + subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() + + "/TX <<< " + subscriptionData.m_pPeer->desc() + " <<< " + subscriptionData.m_pPeer->implPreformatTrafficJsonMessage( - strNotification, false ) ); + strNotification, false ); skutils::dispatch::async( subscriptionData.m_pPeer->m_strPeerQueueID, [subscriptionData, strNotification, idSubscription, this]() -> void { bool bMessageSentOK = false; @@ -587,28 +562,26 @@ bool SkaleStatsSubscriptionManager::subscribe( stats::register_stats_answer( "RPC", "eth_subscription/skaleStats", strNotification.size() ); } catch ( std::exception& ex ) { - clog( dev::Verbosity::VerbosityError, - cc::info( subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( - subscriptionData.m_pPeer->getRelay().serverIndex() ) ) - << ( subscriptionData.m_pPeer->desc() + " " + - cc::error( "error in " ) + - cc::warn( "eth_subscription/skaleStats" ) + - cc::error( " will uninstall watcher callback because of " - "exception: " ) + - cc::warn( ex.what() ) ); + LOG( m_loggerError ) + << subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( + subscriptionData.m_pPeer->getRelay().serverIndex() ) + + ": " + << subscriptionData.m_pPeer->desc() + " " + "error in " + + "eth_subscription/skaleStats" + + " will uninstall watcher callback because of " + "exception: " + + ex.what(); } catch ( ... ) { - clog( dev::Verbosity::VerbosityError, - cc::info( subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( - subscriptionData.m_pPeer->getRelay().serverIndex() ) ) - << ( subscriptionData.m_pPeer->desc() + " " + - cc::error( "error in " ) + - cc::warn( "eth_subscription/skaleStats" ) + - cc::error( " will uninstall watcher callback because of " - "unknown exception" ) ); + LOG( m_loggerError ) + << subscriptionData.m_pPeer->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( + subscriptionData.m_pPeer->getRelay().serverIndex() ) + + ": " + << subscriptionData.m_pPeer->desc() + " " + "error in " + + "eth_subscription/skaleStats" + + " will uninstall watcher callback because of " + "unknown exception"; } if ( !bMessageSentOK ) { stats::register_stats_error( @@ -679,16 +652,12 @@ SkaleWsPeer::SkaleWsPeer( skutils::ws::server& srv, const skutils::ws::hdl_t& hd m_strPeerQueueID( skutils::dispatch::generate_id( this, "relay_peer" ) ) { SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::notice( " peer ctor" ) ); + LOG( m_loggerTrace ) << getLoggerName() + ": " << desc() + " peer ctor"; } SkaleWsPeer::~SkaleWsPeer() { SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::notice( " peer dtor" ) ); + LOG( m_loggerTrace ) << getLoggerName() + ": " << desc() + " peer dtor"; uninstallAllWatches(); skutils::dispatch::remove( m_strPeerQueueID ); } @@ -707,11 +676,10 @@ void SkaleWsPeer::register_ws_conn_for_origin() { pSO->unddos_.register_ws_conn_for_origin( m_strUnDdosOrigin ); if ( ehldr != skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ) { m_strUnDdosOrigin.clear(); - clog( dev::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::fatal( "UN-DDOS:" ) + " " + - cc::error( " cannot accept connection - UN-DDOS protection reported " - "connection count overflow" ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " " + "UN-DDOS:" + " " + + " cannot accept connection - UN-DDOS protection reported " + "connection count overflow"; close( "UN-DDOS protection reported connection count overflow" ); throw std::runtime_error( "Cannot accept " + getRelay().nfoGetSchemeUC() + " connection from " + url_unddos_origin.str() + @@ -727,12 +695,14 @@ void SkaleWsPeer::unregister_ws_conn_for_origin() { } } +std::string SkaleWsPeer::getLoggerName() const { + return getRelay().nfoGetSchemeUC() + "/" + std::to_string( getRelay().serverIndex() ); +} + void SkaleWsPeer::onPeerRegister() { SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::notice( " peer registered" ) ); + LOG( m_loggerDebug ) << getLoggerName() + ": " << desc() + " peer registered"; skutils::ws::peer::onPeerRegister(); // // unddos @@ -743,9 +713,7 @@ void SkaleWsPeer::onPeerUnregister() { // peer will no longer receive onMessage m_pSSCTH.reset(); SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::notice( " peer unregistered" ) ); + LOG( m_loggerDebug ) << getLoggerName() + ": " << desc() + " peer unregistered"; skutils::ws::peer::onPeerUnregister(); uninstallAllWatches(); std::string strQueueIdToRemove = m_strPeerQueueID; @@ -759,23 +727,15 @@ void SkaleWsPeer::onPeerUnregister() { // peer will no longer receive onMessage void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) { SkaleServerOverride* pSO = pso(); if ( pSO->isShutdownMode() ) { - clog( dev::VerbosityWarning, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( cc::ws_rx_inv( " >>> " + getRelay().nfoGetSchemeUC() + "/" + - std::to_string( getRelay().serverIndex() ) + "/RX >>> " ) + - desc() + cc::ws_rx( " >>> " ) + cc::warn( "" ) ); + LOG( m_loggerWarning ) << " >>> " + getLoggerName() + "/RX >>> " + desc() + " >>> " + ""; skutils::dispatch::remove( m_strPeerQueueID ); // remove queue earlier return; } if ( eOpCode != skutils::ws::opcv::text ) { // throw std::runtime_error( "only ws text messages are supported" ); - clog( dev::VerbosityWarning, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( cc::ws_rx_inv( " >>> " + getRelay().nfoGetSchemeUC() + "/" + - std::to_string( getRelay().serverIndex() ) + "/RX >>> " ) + - desc() + cc::ws_rx( " >>> " ) + - cc::error( " got binary message and will try to interpret it as text: " ) + - cc::warn( msg ) ); + LOG( m_loggerWarning ) << " >>> " + getLoggerName() + "/RX >>> " + desc() + " >>> " + + " got binary message and will try to interpret it as text: " + + msg; } skutils::retain_release_ptr< SkaleWsPeer > pThis = this; nlohmann::json jarrRequest; @@ -815,12 +775,9 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) strMethod = "unknown_json_rpc_method"; } std::string e = "Bad JSON RPC request: " + msg; - clog( dev::VerbosityError, cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_tx_inv( " !!! " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + "/ERR !!! " ) + - pThis->desc() + cc::ws_tx( " !!! " ) + cc::warn( e ) ); + LOG( m_loggerError ) << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + "/ERR " + + pThis->desc() + " " + e; nlohmann::json joErrorResponce; joErrorResponce["id"] = joID; nlohmann::json joErrorObj; @@ -855,12 +812,9 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) "bad origin" : "high load"; std::string e = "Banned due to " + reason_part + " JSON RPC request: " + msg; - clog( dev::VerbosityError, cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_tx_inv( " !!! " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + "/ERR !!! " ) + - pThis->desc() + cc::ws_tx( " !!! " ) + cc::warn( e ) ); + LOG( m_loggerError ) << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + "/ERR " + + pThis->desc() + " " + e; nlohmann::json joErrorResponce; joErrorResponce["id"] = joID; nlohmann::json joErrorObj; @@ -884,9 +838,10 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) } // switch( ehldr ) // // WS-processing-lambda - auto fnAsyncMessageHandler = [pThis, jarrRequest, pSO, + auto fnAsyncMessageHandler = [this, pThis, jarrRequest, pSO, isBatch]() -> void { // WS-processing-lambda nlohmann::json jarrBatchAnswer; + std::unique_ptr< dev::Logger > logger; if ( isBatch ) jarrBatchAnswer = nlohmann::json::array(); for ( const nlohmann::json& joRequest : jarrRequest ) { @@ -909,15 +864,11 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) // skutils::task::performance::action a( strPerformanceQueueName, strPerformanceActionName ); - if ( pSO->methodTraceVerbosity( strMethod ) != dev::VerbositySilent ) - clog( pSO->methodTraceVerbosity( strMethod ), - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_rx_inv( " >>> " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + - "/RX >>> " ) + - pThis->desc() + cc::ws_rx( " >>> " ) + - pThis->implPreformatTrafficJsonMessage( joRequest, true ) ); + if ( logger = pSO->getLoggerFromMethodTraceVerbosity( strMethod ) ) + LOG( *logger ) << " >>> " + pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + "/RX >>> " + pThis->desc() + " >>> " + + pThis->implPreformatTrafficJsonMessage( joRequest, true ); std::string strResponse; bool bPassed = false; try { @@ -947,13 +898,9 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) bPassed = true; } catch ( const std::exception& ex ) { rttElement->setError(); - clog( dev::VerbosityError, cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_tx_inv( " !!! " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + - "/ERR !!! " ) + - pThis->desc() + cc::ws_tx( " !!! " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + "/ERR " + pThis->desc() + " " + ex.what(); nlohmann::json joErrorResponce; joErrorResponce["id"] = joID; nlohmann::json joErrorObj; @@ -972,13 +919,9 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) } catch ( ... ) { rttElement->setError(); const char* e = "unknown exception in SkaleServerOverride"; - clog( dev::VerbosityError, cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_tx_inv( " !!! " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + - "/ERR !!! " ) + - pThis->desc() + cc::ws_tx( " !!! " ) + cc::warn( e ) ); + LOG( m_loggerError ) << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + "/ERR " + pThis->desc() + " " + e; nlohmann::json joErrorResponce; joErrorResponce["id"] = joID; nlohmann::json joErrorObj; @@ -996,15 +939,11 @@ void SkaleWsPeer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode ) } a.set_json_err( joErrorResponce ); } - if ( pSO->methodTraceVerbosity( strMethod ) != dev::VerbositySilent ) - clog( pSO->methodTraceVerbosity( strMethod ), - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( cc::ws_tx_inv( " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/" + - std::to_string( pThis->getRelay().serverIndex() ) + - "/TX <<< " ) + - pThis->desc() + cc::ws_tx( " <<< " ) + - pThis->implPreformatTrafficJsonMessage( strResponse, false ) ); + if ( logger = pSO->getLoggerFromMethodTraceVerbosity( strMethod ) ) + LOG( *logger ) << " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + "/TX <<< " + pThis->desc() + " <<< " + + pThis->implPreformatTrafficJsonMessage( strResponse, false ); if ( isBatch ) { nlohmann::json joAnswerPart = nlohmann::json::parse( strResponse ); jarrBatchAnswer.push_back( joAnswerPart ); @@ -1032,10 +971,9 @@ void SkaleWsPeer::onClose( const std::string& reason, int local_close_code, const std::string& local_close_code_as_str ) { SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::warn( " peer close event with code=" ) + cc::c( local_close_code ) + - cc::debug( ", reason=" ) + cc::info( reason ) ); + LOG( m_loggerDebug ) << getLoggerName() + ": " + << desc() + " peer close event with code=" + + std::to_string( local_close_code ) + ", reason=" + reason; skutils::ws::peer::onClose( reason, local_close_code, local_close_code_as_str ); uninstallAllWatches(); // unddos @@ -1045,8 +983,7 @@ void SkaleWsPeer::onClose( void SkaleWsPeer::onFail() { SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityError, cc::fatal( getRelay().nfoGetSchemeUC() ) ) - << ( desc() + cc::error( " peer fail event" ) ); + LOG( m_loggerError ) << getRelay().nfoGetSchemeUC() + ": " << desc() + " peer fail event"; skutils::ws::peer::onFail(); uninstallAllWatches(); // unddos @@ -1056,11 +993,10 @@ void SkaleWsPeer::onFail() { void SkaleWsPeer::onLogMessage( skutils::ws::e_ws_log_message_type_t eWSLMT, const std::string& msg ) { SkaleServerOverride* pSO = pso(); - if ( pSO->opts_.isTraceCalls_ ) - clog( skale::server::helper::dv_from_ws_msg_type( eWSLMT ), - cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + cc::debug( " peer log: " ) + cc::info( msg ) ); + if ( pSO->opts_.isTraceCalls_ ) { + dev::Logger logger = getLoggerFromWsMsgType( eWSLMT ); + LOG( logger ) << getLoggerName() + ": " << desc() + " peer log: " + msg; + } skutils::ws::peer::onLogMessage( eWSLMT, msg ); } @@ -1221,13 +1157,12 @@ void SkaleWsPeer::eth_subscribe( strSubscriptionType = ""; SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + cc::warn( "eth_subscribe" ) + - cc::error( " rpc method, missing valid subscription type in parameters, was " - "specifiedL " ) + - cc::warn( strSubscriptionType ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " " + "error in " + "eth_subscribe" + + " rpc method, missing valid subscription type in parameters, was " + "specifiedL " + + strSubscriptionType; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32603; joError["message"] = @@ -1258,9 +1193,9 @@ void SkaleWsPeer::eth_subscribe_logs( } // for ( idxParam = 0; idxParam < cntParams; ++idxParam ) skutils::retain_release_ptr< SkaleWsPeer > pThis( this ); dev::eth::fnClientWatchHandlerMulti_t fnOnSunscriptionEvent; - fnOnSunscriptionEvent += [pThis]( unsigned iw ) -> void { + fnOnSunscriptionEvent += [this, pThis]( unsigned iw ) -> void { skutils::dispatch::async( "logs-rethread", [=]() -> void { - skutils::dispatch::async( pThis->m_strPeerQueueID, [pThis, iw]() -> void { + skutils::dispatch::async( pThis->m_strPeerQueueID, [this, pThis, iw]() -> void { dev::eth::LocalisedLogEntries le = pThis->ethereum()->checkWatch( iw ); nlohmann::json joResult = skale::server::helper::toJsonByBlock( le ); @@ -1290,14 +1225,13 @@ void SkaleWsPeer::eth_subscribe_logs( std::string strNotification = joNotification.dump(); const SkaleServerOverride* pSO = pThis->pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::ws_tx_inv( " <<< " + - pThis->getRelay().nfoGetSchemeUC() + - "/TX <<< " ) ) - << ( pThis->desc() + cc::ws_tx( " <<< " ) + + LOG( m_loggerDebug ) + << pThis->getRelay().nfoGetSchemeUC() + " <<< " + + pThis->getRelay().nfoGetSchemeUC() + "/TX <<< " + + ": " + << pThis->desc() + " <<< " + pThis->implPreformatTrafficJsonMessage( - strNotification, false ) ); + strNotification, false ); bool bMessageSentOK = false; try { bMessageSentOK = const_cast< SkaleWsPeer* >( pThis.get() ) @@ -1315,24 +1249,24 @@ void SkaleWsPeer::eth_subscribe_logs( stats::register_stats_answer( "RPC", "eth_subscription/logs", strNotification.size() ); } catch ( std::exception& ex ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/logs" ) + - cc::error( " will uninstall watcher callback " - "because of exception: " ) + - cc::warn( ex.what() ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + ": " + << pThis->desc() + " " + "error in " + + "eth_subscription/logs" + + " will uninstall watcher callback " + "because of exception: " + + ex.what(); } catch ( ... ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/logs" ) + - cc::error( " will uninstall watcher callback " - "because of unknown exception" ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + + ": " + << pThis->desc() + " " + "error in " + + "eth_subscription/logs" + + " will uninstall watcher callback " + "because of unknown exception"; } if ( !bMessageSentOK ) { stats::register_stats_error( @@ -1354,19 +1288,15 @@ void SkaleWsPeer::eth_subscribe_logs( setInstalledWatchesLogs_.insert( iw ); std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::info( "eth_subscribe/logs" ) + - cc::debug( " rpc method did installed watch " ) + cc::info( strIW ) ); + LOG( m_loggerTrace ) << getLoggerName() + ": " + << desc() + " eth_subscribe/logs rpc method did installed watch " + + strIW; joResponse["result"] = strIW; } catch ( const std::exception& ex ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + cc::warn( "eth_subscribe/logs" ) + - cc::error( " rpc method, exception " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " error in eth_subscribe/logs rpc method, exception " + + ex.what(); nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1375,11 +1305,9 @@ void SkaleWsPeer::eth_subscribe_logs( return; } catch ( ... ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + cc::warn( "eth_subscribe/logs" ) + - cc::error( " rpc method, unknown exception " ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " error in eth_subscribe/logs rpc method, unknown exception "; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = "error in \"eth_subscribe/logs\" rpc method, unknown exception"; @@ -1395,8 +1323,8 @@ void SkaleWsPeer::eth_subscribe_newPendingTransactions( skutils::retain_release_ptr< SkaleWsPeer > pThis( this ); std::function< void( const unsigned& iw, const dev::eth::Transaction& t ) > fnOnSunscriptionEvent = - [pThis]( const unsigned& iw, const dev::eth::Transaction& t ) -> void { - skutils::dispatch::async( pThis->m_strPeerQueueID, [pThis, iw, t]() -> void { + [this, pThis]( const unsigned& iw, const dev::eth::Transaction& t ) -> void { + skutils::dispatch::async( pThis->m_strPeerQueueID, [this, pThis, iw, t]() -> void { const SkaleServerOverride* pSO = pThis->pso(); dev::h256 h = t.sha3(); // @@ -1410,11 +1338,11 @@ void SkaleWsPeer::eth_subscribe_newPendingTransactions( joNotification["params"] = joParams; std::string strNotification = joNotification.dump(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, cc::info( pThis->getRelay().nfoGetSchemeUC() ) ) - << ( cc::ws_tx_inv( - " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/TX <<< " ) + - pThis->desc() + cc::ws_tx( " <<< " ) + - pThis->implPreformatTrafficJsonMessage( strNotification, false ) ); + LOG( m_loggerDebug ) + << pThis->getRelay().nfoGetSchemeUC() + ": " + << " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/TX <<< " + + pThis->desc() + " <<< " + + pThis->implPreformatTrafficJsonMessage( strNotification, false ); bool bMessageSentOK = false; try { bMessageSentOK = @@ -1429,22 +1357,22 @@ void SkaleWsPeer::eth_subscribe_newPendingTransactions( stats::register_stats_answer( "RPC", "eth_subscription/newPendingTransactions", strNotification.size() ); } catch ( std::exception& ex ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/newPendingTransactions" ) + - cc::error( - " will uninstall watcher callback because of exception: " ) + - cc::warn( ex.what() ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + ": " + << ( pThis->desc() + " " + "error in " + + "eth_subscription/newPendingTransactions" + + + " will uninstall watcher callback because of exception: " + + ex.what() ); } catch ( ... ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/newPendingTransactions" ) + - cc::error( " will uninstall watcher callback because of unknown " - "exception" ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + ": " + << pThis->desc() + " " + "error in " + + "eth_subscription/newPendingTransactions" + + " will uninstall watcher callback because of unknown " + "exception"; } if ( !bMessageSentOK ) { stats::register_stats_error( @@ -1461,20 +1389,16 @@ void SkaleWsPeer::eth_subscribe_newPendingTransactions( iw |= SKALED_WS_SUBSCRIPTION_TYPE_NEW_PENDING_TRANSACTION; std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::info( "eth_subscribe/newPendingTransactions" ) + - cc::debug( " rpc method did installed watch " ) + cc::info( strIW ) ); + LOG( m_loggerTrace ) << getLoggerName() + ": " + << desc() + " " + "eth_subscribe/newPendingTransactions" + + " rpc method did installed watch " + strIW; joResponse["result"] = strIW; } catch ( const std::exception& ex ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newPendingTransactions" ) + - cc::error( " rpc method, exception " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " " + "error in " + + "eth_subscribe/newPendingTransactions" + + " rpc method, exception " + ex.what(); nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1485,12 +1409,10 @@ void SkaleWsPeer::eth_subscribe_newPendingTransactions( return; } catch ( ... ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newPendingTransactions" ) + - cc::error( " rpc method, unknown exception " ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " " + "error in " + + "eth_subscribe/newPendingTransactions" + + " rpc method, unknown exception "; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1506,9 +1428,9 @@ void SkaleWsPeer::eth_subscribe_newHeads( e_server_mode_t /*esm*/, try { skutils::retain_release_ptr< SkaleWsPeer > pThis( this ); std::function< void( const unsigned& iw, const dev::eth::Block& block ) > - fnOnSunscriptionEvent = [pThis, bIncludeTransactions]( + fnOnSunscriptionEvent = [this, pThis, bIncludeTransactions]( const unsigned& iw, const dev::eth::Block& block ) -> void { - skutils::dispatch::async( [pThis, iw, block, bIncludeTransactions]() -> void { + skutils::dispatch::async( [this, pThis, iw, block, bIncludeTransactions]() -> void { const SkaleServerOverride* pSO = pThis->pso(); dev::h256 h = block.info().hash(); Json::Value jv; @@ -1534,13 +1456,11 @@ void SkaleWsPeer::eth_subscribe_newHeads( e_server_mode_t /*esm*/, joNotification["params"] = joParams; std::string strNotification = joNotification.dump(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityDebug, cc::info( pThis->getRelay().nfoGetSchemeUC() ) ) - << ( cc::ws_tx_inv( - " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/TX <<< " ) + - pThis->desc() + cc::ws_tx( " <<< " ) + - pThis->implPreformatTrafficJsonMessage( strNotification, false ) ); - // skutils::dispatch::async( pThis->m_strPeerQueueID, [pThis, strNotification]() -> - // void { + LOG( m_loggerDebug ) + << pThis->getRelay().nfoGetSchemeUC() + ": " + << " <<< " + pThis->getRelay().nfoGetSchemeUC() + "/TX <<< " + + pThis->desc() + " <<< " + + pThis->implPreformatTrafficJsonMessage( strNotification, false ); bool bMessageSentOK = false; try { bMessageSentOK = @@ -1555,22 +1475,20 @@ void SkaleWsPeer::eth_subscribe_newHeads( e_server_mode_t /*esm*/, stats::register_stats_answer( "RPC", "eth_subscription/newHeads", strNotification.size() ); } catch ( std::exception& ex ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/newHeads" ) + - cc::error( - " will uninstall watcher callback because of exception: " ) + - cc::warn( ex.what() ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + ": " + << ( pThis->desc() + " " + "error in " + "eth_subscription/newHeads" + + + " will uninstall watcher callback because of exception: " + + ex.what() ); } catch ( ... ) { - clog( dev::Verbosity::VerbosityError, - cc::info( pThis->getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( pThis->getRelay().serverIndex() ) ) - << ( pThis->desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscription/newHeads" ) + - cc::error( " will uninstall watcher callback because of unknown " - "exception" ) ); + LOG( m_loggerError ) + << pThis->getRelay().nfoGetSchemeUC() + "/" + + std::to_string( pThis->getRelay().serverIndex() ) + ": " + << ( pThis->desc() + " " + "error in " + "eth_subscription/newHeads" + + " will uninstall watcher callback because of unknown " + "exception" ); } if ( !bMessageSentOK ) { stats::register_stats_error( @@ -1587,20 +1505,17 @@ void SkaleWsPeer::eth_subscribe_newHeads( e_server_mode_t /*esm*/, iw |= SKALED_WS_SUBSCRIPTION_TYPE_NEW_BLOCK; std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::info( "eth_subscribe/newHeads" ) + - cc::debug( " rpc method did installed watch " ) + cc::info( strIW ) ); + LOG( m_loggerTrace ) << getLoggerName() + ": " + << desc() + + " eth_subscribe/newHeads rpc method did installed watch " + + strIW; joResponse["result"] = strIW; } catch ( const std::exception& ex ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newHeads(" ) + - cc::error( " rpc method, exception " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + + " error in eth_subscribe/newHeads( rpc method, exception " + + ex.what(); nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1610,12 +1525,9 @@ void SkaleWsPeer::eth_subscribe_newHeads( e_server_mode_t /*esm*/, return; } catch ( ... ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newHeads(" ) + - cc::error( " rpc method, unknown exception " ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " error in eth_subscribe/newHeads( rpc method, unknown exception "; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = "error in \"eth_subscribe/newHeads(\" rpc method, unknown exception"; @@ -1639,20 +1551,16 @@ void SkaleWsPeer::eth_subscribe_skaleStats( throw std::runtime_error( "internal subscription error" ); std::string strIW = dev::toJS( idSubscription | SKALED_WS_SUBSCRIPTION_TYPE_SKALE_STATS ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityTrace, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::info( "eth_subscribe/skaleStats" ) + - cc::debug( " rpc method did installed watch " ) + cc::info( strIW ) ); + LOG( m_loggerTrace ) + << getLoggerName() + ": " + << desc() + " eth_subscribe/skaleStats rpc method did installed watch " + strIW; joResponse["result"] = strIW; } catch ( const std::exception& ex ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newHeads(" ) + - cc::error( " rpc method, exception " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + + " error in eth_subscribe/newHeads( rpc method, exception " + + ex.what(); nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1662,12 +1570,9 @@ void SkaleWsPeer::eth_subscribe_skaleStats( return; } catch ( ... ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_subscribe/newHeads(" ) + - cc::error( " rpc method, unknown exception " ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " error in eth_subscribe/newHeads( rpc method, unknown exception "; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = "error in \"eth_subscribe/SkaleStats(\" rpc method, unknown exception"; @@ -1695,12 +1600,10 @@ void SkaleWsPeer::eth_unsubscribe( } if ( iw == unsigned( -1 ) ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, cc::info( getRelay().nfoGetSchemeUC() ) + - cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + cc::warn( "eth_unsubscribe" ) + - cc::error( " rpc method, bad subscription ID " ) + - cc::j( joParamItem ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " error in eth_unsubscribe rpc method, bad subscription ID " + + joParamItem.dump(); nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1715,13 +1618,10 @@ void SkaleWsPeer::eth_unsubscribe( setInstalledWatchesNewPendingTransactions_.end() ) { std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_unsubscribe/newPendingTransactionWatch" ) + - cc::error( " rpc method, bad subscription ID " ) + - cc::warn( strIW ) ); + LOG( m_loggerError ) + << getLoggerName() + ": " + << desc() + " error in eth_unsubscribe/newPendingTransactionWatch" + + " rpc method, bad subscription ID " + strIW; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1740,13 +1640,9 @@ void SkaleWsPeer::eth_unsubscribe( setInstalledWatchesNewBlocks_.end() ) { std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_unsubscribe/newHeads" ) + - cc::error( " rpc method, bad subscription ID " ) + - cc::warn( strIW ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " error in eth_unsubscribe/newHeads" + + " rpc method, bad subscription ID " + strIW; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1764,13 +1660,9 @@ void SkaleWsPeer::eth_unsubscribe( if ( !bWasUnsubscribed ) { std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_unsubscribe/newHeads" ) + - cc::error( " rpc method, bad subscription ID " ) + - cc::warn( strIW ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " error in eth_unsubscribe/newHeads" + + " rpc method, bad subscription ID " + strIW; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1783,13 +1675,9 @@ void SkaleWsPeer::eth_unsubscribe( if ( setInstalledWatchesLogs_.find( iw ) == setInstalledWatchesLogs_.end() ) { std::string strIW = dev::toJS( iw ); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::info( getRelay().nfoGetSchemeUC() ) + cc::debug( "/" ) + - cc::num10( getRelay().serverIndex() ) ) - << ( desc() + " " + cc::error( "error in " ) + - cc::warn( "eth_unsubscribe/logs" ) + - cc::error( " rpc method, bad subscription ID " ) + - cc::warn( strIW ) ); + LOG( m_loggerError ) << getLoggerName() + ": " + << desc() + " error in eth_unsubscribe/logs" + + " rpc method, bad subscription ID " + strIW; nlohmann::json joError = nlohmann::json::object(); joError["code"] = -32602; joError["message"] = @@ -1810,8 +1698,7 @@ std::string SkaleWsPeer::implPreformatTrafficJsonMessage( return implPreformatTrafficJsonMessage( jo, isRequest ); } catch ( ... ) { } - return cc::error( isRequest ? "bad JSON request" : "bad JSON response" ) + " " + - cc::warn( strJSON ); + return isRequest ? "bad JSON request" : "bad JSON response " + strJSON; } std::string SkaleWsPeer::implPreformatTrafficJsonMessage( @@ -1823,7 +1710,7 @@ std::string SkaleWsPeer::implPreformatTrafficJsonMessage( SkaleServerOverride::stat_transformJsonForLogOutput( jo2, isRequest, SkaleServerOverride::g_nMaxStringValueLengthForJsonLogs, SkaleServerOverride::g_nMaxStringValueLengthForTransactionParams ); - return cc::j( jo2 ); + return jo2.dump(); } @@ -1863,14 +1750,13 @@ SkaleRelayWS::SkaleRelayWS( int ipVer, const char* strBindAddr, SkaleWsPeer* pSkalePeer = nullptr; SkaleServerOverride* pSO = pso(); if ( pSO->opts_.isTraceCalls_ ) - clog( dev::VerbosityTrace, cc::info( m_strSchemeUC ) ) - << ( cc::notice( "Will instantiate new peer" ) ); + LOG( m_loggerTrace ) << m_strSchemeUC + ": " + << "Will instantiate new peer"; if ( pSO->isShutdownMode() ) { - clog( dev::VerbosityWarning, - cc::info( m_strSchemeUC ) + cc::debug( "/" ) + cc::num10( serverIndex() ) ) - << ( cc::ws_rx_inv( " >>> " + m_strSchemeUC + "/" + - std::to_string( serverIndex() ) + "/RX >>> " ) + - cc::warn( "Skipping connection accept while in shutdown mode" ) ); + LOG( m_loggerWarning ) + << m_strSchemeUC + ": " + "/" + std::to_string( serverIndex() ) + << " >>> " + m_strSchemeUC + "/" + std::to_string( serverIndex() ) + "/RX >>> " + + "Skipping connection accept while in shutdown mode"; return pSkalePeer; } pSkalePeer = new SkaleWsPeer( srv, hdl ); @@ -1901,6 +1787,21 @@ SkaleRelayWS::SkaleRelayWS( int ipVer, const char* strBindAddr, }; } +dev::Logger SkaleWsPeer::getLoggerFromWsMsgType( skutils::ws::e_ws_log_message_type_t eWSLMT ) { + switch ( eWSLMT ) { + case skutils::ws::e_ws_log_message_type_t::eWSLMT_debug: + return m_loggerDebug; + case skutils::ws::e_ws_log_message_type_t::eWSLMT_info: + return m_loggerInfo; + case skutils::ws::e_ws_log_message_type_t::eWSLMT_warning: + return m_loggerWarning; + case skutils::ws::e_ws_log_message_type_t::eWSLMT_error: + return m_loggerError; + default: + return m_loggerTrace; + } +} + SkaleRelayWS::~SkaleRelayWS() { stop(); } @@ -1934,12 +1835,12 @@ bool SkaleRelayWS::start( SkaleServerOverride* pSO ) { stop(); m_pSO = pSO; server_disable_ipv6_ = ( ipVer_ == 6 ) ? false : true; - clog( dev::VerbosityDebug, cc::info( m_strSchemeUC ) ) - << ( cc::notice( "Will start server on port " ) + cc::c( m_nPort ) ); + LOG( m_loggerDebug ) << m_strSchemeUC + ": " + << ( "Will start server on port " + std::to_string( m_nPort ) ); if ( !open( m_strScheme_, m_nPort, ( !strInterfaceName_.empty() ) ? strInterfaceName_.c_str() : nullptr ) ) { - clog( dev::VerbosityError, cc::fatal( m_strSchemeUC + " ERROR:" ) ) - << ( cc::error( "Failed to start server on port " ) + cc::c( m_nPort ) ); + LOG( m_loggerError ) << m_strSchemeUC + ": " << +" ERROR:" + << ( "Failed to start server on port " + std::to_string( m_nPort ) ); return false; } std::thread( [pThis]() { @@ -1958,20 +1859,20 @@ bool SkaleRelayWS::start( SkaleServerOverride* pSO ) { } // pThis->m_isRunning = false; } ).detach(); - clog( dev::VerbosityDebug, cc::info( m_strSchemeUC ) ) - << ( cc::success( "OK, server started on port " ) + cc::c( m_nPort ) ); + LOG( m_loggerDebug ) << m_strSchemeUC + ": " + << "OK, server started on port " + std::to_string( m_nPort ); return true; } void SkaleRelayWS::stop() { if ( !isRunning() ) return; - clog( dev::VerbosityDebug, cc::info( m_strSchemeUC ) ) - << ( cc::notice( "Will stop on port " ) + cc::c( m_nPort ) + cc::notice( "..." ) ); + LOG( m_loggerDebug ) << m_strSchemeUC + ": " + << "Will stop on port " + std::to_string( m_nPort ) + "..."; m_isRunning = false; waitWhileInLoop(); close(); - clog( dev::VerbosityInfo, cc::info( m_strSchemeUC ) ) - << ( cc::success( "OK, server stopped on port " ) + cc::c( m_nPort ) ); + LOG( m_loggerInfo ) << m_strSchemeUC + ": " + << "OK, server stopped on port " + std::to_string( m_nPort ); } dev::eth::Interface* SkaleRelayWS::ethereum() const { @@ -2025,8 +1926,8 @@ SkaleServerOverride::SkaleServerOverride( // proxygen-related init skutils::http_pg::init_logging( "skaled" ); skutils::http_pg::install_logging_fail_func( []() -> void { - clog( dev::VerbosityError, "generic" ) << ( cc::fatal( "CRITICAL ERROR:" ) + " " + - cc::error( "Proxygen abort handler called." ) ); + dev::Logger logger{ createLogger( dev::VerbosityError, "SkaleServerOverride" ) }; + LOG( logger ) << "CRITICAL ERROR: Proxygen abort handler called."; } ); // // @@ -2127,28 +2028,29 @@ const dev::eth::ChainParams& SkaleServerOverride::chainParams() const { return chainParams_; } -dev::Verbosity SkaleServerOverride::methodTraceVerbosity( const std::string& strMethod ) const { +std::unique_ptr< dev::Logger > SkaleServerOverride::getLoggerFromMethodTraceVerbosity( + const std::string& strMethod ) const { // skip if disabled completely if ( !this->opts_.isTraceCalls_ && !this->opts_.isTraceSpecialCalls_ ) - return dev::VerbositySilent; + return nullptr; // skip these in any case if ( strMethod == "skale_stats" || strMethod == "skale_performanceTrackingStatus" || strMethod == "skale_performanceTrackingStart" || strMethod == "skale_performanceTrackingStop" || strMethod == "skale_performanceTrackingFetch" ) - return dev::VerbositySilent; + return nullptr; // print special if ( strMethod.find( "admin_" ) == 0 || strMethod.find( "miner_" ) == 0 || strMethod.find( "personal_" ) == 0 || strMethod.find( "debug_" ) ) { - return dev::VerbosityDebug; + return std::make_unique< dev::Logger >( m_loggerDebug ); } if ( this->opts_.isTraceCalls_ ) - return dev::VerbosityTrace; + return std::make_unique< dev::Logger >( m_loggerTrace ); - return dev::VerbositySilent; + return nullptr; } bool SkaleServerOverride::checkAdminOriginAllowed( const std::string& origin ) const { @@ -2170,28 +2072,30 @@ void SkaleServerOverride::logPerformanceWarning( double lfExecutionDuration, int const char* strMethod, nlohmann::json joID ) { std::stringstream ssProtocol; strProtocol = ( strProtocol && strProtocol[0] ) ? strProtocol : "Unknown network protocol"; - ssProtocol << cc::info( strProtocol ); + ssProtocol << strProtocol; if ( ipVer > 0 ) - ssProtocol << cc::debug( "/" ) << cc::notice( "IPv" ) << cc::num10( ipVer ); + ssProtocol << "/" + << "IPv" << ipVer; if ( nServerIndex >= 0 ) - ssProtocol << cc::debug( "/" ) << cc::num10( nServerIndex ); - ssProtocol << cc::debug( "/" ) << cc::notice( esm2str( esm ) ); - ssProtocol << cc::info( std::string( ":" ) ); + ssProtocol << "/" << nServerIndex; + ssProtocol << "/" << esm2str( esm ); + ssProtocol << ":"; std::string strProtocolDescription = ssProtocol.str(); // std::string strCallID = joID.dump(); // std::stringstream ssMessage; - ssMessage << cc::deep_warn( "Performance warning:" ) << " " << cc::c( lfExecutionDuration ) - << cc::warn( " seconds execution time for " ) << cc::info( strMethod ) - << cc::warn( " call with " ) << cc::notice( "id" ) << cc::warn( "=" ) - << cc::info( strCallID ) << cc::warn( " when called from origin " ) - << cc::notice( strOrigin ); + ssMessage << "Performance warning:" + << " " << lfExecutionDuration << " seconds execution time for " << strMethod + << " call with " + << "id" + << "=" << strCallID << " when called from origin " << strOrigin; if ( nServerIndex >= 0 ) - ssMessage << cc::warn( " through server with " ) << cc::notice( "index" ) << cc::warn( "=" ) - << cc::num10( nServerIndex ); + ssMessage << " through server with " + << "index" + << "=" << nServerIndex; std::string strMessage = ssMessage.str(); - clog( dev::VerbosityWarning, strProtocolDescription ) << strMessage; + LOG( m_loggerWarning ) << strProtocolDescription + ": " << strMessage; } void SkaleServerOverride::logTraceServerEvent( bool isError, int ipVer, const char* strProtocol, @@ -2200,69 +2104,67 @@ void SkaleServerOverride::logTraceServerEvent( bool isError, int ipVer, const ch return; std::stringstream ssProtocol; strProtocol = ( strProtocol && strProtocol[0] ) ? strProtocol : "Unknown network protocol"; - ssProtocol << cc::info( strProtocol ); + ssProtocol << strProtocol; if ( ipVer > 0 ) - ssProtocol << cc::debug( "/" ) << cc::notice( "IPv" ) << cc::num10( ipVer ); + ssProtocol << "/" + << "IPv" << ipVer; if ( nServerIndex >= 0 ) - ssProtocol << cc::debug( "/" ) << cc::num10( nServerIndex ); - ssProtocol << cc::debug( "/" ) << cc::notice( esm2str( esm ) ); + ssProtocol << "/" << nServerIndex; + ssProtocol << "/" << esm2str( esm ); if ( isError ) - ssProtocol << cc::fatal( std::string( " ERROR:" ) ); + ssProtocol << " ERROR:"; else - ssProtocol << cc::info( std::string( ":" ) ); + ssProtocol << ":"; std::string strProtocolDescription = ssProtocol.str(); if ( isError ) - clog( dev::VerbosityError, strProtocolDescription ) << strMessage; + LOG( m_loggerError ) << strProtocolDescription + ": " << strMessage; else - clog( dev::VerbosityDebug, strProtocolDescription ) << strMessage; + LOG( m_loggerDebug ) << strProtocolDescription + ": " << strMessage; } -void SkaleServerOverride::logTraceServerTraffic( bool isRX, dev::Verbosity verbosity, int ipVer, +void SkaleServerOverride::logTraceServerTraffic( bool isRX, dev::Logger logger, int ipVer, const char* strProtocol, int nServerIndex, e_server_mode_t esm, const char* strOrigin, const std::string& strPayload ) { - bool isError = verbosity == dev::VerbosityError; - std::stringstream ssProtocol; std::string strProto = ( strProtocol && strProtocol[0] ) ? strProtocol : "Unknown network protocol"; strOrigin = ( strOrigin && strOrigin[0] ) ? strOrigin : "unknown origin"; std::string strErrorSuffix, strOriginSuffix, strDirect; if ( isRX ) { - strDirect = cc::ws_rx( " >>> " ); - ssProtocol << cc::ws_rx_inv( " >>> " + strProto ); + strDirect = " >>> "; + ssProtocol << " >>> " + strProto; if ( ipVer > 0 ) - ssProtocol << cc::debug( "/" ) << cc::notice( "IPv" ) << cc::num10( ipVer ); + ssProtocol << "/" + << "IPv" << ipVer; if ( nServerIndex >= 0 ) - ssProtocol << cc::ws_rx_inv( "/" + std::to_string( nServerIndex ) ); - ssProtocol << cc::debug( "/" ) << cc::notice( esm2str( esm ) ); - ssProtocol << cc::ws_rx_inv( "/RX >>> " ); + ssProtocol << "/" + std::to_string( nServerIndex ); + ssProtocol << "/" << esm2str( esm ); + ssProtocol << "/RX >>> "; } else { - strDirect = cc::ws_tx( " <<< " ); - ssProtocol << cc::ws_tx_inv( " <<< " + strProto ); + strDirect = " <<< "; + ssProtocol << " <<< " + strProto; if ( ipVer > 0 ) - ssProtocol << cc::debug( "/" ) << cc::notice( "IPv" ) << cc::num10( ipVer ); + ssProtocol << "/" + << "IPv" << ipVer; if ( nServerIndex >= 0 ) - ssProtocol << cc::ws_tx_inv( "/" + std::to_string( nServerIndex ) ); - ssProtocol << cc::debug( "/" ) << cc::notice( esm2str( esm ) ); - ssProtocol << cc::ws_tx_inv( "/TX <<< " ); + ssProtocol << "/" + std::to_string( nServerIndex ); + ssProtocol << "/" << esm2str( esm ); + ssProtocol << "/TX <<< "; } - strOriginSuffix = cc::u( strOrigin ); - if ( isError ) - strErrorSuffix = cc::fatal( " ERROR " ); + strOriginSuffix = strOrigin; + std::string strProtocolDescription = ssProtocol.str(); - clog( verbosity, strProtocolDescription ) - << ( strErrorSuffix + strOriginSuffix + strDirect + strPayload ); + LOG( logger ) << strProtocolDescription + ": " + << strErrorSuffix + strOriginSuffix + strDirect + strPayload; } static void stat_check_port_availability_for_server_to_start_listen( int ipVer, const char* strAddr, int nPort, e_server_mode_t esm, const char* strProtocolName, int nServerIndex, SkaleServerOverride* pSO ) { pSO->logTraceServerEvent( false, ipVer, strProtocolName, nServerIndex, esm, - cc::debug( "Will check port " ) + cc::num10( nPort ) + - cc::debug( "/IPv" + std::to_string( ipVer ) ) + cc::debug( "/" ) + - cc::notice( esm2str( esm ) ) + cc::debug( " availability for " ) + - cc::info( strProtocolName ) + cc::debug( " server..." ) ); + "Will check port " + std::to_string( nPort ) + "/IPv" + std::to_string( ipVer ) + "/" + + esm2str( esm ) + " availability for " + strProtocolName + " server..." ); skutils::network::sockaddr46 sa46; std::string strError = skutils::network::resolve_address_for_client_connection( ipVer, strAddr, sa46 ); @@ -2270,8 +2172,7 @@ static void stat_check_port_availability_for_server_to_start_listen( int ipVer, throw std::runtime_error( std::string( "Failed to check " ) + std::string( strProtocolName ) + std::string( " server listen IP address availability for address \"" ) + strAddr + - std::string( "\" on IPv" ) + std::to_string( ipVer ) + cc::debug( "/" ) + - cc::notice( esm2str( esm ) ) + + std::string( "\" on IPv" ) + std::to_string( ipVer ) + "/" + esm2str( esm ) + std::string( ", please check network interface with this IP address exist, error details: " ) + strError ); @@ -2282,10 +2183,8 @@ static void stat_check_port_availability_for_server_to_start_listen( int ipVer, std::to_string( nPort ) + std::string( ", IPv" ) + std::to_string( ipVer ) + std::string( "/" ) + esm2str( esm ) + std::string( " - port is already listening" ) ); pSO->logTraceServerEvent( false, ipVer, strProtocolName, nServerIndex, esm, - cc::notice( "Port " ) + cc::num10( nPort ) + - cc::notice( "/IPv" + std::to_string( ipVer ) ) + cc::debug( "/" ) + - cc::notice( esm2str( esm ) ) + cc::notice( " is free for " ) + - cc::info( strProtocolName ) + cc::notice( " server to start" ) ); + "Port " + std::to_string( nPort ) + "/IPv" + std::to_string( ipVer ) + "/" + + esm2str( esm ) + " is free for " + strProtocolName + " server to start" ); } string hostname_to_ip( string hostname ) { @@ -2384,6 +2283,7 @@ skutils::result_of_http_request SkaleServerOverride::implHandleHttpRequest( // // nlohmann::json jarrBatchAnswer; + std::unique_ptr< dev::Logger > logger; if ( isBatch ) jarrBatchAnswer = nlohmann::json::array(); for ( const nlohmann::json& joRequest : jarrRequest ) { @@ -2398,10 +2298,9 @@ skutils::result_of_http_request SkaleServerOverride::implHandleHttpRequest( rttElement.emplace( "RPC", strProtocol.c_str(), strMethod.c_str(), nServerIndex, ipVer ); // SkaleServerConnectionsTrackHelper sscth( *this ); - if ( methodTraceVerbosity( strMethod ) != dev::VerbositySilent ) - logTraceServerTraffic( true, methodTraceVerbosity( strMethod ), ipVer, - strProtocol.c_str(), nServerIndex, esm, strOrigin.c_str(), - implPreformatTrafficJsonMessage( strBody, true ) ); + if ( logger = getLoggerFromMethodTraceVerbosity( strMethod ) ) + logTraceServerTraffic( true, *logger, ipVer, strProtocol.c_str(), nServerIndex, esm, + strOrigin.c_str(), implPreformatTrafficJsonMessage( strBody, true ) ); std::string strResponse; bool bPassed = false; try { @@ -2447,8 +2346,8 @@ skutils::result_of_http_request SkaleServerOverride::implHandleHttpRequest( bPassed = true; } catch ( const std::exception& ex ) { rttElement->setError(); - logTraceServerTraffic( false, dev::VerbosityError, ipVer, strProtocol.c_str(), - nServerIndex, esm, strOrigin.c_str(), cc::warn( ex.what() ) ); + logTraceServerTraffic( false, m_loggerError, ipVer, strProtocol.c_str(), nServerIndex, + esm, strOrigin.c_str(), ex.what() ); nlohmann::json joErrorResponce; joErrorResponce["jsonrpc"] = "2.0"; joErrorResponce["id"] = joID; @@ -2470,8 +2369,8 @@ skutils::result_of_http_request SkaleServerOverride::implHandleHttpRequest( } catch ( ... ) { rttElement->setError(); const char* e = "unknown exception in SkaleServerOverride"; - logTraceServerTraffic( false, dev::VerbosityError, ipVer, strProtocol.c_str(), - nServerIndex, esm, strOrigin.c_str(), cc::warn( e ) ); + logTraceServerTraffic( false, m_loggerError, ipVer, strProtocol.c_str(), nServerIndex, + esm, strOrigin.c_str(), e ); nlohmann::json joErrorResponce; joErrorResponce["jsonrpc"] = "2.0"; joErrorResponce["id"] = joID; @@ -2491,10 +2390,9 @@ skutils::result_of_http_request SkaleServerOverride::implHandleHttpRequest( } a.set_json_err( joErrorResponce ); } - if ( methodTraceVerbosity( strMethod ) != dev::VerbositySilent ) - logTraceServerTraffic( false, methodTraceVerbosity( strMethod ), ipVer, - strProtocol.c_str(), nServerIndex, esm, strOrigin.c_str(), - implPreformatTrafficJsonMessage( strResponse, false ) ); + if ( logger = getLoggerFromMethodTraceVerbosity( strMethod ) ) + logTraceServerTraffic( false, *logger, ipVer, strProtocol.c_str(), nServerIndex, esm, + strOrigin.c_str(), implPreformatTrafficJsonMessage( strResponse, false ) ); if ( isBatch ) { nlohmann::json joAnswerPart = nlohmann::json::parse( strResponse ); jarrBatchAnswer.push_back( joAnswerPart ); @@ -2530,10 +2428,9 @@ bool SkaleServerOverride::implStartListening( // web socket if ( strAddr.empty() || nPort <= 0 ) return true; logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", nServerIndex, esm, - cc::debug( "starting " ) + cc::info( bIsSSL ? "WSS" : "WS" ) + cc::debug( "/" ) + - cc::num10( nServerIndex ) + cc::debug( "/" ) + cc::notice( esm2str( esm ) ) + - cc::debug( " server on address " ) + cc::info( strAddr ) + - cc::debug( " and port " ) + cc::c( nPort ) + cc::debug( "..." ) ); + "starting " + std::string( bIsSSL ? "WSS" : "WS" ) + "/" + + std::to_string( nServerIndex ) + "/" + esm2str( esm ) + " server on address " + + strAddr + " and port " + std::to_string( nPort ) + "..." ); pSrv.reset( new SkaleRelayWS( ipVer, strAddr.c_str(), bIsSSL ? "wss" : "ws", nPort, esm, nServerIndex, &bns4ws_ ) ); if ( bIsSSL ) { @@ -2547,19 +2444,17 @@ bool SkaleServerOverride::implStartListening( // web socket if ( !pSrv->start( this ) ) throw std::runtime_error( "Failed to start server" ); logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", pSrv->serverIndex(), esm, - cc::success( "OK, started " ) + cc::info( bIsSSL ? "WSS" : "WS" ) + cc::debug( "/" ) + - cc::num10( pSrv->serverIndex() ) + cc::success( " server on address " ) + - cc::info( strAddr ) + cc::success( " and port " ) + cc::c( nPort ) + - cc::debug( "..." ) ); + "OK, started " + std::string( bIsSSL ? "WSS" : "WS" ) + "/" + + std::to_string( pSrv->serverIndex() ) + " server on address " + strAddr + + " and port " + std::to_string( nPort ) + "..." ); return true; } catch ( const std::exception& ex ) { logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", pSrv->serverIndex(), esm, - cc::fatal( "FAILED" ) + cc::error( " to start " ) + cc::warn( bIsSSL ? "WSS" : "WS" ) + - cc::error( " server: " ) + cc::warn( ex.what() ) ); + "FAILED to start " + std::string( bIsSSL ? "WSS" : "WS" ) + " server: " + ex.what() ); } catch ( ... ) { logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", pSrv->serverIndex(), esm, - cc::fatal( "FAILED" ) + cc::error( " to start " ) + cc::warn( bIsSSL ? "WSS" : "WS" ) + - cc::error( " server: " ) + cc::warn( "unknown exception" ) ); + "FAILED to start " + std::string( bIsSSL ? "WSS" : "WS" ) + + " server: " + "unknown exception" ); } try { implStopListening( pSrv, ipVer, bIsSSL, esm ); @@ -2582,11 +2477,9 @@ bool SkaleServerOverride::implStartListening( // proxygen HTTP if ( strAddr.empty() || nPort <= 0 ) return true; logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", -1, esm, - cc::debug( "starting " ) + cc::attention( "proxygen" ) + cc::debug( "/" ) + - cc::info( bIsSSL ? "HTTPS" : "HTTP" ) + cc::debug( "/" ) + - cc::num10( nServerIndex ) + cc::debug( "/" ) + cc::notice( esm2str( esm ) ) + - cc::debug( " server on address " ) + cc::info( strAddr ) + - cc::debug( " and port " ) + cc::c( nPort ) + cc::debug( "..." ) ); + "starting proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + "/" + + std::to_string( nServerIndex ) + "/" + esm2str( esm ) + " server on address " + + strAddr + " and port " + std::to_string( nPort ) + "..." ); // check if somebody is already listening @@ -2602,24 +2495,20 @@ bool SkaleServerOverride::implStartListening( // proxygen HTTP else throw std::runtime_error( "failed to start proxygen server instance" ); logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", pSrv->serverIndex(), esm, - cc::success( "OK, started " ) + cc::attention( "proxygen" ) + cc::debug( "/" ) + - cc::info( bIsSSL ? "HTTPS" : "HTTP" ) + cc::debug( "/" ) + - cc::num10( pSrv->serverIndex() ) + cc::success( " server on address " ) + - cc::info( strAddr ) + cc::success( " and port " ) + cc::c( nPort ) + - cc::success( "/" ) + cc::notice( esm2str( esm ) ) + " " ); + "OK, started proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + "/" + + std::to_string( pSrv->serverIndex() ) + " server on address " + strAddr + + " and port " + std::to_string( nPort ) + "/" + esm2str( esm ) + " " ); return true; } catch ( const std::exception& ex ) { logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", pSrv ? pSrv->serverIndex() : -1, esm, - cc::fatal( "FAILED" ) + cc::error( " to start " ) + cc::attention( "proxygen" ) + - cc::debug( "/" ) + cc::warn( bIsSSL ? "HTTPS" : "HTTP" ) + - cc::error( " server: " ) + cc::warn( ex.what() ) ); + "FAILED to start proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + + " server: " + ex.what() ); } catch ( ... ) { logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", pSrv ? pSrv->serverIndex() : -1, esm, - cc::fatal( "FAILED" ) + cc::error( " to start " ) + cc::attention( "proxygen" ) + - cc::debug( "/" ) + cc::warn( bIsSSL ? "HTTPS" : "HTTP" ) + - cc::error( " server: " ) + cc::warn( "unknown exception" ) ); + "FAILED to start proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + + " server: " + "unknown exception" ); } try { implStopListening( pSrv, ipVer, bIsSSL, esm ); @@ -2644,18 +2533,14 @@ bool SkaleServerOverride::implStopListening( // web socket ( bIsSSL ? bo.nBasePortWSS6_ : bo.nBasePortWS6_ ) ) + nServerIndex; logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", nServerIndex, esm, - cc::notice( "Will stop " ) + cc::info( bIsSSL ? "WSS" : "WS" ) + - cc::notice( " server on address " ) + cc::info( strAddr ) + - cc::success( " and port " ) + cc::c( nPort ) + cc::debug( "/" ) + - cc::notice( esm2str( esm ) ) + cc::notice( "..." ) ); + "Will stop " + std::string( bIsSSL ? "WSS" : "WS" ) + " server on address " + strAddr + + " and port " + std::to_string( nPort ) + "/" + esm2str( esm ) + "..." ); if ( pSrv->isRunning() ) pSrv->stop(); pSrv.reset(); logTraceServerEvent( false, ipVer, bIsSSL ? "WSS" : "WS", nServerIndex, esm, - cc::success( "OK, stopped " ) + cc::info( bIsSSL ? "WSS" : "WS" ) + - cc::success( " server on address " ) + cc::info( strAddr ) + - cc::success( " and port " ) + cc::c( nPort ) + cc::debug( "/" ) + - cc::notice( esm2str( esm ) ) ); + "OK, stopped " + std::string( bIsSSL ? "WSS" : "WS" ) + " server on address " + + strAddr + " and port " + std::to_string( nPort ) + "/" + esm2str( esm ) ); } catch ( ... ) { } return true; @@ -2678,18 +2563,16 @@ bool SkaleServerOverride::implStopListening( // proxygen HTTP ( bIsSSL ? bo.nBasePortHTTPS6_ : bo.nBasePortHTTP6_ ) ) + nServerIndex; logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", nServerIndex, esm, - cc::notice( "Will stop " ) + cc::attention( "proxygen" ) + cc::debug( "/" ) + - cc::info( bIsSSL ? "HTTPS" : "HTTP" ) + cc::notice( " server on address " ) + - cc::info( strAddr ) + cc::success( " and port " ) + cc::c( nPort ) + - cc::debug( "/" ) + cc::notice( esm2str( esm ) ) + cc::notice( "..." ) ); + "Will stop proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + + " server on address " + strAddr + " and port " + std::to_string( nPort ) + "/" + + esm2str( esm ) + "..." ); pSrv->stop(); stats::register_stats_message( bIsSSL ? "HTTPS" : "HTTP", "STOP" ); pSrv.reset(); logTraceServerEvent( false, ipVer, bIsSSL ? "HTTPS" : "HTTP", nServerIndex, esm, - cc::success( "OK, stopped " ) + cc::attention( "proxygen" ) + cc::debug( "/" ) + - cc::info( bIsSSL ? "HTTPS" : "HTTP" ) + cc::success( " server on address " ) + - cc::info( strAddr ) + cc::success( " and port " ) + cc::c( nPort ) + - cc::debug( "/" ) + cc::notice( esm2str( esm ) ) ); + "OK, stopped proxygen/" + std::string( bIsSSL ? "HTTPS" : "HTTP" ) + + " server on address " + strAddr + " and port " + std::to_string( nPort ) + "/" + + esm2str( esm ) ); } catch ( ... ) { } return true; @@ -2848,9 +2731,8 @@ e_server_mode_t SkaleServerOverride::implGuessProxygenRequestESM( return esm; if ( implGuessProxygenRequestESM( serversProxygenHTTPS6nfo_, strDstAddress, nDstPort, esm ) ) return esm; - clog( dev::VerbosityWarning, cc::fatal( "WARNING:" ) ) - << ( cc::warn( "Failed to lookup ESM for " ) + cc::attention( strDstAddress ) + - cc::warn( ":" ) + cc::num10( nDstPort ) ); + LOG( m_loggerWarning ) << ( "Failed to lookup ESM for " + strDstAddress + ":" + + std::to_string( nDstPort ) ); return e_server_mode_t::esm_standard; } bool SkaleServerOverride::implGuessProxygenRequestESM( @@ -2901,8 +2783,7 @@ bool SkaleServerOverride::StartListening() { skutils::http_pg::pg_accumulate_start( fnHandler, pg_threads_, pg_threads_limit_ ); skutils::http_pg::pg_accumulate_clear(); if ( !hProxygenServer_ ) { - clog( dev::VerbosityError, cc::fatal( "PROXYGEN ERROR:" ) ) - << ( cc::error( "Failed to start server" ) ); + LOG( m_loggerError ) << "PROXYGEN ERROR: Failed to start server"; return false; } } @@ -3082,10 +2963,9 @@ void SkaleServerOverride::max_connection_set( size_t cntConnectionsMax ) { void SkaleServerOverride::on_connection_overflow_peer_closed( int ipVer, const char* strProtocol, int nServerIndex, int nPort, e_server_mode_t esm ) { - std::string strMessage = cc::info( strProtocol ) + cc::debug( "/" ) + - cc::num10( nServerIndex ) + cc::warn( " server on port " ) + - cc::num10( nPort ) + - cc::warn( " did closed peer because of connection limit overflow" ); + std::string strMessage = std::string( strProtocol ) + "/" + std::to_string( nServerIndex ) + + " server on port " + std::to_string( nPort ) + + " did closed peer because of connection limit overflow"; logTraceServerEvent( false, ipVer, strProtocol, nServerIndex, esm, strMessage ); } @@ -3176,9 +3056,9 @@ static std::string stat_encode_eth_call_data_chunck_address( void SkaleServerOverride::informational_eth_getBalance( const nlohmann::json& joRequest, nlohmann::json& joResponse ) { - std::cout << ( cc::debug( "Got call to informational version of " ) + - cc::info( "eth_getBalance" ) + cc::debug( " JSON RPC API with request as " ) + - cc::j( joRequest ) + "\n" ); + LOG( m_loggerDebug ) + << "Got call to informational version of eth_getBalance JSON RPC API with request as " + + joRequest.dump(); auto pEthereum = ethereum(); if ( !pEthereum ) throw std::runtime_error( "internal error, no Ethereum interface found" ); @@ -3241,11 +3121,9 @@ void SkaleServerOverride::informational_eth_getBalance( strRevertReason = "EVM revert instruction without description message"; Json::FastWriter fastWriter; std::string strJSON = fastWriter.write( _jsonCallArgs ); - std::string strOut = cc::fatal( "Error message from eth_call():" ) + cc::error( " " ) + - cc::warn( strRevertReason ) + - cc::error( ", with call arguments: " ) + cc::j( strJSON ) + - cc::error( ", and using " ) + cc::info( "blockNumber" ) + - cc::error( "=" ) + cc::bright( blockNumber ); + std::string strOut = "Error message from eth_call(): " + strRevertReason + + ", with call arguments: " + strJSON + ", and using " + + "blockNumber" + "=" + blockNumber; cerror << strOut; cerror << DETAILED_ERROR; throw std::runtime_error( strRevertReason ); @@ -3257,17 +3135,15 @@ void SkaleServerOverride::informational_eth_getBalance( const char* strError = ex.what(); if ( strError == nullptr || strError[0] == '\0' ) strError = "Error without description in informational version of \"eth_getBalance\""; - std::cout << ( cc::fatal( "ERROR:" ) + - cc::error( " Got error in informational version of " ) + - cc::info( "eth_getBalance" ) + cc::debug( " with description: " ) + - cc::error( strError ) + "\n" ); + LOG( m_loggerError ) + << "ERROR: Got error in informational version of eth_getBalance with description: " + << strError; throw ex; } catch ( ... ) { const char* strError = "Unknown error in informational version of \"eth_getBalance\""; - std::cout << ( cc::fatal( "ERROR:" ) + - cc::error( " Got error in informational version of " ) + - cc::info( "eth_getBalance" ) + cc::debug( " with description: " ) + - cc::error( strError ) + "\n" ); + LOG( m_loggerError ) + << "ERROR: Got error in informational version of eth_getBalance with description: " + << strError; throw std::runtime_error( strError ); } } @@ -3378,14 +3254,10 @@ void SkaleServerOverride::setSchainExitTime( const std::string& strOrigin, bool isLocalAddress = skutils::is_local_private_network_address( strIP ); // NOTICE: supports both IPv4 and IPv6 // print info about this method call into log output - clog( dev::VerbosityDebug, cc::warn( "ADMIN-CALL" ) ) - << ( cc::debug( "Got " ) + cc::info( "setSchainExitTime" ) + - cc::debug( " call with " ) + cc::notice( "finishTime" ) + cc::debug( "=" ) + - cc::size10( finishTime ) + cc::debug( ", " ) + cc::notice( "origin" ) + - cc::debug( "=" ) + cc::notice( strOrigin ) + cc::debug( ", " ) + - cc::notice( "remote IP" ) + cc::debug( "=" ) + cc::notice( strIP ) + - cc::debug( ", " ) + cc::notice( "isLocalAddress" ) + cc::debug( "=" ) + - cc::yn( isLocalAddress ) ); + LOG( m_loggerDebug ) << "ADMIN-CALL " + << "Got setSchainExitTime call with finishTime = " + finishTime + << ", origin = " + strOrigin + ", remote IP = " + strIP + + ", isLocalAddress = " + ( isLocalAddress ? "yes" : "no" ); // return call error if call from outside of local network if ( !isLocalAddress ) throw std::runtime_error( @@ -3421,10 +3293,9 @@ void SkaleServerOverride::setSchainExitTime( const std::string& strOrigin, joResponse.Parse( strResponse.data() ); } catch ( const std::exception& ex ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::debug( " during call from " ) + cc::u( strOrigin ) ) - << ( " " + cc::error( "error in " ) + cc::warn( "setSchainExitTime" ) + - cc::error( " rpc method, exception " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << " during call from " + strOrigin + << " error in setSchainExitTime rpc method, exception " + << ex.what(); rapidjson::Value joError; joError.SetObject(); joError.AddMember( "code", -32602, joResponse.GetAllocator() ); @@ -3436,10 +3307,8 @@ void SkaleServerOverride::setSchainExitTime( const std::string& strOrigin, joResponse.AddMember( "error", joError, joResponse.GetAllocator() ); } catch ( ... ) { if ( pSO->opts_.isTraceCalls_ ) - clog( dev::Verbosity::VerbosityError, - cc::debug( " during call from " ) + cc::u( strOrigin ) ) - << ( " " + cc::error( "error in " ) + cc::warn( "setSchainExitTime" ) + - cc::error( " rpc method, unknown exception " ) ); + LOG( m_loggerError ) << " during call from " + strOrigin + << " error in setSchainExitTime rpc method, unknown exception "; rapidjson::Value joError; joError.SetObject(); joError.AddMember( "code", -32602, joResponse.GetAllocator() ); @@ -3550,8 +3419,7 @@ std::string SkaleServerOverride::implPreformatTrafficJsonMessage( return implPreformatTrafficJsonMessage( jo, isRequest ); } catch ( ... ) { } - return cc::error( isRequest ? "bad JSON request" : "bad JSON response" ) + " " + - cc::warn( strJSON ); + return isRequest ? "bad JSON request" : "bad JSON response " + strJSON; } std::string SkaleServerOverride::implPreformatTrafficJsonMessage( @@ -3560,7 +3428,7 @@ std::string SkaleServerOverride::implPreformatTrafficJsonMessage( SkaleServerOverride::stat_transformJsonForLogOutput( jo2, isRequest, SkaleServerOverride::g_nMaxStringValueLengthForJsonLogs, SkaleServerOverride::g_nMaxStringValueLengthForTransactionParams ); - return cc::j( jo2 ); + return jo2.dump(); } size_t SkaleServerOverride::g_nMaxStringValueLengthForJsonLogs = 1024 * 32; diff --git a/libskale/httpserveroverride.h b/libskale/httpserveroverride.h index 0cce6a132..d88a5fe5e 100644 --- a/libskale/httpserveroverride.h +++ b/libskale/httpserveroverride.h @@ -117,6 +117,16 @@ class SkaleStatsSubscriptionManager { bool unsubscribe( const subscription_id_t& idSubscription ); void unsubscribeAll(); virtual SkaleServerOverride& getSSO() = 0; + + +private: + /// Loggers + dev::Logger m_loggerDebug{ dev::createLogger( + dev::VerbosityDebug, "SkaleStatsSubscriptionManager" ) }; + dev::Logger m_loggerInfo{ dev::createLogger( + dev::VerbosityInfo, "SkaleStatsSubscriptionManager" ) }; + dev::Logger m_loggerError{ dev::createLogger( + dev::VerbosityError, "SkaleStatsSubscriptionManager" ) }; }; // class SkaleStatsSubscriptionManager @@ -193,6 +203,17 @@ class SkaleWsPeer : public skutils::ws::peer { void register_ws_conn_for_origin(); void unregister_ws_conn_for_origin(); + /// Loggers + std::string getLoggerName() const; + + dev::Logger getLoggerFromWsMsgType( skutils::ws::e_ws_log_message_type_t eWSLMT ); + + dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "SkaleWsPeer" ) }; + dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "SkaleWsPeer" ) }; + dev::Logger m_loggerTrace{ dev::createLogger( dev::VerbosityTrace, "SkaleWsPeer" ) }; + dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "SkaleWsPeer" ) }; + dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "SkaleWsPeer" ) }; + public: std::string implPreformatTrafficJsonMessage( const std::string& strJSON, bool isRequest ) const; std::string implPreformatTrafficJsonMessage( const nlohmann::json& jo, bool isRequest ) const; @@ -253,6 +274,15 @@ class SkaleRelayWS : public skutils::ws::server, public SkaleServerHelper { std::string nfoGetSchemeUC() const { return m_strSchemeUC; } friend class SkaleWsPeer; + +private: + /// Loggers + dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "SkaleRelayWS" ) }; + dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "SkaleRelayWS" ) }; + dev::Logger m_loggerTrace{ dev::createLogger( dev::VerbosityTrace, "SkaleRelayWS" ) }; + dev::Logger m_loggerWarning{ dev::createLogger( dev::VerbosityWarning, "SkaleRelayWS" ) }; + dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "SkaleRelayWS" ) }; + }; /// class SkaleRelayWS @@ -416,7 +446,8 @@ class SkaleServerOverride : public jsonrpc::AbstractServerConnector, dev::eth::Interface* ethereum() const; dev::eth::ChainParams& chainParams(); const dev::eth::ChainParams& chainParams() const; - dev::Verbosity methodTraceVerbosity( const std::string& strMethod ) const; + std::unique_ptr< dev::Logger > getLoggerFromMethodTraceVerbosity( + const std::string& strMethod ) const; bool checkAdminOriginAllowed( const std::string& origin ) const; protected: @@ -458,7 +489,7 @@ class SkaleServerOverride : public jsonrpc::AbstractServerConnector, nlohmann::json joID ); void logTraceServerEvent( bool isError, int ipVer, const char* strProtocol, int nServerIndex, e_server_mode_t esm, const std::string& strMessage ); - void logTraceServerTraffic( bool isRX, dev::Verbosity verbosity, int ipVer, + void logTraceServerTraffic( bool isRX, dev::Logger verbosity, int ipVer, const char* strProtocol, int nServerIndex, e_server_mode_t esm, const char* strOrigin, const std::string& strPayload ); @@ -481,6 +512,12 @@ class SkaleServerOverride : public jsonrpc::AbstractServerConnector, bool implGuessProxygenRequestESM( std::list< std::shared_ptr< SkaleRelayProxygenHTTP > >& lst, const std::string& strDstAddress, int nDstPort, e_server_mode_t& esm ); + /// Loggers + dev::Logger m_loggerDebug{ createLogger( dev::VerbosityDebug, "SkaleServerOverride" ) }; + dev::Logger m_loggerTrace{ createLogger( dev::VerbosityTrace, "SkaleServerOverride" ) }; + dev::Logger m_loggerWarning{ createLogger( dev::VerbosityWarning, "SkaleServerOverride" ) }; + dev::Logger m_loggerError{ createLogger( dev::VerbosityError, "SkaleServerOverride" ) }; + public: int getServerPortStatusWS( int ipVer, e_server_mode_t esm ) const; int getServerPortStatusWSS( int ipVer, e_server_mode_t esm ) const; diff --git a/libskutils/include/skutils/console_colors.h b/libskutils/include/skutils/console_colors.h index fdce082ff..4ac63e42c 100644 --- a/libskutils/include/skutils/console_colors.h +++ b/libskutils/include/skutils/console_colors.h @@ -6,11 +6,11 @@ #include #include #include -//#include +// #include #include #include -//#include +// #include #include #include diff --git a/libskutils/include/skutils/http.h b/libskutils/include/skutils/http.h index 4ba9b967e..bc8772800 100644 --- a/libskutils/include/skutils/http.h +++ b/libskutils/include/skutils/http.h @@ -82,7 +82,6 @@ typedef int socket_t; #include #include -//#include #include /// configuration @@ -102,7 +101,6 @@ typedef int socket_t; #define __SKUTILS_HTTP_CLIENT_CONNECT_TIMEOUT_MILLISECONDS__ ( 60 * 1000 ) -//#define #define __SKUTILS_HTTP_ENABLE_FILE_REQUEST_HANDLING 1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/libskutils/include/skutils/http_pg.h b/libskutils/include/skutils/http_pg.h index 5a7b06c9b..f6925b6ec 100644 --- a/libskutils/include/skutils/http_pg.h +++ b/libskutils/include/skutils/http_pg.h @@ -14,14 +14,12 @@ #include #include -//#include #include #include #include #pragma GCC diagnostic pop -//#include #include #include diff --git a/libskutils/include/skutils/multithreading.h b/libskutils/include/skutils/multithreading.h index ce798900a..890e51165 100644 --- a/libskutils/include/skutils/multithreading.h +++ b/libskutils/include/skutils/multithreading.h @@ -8,8 +8,6 @@ #include #include -//#define __SKUTILS_MULTITHREADING_DEBUG__ 1 - namespace skutils { namespace multithreading { diff --git a/libskutils/include/skutils/network.h b/libskutils/include/skutils/network.h index 9292d7d28..54db8e583 100644 --- a/libskutils/include/skutils/network.h +++ b/libskutils/include/skutils/network.h @@ -12,10 +12,8 @@ #include #include -//#include #include -//#define SKUTILS_WITH_SSL 1 extern "C" { #include diff --git a/libskutils/include/skutils/rest_call.h b/libskutils/include/skutils/rest_call.h index 94fa2c96c..f567cab4f 100644 --- a/libskutils/include/skutils/rest_call.h +++ b/libskutils/include/skutils/rest_call.h @@ -18,7 +18,6 @@ #include #include -//#include #include #include diff --git a/libskutils/include/skutils/utils.h b/libskutils/include/skutils/utils.h index 7a792f230..3b59bab8a 100644 --- a/libskutils/include/skutils/utils.h +++ b/libskutils/include/skutils/utils.h @@ -23,7 +23,6 @@ #include #include -//#include #include #include @@ -40,11 +39,6 @@ typedef std::vector< string_type_t > string_vector_t; namespace tools { -// std::string format ( const char * format, ... ); -// std::string format_no_throw( const char * format, ... ); -// std::string format ( const char * format, va_list args ); -// std::string format_no_throw( const char * format, va_list args ); - template < class T > bool equal( T d1, T d2, typename std::enable_if< std::is_floating_point< T >::value >::type* = 0 ) { static constexpr double eps = std::numeric_limits< double >::epsilon(); diff --git a/libskutils/src/command_line_parser.cpp b/libskutils/src/command_line_parser.cpp index a7de0fd50..5578f86ec 100644 --- a/libskutils/src/command_line_parser.cpp +++ b/libskutils/src/command_line_parser.cpp @@ -1,8 +1,7 @@ #include #include -#include -//#include #include +#include #include namespace skutils { @@ -221,8 +220,8 @@ bool parser::on_default_value( const std::string& v ) { std::string parser::banner_text() const { const std::string &a = app_name(), &v = app_version(); if ( v.empty() ) - return cc::note( a ) + "\n"; - return cc::note( a ) + cc::debug( " version " ) + cc::note( v ) + cc::debug( "." ) + "\n"; + return a + "\n"; + return a + " version " + v + "." + "\n"; } std::string parser::options_text( parser::e_options_publishing_type_t eoptt // = parser::e_options_publishing_type_t::eoptt_auto @@ -257,52 +256,52 @@ std::string parser::options_text( std::string s; if ( eoptt_effective == e_options_publishing_type_t::eoptt_linear ) { // linear options publishing - s += cc::note( "Options:" ) + "\n"; + s += "Options:\n"; std::for_each( list_sequence_handlers_.cbegin(), list_sequence_handlers_.cend(), [&]( name_sequence_list_t::const_reference name ) { std::string nameXnb = "--" + name; - std::string nameX = cc::debug( "--" ) + cc::note( name ); + std::string nameX = "--" + name; if ( const_cast< parser* >( this )->value_handler( name ) ) { nameXnb += value_suffix1; nameXnb += value_suffix2; - nameX += cc::info( value_suffix1 ); - nameX += cc::warn( value_suffix2 ); + nameX += value_suffix1; + nameX += value_suffix2; } - s += cc::debug( option_space_prefix ); + s += option_space_prefix; s += nameX; std::string strSpace; for ( size_t name_len = nameXnb.length(); name_len < name_len_max; ++name_len ) strSpace += "."; - s += cc::debug( strSpace ); - s += cc::debug( option_space_suffix ); - s += cc::info( description( name ) ) + "\n"; + s += strSpace; + s += option_space_suffix; + s += description( name ) + "\n"; } ); } else { // categorized options publishing std::for_each( list_sequence_categories_.cbegin(), list_sequence_categories_.cend(), [&]( name_sequence_list_t::const_reference strCategory ) { - s += cc::sunny( strCategory ) + cc::note( " options:" ) + "\n"; + s += strCategory + " options:\n"; const name_sequence_list_t& cat_opts = ( const_cast< parser* >( this ) )->map_category_opts_[strCategory]; std::for_each( cat_opts.cbegin(), cat_opts.cend(), [&]( name_sequence_list_t::const_reference name ) { std::string nameXnb = "--" + name; - std::string nameX = cc::debug( "--" ) + cc::note( name ); + std::string nameX = "--" + name; if ( const_cast< parser* >( this )->value_handler( name ) ) { nameXnb += value_suffix1; nameXnb += value_suffix2; - nameX += cc::info( value_suffix1 ); - nameX += cc::warn( value_suffix2 ); + nameX += value_suffix1; + nameX += value_suffix2; } - s += cc::debug( option_space_prefix ); + s += option_space_prefix; s += nameX; std::string strSpace; for ( size_t name_len = nameXnb.length(); name_len < name_len_max; ++name_len ) strSpace += "."; - s += cc::debug( strSpace ); - s += cc::debug( option_space_suffix ); - s += cc::info( description( name ) ) + "\n"; + s += strSpace; + s += option_space_suffix; + s += description( name ) + "\n"; } ); } ); } @@ -411,7 +410,7 @@ static std::string stat_gen_if( const std::pair< std::string, std::string >& x ) for ( i = nLenIfName; i < g_align; ++i ) strSpace += '.'; } - ss << cc::bright( x.first ) << cc::debug( strSpace ) << cc::sunny( x.second ); + ss << x.first << strSpace << x.second; return ss.str(); } @@ -419,19 +418,17 @@ void parser::stat_network_interfaces_info( std::ostream& os ) { std::list< std::pair< std::string, std::string > > lst; // first-interface name, second-address std::list< std::pair< std::string, std::string > >::const_iterator itWalk, itEnd; lst = skutils::network::get_machine_ip_addresses( true, false ); // try IP4 - os << cc::info( "Number of of found IPv4 interfaces" ) + cc::debug( "..................." ) - << cc::size10( lst.size() ) << std::endl; + os << "Number of of found IPv4 interfaces ..................." << lst.size() << "\n"; for ( itWalk = lst.cbegin(), itEnd = lst.cend(); itWalk != itEnd; ++itWalk ) - os << cc::debug( "...." ) - << cc::info( "IPv4 interface" ) + cc::debug( "..................................." ) - << stat_gen_if( *itWalk ) << std::endl; + os << "...." + << "IPv4 interface ..................................." << stat_gen_if( *itWalk ) + << "\n"; lst = skutils::network::get_machine_ip_addresses( false, true ); // try IP6 - os << cc::info( "Number of of found IPv6 interfaces" ) + cc::debug( "..................." ) - << cc::size10( lst.size() ) << std::endl; + os << "Number of of found IPv6 interfaces ..................." << lst.size() << "\n"; for ( itWalk = lst.cbegin(), itEnd = lst.cend(); itWalk != itEnd; ++itWalk ) - os << cc::debug( "...." ) - << cc::info( "IPv6 interface" ) + cc::debug( "..................................." ) - << stat_gen_if( *itWalk ) << std::endl; + os << "...." + << "IPv6 interface ..................................." << stat_gen_if( *itWalk ) + << "\n"; } }; // namespace command_line diff --git a/libskutils/src/dispatch.cpp b/libskutils/src/dispatch.cpp index 12ca74c68..4725f29c8 100644 --- a/libskutils/src/dispatch.cpp +++ b/libskutils/src/dispatch.cpp @@ -9,29 +9,15 @@ #include #include -//#define __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_ASYNC_JOB_STATES__ 1 -//#define __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_QUEUE_STATES__ 1 -//#define __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_LOOP_STATES__ 1 - -#define LOCAL_DEBUG_TRACE( x ) -// static inline void LOCAL_DEBUG_TRACE( const std::string & x ) { if( x.empty() -// ) return; std::cout.flush(); std::cerr.flush(); std::cout << x << "\n"; -// std::cout.flush(); } namespace skutils { namespace dispatch { skutils::multithreading::recursive_mutex_type& get_dispatch_mtx() { - // static skutils::multithreading::recursive_mutex_type g_dispatch_mtx( - // "skutils::dispatch::g_dispatch_mtx" ); - // return g_dispatch_mtx; return skutils::get_ref_mtx(); } static void stat_sleep( duration_t how_much ) { - // auto nNanoSeconds = how_much.count(); - // struct timespec ts{ time_t(nNanoSeconds/1000000000), - // long(nNanoSeconds%1000000000) }; nanosleep( &ts,nullptr ); std::this_thread::sleep_for( how_much ); } bool sleep_while_true( // returns false if timeout is reached and fn() never @@ -286,18 +272,12 @@ void loop::run() { // bool bHaveLoop = false; uv_loop_t uvLoop; - // - // bool bHaveIdler = false; - // uv_idle_t uvIdler; - // + bool bHaveTimerStateCheck = false; uv_timer_t uvTimerStateCheck; auto fnCleanupHere = [&]() -> void { lock_type lock( loop_mtx() ); - // if( bHaveIdler ) { - // bHaveIdler = false; - // uv_idle_stop( &uvIdler ); - // } + if ( bHaveTimerStateCheck ) { bHaveTimerStateCheck = false; uv_timer_stop( &uvTimerStateCheck ); @@ -316,22 +296,13 @@ void loop::run() { try { uv_loop_init( &uvLoop ); uvLoop.data = ( void* ) this; - // - // uv_idle_init( &uvLoop, &uvIdler ); - // uvIdler.data = ( void* ) this; - // bHaveIdler = true; - // + uv_timer_init( &uvLoop, &uvTimerStateCheck ); uvTimerStateCheck.data = ( void* ) this; // p_uvLoop_ = ( &uvLoop ); cancelMode_ = false; - // - // uv_idle_start( &uvIdler, []( uv_idle_t* p_uvIdler ) { - // loop* pLoop = ( loop* ) ( p_uvIdler->data ); - // pLoop->on_idle(); - // } ); - // + uv_timer_start( &uvTimerStateCheck, []( uv_timer_t* p_uvTimer ) { @@ -364,7 +335,7 @@ void loop::run() { } ); } // if ( p_uvAsyncInitForTimers_ != nullptr ) #endif // ( defined __SKUTILS_DISPATCH_ENABLE_ASYNC_INIT_CALL_FOR_TASK_TIMERS__ - // ) + // ) } catch ( ... ) { p_uvLoop_ = nullptr; } @@ -475,23 +446,8 @@ void loop::pending_timer_init() { pending_timer_list_.clear(); } -// void loop::on_idle() { -// //#if ( defined __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_LOOP_STATES__ ) -// // std::cout << skutils::tools::format( "dispatch loop idle %p\n", this ); -// // std::cout.flush(); -// //#endif -// isAlive_ = true; -// if ( on_check_cancel_mode() ) -// return; -// pending_timer_init(); -// on_check_jobs(); -//} void loop::on_state_check() { - //#if ( defined __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_LOOP_STATES__ ) - // std::cout << skutils::tools::format( "dispatch loop state check %p\n", - // this ); std::cout.flush(); - //#endif isAlive_ = true; if ( on_check_cancel_mode() ) return; @@ -500,10 +456,6 @@ void loop::on_state_check() { } bool loop::on_check_cancel_mode() { - //#if ( defined __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_LOOP_STATES__ ) - // std::cout << skutils::tools::format( "dispatch loop check cancel mode - // %p\n", this ); std::cout.flush(); - //#endif if ( cancelMode_ ) { // cancelMode_ = false; uv_loop_t* p_uvLoop = ( uv_loop_t* ) ( void* ) p_uvLoop_; @@ -517,10 +469,7 @@ bool loop::on_check_cancel_mode() { void loop::on_check_jobs() { if ( cancelMode_ ) return; - //#if ( defined __SKUTILS_DISPATCH_DEBUG_CONSOLE_TRACE_LOOP_STATES__ ) - // std::cout << skutils::tools::format( "dispatch loop check jobs %p\n", - // this ); std::cout.flush(); - //#endif + if ( on_check_jobs_ ) on_check_jobs_(); } @@ -1162,14 +1111,7 @@ domain::domain( const size_t nNumberOfThreads, // = 0 // 0 means use CPU count const size_t nQueueLimit // = 0 ) : async_job_count_( 0 ), - accumulator_base_( 0 ) - // , domain_mtx_( - // skutils::tools::format("skutils::dispatch::domain-%p/mutex/main", this - // ) - //) , mtx_with_jobs_( - // skutils::tools::format("skutils::dispatch::domain-%p/mutex/with_jobs", - // this ) ) - , + accumulator_base_( 0 ), shutdown_flag_( true ), thread_pool_( ( nNumberOfThreads > 0 ) ? nNumberOfThreads : skutils::tools::cpu_count(), nQueueLimit ), @@ -1272,11 +1214,6 @@ bool domain::impl_queue_remove( const queue_id_t& id ) { } ); if ( itFound != itTo ) { with_jobs_.erase( itFound ); - LOCAL_DEBUG_TRACE( cc::sunny( "domain::impl_queue_remove()" ) + cc::debug( " did " ) + - cc::error( "erased" ) + cc::debug( " already-removed queue " ) + - cc::bright( id ) + cc::debug( ", " ) + - cc::sunny( "with_jobs_.size()" ) + cc::debug( "=" ) + - cc::size10( with_jobs_.size() ) ); } } // block return true; @@ -1328,12 +1265,10 @@ void domain::impl_startup( size_t nWaitMilliSeconds /*= size_t(-1)*/ ) { try { if ( g_bVerboseDispatchThreadDetailsLogging ) { std::string strThreadStartupMessage = - cc::deep_note( "Dispatch:" ) + " " + - cc::debug( "Started thread " ) + cc::size10( idxThread ) + - cc::debug( " of " ) + cc::size10( cntThreadsToStart ) + - cc::debug( ", have " ) + - cc::size10( size_t( cntRunningThreads_ ) ) + - cc::debug( " running thread(s)" ) + "\n"; + "Dispatch: Started thread " + std::to_string( idxThread ) + + " of " + std::to_string( cntThreadsToStart ) + ", have " + + std::to_string( size_t( cntRunningThreads_ ) ) + + " running thread(s)" + "\n"; std::cout << strThreadStartupMessage; std::cout.flush(); } @@ -1368,38 +1303,30 @@ void domain::impl_startup( size_t nWaitMilliSeconds /*= size_t(-1)*/ ) { if ( strError.empty() ) strError = "Exception without description"; std::string strErrorMessage = - cc::deep_note( "Dispatch:" ) + " " + - cc::fatal( "CRITICAL ERROR:" ) + - cc::error( "Got exception in thread " ) + - cc::size10( idxThread ) + cc::error( " of " ) + - cc::size10( cntThreadsToStart ) + cc::error( ", have " ) + - cc::size10( size_t( cntRunningThreads_ ) ) + - cc::error( " running threads, exception info: " ) + - cc::warn( strError ) + "\n"; + "Dispatch: CRITICAL ERROR: Got exception in thread " + + std::to_string( idxThread ) + " of " + + std::to_string( cntThreadsToStart ) + ", have " + + std::to_string( size_t( cntRunningThreads_ ) ) + + " running threads, exception info: " + strError + "\n"; std::cout << strErrorMessage; std::cout.flush(); } catch ( ... ) { std::string strErrorMessage = - cc::deep_note( "Dispatch:" ) + " " + - cc::fatal( "CRITICAL ERROR:" ) + - cc::error( "Got exception in thread " ) + - cc::size10( idxThread ) + cc::error( " of " ) + - cc::size10( cntThreadsToStart ) + cc::error( ", have " ) + - cc::size10( size_t( cntRunningThreads_ ) ) + - cc::error( " running threads, exception info: " ) + - cc::warn( "Unknown exception" ) + "\n"; + "Dispatch: CRITICAL ERROR: Got exception in thread " + + std::to_string( idxThread ) + " of " + + std::to_string( cntThreadsToStart ) + ", have " + + std::to_string( size_t( cntRunningThreads_ ) ) + + " running threads, exception info: Unknown exception" + "\n"; std::cout << strErrorMessage; std::cout.flush(); } --cntRunningThreads_; if ( g_bVerboseDispatchThreadDetailsLogging ) { std::string strThreadFinalMessage = - cc::deep_note( "Dispatch:" ) + " " + - cc::debug( "Exiting thread " ) + cc::size10( idxThread ) + - cc::debug( " of " ) + cc::size10( cntThreadsToStart ) + - cc::debug( ", have " ) + - cc::size10( size_t( cntRunningThreads_ ) ) + - cc::debug( " running thread(s)" ) + "\n"; + "Dispatch: Exiting thread " + std::to_string( idxThread ) + + " of " + std::to_string( cntThreadsToStart ) + ", have " + + std::to_string( size_t( cntRunningThreads_ ) ) + + " running thread(s)" + "\n"; std::cout << strThreadFinalMessage; std::cout.flush(); } @@ -1414,11 +1341,9 @@ void domain::impl_startup( size_t nWaitMilliSeconds /*= size_t(-1)*/ ) { if ( strError.empty() ) break; std::string strErrorMessage = - cc::deep_note( "Dispatch:" ) + " " + cc::fatal( "CRITICAL ERROR:" ) + - cc::error( " Failed submit initialization task for the " ) + - cc::info( strPerformanceQueueName ) + cc::error( " queue at attempt " ) + - cc::size10( idxAttempt ) + cc::error( " of " ) + cc::size10( cntAttempts ) + - cc::error( ", error is: " ) + cc::warn( strError ) + "\n"; + "Dispatch: CRITICAL ERROR: Failed submit initialization task for the " + + strPerformanceQueueName + " queue at attempt " + std::to_string( idxAttempt ) + + " of " + std::to_string( cntAttempts ) + ", error is: " + strError + "\n"; std::cout << strErrorMessage; std::cout.flush(); } // for( size_t idxAttempt = 0; idxAttempt < 3; ++ idxAttempt ) { @@ -1449,18 +1374,15 @@ void domain::impl_startup( size_t nWaitMilliSeconds /*= size_t(-1)*/ ) { // throw std::runtime_error( // "dispatch domain failed to initialize all threads in thread pool" ); std::string strWarningMessage = - cc::deep_note( "Dispatch:" ) + " " + cc::warn( "WARNING: expected " ) + - cc::size10( size_t( cntThreadsInPool ) ) + - cc::warn( " threads in pool to be started at this time but have " ) + - cc::size10( size_t( cntStartedAndRunningThreads ) ) + cc::warn( ", startup is slow!" ) + - "\n"; + "Dispatch: WARNING: expected " + std::to_string( size_t( cntThreadsInPool ) ) + + " threads in pool to be started at this time but have " + + std::to_string( size_t( cntStartedAndRunningThreads ) ) + ", startup is slow!" + "\n"; std::cout << strWarningMessage; std::cout.flush(); } else { - std::string strSuccessMessage = cc::deep_note( "Dispatch:" ) + " " + - cc::success( "Have all " ) + - cc::size10( size_t( cntThreadsInPool ) ) + - cc::success( " threads in pool started fast" ) + "\n"; + std::string strSuccessMessage = "Dispatch: Have all " + + std::to_string( size_t( cntThreadsInPool ) ) + + " threads in pool started fast" + "\n"; std::cout << strSuccessMessage; std::cout.flush(); } @@ -1479,9 +1401,9 @@ void domain::impl_shutdown() { if ( cntThreads > 0 ) { for ( ; true; ) { if ( g_bVerboseDispatchThreadDetailsLogging ) { - std::string strMessage = cc::deep_note( "Dispatch:" ) + " " + cc::debug( "Have " ) + - cc::size10( size_t( cntRunningThreads_ ) ) + - cc::debug( " thread(s) still running..." ) + "\n"; + std::string strMessage = "Dispatch: Have " + + std::to_string( size_t( cntRunningThreads_ ) ) + + " thread(s) still running..." + "\n"; std::cout << strMessage; std::cout.flush(); } @@ -1493,39 +1415,34 @@ void domain::impl_shutdown() { std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) ); } // for( ; true; ) } // if( cntThreads > 0 ) - std::cout << cc::deep_note( "Dispatch:" ) + " " + cc::success( "All threads stopped" ) + "\n"; + std::cout << "Dispatch: All threads stopped\n"; std::cout.flush(); // wait loop to shutdown if ( pLoop ) { if ( g_bVerboseDispatchThreadDetailsLogging ) { - std::cout << cc::deep_note( "Dispatch:" ) + " " + - cc::debug( "Waiting for dispatch loop" ) + "\n"; + std::cout << "Dispatch: Waiting for dispatch loop\n"; std::cout.flush(); } pLoop->wait(); try { if ( g_bVerboseDispatchThreadDetailsLogging ) { - std::cout << cc::deep_note( "Dispatch:" ) + " " + - cc::debug( "Stopping for dispatch loop" ) + "\n"; + std::cout << "Dispatch: Stopping for dispatch loop\n"; std::cout.flush(); } if ( loop_thread_.joinable() ) loop_thread_.join(); - std::cout << cc::deep_note( "Dispatch:" ) + " " + - cc::success( "Dispatch loop stopped" ) + "\n"; + std::cout << "Dispatch: Dispatch loop stopped\n"; std::cout.flush(); } catch ( ... ) { } } // if( pLoop ) // shutdown, remove all queues if ( g_bVerboseDispatchThreadDetailsLogging ) { - std::cout << cc::deep_note( "Dispatch:" ) + " " + cc::debug( "Removing dispatch queues" ) + - "\n"; + std::cout << "Dispatch: Removing dispatch queues\n"; std::cout.flush(); } queue_remove_all(); - std::cout << cc::deep_note( "Dispatch:" ) + " " + cc::success( "All dispatch queues removed" ) + - "\n"; + std::cout << "Dispatch: All dispatch queues removed\n"; std::cout.flush(); } queue_ptr_t domain::impl_find_queue_to_run() { // find queue with minimal accumulator and @@ -1538,33 +1455,16 @@ queue_ptr_t domain::impl_find_queue_to_run() { // find queue with minimal accum for ( ; itWalk != itEnd; ) { queue_ptr_t& pQueue = const_cast< queue_ptr_t& >( *itWalk ); if ( pQueue->is_removed() ) { - LOCAL_DEBUG_TRACE( cc::sunny( "domain::impl_find_queue_to_run()" ) + - cc::debug( " will " ) + cc::success( "erase" ) + - cc::debug( " pre-removed queue " ) + cc::bright( pQueue->get_id() ) + - cc::debug( ", " ) + cc::sunny( "with_jobs_.size()" ) + - cc::debug( "=" ) + cc::size10( with_jobs_.size() ) ); itWalk = with_jobs_.erase( itWalk ); itEnd = with_jobs_.end(); continue; } if ( pQueue->async_job_count() == 0 ) { - LOCAL_DEBUG_TRACE( cc::sunny( "domain::impl_find_queue_to_run()" ) + - cc::debug( " will " ) + cc::success( "erase" ) + - cc::debug( " no-jobs queue " ) + cc::bright( pQueue->get_id() ) + - cc::debug( ", " ) + cc::sunny( "with_jobs_.size()" ) + - cc::debug( "=" ) + cc::size10( with_jobs_.size() ) ); itWalk = with_jobs_.erase( itWalk ); itEnd = with_jobs_.end(); continue; } if ( pQueue->awaiting_sync_run_ > 0 ) { - //++ itWalk; - LOCAL_DEBUG_TRACE( cc::sunny( "domain::impl_find_queue_to_run()" ) + - cc::debug( " will " ) + cc::success( "erase" ) + - cc::debug( " awaiting sync-run queue " ) + - cc::bright( pQueue->get_id() ) + cc::debug( ", " ) + - cc::sunny( "with_jobs_.size()" ) + cc::debug( "=" ) + - cc::size10( with_jobs_.size() ) ); itWalk = with_jobs_.erase( itWalk ); itEnd = with_jobs_.end(); continue; @@ -1572,11 +1472,6 @@ queue_ptr_t domain::impl_find_queue_to_run() { // find queue with minimal accum pQueue->is_running_ = true; // mark it as running pQueueFound = pQueue; with_jobs_.erase( itWalk ); // remove it from with_jobs_ - LOCAL_DEBUG_TRACE( cc::sunny( "domain::impl_find_queue_to_run()" ) + cc::debug( " did " ) + - cc::success( "successfully" ) + cc::debug( " fetched queue " ) + - cc::bright( pQueueFound->get_id() ) + cc::debug( ", " ) + - cc::sunny( "with_jobs_.size()" ) + cc::debug( "=" ) + - cc::size10( with_jobs_.size() ) ); break; } // for( ; itWalk != itEnd; ) return pQueueFound; @@ -1659,8 +1554,6 @@ loop_ptr_t domain::get_loop() { pLoop_ = pLoop; domain_ptr_t pThisDomain = this; pLoop->on_check_jobs_ = [pThisDomain]() -> void { - // if ( pLoop->cancelMode_ ) - // return; if ( pThisDomain->shutdown_flag_ ) return; bool bJobsEmpty = true; @@ -1673,40 +1566,8 @@ loop_ptr_t domain::get_loop() { // pThisDomain.get_unconst()->fetch_lock_.notify_one(); } }; - // init loop - // pLoop->on_job_will_add_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> bool { - // return true; - // }; - // pLoop->on_job_was_added_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> void { - // }; - // pLoop->on_job_will_remove_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> bool - //{ return true; - // }; - // pLoop->on_job_did_removed_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> void - //{ - // }; - // pLoop->on_job_will_execute_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> bool - //{ return true; - // }; - // pLoop->on_job_did_executed_ = [&] ( const - // skutils::dispatch::job_id_t & id ) -> void - //{ - // }; - // pLoop->on_job_exception_ = [&] ( const - // skutils::dispatch::job_id_t & id, - // std::exception - //* pe ) -> void { - // }; + loop_thread_ = std::thread( [pLoop]() -> void { pLoop->run(); } ); - // skutils::dispatch::sleep_while_true( - // [ pLoop ] () -> bool { - // return (!pLoop->isAlive_); - // } ); pLoop->wait_until_startup(); return pLoop_; } @@ -1726,14 +1587,9 @@ void domain::on_queue_job_added( queue& q ) { size_t cntJobs = q.async_job_count(); if ( cntJobs > 0 && ( !q.is_running() ) ) { with_jobs_.insert( &q ); - LOCAL_DEBUG_TRACE( cc::sunny( "domain::on_queue_job_added()" ) + - cc::debug( " did added work-able queue " ) + - cc::bright( q.get_id() ) + cc::debug( ", " ) + - cc::sunny( "with_jobs_.size()" ) + cc::debug( "=" ) + - cc::size10( with_jobs_.size() ) ); } } // block - // fetch_lock_.notify_all(); + fetch_lock_.notify_one(); } void domain::on_queue_job_complete( queue& q ) { @@ -1742,14 +1598,9 @@ void domain::on_queue_job_complete( queue& q ) { size_t cntJobs = q.async_job_count(); if ( cntJobs > 0 && ( !q.is_running() ) ) { with_jobs_.insert( &q ); - LOCAL_DEBUG_TRACE( cc::sunny( "domain::on_queue_job_complete()" ) + - cc::debug( " did added work-able queue " ) + - cc::bright( q.get_id() ) + cc::debug( ", " ) + - cc::sunny( "with_jobs_.size()" ) + cc::debug( "=" ) + - cc::size10( with_jobs_.size() ) ); } } // block - // fetch_lock_.notify_all(); + fetch_lock_.notify_one(); } diff --git a/libskutils/src/http.cpp b/libskutils/src/http.cpp index a0ece1234..bd77c25cb 100644 --- a/libskutils/src/http.cpp +++ b/libskutils/src/http.cpp @@ -18,8 +18,6 @@ #endif // (!defined _WIN32) -//#define __SKUTILS_HTTP_DEBUG_CONSOLE_TRACE_HTTP_TASK_STATES__ 1 - namespace skutils { namespace http { @@ -2017,7 +2015,7 @@ bool server::listen_internal() { } } } catch ( const std::exception& ex ) { - std::cerr << ex.what() << std::endl; + std::cerr << ex.what() << "\n"; } is_running_ = false; is_in_loop_ = false; diff --git a/libskutils/src/http_pg.cpp b/libskutils/src/http_pg.cpp index 83952d64c..b56008ec2 100644 --- a/libskutils/src/http_pg.cpp +++ b/libskutils/src/http_pg.cpp @@ -75,21 +75,19 @@ std::atomic_uint64_t request_site::g_instance_counter = 0; request_site::request_site( request_sink& a_sink, server_side_request_handler* pSSRQ ) : sink_( a_sink ), pSSRQ_( pSSRQ ), nInstanceNumber_( g_instance_counter++ ) { - strLogPrefix_ = cc::notice( "PG" ) + cc::normal( "/" ) + cc::notice( "rq" ) + - cc::normal( "/" ) + cc::notice( "site" ) + cc::normal( "/" ) + - cc::size10( nInstanceNumber_ ) + " "; - pg_log( strLogPrefix_ + cc::debug( "constructor" ) + "\n" ); + strLogPrefix_ = "PG/rq/site/" + std::to_string( nInstanceNumber_ ) + " "; + pg_log( strLogPrefix_ + "constructor\n" ); } request_site::~request_site() { - pg_log( strLogPrefix_ + cc::debug( "destructor" ) + "\n" ); + pg_log( strLogPrefix_ + "destructor\n" ); } void request_site::onRequest( std::unique_ptr< proxygen::HTTPMessage > req ) noexcept { sink_.OnRecordRequestCountIncrement(); strHttpMethod_ = skutils::tools::to_upper( skutils::tools::trim_copy( req->getMethodString() ) ); - pg_log( strLogPrefix_ + cc::info( strHttpMethod_ ) + cc::debug( " request query" ) + "\n" ); + pg_log( strLogPrefix_ + strHttpMethod_ + " request query\n" ); const folly::SocketAddress& origin_address = req->getClientAddress(); std::string strClientAddress = origin_address.getAddressStr(); // getFullyQualified() ipVer_ = @@ -102,13 +100,12 @@ void request_site::onRequest( std::unique_ptr< proxygen::HTTPMessage > req ) noe strDstAddress_ = req->getDstAddress().getAddressStr(); // getFullyQualified() std::string strDstPort = req->getDstPort(); nDstPort_ = ( !strDstPort.empty() ) ? atoi( strDstPort.c_str() ) : 0; - pg_log( strLogPrefix_ + cc::debug( "request query " ) + cc::sunny( strHttpMethod_ ) + - cc::debug( " from origin " ) + cc::info( strOrigin_ ) + cc::debug( ", path " ) + - cc::p( strPath_ ) + "\n" ); + pg_log( strLogPrefix_ + "request query " + strHttpMethod_ + " from origin " + strOrigin_ + + ", path " + strPath_ + "\n" ); size_t nHeaderIdx = 0; req->getHeaders().forEach( [&]( std::string& name, std::string& value ) { - pg_log( strLogPrefix_ + cc::debug( "header " ) + cc::num10( nHeaderIdx ) + " " + - cc::attention( name ) + cc::debug( "=" ) + cc::attention( value ) + "\n" ); + pg_log( strLogPrefix_ + "header " + std::to_string( nHeaderIdx ) + " " + name + "=" + + value + "\n" ); ++nHeaderIdx; } ); if ( strHttpMethod_ == "OPTIONS" ) { @@ -126,71 +123,63 @@ void request_site::onRequest( std::unique_ptr< proxygen::HTTPMessage > req ) noe } void request_site::onBody( std::unique_ptr< folly::IOBuf > body ) noexcept { - pg_log( strLogPrefix_ + cc::info( strHttpMethod_ ) + cc::debug( " body query" ) + "\n" ); + pg_log( strLogPrefix_ + strHttpMethod_ + " body query" + "\n" ); if ( strHttpMethod_ == "OPTIONS" ) return; auto cnt = body->computeChainDataLength(); auto pData = body->data(); std::string strIn; strIn.insert( strIn.end(), pData, pData + cnt ); - pg_log( strLogPrefix_ + cc::debug( "got body part number " ) + cc::size10( nBodyPartNumber_ ) + - "\n" ); - pg_log( - strLogPrefix_ + cc::debug( "got body part size " ) + cc::size10( strIn.size() ) + "\n" ); - pg_log( strLogPrefix_ + cc::debug( "got body part content " ) + cc::normal( strIn ) + "\n" ); + pg_log( strLogPrefix_ + "got body part number " + std::to_string( nBodyPartNumber_ ) + "\n" ); + pg_log( strLogPrefix_ + "got body part size " + std::to_string( strIn.size() ) + "\n" ); + pg_log( strLogPrefix_ + "got body part content " + strIn + "\n" ); strBody_ += strIn; - pg_log( strLogPrefix_ + cc::debug( "accumulated so far body size " ) + - cc::size10( strBody_.size() ) + "\n" ); - pg_log( strLogPrefix_ + cc::debug( "accumulated so far body content part(s) " ) + - cc::normal( strBody_ ) + "\n" ); + pg_log( strLogPrefix_ + "accumulated so far body size " + std::to_string( strBody_.size() ) + + "\n" ); + pg_log( strLogPrefix_ + "accumulated so far body content part(s) " + strBody_ + "\n" ); ++nBodyPartNumber_; } void request_site::onEOM() noexcept { - pg_log( strLogPrefix_ + cc::info( strHttpMethod_ ) + cc::debug( "EOM query" ) + "\n" ); + pg_log( strLogPrefix_ + strHttpMethod_ + "EOM query" + "\n" ); if ( strHttpMethod_ == "OPTIONS" ) { proxygen::ResponseBuilder( downstream_ ).sendWithEOM(); return; } - pg_log( strLogPrefix_ + cc::debug( "finally got " ) + cc::size10( nBodyPartNumber_ ) + - cc::debug( " body part(s)" ) + "\n" ); - pg_log( strLogPrefix_ + cc::debug( "finally got body size " ) + cc::size10( strBody_.size() ) + - "\n" ); pg_log( - strLogPrefix_ + cc::debug( "finally got body content " ) + cc::normal( strBody_ ) + "\n" ); + strLogPrefix_ + "finally got " + std::to_string( nBodyPartNumber_ ) + " body part(s)\n" ); + pg_log( strLogPrefix_ + "finally got body size " + std::to_string( strBody_.size() ) + "\n" ); + pg_log( strLogPrefix_ + "finally got body content " + strBody_ + "\n" ); nlohmann::json joID = "0xBADF00D", joIn; skutils::result_of_http_request rslt; rslt.isBinary_ = false; try { joIn = nlohmann::json::parse( strBody_ ); - pg_log( strLogPrefix_ + cc::debug( "got body JSON " ) + cc::j( joIn ) + "\n" ); + pg_log( strLogPrefix_ + "got body JSON " + joIn.dump() + "\n" ); if ( joIn.count( "id" ) > 0 ) joID = joIn["id"]; rslt = pSSRQ_->onRequest( joIn, strOrigin_, ipVer_, strDstAddress_, nDstPort_ ); if ( rslt.isBinary_ ) - pg_log( strLogPrefix_ + cc::debug( "got binary answer " ) + + pg_log( strLogPrefix_ + "got binary answer " + cc::binary_table( ( const void* ) ( void* ) rslt.vecBytes_.data(), size_t( rslt.vecBytes_.size() ) ) + "\n" ); else - pg_log( strLogPrefix_ + cc::debug( "got answer JSON " ) + cc::j( rslt.joOut_ ) + "\n" ); + pg_log( strLogPrefix_ + "got answer JSON " + rslt.joOut_.dump() + "\n" ); } catch ( const std::exception& ex ) { - pg_log( strLogPrefix_ + cc::error( "problem with body " ) + cc::warn( strBody_ ) + - cc::error( ", error info: " ) + cc::warn( ex.what() ) + "\n" ); + pg_log( + strLogPrefix_ + "problem with body " + strBody_ + ", error info: " + ex.what() + "\n" ); rslt.isBinary_ = false; rslt.joOut_ = server_side_request_handler::json_from_error_text( ex.what(), joID ); - pg_log( - strLogPrefix_ + cc::error( "got error answer JSON " ) + cc::j( rslt.joOut_ ) + "\n" ); + pg_log( strLogPrefix_ + "got error answer JSON " + rslt.joOut_.dump() + "\n" ); } catch ( ... ) { - pg_log( strLogPrefix_ + cc::error( "problem with body " ) + cc::warn( strBody_ ) + - cc::error( ", error info: " ) + cc::warn( "unknown exception in HTTP handler" ) + - "\n" ); + pg_log( strLogPrefix_ + "problem with body " + strBody_ + + ", error info: " + "unknown exception in HTTP handler" + "\n" ); rslt.isBinary_ = false; rslt.joOut_ = server_side_request_handler::json_from_error_text( "unknown exception in HTTP handler", joID ); - pg_log( - strLogPrefix_ + cc::error( "got error answer JSON " ) + cc::j( rslt.joOut_ ) + "\n" ); + pg_log( strLogPrefix_ + "got error answer JSON " + rslt.joOut_.dump() + "\n" ); } proxygen::ResponseBuilder bldr( downstream_ ); bldr.status( 200, "OK" ); @@ -211,17 +200,16 @@ void request_site::onEOM() noexcept { void request_site::onUpgrade( proxygen::UpgradeProtocol /*protocol*/ ) noexcept { // handler doesn't support upgrades - pg_log( strLogPrefix_ + cc::debug( "upgrade query" ) + "\n" ); + pg_log( strLogPrefix_ + "upgrade query\n" ); } void request_site::requestComplete() noexcept { - pg_log( strLogPrefix_ + cc::debug( "complete notification" ) + "\n" ); + pg_log( strLogPrefix_ + "complete notification\n" ); delete this; } void request_site::onError( proxygen::ProxygenError err ) noexcept { - pg_log( - strLogPrefix_ + cc::error( "error notification: " ) + cc::size10( size_t( err ) ) + "\n" ); + pg_log( strLogPrefix_ + "error notification: " + std::to_string( size_t( err ) ) + "\n" ); delete this; } @@ -276,19 +264,19 @@ std::string server_side_request_handler::answer_from_error_text( server::server( pg_on_request_handler_t h, const pg_accumulate_entries& entries, int32_t threads, int32_t threads_limit ) : h_( h ), entries_( entries ), threads_( threads ), threads_limit_( threads_limit ) { - strLogPrefix_ = cc::notice( "PG" ) + cc::normal( "/" ) + cc::notice( "server" ) + " "; - pg_log( strLogPrefix_ + cc::debug( "constructor" ) + "\n" ); + strLogPrefix_ = "PG/server "; + pg_log( strLogPrefix_ + "constructor\n" ); } server::~server() { - pg_log( strLogPrefix_ + cc::debug( "destructor" ) + "\n" ); + pg_log( strLogPrefix_ + "destructor\n" ); stop(); } bool server::start() { stop(); - pg_log( strLogPrefix_ + cc::debug( "will start server thread" ) + "\n" ); + pg_log( strLogPrefix_ + "will start server thread\n" ); /* int32_t http_port = 11000; @@ -388,25 +376,25 @@ bool server::start() { server_->start(); } ) ); - pg_log( strLogPrefix_ + cc::debug( "did started server thread" ) + "\n" ); + pg_log( strLogPrefix_ + "did started server thread\n" ); return true; } void server::stop() { if ( server_ ) { - pg_log( strLogPrefix_ + cc::debug( "will stop server instance" ) + "\n" ); + pg_log( strLogPrefix_ + "will stop server instance\n" ); server_->stop(); - pg_log( strLogPrefix_ + cc::debug( "did stopped server instance" ) + "\n" ); + pg_log( strLogPrefix_ + "did stopped server instance\n" ); } if ( thread_.joinable() ) { - pg_log( strLogPrefix_ + cc::debug( "will stop server thread" ) + "\n" ); + pg_log( strLogPrefix_ + "will stop server thread\n" ); thread_.join(); - pg_log( strLogPrefix_ + cc::debug( "did stopped server thread" ) + "\n" ); + pg_log( strLogPrefix_ + "did stopped server thread\n" ); } if ( server_ ) { - pg_log( strLogPrefix_ + cc::debug( "will release server instance" ) + "\n" ); + pg_log( strLogPrefix_ + "will release server instance\n" ); server_.reset(); - pg_log( strLogPrefix_ + cc::debug( "did released server instance" ) + "\n" ); + pg_log( strLogPrefix_ + "did released server instance\n" ); } } diff --git a/libskutils/src/network.cpp b/libskutils/src/network.cpp index dd3cc5d43..8dded5def 100644 --- a/libskutils/src/network.cpp +++ b/libskutils/src/network.cpp @@ -74,8 +74,7 @@ void basic_stream_socket_init( int native_fd, std::ostream& osLog ) { || ret_rcv_timeoout || ret_snd_timeoout #endif ) - osLog << cc::error( "Failed to enable keep alive on TCP client socket" ) << native_fd - << cc::error( "." ); + osLog << "Failed to enable keep alive on TCP client socket" << native_fd << "."; } std::string get_canonical_host_name() { @@ -255,10 +254,8 @@ int get_address_info46( int ipVersion, const char* ads, sockaddr46** result ) { ::memset( &hints, 0, sizeof( hints ) ); ( *result ) = nullptr; if ( ipVersion == 6 ) { - //#if !defined(__ANDROID__) hints.ai_family = AF_INET6; hints.ai_flags = AI_V4MAPPED; - //#endif } else { hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; @@ -316,7 +313,7 @@ std::string resolve_address_for_client_connection( } res = res->ai_next; } - //#if defined(LWS_FALLBACK_GETHOSTBYNAME) + // #if defined(LWS_FALLBACK_GETHOSTBYNAME) } else if ( n == EAI_SYSTEM ) { // ...log... ( "getaddrinfo (ipv4) failed, trying gethostbyname" ); struct hostent* host = gethostbyname( ads ); @@ -326,7 +323,7 @@ std::string resolve_address_for_client_connection( cce = "gethostbyname (ipv4) failed"; goto oom4; } - //#endif + // #endif } else { cce = "getaddrinfo failed"; goto oom4; diff --git a/libskutils/src/stats.cpp b/libskutils/src/stats.cpp index d77dcbd20..99408d69c 100644 --- a/libskutils/src/stats.cpp +++ b/libskutils/src/stats.cpp @@ -236,9 +236,9 @@ std::string named_event_stats::getEventStatsDescription( time_point tpNow, return ""; std::string strSpace( " " ), strCommaSpace( ", " ), strSuffixPerSecond( " p/s" ); if ( isColored ) { - strSpace = cc::debug( strSpace ); - strCommaSpace = cc::debug( strCommaSpace ); - strSuffixPerSecond = cc::debug( strSuffixPerSecond ); + strSpace = strSpace; + strCommaSpace = strCommaSpace; + strSuffixPerSecond = strSuffixPerSecond; } std::stringstream ss; bool isNotFirst = false; @@ -256,8 +256,8 @@ std::string named_event_stats::getEventStatsDescription( time_point tpNow, else strEPS = skutils::tools::format( "%.3lf", lfEPS ); if ( isColored ) { - eventName = cc::info( eventName ); - strEPS = cc::note( strEPS ); + eventName = eventName; + strEPS = strEPS; } if ( isNotFirst ) ss << strCommaSpace; diff --git a/libskutils/src/utils.cpp b/libskutils/src/utils.cpp index abb760c96..0edb99b13 100644 --- a/libskutils/src/utils.cpp +++ b/libskutils/src/utils.cpp @@ -292,8 +292,8 @@ bool stat_remove_all_content_in_directory( const char* s ) { strCmd += " 1>/dev/nullptr 2>/dev/nullptr"; int nErrorCode = ::system( strCmd.c_str() ); if ( nErrorCode != 0 ) { - std::cerr << cc::error( "Command \"" ) << cc::p( strCmd ) << cc::error( "\" returned " ) - << cc::c( int64_t( nErrorCode ) ) << cc::error( " error code\n" ); + std::cerr << "Command \"" << strCmd << "\" returned " << int64_t( nErrorCode ) + << " error code\n"; return false; } return true; @@ -480,8 +480,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strDays = skutils::tools::format( "%" PRId64, days ); strDaysSuffix = "d"; if ( isColored ) { - strDays = cc::note( strDays ); - strDaysSuffix = cc::debug( strDaysSuffix ); + strDays = strDays; + strDaysSuffix = strDaysSuffix; } ss << strDays << strDaysSuffix; } @@ -489,8 +489,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strHours = skutils::tools::format( "%02d", int( hours ) ); strHoursSuffix = "h"; if ( isColored ) { - strHours = cc::note( strHours ); - strHoursSuffix = cc::debug( strHoursSuffix ); + strHours = strHours; + strHoursSuffix = strHoursSuffix; } ss << strHours << strHoursSuffix; } @@ -498,8 +498,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strMinutes = skutils::tools::format( "%02d", int( minutes ) ); strMinutesSuffix = "m"; if ( isColored ) { - strMinutes = cc::note( strMinutes ); - strMinutesSuffix = cc::debug( strMinutesSuffix ); + strMinutes = strMinutes; + strMinutesSuffix = strMinutesSuffix; } ss << strMinutes << strMinutesSuffix; } @@ -507,8 +507,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strSeconds = skutils::tools::format( "%02d", int( seconds ) ); strSecondsSuffix = "s"; if ( isColored ) { - strSeconds = cc::note( strSeconds ); - strSecondsSuffix = cc::debug( strSecondsSuffix ); + strSeconds = strSeconds; + strSecondsSuffix = strSecondsSuffix; } ss << strSeconds << strSecondsSuffix; } @@ -516,8 +516,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strMilliSeconds = skutils::tools::format( "%03d", int( milliseconds ) ); strMilliSecondsSuffix = "ms"; if ( isColored ) { - strMilliSeconds = cc::note( strMilliSeconds ); - strMilliSecondsSuffix = cc::debug( strMilliSecondsSuffix ); + strMilliSeconds = strMilliSeconds; + strMilliSecondsSuffix = strMilliSecondsSuffix; } ss << strMilliSeconds << strMilliSecondsSuffix; } @@ -526,8 +526,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strMicroSeconds = skutils::tools::format( "%03d", int( microseconds ) ); strMicroSecondsSuffix = "μs"; if ( isColored ) { - strMicroSeconds = cc::note( strMicroSeconds ); - strMicroSecondsSuffix = cc::debug( strMicroSecondsSuffix ); + strMicroSeconds = strMicroSeconds; + strMicroSecondsSuffix = strMicroSecondsSuffix; } ss << strMicroSeconds << strMicroSecondsSuffix; } @@ -536,8 +536,8 @@ std::string nanoseconds_2_lifetime_str( uint64_t ns, bool isColored /*= false*/ strNanoSeconds = skutils::tools::format( "%03d", int( ns ) ); strNanoSecondsSuffix = "ns"; if ( isColored ) { - strNanoSeconds = cc::note( strNanoSeconds ); - strNanoSecondsSuffix = cc::debug( strNanoSecondsSuffix ); + strNanoSeconds = strNanoSeconds; + strNanoSecondsSuffix = strNanoSecondsSuffix; } ss << strNanoSeconds << strNanoSecondsSuffix; } @@ -1065,8 +1065,6 @@ unsigned char* md5::raw_digest() { uint1* s = new uint1[16]; if ( !finalized ) { delete[] s; - // std::cerr << "md5::raw_digest: cannot get digest if you haven't finalized the digest" << - // std::endl; s = nullptr; } else memcpy( s, digest, 16 ); @@ -1077,8 +1075,6 @@ char* md5::hex_digest() { char* s = new char[33]; ::memset( s, 0, 33 ); if ( !finalized ) { - // std::cerr << "md5::hex_digest: cannot get digest if you haven't finalized the digest!" << - // std::endl; return s; } for ( i = 0; i < 16; i++ ) @@ -1675,26 +1671,26 @@ void json_config_file_accessor::reloadConfigIfNeeded() { throw std::runtime_error( "Failed to access modified configuration file" ); if ( configModificationTime_ == tt ) return; - std::string strLogPrefix = cc::deep_info( "Reload configuration file" ); + std::string strLogPrefix = "Reload configuration file"; try { - std::cout << strLogPrefix << cc::debug( " Loading configuration from " ) - << cc::p( configPath_ ) << cc::debug( " ... " ) << "\n"; + std::cout << strLogPrefix << " Loading configuration from " << configPath_ << " ... " + << "\n"; std::ifstream ifs( configPath_.c_str() ); - std::cout << strLogPrefix << cc::debug( " Parsing configuration JSON ... " ) << "\n"; + std::cout << strLogPrefix << " Parsing configuration JSON ... " + << "\n"; nlohmann::json joNewConfig = nlohmann::json::parse( ifs ); joConfig_ = joNewConfig; configModificationTime_ = tt; - std::cout << strLogPrefix << cc::success( " Done, loaded configuration file " ) - << cc::p( configPath_ ) << "\n"; + std::cout << strLogPrefix << " Done, loaded configuration file " << configPath_ << "\n"; } catch ( std::exception& ex ) { - std::cout << strLogPrefix << cc::error( " Failed to reload modified configuration file " ) - << cc::p( configPath_ ) << cc::error( ": " ) << cc::warn( ex.what() ) << "\n"; + std::cout << strLogPrefix << " Failed to reload modified configuration file " << configPath_ + << ": " << ex.what() << "\n"; throw std::runtime_error( std::string( "Failed to reload modified configuration file: " ) + ex.what() ); } catch ( ... ) { - std::cout << strLogPrefix << cc::error( " Failed to reload modified configuration file " ) - << cc::p( configPath_ ) << cc::error( ": " ) << cc::warn( "unknown exception" ) - << "\n"; + std::cout << strLogPrefix << " Failed to reload modified configuration file " << configPath_ + << ": " + << "unknown exception\n"; throw std::runtime_error( "Failed to reload modified configuration file: unknown exception" ); } diff --git a/libskutils/src/ws.cpp b/libskutils/src/ws.cpp index 17ec59a09..54f6868c8 100644 --- a/libskutils/src/ws.cpp +++ b/libskutils/src/ws.cpp @@ -547,9 +547,9 @@ std::string traffic_stats::getLifeTimeDescription( std::string strChangeType( last_instance_state_changing_type_as_str() ), strAgoSuffix( " ago" ), strSpace( " " ); if ( isColored ) { - strChangeType = cc::debug( strChangeType ); - strAgoSuffix = cc::debug( strAgoSuffix ); - strSpace = cc::debug( strSpace ); + strChangeType = strChangeType; + strAgoSuffix = strAgoSuffix; + strSpace = strSpace; } nanoseconds nsx = changed_ago( tpNow ); uint64_t ns = nsx.count(); @@ -582,24 +582,24 @@ std::string traffic_stats::getTrafficStatsDescription( strBpsComposed = "N/A"; } if ( isColored ) { - strBytesPrefix = cc::debug( strBytesPrefix ); - strBytesSuffix = cc::debug( strBytesSuffix ); - strTx = cc::ws_tx( strTx ); - strRx = cc::ws_rx( strRx ); - strTxValue = cc::ws_tx( strTxValue ); - strRxValue = cc::ws_rx( strRxValue ); + strBytesPrefix = strBytesPrefix; + strBytesSuffix = strBytesSuffix; + strTx = strTx; + strRx = strRx; + strTxValue = strTxValue; + strRxValue = strRxValue; if ( !strTxBPS.empty() ) - strTxBPS = cc::ws_tx( strTxBPS ); + strTxBPS = strTxBPS; if ( !strRxBPS.empty() ) - strRxBPS = cc::ws_rx( strRxBPS ); + strRxBPS = strRxBPS; if ( !strBpsComposed.empty() ) - strBpsComposed = cc::error( strBpsComposed ); - strSlash = cc::debug( strSlash ); - strSpace = cc::debug( strSpace ); + strBpsComposed = strBpsComposed; + strSlash = strSlash; + strSpace = strSpace; if ( !strBpsPrefix.empty() ) - strBpsPrefix = cc::debug( strBpsPrefix ); + strBpsPrefix = strBpsPrefix; if ( !strBpsSuffix.empty() ) - strBpsSuffix = cc::debug( strBpsSuffix ); + strBpsSuffix = strBpsSuffix; } if ( bHaveBpsInfo ) strBpsComposed = strTxBPS + strSlash + strRxBPS; @@ -664,7 +664,7 @@ basic_network_settings::basic_network_settings( basic_network_settings* pBNS ) timeout_handshake_open_( 60 ) // seconds, default value in wspp is 5000, 0 means not use , timeout_handshake_close_( 60 ) // seconds, default value in wspp is 5000, 0 means not use - //#if(defined __HAVE_skutils_WS_BACKEND_NLWS__) + // #if(defined __HAVE_skutils_WS_BACKEND_NLWS__) // , max_message_size_( 0 ) // bytes, 0 is // unlimited , max_body_size_( 0 ) // bytes, 0 is // unlimited #else /// (defined @@ -673,7 +673,7 @@ basic_network_settings::basic_network_settings( basic_network_settings* pBNS ) max_message_size_( 32 * 1000 * 1000 ) // bytes, default value in wspp is 32000000 , max_body_size_( 32 * 1000 * 1000 ) // bytes, default value in wspp is 32000000 - //#endif /// else from (defined __HAVE_skutils_WS_BACKEND_NLWS__) + // #endif /// else from (defined __HAVE_skutils_WS_BACKEND_NLWS__) , timeout_restart_on_close_( 3 ) // seconds , @@ -1055,36 +1055,6 @@ void basic_api::locked_execute( fn_lock_callback_t fn ) { lock_type lock( mtx_api() ); fn(); } -// bool basic_api::try_locked_execute( fn_lock_callback_t fn, size_t cntAttempts, uint64_t -// nMillisecondsWaitBetweenAttempts ) { if( cntAttempts < 1 ) return false; if( ! fn -// ) return false; -// //++ cntTryLockExecutes_; -// bool bWasLocked = false; -// for( size_t i = 0; i < cntAttempts; ++ i ) { -// if( ! initialized_ ) -// break; -// bWasLocked = mtx_api().try_lock(); -// if( bWasLocked ) -// break; -// if( ! initialized_ ) -// break; -// if( nMillisecondsWaitBetweenAttempts > 0 && i < (cntAttempts-1) ) -// std::this_thread::sleep_for( -// std::chrono::milliseconds(nMillisecondsWaitBetweenAttempts) ); } // for( size_t i = -// 0; i < cntAttempts; ++ i ) if( bWasLocked ) { try { fn(); -// } catch( ... ) { -// //-- cntTryLockExecutes_; -// mtx_api().unlock(); -// throw; -// } -// //-- cntTryLockExecutes_; -// mtx_api().unlock(); -// } // if( bWasLocked ) -// else { -// //-- cntTryLockExecutes_; -// } -// return bWasLocked; -// } void basic_api::clear_fields() { interface_name_.clear(); @@ -1112,8 +1082,7 @@ void basic_api::clear_fields() { }; // initialized_ = false; - // while( cntTryLockExecutes_ > 0 ) - // std::this_thread::sleep_for( std::chrono::milliseconds(10) ); + ctx_ = nullptr; ::memset( &ctx_info_, 0, sizeof( struct lws_context_creation_info ) ); ctx_info_.port = CONTEXT_PORT_NO_LISTEN; @@ -1137,17 +1106,7 @@ void basic_api::clear_fields() { // unsigned int walk_protocol_id = 0; vec_lws_protocols_.clear(); - // - // vec_lws_protocols_.push_back( { // the first protocol must always be the HTTP - // handler "http-only", // name - // stat_callback_http, - // // callback 0, // per_session_data_size, no per session data. g_nDefaultBufferSizeRX, // - // rx_buffer_size, max frame size / rx buffer walk_protocol_id, // id, ignored by lws - // nullptr, // user - // g_nDefaultBufferSizeTX // tx_packet_size - // } ); - // ++ walk_protocol_id; - // + default_protocol_index_ = vec_lws_protocols_.size(); vec_lws_protocols_.push_back( { g_strDefaultProtocolName.c_str(), stat_callback_server, @@ -1249,13 +1208,11 @@ int basic_api::stat_callback_http( struct lws* wsi, enum lws_callback_reasons re bool isClose = false; switch ( reason ) { case LWS_CALLBACK_ESTABLISHED: - // ctx = ::lws_get_context( wsi ); - // self = server_api::stat_get( ctx ); - //::lws_callback_on_writable( wsi ); + isClose = true; break; case LWS_CALLBACK_HTTP: - //::lws_serve_http_file( wsi, "example.html", "text/html", nullptr, 0 ); + isClose = true; break; default: @@ -1277,16 +1234,9 @@ int basic_api::stat_callback_client( struct lws* wsi, enum lws_callback_reasons reason, void* /*user*/, void* in, size_t len ) { client_api* self = nullptr; switch ( reason ) { - // case LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: - // return 1; // disallow compression - // case LWS_CALLBACK_PROTOCOL_INIT: // per vhost - // lws_protocol_vh_priv_zalloc( lws_get_vhost(wsi), lws_get_protocol(wsi), - // sizeof(struct per_vhost_data__lws_mirror) ); break; case LWS_CALLBACK_CLIENT_ESTABLISHED: self = client_api::stat_get( wsi ); if ( self ) { - // self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, "NLWS: - // LWS_CALLBACK_CLIENT_ESTABLISHED: connect with server success" ); int fd = ::lws_get_socket_fd( wsi ); self->cid_ = fd; self->connection_flag_ = true; @@ -1297,8 +1247,6 @@ int basic_api::stat_callback_client( case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: self = client_api::stat_get( wsi ); if ( self ) { - // self->onLogMessage( e_ws_log_message_type_t::eWSLMT_error, "NLWS: - // LWS_CALLBACK_CLIENT_CONNECTION_ERROR: connect with server error" ); self->destroy_flag_ = true; self->connection_flag_ = false; self->clientThreadStopFlag_ = true; @@ -1308,8 +1256,6 @@ int basic_api::stat_callback_client( case LWS_CALLBACK_CLOSED: self = client_api::stat_get( wsi ); if ( self ) { - // self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, "NLWS: - // LWS_CALLBACK_CLOSED" ); self->destroy_flag_ = true; self->connection_flag_ = true; self->clientThreadStopFlag_ = true; @@ -1320,21 +1266,12 @@ int basic_api::stat_callback_client( case LWS_CALLBACK_CLIENT_RECEIVE: self = client_api::stat_get( wsi ); if ( self ) { - // if( self->writeable_flag_ ) { - // //self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, - //"NLWS: LWS_CALLBACK_CLIENT_RECEIVE: client received data" ); - // self->destroy_flag_ = true; self->onDisconnect( "read - // attempt when writable" - // ); return - // 0; - // } message_payload_data data; if ( impl_frame_is_binary( wsi, ( uint8_t* ) in, len ) ) data.set_binary( ( uint8_t* ) in, len ); else data.set_text( ( char* ) in, len ); - ////size_t nRemain = ::lws_remaining_packet_payload( wsi ); bool isFinalFragment = ( - /// nRemain == 0 ) ? true : false; + bool isFinalFragment = ::lws_is_final_fragment( wsi ); self->onMessage( data, isFinalFragment ); } @@ -1355,7 +1292,7 @@ int basic_api::stat_callback_client( // if ( !cached_delayed_close_reason.empty() ) { self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, - cc::debug( "Processing close action for client connection" ) ); + "Processing close action for client connection" ); ::lws_close_reason( wsi, cached_delayed_close_status, ( unsigned char* ) cached_delayed_close_reason.c_str(), cached_delayed_close_reason.length() ); @@ -1415,11 +1352,7 @@ int basic_api::stat_callback_client( // https://libwebsockets.org/lws-api-doc-master/html/md_README_8coding.html } // if( self ) break; - /* - case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: - lwsl_err( "LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS\n" ); - break; - */ + default: break; } // switch( reason ) @@ -1431,17 +1364,8 @@ int basic_api::stat_callback_server( lws_context* ctx = nullptr; server_api* self = nullptr; - // const size_t nPre = LWS_SEND_BUFFER_PRE_PADDING, nPost = - // LWS_SEND_BUFFER_POST_PADDING; unsigned char buf[ nPre + 512 + nPost ]; - // unsigned char - // * p = &buf[nPre]; switch ( reason ) { - // case LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: - // return 1; // disallow compression - // case LWS_CALLBACK_PROTOCOL_INIT: // per vhost - // lws_protocol_vh_priv_zalloc( lws_get_vhost(wsi), lws_get_protocol(wsi), - // sizeof(struct per_vhost_data__lws_mirror) ); break; case LWS_CALLBACK_ESTABLISHED: ctx = ::lws_get_context( wsi ); self = server_api::stat_get( ctx ); @@ -1491,12 +1415,12 @@ int basic_api::stat_callback_server( pcd->delayed_close_reason_.clear(); pcd->delayed_close_status_ = 0; // - // self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, cc::debug("Processing - // writable state for ") + strDescC ); + // self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, "Processing + // writable state for " + strDescC ); if ( !cached_delayed_close_reason.empty() ) { std::string strDescC = pcd->description( true ); self->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, - cc::debug( "Processing close action for " ) + strDescC ); + "Processing close action for " + strDescC ); ::lws_close_reason( wsi, cached_delayed_close_status, ( unsigned char* ) cached_delayed_close_reason.c_str(), cached_delayed_close_reason.length() ); @@ -1704,11 +1628,6 @@ bool client_api::init( bool isSSL, const std::string& strHost, int nPort, #endif /// if( defined __skutils_WS_OFFER_DETAILED_NLWS_CONFIGURATION_OPTIONS__ ) ctx_info_.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; - // ctx_info_.ssl_options_set = // compatibility with old implementation based on - // wspp SSL_OP_NO_SSLv2 //| SSL_OP_NO_SSLv3 | - // SSL_OP_SINGLE_DH_USE - // //| SSL_OP_ALL - // ; vec_lws_protocols_[default_protocol_index_].per_session_data_size = 0; // sizeof(struct client_session_data); @@ -1822,11 +1741,6 @@ bool client_api::init( bool isSSL, const std::string& strHost, int nPort, ctx_info_.iface = ( !interface_name_.empty() ) ? ( const_cast< char* >( interface_name_.c_str() ) ) : nullptr; - // - // - // - // - // ctx_ = ::lws_create_context( &ctx_info_ ); if ( ctx_ == nullptr ) { @@ -1848,18 +1762,6 @@ bool client_api::init( bool isSSL, const std::string& strHost, int nPort, SSL_load_error_strings(); SSL_library_init(); } - // wsi_ = - // ::lws_client_connect( - // ctx_, - // strHost.c_str(), - // nPort, - // ssl_flags_, - // sp.c_str(), - // strOrigin.c_str(), // "origin" - // nullptr, - // g_strDefaultProtocolName.c_str(), // protocols_[cpi].name - // -1 - // ); struct lws_client_connect_info cci; ::memset( &cci, 0, sizeof( struct lws_client_connect_info ) ); cci.context = ctx_; @@ -1903,9 +1805,7 @@ bool client_api::init( bool isSSL, const std::string& strHost, int nPort, std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) ); if ( !threadInitSuccess ) return false; - // do_writable_callbacks_all_protocol(); - // while( ! ( connection_flag_ || destroy_flag_ ) ) - // std::this_thread::sleep_for( std::chrono::milliseconds(20) ); + initialized_ = true; return true; } @@ -1933,14 +1833,9 @@ void client_api::close( int nCloseStatus, const std::string& msg ) { return; if ( wsi_ == nullptr ) return; - ///::lws_close_reason( wsi_, (lws_close_status)nCloseStatus, (unsigned char *)msg.c_str(), - /// msg.length() ); deinit(); + delayed_close_reason_ = msg; delayed_close_status_ = nCloseStatus; - // - // clientThreadStopFlag_ = true; - // while( ! clientThreadWasStopped_ ) - // std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); } void client_api::delay_deinit() { if ( delayed_de_init_ ) @@ -2013,9 +1908,7 @@ client_api* client_api::stat_get( void* ctx ) { return nullptr; } client_api* api = itFind->second; - // assert( api ); - // assert( api->wsi_ ); - // assert( api->wsi_ == ctx ); + return api; } @@ -2086,22 +1979,8 @@ std::string list_srvmodes_as_str() { int g_lws_service_timeout_ms = 1000; -srvmode_t g_default_srvmode = srvmode_t:: - //#if ( defined LWS_WITH_LIBUV ) - // srvmode_uv; - //#else - //#if ( defined LWS_WITH_LIBEV ) - // srvmode_ev; - //#else - //#if ( defined LWS_WITH_LIBEVENT ) - // srvmode_event; - //#else +srvmode_t g_default_srvmode = srvmode_t::srvmode_simple; - srvmode_simple; - -//#endif -//#endif -//#endif bool g_default_explicit_vhost_enable = true; // srvmode_simple and srvmode_external_poll only bool g_default_dynamic_vhost_enable = false; @@ -2119,7 +1998,7 @@ void server_api::connection_data::setPeer( peer_ptr_t pPeer ) { return; if ( pPeer_ ) { pPeer_->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, - cc::debug( "Server API entry destruction for " ) + description( true ) ); + "Server API entry destruction for " + description( true ) ); pPeer_->ref_release(); pPeer_ = nullptr; sn_ = 0; @@ -2129,20 +2008,20 @@ void server_api::connection_data::setPeer( peer_ptr_t pPeer ) { pPeer_->ref_retain(); sn_ = pPeer_->serial_number(); pPeer_->onLogMessage( e_ws_log_message_type_t::eWSLMT_debug, - cc::debug( "Server API entry construction for " ) + description( true ) ); + "Server API entry construction for " + description( true ) ); } } std::string server_api::connection_data::unique_string_identifier( bool isColored /*= false*/ ) const { std::string strCid( peer::stat_getCidString( cid_ ) ), strSlash( "/" ); if ( isColored ) { - strSlash = cc::debug( strSlash ); + strSlash = strSlash; if ( !strCid.empty() ) - strCid = cc::bright( strCid ); + strCid = strCid; } std::string strPeerSerialNumber = skutils::tools::format( "%" PRIu64, uint64_t( sn_ ) ); if ( isColored ) - strPeerSerialNumber = cc::notice( strPeerSerialNumber ); + strPeerSerialNumber = strPeerSerialNumber; std::stringstream ss; ss << strCid << strSlash << strPeerSerialNumber; return ss.str(); @@ -2152,17 +2031,16 @@ std::string server_api::connection_data::description( bool isColored /*= false*/ strValueIP( strPeerRemoteIP_ ), strNameCloseStatus( "close status" ), strValueCloseStatus( skutils::tools::format( "%d", delayed_close_status_ ) ), strNameCloseReason( "close reason" ), - strValueCloseReason( - isColored ? cc::warn( delayed_close_reason_ ) : delayed_close_reason_ ); + strValueCloseReason( isColored ? delayed_close_reason_ : delayed_close_reason_ ); if ( isColored ) { - strEq = cc::debug( strEq ); - strSeparator = cc::debug( strSeparator ); - strNameUis = cc::notice( strNameUis ); - strNameIP = cc::notice( strNameIP ); - strNameCloseStatus = cc::notice( strNameCloseStatus ); - strNameCloseReason = cc::notice( strNameCloseReason ); - strValueIP = cc::u( strValueIP ); - strValueCloseStatus = cc::warn( strValueCloseStatus ); + strEq = strEq; + strSeparator = strSeparator; + strNameUis = strNameUis; + strNameIP = strNameIP; + strNameCloseStatus = strNameCloseStatus; + strNameCloseReason = strNameCloseReason; + strValueIP = strValueIP; + strValueCloseStatus = strValueCloseStatus; } std::stringstream ss; ss << strNameUis << strEq << unique_string_identifier( isColored ); @@ -2627,35 +2505,7 @@ struct my_uv_counter_struct { volatile bool stop_loop_ = false; my_uv_counter_struct( server_api& api ) : api_( api ) {} }; /// struct my_uv_counter_struct - // static void my_uv_signal_cb( uv_signal_t * watcher, int signum ) { - // //struct my_uv_counter_struct * c = (struct my_uv_counter_struct *)t->data; - // //server_api & self = c->api_; - // //self.serverInterruptFlag_ = true; - // ::lwsl_err( "Signal %d caught, exiting...\n", watcher->signum ); - // switch( watcher->signum ) { - // case SIGTERM: - // case SIGINT: - // break; - // default: - // ::signal( SIGABRT, SIG_DFL ); - // ::abort(); - // break; - // } - // if( self.ctx_ ) { - // lwsl_debug( "my_uv_signal_cb() will cancel lws service\n" ); - // ::lws_cancel_service( self.ctx_ ); - // } - // } -// static void my_uv_stopping_timer_cb( uv_timer_t* t ) { -// struct my_uv_counter_struct* c = ( struct my_uv_counter_struct* ) t->data; -// server_api& self = c->api_; -// if ( self.serverInterruptFlag_ ) { -// if ( self.ctx_ ) -// ::lws_libuv_stop( self.ctx_ ); -// ::uv_stop( t->loop ); -// return; -// } -//} + static void my_uv_timer_cb( uv_timer_t* t ) { struct my_uv_counter_struct* c = ( struct my_uv_counter_struct* ) t->data; server_api& self = c->api_; @@ -2689,26 +2539,14 @@ static void my_uv_timer_test_cancel_cb( uv_timer_t* t ) { static void my_uv_timer_close_cb( uv_handle_t* h ) { ::lwsl_notice( "timer close cb %p, loop has %d handles\n", h, h->loop->active_handles ); } -// static void my_uv_outer_signal_cb( uv_signal_t * s, int signum ) { -// ::lwsl_notice( "Foreign loop got signal %d\n", signum ); -// ::uv_signal_stop( s ); -// ::uv_stop( s->loop ); -// } + static void my_uv_lws_uv_close_cb( uv_handle_t* /*handle*/ ) { //::lwsl_err( "%s\n", __func__ ); } static void my_uv_lws_uv_walk_cb( uv_handle_t* handle, void* /*arg*/ ) { ::uv_close( handle, my_uv_lws_uv_close_cb ); } -// static void my_uv_idle_cb( uv_idle_t* uvi ) { -// server_api* self = ( server_api* ) uvi->data; -// if ( self->serverInterruptFlag_ ) { -// if ( self->ctx_ ) -// ::lws_libuv_stop( self->ctx_ ); -// else -// return; -// } -//} + #endif // (defined LWS_WITH_LIBUV) @@ -2776,12 +2614,6 @@ void server_api::service( fn_continue_status_flag_t fnContinueStatusFlag ) { }; ev_timer timeout_watcher; - // for( n = 0; n < (int)ARRAY_SIZE(sigs); n++ ) { - // ev_init(&signals[n], signal_cb); - // ev_signal_set(&signals[n], sigs[n]); - // ev_signal_start(loop, &signals[n]); - // } - server_api::stat_ptr_reg( &timeout_watcher, this ); ::lws_ev_initloop( ctx_, loop, 0 ); ev_timer_init( &timeout_watcher, my_ev_timeout_cb, 0.05, 0.05 ); @@ -2848,11 +2680,6 @@ void server_api::service( fn_continue_status_flag_t fnContinueStatusFlag ) { ::uv_timer_init( pUvLoop_.get(), &timer_outer ); timer_outer.data = &ctr; - // ctr.cur_ = 0; - // ctr.lim_ = ctr.cur_ + 5; // TO-CHECK: wth is this? - // ctr.stop_loop_ = true; - // ::uv_timer_start( &timer_outer, my_uv_timer_cb, 0, 1000 ); - // ::lwsl_notice( "running loop without libwebsockets for %d s\n", int( ctr.lim_ ) ); ::uv_run( pUvLoop_.get(), UV_RUN_DEFAULT ); fn_internal_interrupt_action_ = nullptr; @@ -2978,7 +2805,7 @@ void server_api::onHttp( connection_identifier_t cid ) { } void server_api::onFail( connection_identifier_t cid, const std::string& strMessage ) { onLogMessage( e_ws_log_message_type_t::eWSLMT_error, - cc::error( "Error: " ) + cc::warn( strMessage ) + " on cid " + cc::num10( cid ) ); + "Error: " + strMessage + " on cid " + std::to_string( cid ) ); lock_type lock( mtx_api() ); if ( impl_removeConnection( cid ) ) { if ( onFail_ ) @@ -3333,13 +3160,10 @@ nlohmann::json peer::toJSON( bool bSkipEmptyStats /*= true*/ ) const { jo["stats"] = traffic_stats::toJSON( bSkipEmptyStats ); return jo; } -std::string peer::getShortTypeDescrition( bool isColored /*= false*/ ) const { +// TODO - remove unused argument +std::string peer::getShortTypeDescrition( bool /*= false*/ ) const { // lock_type lock( ref_mtx() ); std::string s( "peer" ); - if ( isColored ) { - if ( !s.empty() ) - s = cc::info( s ); - } return s; } std::string peer::getShortPeerDescription( @@ -3347,12 +3171,6 @@ std::string peer::getShortPeerDescription( // lock_type lock( ref_mtx() ); std::stringstream ss; std::string strSpace( " " ), strCommaSpace( ", " ), strIP( getRemoteIp() ); - if ( isColored ) { - strSpace = cc::debug( strSpace ); - strCommaSpace = cc::debug( strCommaSpace ); - if ( !strIP.empty() ) - strIP = cc::u( strIP ); - } traffic_stats::time_point tpNow = traffic_stats::clock::now(); ss << unique_string_identifier( isColored ) << strSpace << getShortTypeDescrition( isColored ) << strSpace << strIP; @@ -3364,15 +3182,10 @@ std::string peer::getShortPeerDescription( } std::string peer::unique_string_identifier( bool isColored /*= false*/ ) const { std::string strCid( getCidString() ), strSlash( "/" ); - if ( isColored ) { - strSlash = cc::debug( strSlash ); - if ( !strCid.empty() ) - strCid = cc::bright( strCid ); - } size_t s_no = serial_number(); std::string strPeerSerialNumber = skutils::tools::format( "%" PRIu64, uint64_t( s_no ) ); if ( isColored ) - strPeerSerialNumber = cc::notice( strPeerSerialNumber ); + strPeerSerialNumber = strPeerSerialNumber; std::stringstream ss; ss << strCid << strSlash << strPeerSerialNumber; return ss.str(); @@ -3467,13 +3280,13 @@ void peer::close( const std::string& msg, if ( strWhat == nullptr || strWhat[0] == '\0' ) strWhat = "unknown exception"; std::stringstream ss; - ss << cc::error( "Exception: " ) << cc::warn( strWhat ); + ss << "Exception: " << strWhat; srv_.onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); // clean_up( cid_ ); traffic_stats::event_add( g_strEventNameWebSocketPeerDisconnectFail ); } catch ( ... ) { std::stringstream ss; - ss << cc::error( "Unknown exception" ); + ss << "Unknown exception"; srv_.onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); // clean_up( cid_ ); traffic_stats::event_add( g_strEventNameWebSocketPeerDisconnectFail ); @@ -3522,8 +3335,8 @@ void peer::onFail() { traffic_stats::log_close(); } bool peer::sendMessage( const std::string& msg, opcv eOpCode ) { - // ss << cc::debug(">>> ") << cc::warn(getSender()) << cc::debug(", ") << - // cc::warn(getCidString()) << cc::debug(", ") << cc::c(msg) << "/n"; + // ss << ">>> " << getSender() << ", " << + // getCidString() << ", " << msg << "/n"; std::string strCid = getCidString(); std::string strRemoteIp = getRemoteIp(); try { @@ -3544,13 +3357,13 @@ bool peer::sendMessage( const std::string& msg, opcv eOpCode ) { if ( strWhat == nullptr || strWhat[0] == '\0' ) strWhat = "unknown exception"; std::stringstream ss; - ss << cc::error( "nlws-peer sendMessage(" ) << cc::warn( strCid ) << cc::error( "," ) - << cc::u( strRemoteIp ) << cc::error( ") failed, exception: " ) << cc::warn( strWhat ); + ss << "nlws-peer sendMessage(" << strCid << "," << strRemoteIp + << ") failed, exception: " << strWhat; srv_.onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); } catch ( ... ) { std::stringstream ss; - ss << cc::error( "nlws-peer sendMessage(" ) << cc::warn( strCid ) << cc::error( "," ) - << cc::u( strRemoteIp ) << cc::error( ") failed, unknown exception" ); + ss << "nlws-peer sendMessage(" << strCid << "," << strRemoteIp + << ") failed, unknown exception"; srv_.onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); } return false; @@ -3594,7 +3407,7 @@ server::server( basic_network_settings* pBNS ) }; api_.onFail_ = [this]( connection_identifier_t cid, const std::string& strMessage ) { if ( !strMessage.empty() ) - onLogMessage( e_ws_log_message_type_t::eWSLMT_error, cc::error( strMessage ) ); + onLogMessage( e_ws_log_message_type_t::eWSLMT_error, strMessage ); onFail( cid ); }; api_.onLogMessage_ = [this]( e_ws_log_message_type_t eWSLMT, const std::string& strMessage ) { @@ -3631,7 +3444,7 @@ bool server::isServerSide() const { return true; } std::string server::type() const { - return api_.use_ssl_ ? cc::success( "SSL/TLS" ) : cc::fatal( "non-secure" ); + return api_.use_ssl_ ? "SSL/TLS" : "non-secure"; } int server::port() const { return api_.ctx_info_.port; @@ -3785,8 +3598,7 @@ void server::onOpen( hdl_t hdl ) { if ( !pPeer ) { std::string strRemoteIp = getRemoteIp( hdl ); std::stringstream ss; - ss << cc::error( "Failed to instantiate peer(" ) << cc::u( strRemoteIp ) - << cc::error( ")" ); + ss << "Failed to instantiate peer(" << strRemoteIp << ")"; onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); close( hdl, close_status::internal_endpoint_error, "internal peer initialization error" ); return; @@ -3825,8 +3637,7 @@ void server::onMessage( hdl_t hdl, opcv eOpCode, const std::string& msg ) { // std::string strRemoteIp = getRemoteIp( hdl ); std::stringstream ss; - ss << cc::warn( "No instantiated peer(" ) << cc::u( strRemoteIp ) - << cc::warn( ") for message (" ) << cc::str( msg ) << cc::warn( "<<" ); + ss << "No instantiated peer(" << strRemoteIp << ") for message (" << msg << "<<"; onLogMessage( e_ws_log_message_type_t::eWSLMT_warning, ss.str() ); // basic_socket::onMessage( hdl, eOpCode, msg ); @@ -3873,7 +3684,7 @@ client::client( basic_network_settings* pBNS ) : api_( pBNS ) { }; api_.onFail_ = [this]( const std::string& strMessage ) { if ( !strMessage.empty() ) - onLogMessage( e_ws_log_message_type_t::eWSLMT_error, cc::error( strMessage ) ); + onLogMessage( e_ws_log_message_type_t::eWSLMT_error, strMessage ); setConnected( false ); onFail( api_.cid_ ); }; @@ -3901,7 +3712,7 @@ bool client::is_ssl() const { return api_.ssl_flags_ ? true : false; } std::string client::type() const { - return api_.ssl_flags_ ? cc::success( "SSL/TLS" ) : cc::fatal( "non-secure" ); + return api_.ssl_flags_ ? "SSL/TLS" : "non-secure"; } std::string client::uri() const { return api_.strURL_; @@ -3925,11 +3736,12 @@ bool client::open( const std::string& uri, const char* strInterfaceName ) { if ( strWhat == nullptr || strWhat[0] == '\0' ) strWhat = "unknown exception"; std::stringstream ss; - ss << cc::error( "open: " ) << cc::warn( strWhat ); + ss << "open: " << strWhat; onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); } catch ( ... ) { std::stringstream ss; - ss << cc::error( "open: " ) << cc::warn( "unknown exception" ); + ss << "open: " + << "unknown exception"; onLogMessage( e_ws_log_message_type_t::eWSLMT_error, ss.str() ); } traffic_stats::event_add( g_strEventNameWebSocketClientConnectFail ); diff --git a/libweb3jsonrpc/AdminEth.cpp b/libweb3jsonrpc/AdminEth.cpp index 983dcdb7c..47ea888a8 100644 --- a/libweb3jsonrpc/AdminEth.cpp +++ b/libweb3jsonrpc/AdminEth.cpp @@ -167,7 +167,7 @@ Json::Value AdminEth::admin_eth_vmTrace( // e.finalize(); // Json::Reader().parse(st.json(), ret); } catch ( Exception const& _e ) { - cwarn << diagnostic_information( _e ); + LOG( m_loggerWarning ) << diagnostic_information( _e ); } } diff --git a/libweb3jsonrpc/AdminEth.h b/libweb3jsonrpc/AdminEth.h index cf11e57c8..92f5e75e0 100644 --- a/libweb3jsonrpc/AdminEth.h +++ b/libweb3jsonrpc/AdminEth.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include "AdminEthFace.h" @@ -58,6 +59,9 @@ class AdminEth : public AdminEthFace { std::function< void( Address const& ) > m_setMiningBenefactor; h256 blockHash( std::string const& _blockNumberOrHash ) const; + + /// Loggers + Logger m_loggerWarning{ createLogger( VerbosityWarning, "AdminEth" ) }; }; } // namespace rpc diff --git a/libweb3jsonrpc/Eth.cpp b/libweb3jsonrpc/Eth.cpp index 4c03c2abf..3a0812a96 100644 --- a/libweb3jsonrpc/Eth.cpp +++ b/libweb3jsonrpc/Eth.cpp @@ -556,8 +556,8 @@ Json::Value Eth::eth_getBlockByHash( string const& _blockHash, bool _includeTran try { baseFeePerGas = client()->gasBidPrice( client()->numberFromHash( h ) - 1 ); } catch ( std::invalid_argument& _e ) { - cdebug << "Cannot get gas price for block " << h; - cdebug << _e.what(); + LOG( m_loggerDebug ) << "Cannot get gas price for block " << h; + LOG( m_loggerDebug ) << _e.what(); // set default gasPrice // probably the price was rotated out as we are asking the price for the old block baseFeePerGas = client()->gasBidPrice(); @@ -621,8 +621,8 @@ Json::Value Eth::eth_getBlockByNumber( string const& _blockNumber, bool _include try { baseFeePerGas = client()->gasBidPrice( bn - 1 ); } catch ( std::invalid_argument& _e ) { - cdebug << "Cannot get gas price for block " << bn; - cdebug << _e.what(); + LOG( m_loggerDebug ) << "Cannot get gas price for block " << bn; + LOG( m_loggerDebug ) << _e.what(); // set default gasPrice // probably the price was rotated out as we are asking the price for the old block baseFeePerGas = client()->gasBidPrice(); @@ -843,8 +843,6 @@ Json::Value Eth::eth_getFilterChanges( string const& _filterId ) { try { unsigned int id = static_cast< unsigned int >( jsToInt( _filterId ) ); auto entries = client()->checkWatch( id ); - // if (entries.size()) - // cnote << "FIRING WATCH" << id << entries.size(); return toJson( entries ); } catch ( ... ) { BOOST_THROW_EXCEPTION( JsonRpcException( Errors::ERROR_RPC_INVALID_PARAMS ) ); @@ -855,8 +853,6 @@ Json::Value Eth::eth_getFilterChangesEx( string const& _filterId ) { try { unsigned int id = static_cast< unsigned int >( jsToInt( _filterId ) ); auto entries = client()->checkWatch( id ); - // if (entries.size()) - // cnote << "FIRING WATCH" << id << entries.size(); return toJsonByBlock( entries ); } catch ( ... ) { BOOST_THROW_EXCEPTION( JsonRpcException( Errors::ERROR_RPC_INVALID_PARAMS ) ); @@ -875,15 +871,6 @@ Json::Value Eth::eth_getFilterLogs( string const& _filterId ) { } } -// Json::Value Eth::eth_getFilterLogsEx( string const& _filterId ) { -// try { -// return toJsonByBlock( -// client()->logs( static_cast< unsigned int >( jsToInt( _filterId ) ) ) ); -// } catch ( ... ) { -// BOOST_THROW_EXCEPTION( JsonRpcException( Errors::ERROR_RPC_INVALID_PARAMS ) ); -// } -//} - Json::Value Eth::eth_getLogs( Json::Value const& _json ) { try { LogFilter filter = toLogFilter( _json ); @@ -914,14 +901,6 @@ Json::Value Eth::eth_getLogs( Json::Value const& _json ) { } } -// Json::Value Eth::eth_getLogsEx( Json::Value const& _json ) { -// try { -// return toJsonByBlock( client()->logs( toLogFilter( _json ) ) ); -// } catch ( ... ) { -// BOOST_THROW_EXCEPTION( JsonRpcException( Errors::ERROR_RPC_INVALID_PARAMS ) ); -// } -//} - Json::Value Eth::eth_getWork() { try { Json::Value ret( Json::arrayValue ); diff --git a/libweb3jsonrpc/Eth.h b/libweb3jsonrpc/Eth.h index ae4c011f2..7be1d2399 100644 --- a/libweb3jsonrpc/Eth.h +++ b/libweb3jsonrpc/Eth.h @@ -242,6 +242,9 @@ class Eth : public dev::rpc::EthFace, public skutils::json_config_file_accessor #ifdef HISTORIC_STATE std::unique_ptr< _detail::GappedTransactionIndexCache > m_gapCache; #endif + +private: + dev::Logger m_loggerDebug{ dev::createLogger( dev::VerbosityDebug, "Eth" ) }; }; } // namespace rpc diff --git a/libweb3jsonrpc/IpcServerBase.cpp b/libweb3jsonrpc/IpcServerBase.cpp index 539216571..df83fb74a 100644 --- a/libweb3jsonrpc/IpcServerBase.cpp +++ b/libweb3jsonrpc/IpcServerBase.cpp @@ -40,7 +40,7 @@ int const c_bufferSize = 1024; template < class S > IpcServerBase< S >::IpcServerBase( string const& _path ) : m_path( _path ) { - clog( VerbosityInfo, "rpc" ) << "JSON-RPC socket path: " << _path; + LOG( m_loggerInfo ) << "JSON-RPC socket path: " << _path; } template < class S > @@ -84,7 +84,7 @@ bool IpcServerBase< S >::SendResponse( string const& _response, void* _addInfo ) } else fullyWritten = true; } while ( !fullyWritten && !errorOccured ); - clog( VerbosityTrace, "rpc" ) << _response; + LOG( m_loggerTrace ) << _response; return fullyWritten && !errorOccured; } @@ -124,7 +124,7 @@ void IpcServerBase< S >::GenerateResponse( S _connection ) { if ( depth == 0 ) { std::string r = request.substr( 0, i + 1 ); request.erase( 0, i + 1 ); - clog( VerbosityTrace, "rpc" ) << r; + LOG( m_loggerTrace ) << r; OnRequest( r, reinterpret_cast< void* >( ( intptr_t ) _connection ) ); // l_sergiy: migration to new // json-rpc-cpp diff --git a/libweb3jsonrpc/IpcServerBase.h b/libweb3jsonrpc/IpcServerBase.h index 04c6e5a77..38aeb7a4e 100644 --- a/libweb3jsonrpc/IpcServerBase.h +++ b/libweb3jsonrpc/IpcServerBase.h @@ -25,6 +25,7 @@ #pragma once #include +#include #include #include #include @@ -58,5 +59,10 @@ class IpcServerBase : public jsonrpc::AbstractServerConnector { std::unordered_set< S > m_sockets; std::mutex x_sockets; std::thread m_listeningThread; // TODO use asio for parallel request processing + +private: + /// Loggers + Logger m_loggerInfo{ createLogger( VerbosityInfo, "IpcServerBase" ) }; + Logger m_loggerTrace{ createLogger( VerbosityTrace, "IpcServerBase" ) }; }; } // namespace dev diff --git a/libweb3jsonrpc/Skale.cpp b/libweb3jsonrpc/Skale.cpp index e8930dc1d..79c31cdcc 100644 --- a/libweb3jsonrpc/Skale.cpp +++ b/libweb3jsonrpc/Skale.cpp @@ -75,7 +75,7 @@ Skale::~Skale() { threadExitRequested = true; if ( snapshotDownloadFragmentMonitorThread != nullptr && snapshotDownloadFragmentMonitorThread->joinable() ) { - clog( VerbosityInfo, "Skale" ) << "Joining downloadSnapshotFragmentMonitorThread"; + LOG( m_loggerInfo ) << "Joining downloadSnapshotFragmentMonitorThread"; snapshotDownloadFragmentMonitorThread->join(); } } @@ -103,15 +103,15 @@ void Skale::onShutdownInvoke( fn_on_shutdown_t fn ) { std::string Skale::skale_shutdownInstance() { if ( !g_bShutdownViaWeb3Enabled ) { - cwarn << "\nINSTANCE SHUTDOWN ATTEMPT WHEN DISABLED\n\n"; + LOG( m_loggerWarning ) << "\nINSTANCE SHUTDOWN ATTEMPT WHEN DISABLED\n\n"; return toJS( "disabled" ); } if ( g_bNodeInstanceShouldShutdown ) { - cnote << "\nSECONDARY INSTANCE SHUTDOWN EVENT\n\n"; + LOG( m_loggerInfo ) << "\nSECONDARY INSTANCE SHUTDOWN EVENT\n\n"; return toJS( "in progress(secondary attempt)" ); } g_bNodeInstanceShouldShutdown = true; - cnote << "\nINSTANCE SHUTDOWN EVENT\n\n"; + LOG( m_loggerInfo ) << "\nINSTANCE SHUTDOWN EVENT\n\n"; for ( auto& fn : g_list_fn_on_shutdown ) { if ( !fn ) continue; @@ -121,9 +121,9 @@ std::string Skale::skale_shutdownInstance() { std::string s = ex.what(); if ( s.empty() ) s = "no description"; - cerror << "Exception in shutdown event handler: " << s; + LOG( m_loggerError ) << "Exception in shutdown event handler: " << s; } catch ( ... ) { - cerror << "Unknown exception in shutdown event handler"; + LOG( m_loggerError ) << "Unknown exception in shutdown event handler"; } } // for( auto & fn : g_list_fn_on_shutdown ) g_list_fn_on_shutdown.clear(); @@ -215,15 +215,13 @@ nlohmann::json Skale::impl_skale_getSnapshot( const nlohmann::json& joRequest, C sleep( SNAPSHOT_DOWNLOAD_MONITOR_THREAD_SLEEP_MS ); } - clog( VerbosityInfo, "skale_downloadSnapshotFragmentMonitorThread" ) - << "Unlocking shared space."; + LOG( m_loggerInfo ) << "Unlocking shared space."; std::lock_guard< std::mutex > lock( m_snapshot_mutex ); if ( currentSnapshotBlockNumber >= 0 ) { try { fs::remove( currentSnapshotPath ); - clog( VerbosityInfo, "skale_downloadSnapshotFragmentMonitorThread" ) - << "Deleted snapshot file."; + LOG( m_loggerInfo ) << "Deleted snapshot file."; } catch ( ... ) { } currentSnapshotBlockNumber = -1; @@ -324,8 +322,7 @@ nlohmann::json Skale::impl_skale_downloadSnapshotFragmentJSON( const nlohmann::j std::string strBase64 = skutils::tools::base64::encode( buffer.data(), sizeOfChunk ); if ( sizeOfChunk + idxFrom == sizeOfFile ) - clog( VerbosityInfo, "skale_downloadSnapshotFragment" ) - << "Sent all chunks for " << currentSnapshotPath.string(); + LOG( m_loggerInfo ) << "Sent all chunks for " << currentSnapshotPath.string(); joResponse["size"] = sizeOfChunk; joResponse["data"] = strBase64; @@ -424,16 +421,15 @@ Json::Value Skale::skale_getSnapshotSignature( unsigned blockNumber ) { cli.optsSSL_ = ssl_options; bool fl = cli.open( sgxServerURL ); if ( !fl ) { - clog( VerbosityError, "skale_getSnapshotSignature" ) - << "FATAL:" - << " Exception while trying to connect to sgx server: " - << "connection refused"; + LOG( m_loggerInfo ) << "FATAL:" + << " Exception while trying to connect to sgx server: " + << "connection refused"; } skutils::rest::data_t d; while ( true ) { - clog( VerbosityInfo, "skale_getSnapshotSignature" ) << ">>> SGX call >>>" - << " " << joCall; + LOG( m_loggerInfo ) << ">>> SGX call >>>" + << " " << joCall; d = cli.call( joCall ); if ( d.ei_.et_ != skutils::http::common_network_exception::error_type::et_no_error ) { @@ -441,16 +437,14 @@ Json::Value Skale::skale_getSnapshotSignature( unsigned blockNumber ) { skutils::http::common_network_exception::error_type::et_unknown || d.ei_.et_ == skutils::http::common_network_exception::error_type::et_fatal ) { - clog( VerbosityError, "skale_getSnapshotSignature" ) - << "ERROR:" - << " Exception while trying to connect to sgx server: " - << " error with connection: " - << " retrying... "; + LOG( m_loggerError ) << "ERROR:" + << " Exception while trying to connect to sgx server: " + << " error with connection: " + << " retrying... "; } else { - clog( VerbosityError, "skale_getSnapshotSignature" ) - << "ERROR:" - << " Exception while trying to connect to sgx server: " - << " error with ssl certificates " << d.ei_.strError_; + LOG( m_loggerError ) << "ERROR:" + << " Exception while trying to connect to sgx server: " + << " error with ssl certificates " << d.ei_.strError_; } } else { break; @@ -459,8 +453,8 @@ Json::Value Skale::skale_getSnapshotSignature( unsigned blockNumber ) { if ( d.empty() ) { static const char g_strErrMsg[] = "SGX Server call to blsSignMessageHash failed"; - clog( VerbosityError, "skale_getSnapshotSignature" ) << "!!! SGX call error !!!" - << " " << g_strErrMsg; + LOG( m_loggerError ) << "SGX call error" + << " " << g_strErrMsg; throw std::runtime_error( g_strErrMsg ); } @@ -541,7 +535,7 @@ std::string Skale::oracle_submitRequest( std::string& request ) { std::string receipt; std::string errorMessage; - clog( VerbosityDebug, "Oracle request:" ) << request; + LOG( m_loggerDebug ) << request; uint64_t status = this->m_client.submitOracleRequest( request, receipt, errorMessage ); if ( status != ORACLE_SUCCESS ) { @@ -571,7 +565,7 @@ std::string Skale::oracle_checkResult( std::string& receipt ) { throw jsonrpc::JsonRpcException( status, skutils::tools::format( "Oracle request failed with status %zu", status ) ); } - clog( VerbosityDebug, "Oracle result:" ) << result; + LOG( m_loggerDebug ) << result; return result; } catch ( jsonrpc::JsonRpcException const& e ) { throw e; diff --git a/libweb3jsonrpc/Skale.h b/libweb3jsonrpc/Skale.h index e76ee732a..9faf45b8f 100644 --- a/libweb3jsonrpc/Skale.h +++ b/libweb3jsonrpc/Skale.h @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -114,6 +115,12 @@ class Skale : public dev::rpc::SkaleFace { std::unique_ptr< std::thread > snapshotDownloadFragmentMonitorThread; std::atomic_bool threadExitRequested = false; mutable std::mutex m_snapshot_mutex; + + /// Loggers + Logger m_loggerDebug{ createLogger( VerbosityDebug, "Skale" ) }; + Logger m_loggerInfo{ createLogger( VerbosityInfo, "Skale" ) }; + Logger m_loggerWarning{ createLogger( VerbosityWarning, "Skale" ) }; + Logger m_loggerError{ createLogger( VerbosityError, "Skale" ) }; }; namespace snapshot { diff --git a/libweb3jsonrpc/SkalePerformanceTracker.cpp b/libweb3jsonrpc/SkalePerformanceTracker.cpp index cfb61e9f1..f372b6e63 100644 --- a/libweb3jsonrpc/SkalePerformanceTracker.cpp +++ b/libweb3jsonrpc/SkalePerformanceTracker.cpp @@ -53,7 +53,7 @@ SkalePerformanceTracker::SkalePerformanceTracker( const std::string& configPath Json::Value SkalePerformanceTracker::skale_performanceTrackingStatus( const Json::Value& /*request*/ ) { - std::string strLogPrefix = cc::deep_info( "Performance tracking status" ); + std::string strLogPrefix = "Performance tracking status"; try { skutils::task::performance::tracker_ptr pTracker = skutils::task::performance::get_default_tracker(); @@ -71,25 +71,22 @@ Json::Value SkalePerformanceTracker::skale_performanceTrackingStatus( Json::Reader().parse( s, ret ); return ret; } catch ( Exception const& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << ( strLogPrefix + " " + + "FATAL:" + " Exception while processing request: " + ex.what() ); throw jsonrpc::JsonRpcException( exceptionToErrorMessage() ); } catch ( const std::exception& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + " " + + "FATAL:" + " Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( ex.what() ); } catch ( ... ) { - clog( VerbosityError, "IMA" ) << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + - cc::warn( "unknown exception" ) ); + LOG( m_loggerError ) << strLogPrefix + " " + "FATAL:" + + " Exception while processing request: " + "unknown exception"; throw jsonrpc::JsonRpcException( "unknown exception" ); } } Json::Value SkalePerformanceTracker::skale_performanceTrackingStart( const Json::Value& request ) { - std::string strLogPrefix = cc::deep_info( "Performance tracking start" ); + std::string strLogPrefix = "Performance tracking start"; try { Json::FastWriter fastWriter; const std::string strRequest = fastWriter.write( request ); @@ -118,26 +115,23 @@ Json::Value SkalePerformanceTracker::skale_performanceTrackingStart( const Json: Json::Reader().parse( s, ret ); return ret; } catch ( Exception const& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( exceptionToErrorMessage() ); } catch ( const std::exception& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( ex.what() ); } catch ( ... ) { - clog( VerbosityError, "IMA" ) << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + - cc::warn( "unknown exception" ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: unknown exception"; throw jsonrpc::JsonRpcException( "unknown exception" ); } } Json::Value SkalePerformanceTracker::skale_performanceTrackingStop( const Json::Value& /*request*/ ) { - std::string strLogPrefix = cc::deep_info( "Performance tracking stop" ); + std::string strLogPrefix = "Performance tracking stop"; try { skutils::task::performance::tracker_ptr pTracker = skutils::task::performance::get_default_tracker(); @@ -158,25 +152,22 @@ Json::Value SkalePerformanceTracker::skale_performanceTrackingStop( Json::Reader().parse( s, ret ); return ret; } catch ( Exception const& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( exceptionToErrorMessage() ); } catch ( const std::exception& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( ex.what() ); } catch ( ... ) { - clog( VerbosityError, "IMA" ) << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + - cc::warn( "unknown exception" ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: unknown exception"; throw jsonrpc::JsonRpcException( "unknown exception" ); } } Json::Value SkalePerformanceTracker::skale_performanceTrackingFetch( const Json::Value& request ) { - std::string strLogPrefix = cc::deep_info( "Performance tracking fetch" ); + std::string strLogPrefix = "Performance tracking fetch"; try { Json::FastWriter fastWriter; const std::string strRequest = fastWriter.write( request ); @@ -204,19 +195,16 @@ Json::Value SkalePerformanceTracker::skale_performanceTrackingFetch( const Json: Json::Reader().parse( s, ret ); return ret; } catch ( Exception const& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( exceptionToErrorMessage() ); } catch ( const std::exception& ex ) { - clog( VerbosityError, "IMA" ) - << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + cc::warn( ex.what() ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: " + ex.what(); throw jsonrpc::JsonRpcException( ex.what() ); } catch ( ... ) { - clog( VerbosityError, "IMA" ) << ( strLogPrefix + " " + cc::fatal( "FATAL:" ) + - cc::error( " Exception while processing request: " ) + - cc::warn( "unknown exception" ) ); + LOG( m_loggerError ) << strLogPrefix + + " FATAL: Exception while processing request: unknown exception"; throw jsonrpc::JsonRpcException( "unknown exception" ); } } diff --git a/libweb3jsonrpc/SkalePerformanceTracker.h b/libweb3jsonrpc/SkalePerformanceTracker.h index bf284c4ff..2a1430f75 100644 --- a/libweb3jsonrpc/SkalePerformanceTracker.h +++ b/libweb3jsonrpc/SkalePerformanceTracker.h @@ -30,6 +30,7 @@ #include #include #include +#include #include @@ -58,6 +59,9 @@ class SkalePerformanceTracker : public dev::rpc::SkalePerformanceTrackerFace, virtual Json::Value skale_performanceTrackingStart( const Json::Value& request ) override; virtual Json::Value skale_performanceTrackingStop( const Json::Value& request ) override; virtual Json::Value skale_performanceTrackingFetch( const Json::Value& request ) override; + +private: + Logger m_loggerError{ createLogger( VerbosityError, "SkalePerformanceTracker - IMA" ) }; }; }; // namespace rpc diff --git a/libweb3jsonrpc/SkaleStats.cpp b/libweb3jsonrpc/SkaleStats.cpp index a79a01c47..dac6657ef 100644 --- a/libweb3jsonrpc/SkaleStats.cpp +++ b/libweb3jsonrpc/SkaleStats.cpp @@ -52,8 +52,6 @@ #include #include -//#include "../libconsensus/libBLS/bls/bls.h" - #include #include @@ -801,53 +799,4 @@ skutils::url SkaleStats::pick_own_s_chain_url() { } }; // namespace rpc -}; // namespace dev - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// void ttt123() { -// const char strLogPrefix[] = "----------- "; -// dev::bytes vecComputeMessagesHash; -// vecComputeMessagesHash.push_back( 'M' ); -// vecComputeMessagesHash.push_back( 'a' ); -// vecComputeMessagesHash.push_back( 'i' ); -// vecComputeMessagesHash.push_back( 'n' ); -// vecComputeMessagesHash.push_back( 'n' ); -// vecComputeMessagesHash.push_back( 'e' ); -// vecComputeMessagesHash.push_back( 't' ); -// std::cout << ( strLogPrefix + cc::debug( " Accumulated vector " ) + -// cc::binary_singleline( ( void* ) vecComputeMessagesHash.data(), -// vecComputeMessagesHash.size(), "" ) ) -// << "\n"; -// dev::rpc::stat_re_compute_vec_2_h256vec( vecComputeMessagesHash ); -// std::cout << ( strLogPrefix + cc::debug( " Computed hash from vector " ) + -// cc::binary_singleline( ( void* ) vecComputeMessagesHash.data(), -// vecComputeMessagesHash.size(), "" ) ) -// << "\n"; -// // we should get 8d646f556e5d9d6f1edcf7a39b77f5ac253776eb34efcfd688aacbee518efc26 -//} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// void ttt123() { -// const char strLogPrefix[] = "----------- "; -// dev::bytes vecComputeMessagesHash; -// dev::u256 uAddr( "0xd2aaa00300000000000000000000000000000000" ); -// std::cout << ( strLogPrefix + cc::debug( " Test address " ) + cc::notice( dev::toJS( uAddr ) ) -// ) -// << "\n"; -// std::cout << ( strLogPrefix + cc::debug( " Initial vector " ) + -// cc::binary_singleline( ( void* ) vecComputeMessagesHash.data(), -// vecComputeMessagesHash.size(), "" ) ) -// << "\n"; -// dev::rpc::stat_append_address_2_vec( vecComputeMessagesHash, uAddr ); -// std::cout << ( strLogPrefix + cc::debug( " Vector with appended address " ) + -// cc::binary_singleline( ( void* ) vecComputeMessagesHash.data(), -// vecComputeMessagesHash.size(), "" ) ) -// << "\n"; -//} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +}; // namespace dev \ No newline at end of file diff --git a/libweb3jsonrpc/SkaleStats.h b/libweb3jsonrpc/SkaleStats.h index 2d2e1e497..10774b8f0 100644 --- a/libweb3jsonrpc/SkaleStats.h +++ b/libweb3jsonrpc/SkaleStats.h @@ -32,7 +32,7 @@ #include -//#include +// #include #include #include @@ -62,11 +62,11 @@ class Interface; }; // namespace eth // if following is defined then pending IMA transactions will be tracked in dispatch timer based job -//#define __IMA_PTX_ENABLE_TRACKING_PARALLEL 1 +// #define __IMA_PTX_ENABLE_TRACKING_PARALLEL 1 // if following is defined then pending IMA transactions will be tracked on-the-fly during // insert/erase -//#define __IMA_PTX_ENABLE_TRACKING_ON_THE_FLY 1 +// #define __IMA_PTX_ENABLE_TRACKING_ON_THE_FLY 1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/libweb3jsonrpc/SkaleStatsSite.h b/libweb3jsonrpc/SkaleStatsSite.h index 91d688496..6ab41f208 100644 --- a/libweb3jsonrpc/SkaleStatsSite.h +++ b/libweb3jsonrpc/SkaleStatsSite.h @@ -24,7 +24,6 @@ #pragma once -//#include #include namespace dev { diff --git a/libweb3jsonrpc/Test.cpp b/libweb3jsonrpc/Test.cpp index 300ac5d71..10cf7f96a 100644 --- a/libweb3jsonrpc/Test.cpp +++ b/libweb3jsonrpc/Test.cpp @@ -67,7 +67,7 @@ string Test::test_getLogHash( string const& _txHash ) { } return toJS( dev::EmptyListSHA3 ); } catch ( std::exception const& ex ) { - cwarn << ex.what(); + LOG( m_loggerWarning ) << ex.what(); throw JsonRpcException( Errors::ERROR_RPC_INTERNAL_ERROR, ex.what() ); } } diff --git a/libweb3jsonrpc/Test.h b/libweb3jsonrpc/Test.h index dbfde207f..0e52982db 100644 --- a/libweb3jsonrpc/Test.h +++ b/libweb3jsonrpc/Test.h @@ -24,6 +24,7 @@ #pragma once #include "TestFace.h" +#include namespace dev { @@ -46,6 +47,8 @@ class Test : public TestFace { private: eth::Client& m_eth; + + Logger m_loggerWarning{ createLogger( VerbosityWarning, "Test" ) }; }; } // namespace rpc diff --git a/libweb3jsonrpc/UnixSocketServer.cpp b/libweb3jsonrpc/UnixSocketServer.cpp index 4579aaf2f..3adc9f554 100644 --- a/libweb3jsonrpc/UnixSocketServer.cpp +++ b/libweb3jsonrpc/UnixSocketServer.cpp @@ -121,11 +121,12 @@ void UnixDomainSocketServer::Listen() { GenerateResponse( connection ); CloseConnection( connection ); } catch ( const std::exception& ex ) { - cerror << "CRITICAL " << ex.what() << " in UnixDomainSocketServer"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) + << "CRITICAL " << ex.what() << " in UnixDomainSocketServer"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; } catch ( ... ) { - cerror << "CRITICAL unknown exception in UnixDomainSocketServer"; - cerror << "\n" << skutils::signal::generate_stack_trace() << "\n" << std::endl; + LOG( m_loggerError ) << "CRITICAL unknown exception in UnixDomainSocketServer"; + LOG( m_loggerError ) << "\n" << skutils::signal::generate_stack_trace() << "\n"; } // catch } }.detach(); } diff --git a/libweb3jsonrpc/UnixSocketServer.h b/libweb3jsonrpc/UnixSocketServer.h index d2c98013d..fe110ea3e 100644 --- a/libweb3jsonrpc/UnixSocketServer.h +++ b/libweb3jsonrpc/UnixSocketServer.h @@ -40,6 +40,9 @@ class UnixDomainSocketServer : public IpcServerBase< int > { sockaddr_un m_address; std::atomic< int > m_socket{ 0 }; + +private: + Logger m_loggerError{ createLogger( VerbosityError, "UnixDomainSocketServer" ) }; }; } // namespace dev diff --git a/rlp/main.cpp b/rlp/main.cpp index 1b2e0b512..84933b5a2 100644 --- a/rlp/main.cpp +++ b/rlp/main.cpp @@ -41,7 +41,7 @@ namespace js = json_spirit; namespace po = boost::program_options; void version() { - cout << "rlp version " << dev::Version << endl; + cout << "rlp version " << dev::Version << "\n"; exit( 0 ); } @@ -139,21 +139,21 @@ void putOut( bytes _out, Encoding _encoding, bool _encrypt, bool _quiet ) { if ( _encrypt ) crypto::Secp256k1PP::get()->encrypt( toPublic( Secret( h ) ), _out ); if ( !_quiet ) - cerr << "Keccak of RLP: " << h.hex() << endl; + cerr << "Keccak of RLP: " << h.hex() << "\n"; switch ( _encoding ) { case Encoding::Hex: case Encoding::Auto: - cout << toHex( _out ) << endl; + cout << toHex( _out ) << "\n"; break; case Encoding::Base64: - cout << toBase64( &_out ) << endl; + cout << toBase64( &_out ) << "\n"; break; case Encoding::Binary: cout.write( ( char const* ) _out.data(), _out.size() ); break; case Encoding::Keccak: - cout << sha3( _out ).hex() << endl; + cout << sha3( _out ).hex() << "\n"; break; } } @@ -233,15 +233,12 @@ int main( int argc, char** argv ) { } if ( vm.count( "help" ) ) { cout << "Usage rlp [OPTIONS]\nModes:\n" - << " create Given a simplified JSON string, output the RLP." << endl - << " render [ | -- ] Render the given RLP." << endl - << " list [ | -- ] List the items in the RLP list by hash and size." - << endl - << " extract [ | -- ] Extract all items in the RLP list, named by hash." - << endl + << " create Given a simplified JSON string, output the RLP.\n" + << " render [ | -- ] Render the given RLP.\n" + << " list [ | -- ] List the items in the RLP list by hash and size.\n" + << " extract [ | -- ] Extract all items in the RLP list, named by hash.\n" << " assemble [ | ] ... Given a manifest & files, " - "output the RLP." - << endl + "output the RLP.\n" << renderOptions << generalOptions; exit( 0 ); } @@ -296,7 +293,6 @@ int main( int argc, char** argv ) { if ( b != '\n' && b != ' ' && b != '\t' ) { if ( encoding == Encoding::Hex && ( b < '0' || b > '9' ) && ( b < 'a' || b > 'f' ) && ( b < 'A' || b > 'F' ) ) { - // cerr << "'" << b << "':" << (int)b << endl; encoding = Encoding::Base64; } if ( encoding == Encoding::Base64 && ( b < '0' || b > '9' ) && @@ -335,29 +331,29 @@ int main( int argc, char** argv ) { switch ( mode ) { case Mode::ListArchive: { if ( !rlp.isList() ) { - cout << "Error: Invalid format; RLP data is not a list." << endl; + cout << "Error: Invalid format; RLP data is not a list.\n"; exit( 1 ); } - cout << rlp.itemCount() << " items:" << endl; + cout << rlp.itemCount() << " items:\n"; for ( auto i : rlp ) { if ( !i.isData() ) { - cout << "Error: Invalid format; RLP list item is not data." << endl; + cout << "Error: Invalid format; RLP list item is not data.\n"; if ( !lenience ) exit( 1 ); } - cout << " " << i.size() << " bytes: " << sha3( i.data() ) << endl; + cout << " " << i.size() << " bytes: " << sha3( i.data() ) << "\n"; } break; } case Mode::ExtractArchive: { if ( !rlp.isList() ) { - cout << "Error: Invalid format; RLP data is not a list." << endl; + cout << "Error: Invalid format; RLP data is not a list.\n"; exit( 1 ); } - cout << rlp.itemCount() << " items:" << endl; + cout << rlp.itemCount() << " items:\n"; for ( auto i : rlp ) { if ( !i.isData() ) { - cout << "Error: Invalid format; RLP list item is not data." << endl; + cout << "Error: Invalid format; RLP list item is not data.\n"; if ( !lenience ) exit( 1 ); } @@ -406,7 +402,7 @@ int main( int argc, char** argv ) { strings addedInputs; for ( auto i : otherInputs ) if ( !boost::filesystem::is_regular_file( i ) ) - cerr << "Skipped " << i << std::endl; + cerr << "Skipped " << i << "\n"; else addedInputs.push_back( i ); @@ -465,7 +461,7 @@ int main( int argc, char** argv ) { out << vb.get_int(); break; default: - cerr << "ERROR: Unsupported type in JSON." << endl; + cerr << "ERROR: Unsupported type in JSON.\n"; if ( !lenience ) exit( 1 ); } @@ -476,7 +472,7 @@ int main( int argc, char** argv ) { default:; } } catch ( ... ) { - cerr << "Error: Invalid format; bad RLP." << endl; + cerr << "Error: Invalid format; bad RLP.\n"; exit( 1 ); } diff --git a/skale-key/KeyAux.h b/skale-key/KeyAux.h index 3ce52128a..a005e51f2 100644 --- a/skale-key/KeyAux.h +++ b/skale-key/KeyAux.h @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -52,10 +53,10 @@ string createPassword( std::string const& _prompt ) { string confirm = getPassword( "Please confirm the passphrase by entering it again: " ); if ( ret == confirm ) break; - cout << "Passwords were different. Try again." << endl; + cwarn << "Passwords were different. Try again."; } return ret; - // cout << "Enter a hint to help you remember this passphrase: " << flush; + // cdebug << "Enter a hint to help you remember this passphrase: " << flush; // cin >> hint; // return make_pair(ret, hint); } @@ -69,11 +70,11 @@ pair< string, string > createPassword( KeyManager& _keyManager, std::string cons string confirm = getPassword( "Please confirm the passphrase by entering it again: " ); if ( pass == confirm ) break; - cout << "Passwords were different. Try again." << endl; + cwarn << "Passwords were different. Try again."; } string hint = _hint; if ( hint.empty() && !pass.empty() && !_keyManager.haveHint( pass ) ) { - cout << "Enter a hint to help you remember this passphrase: " << flush; + cdebug << "Enter a hint to help you remember this passphrase: " << flush; getline( cin, hint ); } return make_pair( pass, hint ); @@ -140,21 +141,21 @@ class KeyCLI { try { m_toSign.data = fromHex( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--tx-nonce" && i + 1 < argc ) try { m_toSign.nonce = u256( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--force-nonce" && i + 1 < argc ) try { m_forceNonce = u256( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( ( arg == "--tx-dest" || arg == "--tx-to" || arg == "--tx-destination" ) && @@ -163,28 +164,28 @@ class KeyCLI { m_toSign.creation = false; m_toSign.to = toAddress( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--tx-gas" && i + 1 < argc ) try { m_toSign.gas = u256( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--tx-gasprice" && i + 1 < argc ) try { m_toSign.gasPrice = u256( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--tx-value" && i + 1 < argc ) try { m_toSign.value = u256( argv[++i] ); } catch ( ... ) { - cerr << "Invalid argument to " << arg << endl; + cerror << "Invalid argument to " << arg; exit( -1 ); } else if ( arg == "--decode-tx" || arg == "decode" ) @@ -273,7 +274,7 @@ class KeyCLI { return getPassword( "Enter passphrase for key (hint:" + keyManager().passwordHint( a ) + "): " ); } ); - cerr << "Bad file, UUID or address: " << _signKey << endl; + cerror << "Bad file, UUID or address: " << _signKey; exit( -1 ); } } @@ -289,7 +290,9 @@ class KeyCLI { try { wallet.create( m_masterPassword ); } catch ( Exception const& _e ) { - cerr << "unable to create wallet" << endl << boost::diagnostic_information( _e ); + cerror << "unable to create wallet" + << "\n" + << boost::diagnostic_information( _e ); } break; } @@ -298,37 +301,36 @@ class KeyCLI { TransactionBase t = m_inputs.empty() ? TransactionBase( m_toSign ) : TransactionBase( inputData( m_inputs[0] ), CheckTransaction::None ); - cout << "Transaction " << t.sha3().hex() << endl; + cdebug << "Transaction " << t.sha3().hex(); if ( t.isCreation() ) { - cout << " type: creation" << endl; - cout << " code: " << toHex( t.data() ) << endl; + cdebug << " type: creation"; + cdebug << " code: " << toHex( t.data() ); } else { - cout << " type: message" << endl; - cout << " to: " << t.to() << endl; - cout << " data: " << ( t.data().empty() ? "none" : toHex( t.data() ) ) << endl; + cdebug << " type: message"; + cdebug << " to: " << t.to(); + cdebug << " data: " << ( t.data().empty() ? "none" : toHex( t.data() ) ); } try { auto s = t.sender(); if ( t.isCreation() ) - cout << " creates: " << toAddress( s, t.nonce() ) << endl; - cout << " from: " << s << endl; + cdebug << " creates: " << toAddress( s, t.nonce() ); + cdebug << " from: " << s; } catch ( ... ) { - cout << " from: " << endl; + cdebug << " from: "; } - cout << " value: " << formatBalance( t.value() ) << " (" << t.value() << " wei)" - << endl; - cout << " nonce: " << t.nonce() << endl; - cout << " gas: " << t.gas() << endl; - cout << " gas price: " << formatBalance( t.gasPrice() ) << " (" << t.gasPrice() - << " wei)" << endl; - cout << " signing hash: " << t.sha3( WithoutSignature ).hex() << endl; + cdebug << " value: " << formatBalance( t.value() ) << " (" << t.value() << " wei)"; + cdebug << " nonce: " << t.nonce(); + cdebug << " gas: " << t.gas(); + cdebug << " gas price: " << formatBalance( t.gasPrice() ) << " (" << t.gasPrice() + << " wei)"; + cdebug << " signing hash: " << t.sha3( WithoutSignature ).hex(); if ( t.safeSender() ) { - cout << " v: " << ( int ) t.signature().v << endl; - cout << " r: " << t.signature().r << endl; - cout << " s: " << t.signature().s << endl; + cdebug << " v: " << ( int ) t.signature().v; + cdebug << " r: " << t.signature().r; + cdebug << " s: " << t.signature().s; } } catch ( Exception& ex ) { - cerr << "Invalid transaction: " << ex.what() << endl; + cerror << "Invalid transaction: " << ex.what(); } break; } @@ -345,14 +347,14 @@ class KeyCLI { if ( m_forceNonce ) t.setNonce( m_forceNonce ); t.sign( s ); - cout << t.sha3() << ": "; + cdebug << t.sha3() << ": "; if ( isFile ) { writeFile( i + ".signed", toHex( t.toBytes() ) ); - cout << i + ".signed" << endl; + cdebug << i + ".signed"; } else - cout << toHex( t.toBytes() ) << endl; + cdebug << toHex( t.toBytes() ); } catch ( Exception& ex ) { - cerr << "Invalid transaction: " << ex.what() << endl; + cerror << "Invalid transaction: " << ex.what(); } } break; @@ -362,34 +364,33 @@ class KeyCLI { for ( auto i : m_inputs ) { Address a = userToAddress( i ); if ( !keyManager().accountName( a ).empty() ) - cout << keyManager().accountName( a ) << " (" << a.abridged() << ")" << endl; + cdebug << keyManager().accountName( a ) << " (" << a.abridged() << ")"; else - cout << a.abridged() << endl; - cout << " Address: " << a.hex() << endl; + cdebug << a.abridged(); + cdebug << " Address: " << a.hex(); if ( m_showSecret ) { Secret s = keyManager( true ).secret( a ); - cout << " Secret: " - << ( m_showSecret ? toHex( s.ref() ) : - ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ) - << endl; + cdebug << " Secret: " + << ( m_showSecret ? toHex( s.ref() ) : + ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ); } } break; } case OperationMode::ListBare: if ( secretStore().keys().empty() ) - cout << "No keys found." << endl; + cdebug << "No keys found."; else for ( h128 const& u : std::set< h128 >() + secretStore().keys() ) - cout << toUUID( u ) << endl; + cdebug << toUUID( u ); break; case OperationMode::NewBare: { if ( m_lock.empty() ) m_lock = createPassword( "Enter a passphrase with which to secure this account: " ); auto k = makeKey(); h128 u = secretStore().importSecret( k.secret().ref(), m_lock ); - cout << "Created key " << toUUID( u ) << endl; - cout << " Address: " << k.address().hex() << endl; + cdebug << "Created key " << toUUID( u ); + cdebug << " Address: " << k.address().hex(); break; } case OperationMode::ImportBare: @@ -407,12 +408,11 @@ class KeyCLI { u = secretStore().importSecret( b, lockPassword( toAddress( Secret( b ) ).abridged() ) ); if ( !u ) { - cerr << cc::warn( "Cannot import " ) << input - << cc::warn( " not a file or secret." ) << endl; + cerror << "Cannot import " << input << " not a file or secret." + << "\n"; continue; } - cout << cc::success( "Successfully imported " ) << input << cc::success( " as " ) - << toUUID( u ); + cdebug << "Successfully imported " << input << " as " << toUUID( u ); } break; case OperationMode::InspectBare: @@ -421,28 +421,26 @@ class KeyCLI { h128 u = secretStore().readKey( i, false ); bytesSec s = secretStore().secret( u, [&]() { return getPassword( "Enter passphrase for key " + i + ": " ); } ); - cout << "Key " << i << ":" << endl; - cout << " UUID: " << toUUID( u ) << ":" << endl; - cout << " Address: " << toAddress( Secret( s ) ).hex() << endl; - cout << " Secret: " - << ( m_showSecret ? toHex( s.ref() ) : - ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ) - << endl; + cdebug << "Key " << i << ":"; + cdebug << " UUID: " << toUUID( u ) << ":"; + cdebug << " Address: " << toAddress( Secret( s ) ).hex(); + cdebug << " Secret: " + << ( m_showSecret ? toHex( s.ref() ) : + ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ); } else if ( h128 u = fromUUID( i ) ) { bytesSec s = secretStore().secret( u, [&]() { return getPassword( "Enter passphrase for key " + toUUID( u ) + ": " ); } ); - cout << "Key " << i << ":" << endl; - cout << " Address: " << toAddress( Secret( s ) ).hex() << endl; - cout << " Secret: " - << ( m_showSecret ? toHex( s.ref() ) : - ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ) - << endl; + cdebug << "Key " << i << ":"; + cdebug << " Address: " << toAddress( Secret( s ) ).hex(); + cdebug << " Secret: " + << ( m_showSecret ? toHex( s.ref() ) : + ( toHex( s.ref().cropped( 0, 8 ) ) + "..." ) ); } else if ( Address a = toAddress( i ) ) { - cout << "Key " << a.abridged() << ":" << endl; - cout << " Address: " << a.hex() << endl; + cdebug << "Key " << a.abridged() << ":"; + cdebug << " Address: " << a.hex(); } else - cerr << "Couldn't inspect " << i << "; not found." << endl; + cerror << "Couldn't inspect " << i << "; not found."; break; case OperationMode::ExportBare: break; @@ -456,19 +454,19 @@ class KeyCLI { "Enter passphrase for key " + toUUID( u ) + ": " ); }, kdf() ) ) - cerr << "Re-encoded " << toUUID( u ) << endl; + cerror << "Re-encoded " << toUUID( u ); else - cerr << "Couldn't re-encode " << toUUID( u ) - << "; key corrupt or incorrect passphrase supplied." << endl; + cerror << "Couldn't re-encode " << toUUID( u ) + << "; key corrupt or incorrect passphrase supplied."; else - cerr << "Couldn't re-encode " << i << "; not found." << endl; + cerror << "Couldn't re-encode " << i << "; not found."; break; case OperationMode::KillBare: for ( auto const& i : m_inputs ) if ( h128 u = fromUUID( i ) ) secretStore().kill( u ); else - cerr << "Couldn't kill " << i << "; not found." << endl; + cerror << "Couldn't kill " << i << "; not found."; break; case OperationMode::New: { keyManager(); @@ -480,18 +478,18 @@ class KeyCLI { bool usesMaster = m_lock.empty(); h128 u = usesMaster ? keyManager().import( k.secret(), m_name ) : keyManager().import( k.secret(), m_name, m_lock, m_lockHint ); - cout << "Created key " << toUUID( u ) << endl; - cout << " Name: " << m_name << endl; + cdebug << "Created key " << toUUID( u ); + cdebug << " Name: " << m_name; if ( usesMaster ) - cout << " Uses master passphrase." << endl; + cdebug << " Uses master passphrase."; else - cout << " Password hint: " << m_lockHint << endl; - cout << " Address: " << k.address().hex() << endl; + cdebug << " Password hint: " << m_lockHint; + cdebug << " Address: " << k.address().hex(); break; } case OperationMode::Import: { if ( m_inputs.size() != 1 ) { - cerr << "Error: exactly one key must be given to import." << endl; + cerror << "Error: exactly one key must be given to import."; break; } @@ -500,31 +498,32 @@ class KeyCLI { bytesSec s = keyManager().store().secret( u, [&]() { return ( pw = getPassword( "Enter the passphrase for the key: " ) ); } ); if ( s.size() != 32 ) { - cerr << "Error: couldn't decode key or invalid secret size." << endl; + cerror << "Error: couldn't decode key or invalid secret size."; break; } bool usesMaster = true; if ( pw != m_masterPassword && m_lockHint.empty() ) { - cout << "Enter a hint to help you remember the key's passphrase: " << flush; + cdebug << "Enter a hint to help you remember the key's passphrase: "; + cdebug.flush(); getline( cin, m_lockHint ); usesMaster = false; } keyManager().importExisting( u, m_name, pw, m_lockHint ); auto a = keyManager().address( u ); - cout << "Imported key " << toUUID( u ) << endl; - cout << " Name: " << m_name << endl; + cdebug << "Imported key " << toUUID( u ); + cdebug << " Name: " << m_name; if ( usesMaster ) - cout << " Uses master passphrase." << endl; + cdebug << " Uses master passphrase."; else - cout << " Password hint: " << m_lockHint << endl; - cout << " Address: " << a.hex() << endl; + cdebug << " Password hint: " << m_lockHint; + cdebug << " Address: " << a.hex(); break; } case OperationMode::ImportWithAddress: { if ( m_inputs.size() != 1 ) { - cerr << "Error: exactly one key must be given to import." << endl; + cerror << "Error: exactly one key must be given to import."; break; } keyManager(); @@ -542,15 +541,14 @@ class KeyCLI { u = keyManager().store().importSecret( b, lockPassword( toAddress( Secret( b ) ).abridged() ) ); if ( !u ) { - cerr << cc::warn( "Cannot import " ) << i << cc::warn( " not a file or secret." ) - << endl; + cerror << "Cannot import " << i << " not a file or secret."; break; } keyManager().importExisting( u, m_name, m_address ); - cout << cc::success( "Successfully imported " ) << i << cc::success( ":" ) << endl; - cout << cc::success( " Name: " ) << m_name << endl; - cout << cc::success( " UUID: " ) << toUUID( u ) << endl; - cout << cc::success( " Address: " ) << m_address << endl; + cdebug << "Successfully imported " << i << ":"; + cdebug << " Name: " << m_name; + cdebug << " UUID: " << toUUID( u ); + cdebug << " Address: " << m_address; break; } case OperationMode::ImportPresale: { @@ -573,19 +571,19 @@ class KeyCLI { "): " ); } ); if ( !s ) { - cerr << "Invalid password for address " << a << endl; + cerror << "Invalid password for address " << a; continue; } pair< string, string > np = createPassword( keyManager(), "Enter new passphrase for key '" + i + "': " ); if ( keyManager().recode( a, np.first, np.second, [&]() { return pw; }, kdf() ) ) - cout << "Re-encoded key '" << i << "' successfully." << endl; + cdebug << "Re-encoded key '" << i << "' successfully."; else - cerr << "Couldn't re-encode '" << i - << "''; key corrupt or incorrect passphrase supplied." << endl; + cerror << "Couldn't re-encode '" << i + << "''; key corrupt or incorrect passphrase supplied."; } else - cerr << "Couldn't re-encode " << i << "; not found." << endl; + cerror << "Couldn't re-encode " << i << "; not found."; break; case OperationMode::Kill: { unsigned count = 0; @@ -593,15 +591,15 @@ class KeyCLI { if ( Address a = userToAddress( i ) ) keyManager().kill( a ); else - cerr << "Couldn't kill " << i << "; not found." << endl; + cerror << "Couldn't kill " << i << "; not found."; ++count; } - cout << count << " key(s) deleted." << endl; + cdebug << count << " key(s) deleted."; break; } case OperationMode::List: { if ( keyManager().store().keys().empty() ) { - cout << "No keys found." << endl; + cdebug << "No keys found."; break; } @@ -610,13 +608,13 @@ class KeyCLI { for ( auto const& u : keyManager().store().keys() ) if ( Address a = keyManager().address( u ) ) { got.insert( a ); - cout << toUUID( u ) << " " << a.abridged(); - cout << " " << a << " "; - cout << " " << keyManager().accountName( a ) << endl; + cdebug << toUUID( u ) << " " << a.abridged(); + cdebug << " " << a << " "; + cdebug << " " << keyManager().accountName( a ); } else bare.push_back( u ); for ( auto const& u : bare ) - cout << toUUID( u ) << " (Bare)" << endl; + cdebug << toUUID( u ) << " (Bare)"; break; } default: @@ -631,85 +629,112 @@ class KeyCLI { } static void streamHelp( ostream& _out ) { - _out << "Secret-store (\"bare\") operation modes:" << endl - << " listbare List all secret available in secret-store." << endl + _out << "Secret-store (\"bare\") operation modes:" + << "\n" + << " listbare List all secret available in secret-store." + << "\n" << " newbare Generate and output a key without interacting with wallet and dump " "the JSON." - << endl + << "\n" << " importbare [ | , ... ] Import keys from given sources." - << endl - << " recodebare [ | , ... ] Decrypt and re-encrypt given keys." << endl + << "\n" + << " recodebare [ | , ... ] Decrypt and re-encrypt given keys." + << "\n" << " inspectbare [ | , ... ] Output information on given keys." - << endl - // << " exportbare [ , ... ] Export given keys." << endl - << " killbare [ , ... ] Delete given keys." << endl - << "Secret-store configuration:" << endl + << "\n" + // << " exportbare [ , ... ] Export given keys." << "\n" + << " killbare [ , ... ] Delete given keys." + << "\n" + << "Secret-store configuration:" + << "\n" << " --secrets-path Specify Web3 secret-store path (default: " - << SecretStore::defaultPath() << ")" << endl - << endl - << "Wallet operating modes:" << endl - << " createwallet Create an Ethereum master wallet." << endl - << " list List all keys available in wallet." << endl - << " new Create a new key with given name and add it in the wallet." << endl + << SecretStore::defaultPath() << ")" + << "\n" + << "\n" + << "Wallet operating modes:" + << "\n" + << " createwallet Create an Ethereum master wallet." + << "\n" + << " list List all keys available in wallet." + << "\n" + << " new Create a new key with given name and add it in the wallet." + << "\n" << " import [||] Import keys from given source and " "place in wallet." - << endl + << "\n" << " importpresale Import a presale wallet into a key with the " "given name." - << endl + << "\n" << " importwithaddress [||]
Import keys " "from given source with given address and place in wallet." - << endl - << " export [
| , ... ] Export given keys." << endl + << "\n" + << " export [
| , ... ] Export given keys." + << "\n" << " inspect [
|| ] ... Print information on the given keys." - << endl + << "\n" // << " recode [
|| , ... ] Decrypt and re-encrypt - // given keys." << endl - << " kill [
|, ... ] Delete given keys." << endl - << "Wallet configuration:" << endl + // given keys." << "\n" + << " kill [
|, ... ] Delete given keys." + << "\n" + << "Wallet configuration:" + << "\n" << " --wallet-path Specify Ethereum wallet path (default: " - << KeyManager::defaultPath() << ")" << endl - << " -m, --master Specify wallet (master) passphrase." << endl - << endl - << "Transaction operating modes:" << endl - << " decode ( [ | ] ) Decode given transaction." << endl + << KeyManager::defaultPath() << ")" + << "\n" + << " -m, --master Specify wallet (master) passphrase." + << "\n" + << "\n" + << "Transaction operating modes:" + << "\n" + << " decode ( [ | ] ) Decode given transaction." + << "\n" << " sign [
|| ] ( [ | , ... ] ) (Re-)Sign given " "transaction." - << endl + << "\n" << "Transaction specification options (to be used when no transaction hex or file is " "given):" - << endl + << "\n" << " --tx-dest
Specify the destination address for the transaction to " "be signed." - << endl + << "\n" << " --tx-data Specify the hex data for the transaction to be signed." - << endl - << " --tx-nonce Specify the nonce for the transaction to be signed." << endl - << " --tx-gas Specify the gas for the transaction to be signed." << endl + << "\n" + << " --tx-nonce Specify the nonce for the transaction to be signed." + << "\n" + << " --tx-gas Specify the gas for the transaction to be signed." + << "\n" << " --tx-gasprice Specify the gas price for the transaction to be signed." - << endl - << " --tx-value Specify the value for the transaction to be signed." << endl - << "Transaction signing options:" << endl + << "\n" + << " --tx-value Specify the value for the transaction to be signed." + << "\n" + << "Transaction signing options:" + << "\n" << " --force-nonce Override the nonce for any transactions to be signed." - << endl - << endl - << "Encryption configuration:" << endl + << "\n" + << "\n" + << "Encryption configuration:" + << "\n" << " --kdf Specify KDF to use when encrypting (default: sc rypt)" - << endl + << "\n" << " --kdf-param Specify a parameter for the KDF." - << endl + << "\n" // << " --cipher Specify cipher to use when encrypting - //(default: aes-128-ctr)" << endl + //(default: aes-128-ctr)" << "\n" // << " --cipher-param Specify a parameter for the cipher." - //<< endl + //<< "\n" << " --lock Specify passphrase for when encrypting a (the) key." - << endl - << " --hint Specify hint for the --lock passphrase." << endl - << endl - << "Decryption configuration:" << endl - << " --unlock Specify passphrase for a (the) key." << endl - << "Key generation configuration:" << endl - << " --no-icap Don't bother to make a direct-ICAP capable key." << endl; + << "\n" + << " --hint Specify hint for the --lock passphrase." + << "\n" + << "\n" + << "Decryption configuration:" + << "\n" + << " --unlock Specify passphrase for a (the) key." + << "\n" + << "Key generation configuration:" + << "\n" + << " --no-icap Don't bother to make a direct-ICAP capable key." + << "\n"; } static bytes inputData( std::string const& _input, bool* _isFile = nullptr ) { @@ -733,7 +758,7 @@ class KeyCLI { if ( _w.load( m_masterPassword ) ) break; if ( !m_masterPassword.empty() ) { - cout << "Password invalid. Try again." << endl; + cdebug << "Password invalid. Try again."; m_masterPassword.clear(); } m_masterPassword = getPassword( "Please enter your MASTER passphrase: " ); @@ -758,7 +783,7 @@ class KeyCLI { if ( m_keyManager->exists() ) openWallet( *m_keyManager ); else if ( !walletLess ) { - cerr << "Couldn't open wallet. Does it exist?" << endl; + cerror << "Couldn't open wallet. Does it exist?"; exit( -1 ); } } diff --git a/skale-vm/main.cpp b/skale-vm/main.cpp index c3426517f..565343ac3 100644 --- a/skale-vm/main.cpp +++ b/skale-vm/main.cpp @@ -58,8 +58,8 @@ int64_t maxBlockGasLimit() { void version() { const auto* buildinfo = skale_get_buildinfo(); - cout << "skale-vm " << buildinfo->project_version << "\n"; - cout << "Build: " << buildinfo->system_name << "/" << buildinfo->build_type << "\n"; + cnote << "skale-vm " << buildinfo->project_version << "\n"; + cnote << "Build: " << buildinfo->system_name << "/" << buildinfo->build_type << "\n"; exit( 0 ); } @@ -208,12 +208,12 @@ int main( int argc, char** argv ) { else if ( inputFile.empty() ) inputFile = arg; // Assign input file name only once. else { - cerr << "Unknown argument: " << arg << '\n'; + cerror << "Unknown argument: " << arg << '\n'; return -1; } } if ( vm.count( "help" ) ) { - cout << allowedOptions; + cnote << allowedOptions; return 0; } if ( vm.count( "version" ) ) { @@ -256,7 +256,7 @@ int main( int argc, char** argv ) { else if ( network == "Main" ) networkName = Network::MainNetwork; else { - cerr << "Unknown network type: " << network << "\n"; + cerror << "Unknown network type: " << network << "\n"; return -1; } } @@ -268,7 +268,7 @@ int main( int argc, char** argv ) { // Read code from input file. if ( !inputFile.empty() ) { if ( !code.empty() ) - cerr << "--code argument overwritten by input file " << inputFile << '\n'; + cerror << "--code argument overwritten by input file " << inputFile << '\n'; if ( inputFile == "-" ) for ( int i = cin.get(); i != -1; i = cin.get() ) @@ -352,45 +352,43 @@ int main( int argc, char** argv ) { bytes output = std::move( res.output ); if ( mode == Mode::Statistics ) { - - cout << "Gas used: " << res.gasUsed << " (+" << t.baseGasRequired( evmSchedule ) - << " for transaction, -" << res.gasRefunded << " refunded)\n"; - - cout << "Output: " << toHex( output ) << "\n"; + cnote << "Gas used: " << res.gasUsed << " (+" << t.baseGasRequired( evmSchedule ) + << " for transaction, -" << res.gasRefunded << " refunded)\n"; + cnote << "Output: " << toHex( output ) << "\n"; LogEntries logs = executive.logs(); - cout << logs.size() << " logs" << ( logs.empty() ? "." : ":" ) << "\n"; + cnote << logs.size() << " logs" << ( logs.empty() ? "." : ":" ) << "\n"; for ( LogEntry const& l : logs ) { - cout << " " << l.address.hex() << ": " << toHex( t.data() ) << "\n"; + cnote << " " << l.address.hex() << ": " << toHex( t.data() ) << "\n"; for ( h256 const& topic : l.topics ) - cout << " " << topic.hex() << "\n"; + cnote << " " << topic.hex() << "\n"; } - cout << total << " operations in " << execTime << " seconds.\n"; - cout << "Maximum memory usage: " << memTotal * 32 << " bytes\n"; - cout << "Expensive operations:\n"; + cnote << total << " operations in " << execTime << " seconds.\n"; + cnote << "Maximum memory usage: " << memTotal * 32 << " bytes\n"; + cnote << "Expensive operations:\n"; for ( auto const inst : { Instruction::SSTORE, Instruction::SLOAD, Instruction::CALL, Instruction::CREATE, Instruction::CALLCODE, Instruction::DELEGATECALL, Instruction::MSTORE8, Instruction::MSTORE, Instruction::MLOAD, Instruction::SHA3 } ) { auto const& count = counts[static_cast< _byte_ >( inst )]; if ( count.first != 0 ) - cout << " " << instructionInfo( inst ).name << " x " << count.first << " (" - << count.second << " gas)\n"; + cnote << " " << instructionInfo( inst ).name << " x " << count.first << " (" + << count.second << " gas)\n"; } } else if ( mode == Mode::Trace ) - cout << st.json( styledJson ); + cnote << st.json( styledJson ); else if ( mode == Mode::OutputOnly ) - cout << toHex( output ) << '\n'; + cnote << toHex( output ) << '\n'; else if ( mode == Mode::Test ) { // Output information needed for test verification and benchmarking // in YAML-like dictionaly format. auto exception = res.excepted != TransactionException::None; - cout << "output: '" << toHex( output ) << "'\n"; - cout << "exception: " << boolalpha << exception << '\n'; - cout << "gas used: " << res.gasUsed << '\n'; - cout << "gas/sec: " << scientific << setprecision( 3 ) << uint64_t( res.gasUsed ) / execTime - << '\n'; - cout << "exec time: " << fixed << setprecision( 6 ) << execTime << '\n'; + cnote << "output: '" << toHex( output ) << "'\n"; + cnote << "exception: " << boolalpha << exception << '\n'; + cnote << "gas used: " << res.gasUsed << '\n'; + cnote << "gas/sec: " << scientific << setprecision( 3 ) + << uint64_t( res.gasUsed ) / execTime << '\n'; + cnote << "exec time: " << fixed << setprecision( 6 ) << execTime << '\n'; } diff --git a/skaled/AccountManager.cpp b/skaled/AccountManager.cpp index 1b13e5dce..fe7628ac8 100644 --- a/skaled/AccountManager.cpp +++ b/skaled/AccountManager.cpp @@ -56,12 +56,12 @@ bool AccountManager::execute( int argc, char** argv ) { } ); m_keyManager->import( k.secret(), name, pw, "Same passphrase as used for presale key" ); - cout << " Address: {" << k.address().hex() << "}\n"; + LOG( m_loggerInfo ) << " Address: {" << k.address().hex() << "}"; } catch ( Exception const& _e ) { if ( auto err = boost::get_error_info< errinfo_comment >( _e ) ) - cout << " Decryption failed: " << *err << "\n"; + LOG( m_loggerError ) << " Decryption failed: " << *err; else - cout << " Decryption failed: Unknown reason.\n"; + LOG( m_loggerError ) << " Decryption failed: Unknown reason."; return false; } } else @@ -71,7 +71,7 @@ bool AccountManager::execute( int argc, char** argv ) { if ( argc < 3 || string( argv[2] ) == "list" ) { openWallet(); if ( m_keyManager->store().keys().empty() ) - cout << "No keys found.\n"; + LOG( m_loggerInfo ) << "No keys found."; else { vector< u128 > bare; AddressHash got; @@ -79,19 +79,19 @@ bool AccountManager::execute( int argc, char** argv ) { for ( auto const& u : m_keyManager->store().keys() ) { if ( Address a = m_keyManager->address( u ) ) { got.insert( a ); - cout << "Account #" << k << ": {" << a.hex() << "}\n"; + LOG( m_loggerInfo ) << "Account #" << k << ": {" << a.hex() << "}"; k++; } else bare.push_back( u ); } for ( auto const& a : m_keyManager->accounts() ) if ( !got.count( a ) ) { - cout << "Account #" << k << ": {" << a.hex() << "}" - << " (Brain)\n"; + LOG( m_loggerInfo ) << "Account #" << k << ": {" << a.hex() << "}" + << " (Brain)"; k++; } for ( auto const& u : bare ) { - cout << "Account #" << k << ": " << toUUID( u ) << " (Bare)\n"; + LOG( m_loggerInfo ) << "Account #" << k << ": " << toUUID( u ) << " (Bare)"; k++; } } @@ -103,28 +103,28 @@ bool AccountManager::execute( int argc, char** argv ) { lock = createPassword( "Enter a passphrase with which to secure this account:" ); auto k = makeKey(); h128 u = m_keyManager->import( k.secret(), name, lock, lockHint ); - cout << "Created key " << toUUID( u ) << "\n"; - cout << " Address: " << k.address().hex() << "\n"; + LOG( m_loggerInfo ) << "Created key " << toUUID( u ); + LOG( m_loggerInfo ) << " Address: " << k.address().hex(); } else if ( 3 < argc && string( argv[2] ) == "import" ) { openWallet(); h128 u = m_keyManager->store().importKey( argv[3] ); if ( !u ) { - cerr << "Error: reading key file failed\n"; + LOG( m_loggerError ) << "Error: reading key file failed"; return false; } string pw; bytesSec s = m_keyManager->store().secret( u, [&]() { return ( pw = getPassword( "Enter the passphrase for the key: " ) ); } ); if ( s.empty() ) { - cerr << "Error: couldn't decode key or invalid secret size.\n"; + LOG( m_loggerError ) << "Error: couldn't decode key or invalid secret size."; return false; } else { string lockHint; string name; m_keyManager->importExisting( u, name, pw, lockHint ); auto a = m_keyManager->address( u ); - cout << "Imported key " << toUUID( u ) << "\n"; - cout << " Address: " << a.hex() << "\n"; + LOG( m_loggerInfo ) << "Imported key " << toUUID( u ); + LOG( m_loggerInfo ) << " Address: " << a.hex(); } } else if ( 3 < argc && string( argv[2] ) == "update" ) { openWallet(); @@ -145,14 +145,14 @@ bool AccountManager::execute( int argc, char** argv ) { recoded = m_keyManager->store().recode( u, newP, oldP, dev::KDF::Scrypt ); } if ( recoded ) - cerr << "Re-encoded " << i << "\n"; + LOG( m_loggerError ) << "Re-encoded " << i; else - cerr << "Couldn't re-encode " << i - << "; key does not exist, corrupt or incorrect passphrase supplied." - << "\n"; + LOG( m_loggerError ) + << "Couldn't re-encode " << i + << "; key does not exist, corrupt or incorrect passphrase supplied."; } else - cerr << "Couldn't re-encode " << i << "; does not represent an address or uuid." - << "\n"; + LOG( m_loggerError ) + << "Couldn't re-encode " << i << "; does not represent an address or uuid."; } } else streamAccountHelp( cout ); @@ -168,8 +168,7 @@ string AccountManager::createPassword( string const& _prompt ) const { string confirm = getPassword( "Please confirm the passphrase by entering it again: " ); if ( ret == confirm ) break; - cout << "Passwords were different. Try again." - << "\n"; + LOG( m_loggerInfo ) << "Passwords were different. Try again."; } return ret; } @@ -190,13 +189,12 @@ bool AccountManager::openWallet() { m_keyManager->load( getPassword( "Please enter your MASTER passphrase: " ) ) ) return true; else { - cerr << "Couldn't open wallet. Please check passphrase." - << "\n"; + LOG( m_loggerError ) << "Couldn't open wallet. Please check passphrase." + << "\n"; return false; } } else { - cerr << "Couldn't open wallet. Does it exist?" - << "\n"; + LOG( m_loggerError ) << "Couldn't open wallet. Does it exist?"; return false; } } diff --git a/skaled/AccountManager.h b/skaled/AccountManager.h index e6ae91a78..80c645934 100644 --- a/skaled/AccountManager.h +++ b/skaled/AccountManager.h @@ -21,6 +21,7 @@ * @date 2016 */ #pragma once +#include #include /** @@ -49,4 +50,10 @@ class AccountManager { bool openWallet(); std::unique_ptr< dev::eth::KeyManager > m_keyManager; + + /// Loggers + mutable dev::Logger m_loggerInfo{ dev::createLogger( dev::VerbosityInfo, "AccountManager" ) }; + mutable dev::Logger m_loggerWarning{ dev::createLogger( + dev::VerbosityWarning, "AccountManager" ) }; + mutable dev::Logger m_loggerError{ dev::createLogger( dev::VerbosityError, "AccountManager" ) }; }; diff --git a/skaled/main.cpp b/skaled/main.cpp index 7dd46d88f..6a30aa87a 100644 --- a/skaled/main.cpp +++ b/skaled/main.cpp @@ -136,23 +136,19 @@ static void version() { ver = pv.substr( 0, pos ); } else ver = pv; - std::cout << cc::info( "Skaled" ) << cc::debug( "............................" ) - << cc::attention( ver ) << "\n"; + clog( VerbosityInfo, "main - version" ) << "Skaled ............................" << ver << "\n"; if ( !commit.empty() ) - cout << cc::info( "Commit" ) << cc::debug( "............................" ) - << cc::attention( commit ) << "\n"; - std::cout << cc::info( "Skale network protocol version" ) << cc::debug( "...." ) - << cc::num10( dev::eth::c_protocolVersion ) << cc::debug( "." ) - << cc::num10( c_minorProtocolVersion ) << "\n"; - std::cout << cc::info( "Client database version" ) << cc::debug( "..........." ) - << cc::num10( dev::eth::c_databaseVersion ) << "\n"; - std::cout << cc::info( "Build" ) << cc::debug( "............................." ) - << cc::attention( buildinfo->system_name ) << cc::debug( "/" ) - << cc::attention( buildinfo->build_type ) << "\n"; - std::cout << "Working dir" - << "......................" << std::filesystem::current_path().string() << endl; - - std::cout.flush(); + clog( VerbosityInfo, "main - version" ) + << "Commit ............................." << commit << "\n"; + clog( VerbosityInfo, "main - version" ) + << "Skale network protocol version ...." << dev::eth::c_protocolVersion << "." + << c_minorProtocolVersion << "\n"; + clog( VerbosityInfo, "main - version" ) + << "Client database version ..........." << dev::eth::c_databaseVersion << "\n"; + clog( VerbosityInfo, "main - version" ) + << "Build ............................." << buildinfo->system_name << "/" + << buildinfo->build_type << "\n"; + clog( VerbosityInfo, "main - version" ).flush(); } static std::string clientVersion() { @@ -163,10 +159,12 @@ static std::string clientVersion() { static std::string clientVersionColorized() { const auto* buildinfo = skale_get_buildinfo(); - return cc::info( "skaled" ) + cc::debug( "/" ) + cc::attention( buildinfo->project_version ) + - cc::debug( "/" ) + cc::attention( buildinfo->system_name ) + cc::debug( "/" ) + - cc::attention( buildinfo->compiler_id ) + cc::notice( buildinfo->compiler_version ) + - cc::debug( "/" ) + cc::attention( buildinfo->build_type ); + return std::string( "skaled/" ) + buildinfo->project_version + "/" + buildinfo->system_name + + "/" + buildinfo->compiler_id + buildinfo->compiler_version + "/" + buildinfo->build_type; +} + +static std::string flag_ed( bool flagBool_ ) { + return flagBool_ ? "enabled" : "disabled"; } /* @@ -269,9 +267,10 @@ void downloadSnapshot( unsigned block_number, std::shared_ptr< SnapshotManager > return true; // continue download }, isBinaryDownload, &strErrorDescription ); - std::cout << " \r"; // clear - // progress - // line + clog( VerbosityInfo, "downloadSnapshot" ) + << " \r"; // clear + // progress + // line if ( !bOK ) { if ( strErrorDescription.empty() ) strErrorDescription = "download failed, connection problem during download"; @@ -371,8 +370,8 @@ voteForSnapshotHash( return { listUrlsToDownload, votedHash }; } catch ( std::exception& ex ) { - std::throw_with_nested( std::runtime_error( - cc::error( "Exception while collecting snapshot hash from other skaleds " ) ) ); + std::throw_with_nested( + std::runtime_error( "Exception while collecting snapshot hash from other skaleds " ) ); } } @@ -638,6 +637,12 @@ int main( int argc, char** argv ) try { strings passwordsToNote; Secrets toImport; + /// Loggers + Logger loggerDebug{ createLogger( VerbosityDebug, "main" ) }; + Logger loggerInfo{ createLogger( VerbosityInfo, "main" ) }; + Logger loggerWarning{ createLogger( VerbosityWarning, "main" ) }; + Logger loggerError{ createLogger( VerbosityError, "main" ) }; + MinerCLI m( MinerCLI::OperationMode::None ); fs::path configPath; @@ -896,12 +901,12 @@ int main( int argc, char** argv ) try { po::store( parsed, vm ); po::notify( vm ); } catch ( po::error const& e ) { - cerr << e.what(); + LOG( loggerError ) << e.what(); return EX_USAGE; } for ( size_t i = 0; i < unrecognisedOptions.size(); ++i ) if ( !m.interpretOption( i, unrecognisedOptions ) ) { - cerr << "Invalid argument: " << unrecognisedOptions[i] << "\n"; + LOG( loggerError ) << "Invalid argument: " << unrecognisedOptions[i]; return EX_USAGE; } @@ -914,12 +919,12 @@ int main( int argc, char** argv ) try { return 0; } if ( vm.count( "help" ) ) { - cout << "NAME:\n" - << " skaled " << Version << '\n' - << "USAGE:\n" - << " skaled [options]\n\n"; - cout << clientDefaultMode << clientTransacting << clientNetworking; - cout << vmOptions << loggingProgramOptions << generalOptions; + LOG( loggerInfo ) << "NAME:\n" + << " skaled " << Version << '\n' + << "USAGE:\n" + << " skaled [options]"; + LOG( loggerInfo ) << clientDefaultMode << clientTransacting << clientNetworking; + LOG( loggerInfo ) << vmOptions << loggingProgramOptions << generalOptions; return 0; } @@ -958,52 +963,41 @@ int main( int argc, char** argv ) try { skutils::url u; try { u = skutils::url( strURL ); - std::cout << ( cc::debug( "Using URL" ) + cc::debug( "................" ) + - cc::u( u.str() ) + "\n" ); + LOG( loggerDebug ) << "Using URL ................" + u.str(); } catch ( const std::exception& ex ) { - std::cout << ( cc::fatal( "ERROR:" ) + cc::error( " Failed to parse test URL: " ) + - cc::warn( ex.what() ) + "\n" ); + LOG( loggerError ) << "ERROR: Failed to parse test URL: " + std::string( ex.what() ); return EX_TEMPFAIL; } catch ( ... ) { - std::cout << ( cc::fatal( "ERROR:" ) + cc::error( " Failed to parse test URL: " ) + - cc::warn( "unknown exception" ) + "\n" ); + LOG( loggerError ) << "ERROR: Failed to parse test URL: unknown exception"; return EX_TEMPFAIL; } nlohmann::json joIn, joOut; try { if ( !strJSON.empty() ) { joIn = nlohmann::json::parse( strJSON ); - std::cout << ( cc::debug( "Input JSON is" ) + cc::debug( "............" ) + - cc::j( joIn ) + "\n" ); + LOG( loggerDebug ) << "Input JSON is ............" + joIn.dump(); } else - std::cout << ( cc::error( "NOTICE:" ) + - cc::warn( " No valid JSON specified for test call" ) + "\n" ); + LOG( loggerWarning ) << "NOTICE: No valid JSON specified for test call"; } catch ( const std::exception& ex ) { - std::cout << ( cc::fatal( "ERROR:" ) + - cc::error( " Failed to parse specified test JSON: " ) + - cc::warn( ex.what() ) + "\n" ); + LOG( loggerError ) << "ERROR: Failed to parse specified test JSON: " + + std::string( ex.what() ); return EX_TEMPFAIL; } catch ( ... ) { - std::cout << ( cc::fatal( "ERROR:" ) + - cc::error( " Failed to parse specified test JSON: " ) + - cc::warn( "unknown exception" ) + "\n" ); + LOG( loggerError ) << "ERROR: Failed to parse specified test JSON: unknown exception"; return EX_TEMPFAIL; } skutils::http::SSL_client_options optsSSL; if ( !strPathCA.empty() ) { optsSSL.ca_file = skutils::tools::trim_copy( strPathCA ); - std::cout << ( cc::debug( "Using CA file " ) + cc::debug( "..........." ) + - cc::p( strPathCA ) + "\n" ); + LOG( loggerDebug ) << "Using CA file ..........." + strPathCA; } if ( !strPathCert.empty() ) { optsSSL.client_cert = skutils::tools::trim_copy( strPathCert ); - std::cout << ( cc::debug( "Using CERT file " ) + cc::debug( "........." ) + - cc::p( strPathCert ) + "\n" ); + LOG( loggerDebug ) << "Using CERT file ........." + strPathCert; } if ( !strPathKey.empty() ) { optsSSL.client_key = skutils::tools::trim_copy( strPathKey ); - std::cout << ( cc::debug( "Using KEY file " ) + cc::debug( ".........." ) + - cc::p( strPathKey ) + "\n" ); + LOG( loggerDebug ) << "Using KEY file .........." + strPathKey; } try { skutils::rest::client cli( skutils::rest::g_nClientConnectionTimeoutMS ); @@ -1021,32 +1015,27 @@ int main( int argc, char** argv ) try { throw std::runtime_error( "REST call error: " + d.err_s_ ); if ( d.empty() ) throw std::runtime_error( "EMPTY answer received" ); - std::cout << ( cc::debug( "Raw received data is" ) + cc::debug( "....." ) + - cc::normal( d.s_ ) + "\n" ); + LOG( loggerDebug ) << "Raw received data is ....." + d.s_; joOut = nlohmann::json::parse( d.s_ ); - std::cout << ( cc::debug( "Output JSON is" ) + cc::debug( "..........." ) + - cc::j( joOut ) + "\n" ); + LOG( loggerDebug ) << "Output JSON is ..........." + joOut.dump(); } catch ( const std::exception& ex ) { - std::cout << ( cc::fatal( "ERROR:" ) + cc::error( " JSON RPC call failed: " ) + - cc::warn( ex.what() ) + "\n" ); + LOG( loggerError ) << "ERROR: JSON RPC call failed: " + std::string( ex.what() ); return EX_TEMPFAIL; } catch ( ... ) { - std::cout << ( cc::fatal( "ERROR:" ) + cc::error( " JSON RPC call failed: " ) + - cc::warn( "unknown exception" ) + "\n" ); + LOG( loggerError ) << "ERROR: JSON RPC call failed: unknown exception"; return EX_TEMPFAIL; } return 0; } - std::cout << cc::bright( "skaled " ) << cc::sunny( Version ) << "\n" - << cc::bright( "client " ) << clientVersionColorized() << "\n"; - std::cout.flush(); + LOG( loggerInfo ) << "skaled " << Version << "\n" + << "client " << clientVersionColorized(); + LOG( loggerInfo ).flush(); version(); pid_t this_process_pid = getpid(); - std::cout << cc::debug( "This process " ) << cc::info( "PID" ) << cc::debug( "=" ) - << cc::size10( size_t( this_process_pid ) ) << "\n"; - std::cout.flush(); + LOG( loggerDebug ) << "This process PID = " << size_t( this_process_pid ); + LOG( loggerDebug ).flush(); setupLogging( loggingOptions ); @@ -1060,8 +1049,8 @@ int main( int argc, char** argv ) try { n = nMin; nDispatchThreads = n; } - clog( VerbosityInfo, "main" ) << cc::debug( "Using " ) << cc::size10( nDispatchThreads ) - << cc::debug( " threads in task dispatcher" ) << std::endl; + LOG( loggerInfo ) << "Using " << std::to_string( nDispatchThreads ) + << " threads in task dispatcher"; skutils::dispatch::default_domain( nDispatchThreads ); // skutils::dispatch::default_domain( 48 ); @@ -1096,21 +1085,21 @@ int main( int argc, char** argv ) try { new skutils::json_config_file_accessor( configPath.string() ) ); dev::db::DBFactory::setReopenPeriodMs( chainParams.sChain.levelDBReopenIntervalMs ); } catch ( const char* str ) { - clog( VerbosityError, "main" ) << "Error: " << str << ": " << configPath; + LOG( loggerError ) << "Error: " << str << ": " << configPath; return EX_USAGE; } catch ( const json_spirit::Error_position& err ) { - clog( VerbosityError, "main" ) << "error in parsing config json:"; - clog( VerbosityError, "main" ) << configJSON; - clog( VerbosityError, "main" ) << err.reason_ << " line " << err.line_; + LOG( loggerError ) << "error in parsing config json:"; + LOG( loggerError ) << configJSON; + LOG( loggerError ) << err.reason_ << " line " << err.line_; return EX_CONFIG; } catch ( const std::exception& ex ) { - clog( VerbosityError, "main" ) << "provided configuration is incorrect"; - clog( VerbosityError, "main" ) << configJSON; - clog( VerbosityError, "main" ) << nested_exception_what( ex ); + LOG( loggerError ) << "provided configuration is incorrect"; + LOG( loggerError ) << configJSON; + LOG( loggerError ) << nested_exception_what( ex ); return EX_CONFIG; } catch ( ... ) { - clog( VerbosityError, "main" ) << "provided configuration is incorrect"; - clog( VerbosityError, "main" ) << configJSON; + LOG( loggerError ) << "provided configuration is incorrect"; + LOG( loggerError ) << configJSON; return EX_CONFIG; } } @@ -1121,21 +1110,18 @@ int main( int argc, char** argv ) try { if ( vm.count( "main-net-url" ) ) { if ( !g_configAccesssor ) { - clog( VerbosityError, "main" ) - << "config= should be specified before --main-net-url=\n"; + LOG( loggerError ) << "config= should be specified before --main-net-url="; return EX_SOFTWARE; } skutils::json_config_file_accessor::g_strImaMainNetURL = skutils::tools::trim_copy( vm["main-net-url"].as< string >() ); if ( !g_configAccesssor->validateImaMainNetURL() ) { - clog( VerbosityError, "main" ) - << "bad --main-net-url= parameter value: " - << skutils::json_config_file_accessor::g_strImaMainNetURL << "\n"; + LOG( loggerError ) << "bad --main-net-url= parameter value: " + << skutils::json_config_file_accessor::g_strImaMainNetURL; return EX_SOFTWARE; } - clog( VerbosityDebug, "main" ) - << cc::notice( "Main Net URL" ) + cc::debug( " is: " ) - << cc::u( skutils::json_config_file_accessor::g_strImaMainNetURL ); + LOG( loggerDebug ) << "Main Net URL is: " + << skutils::json_config_file_accessor::g_strImaMainNetURL; } if ( !chainConfigIsSet ) @@ -1174,8 +1160,7 @@ int main( int argc, char** argv ) try { is_ipc = true; if ( vm.count( "no-ipc" ) ) is_ipc = false; - clog( VerbosityDebug, "main" ) << cc::notice( "IPC server" ) + cc::debug( " is: " ) - << ( is_ipc ? cc::success( "on" ) : cc::error( "off" ) ); + LOG( loggerDebug ) << "IPC server is: " << ( is_ipc ? "on" : "off" ); // First, get "httpRpcPort", "httpsRpcPort", "wsRpcPort", "wssRpcPort" ... from config.json // Second, get them from command line parameters (higher priority source) @@ -1191,10 +1176,9 @@ int main( int argc, char** argv ) try { if ( !( 0 <= nPort && nPort <= 65535 ) ) nPort = -1; else - clog( VerbosityDebug, "main" ) - << cc::debug( "Got " ) - << cc::notice( strDescription ) + cc::debug( " from configuration JSON: " ) - << cc::num10( nPort ); + LOG( loggerDebug ) + << "Got " + << std::string( strDescription ) + " from configuration JSON: " << nPort; if ( vm.count( strCommandLineKey ) ) { std::string strPort = vm[strCommandLineKey].as< string >(); if ( !strPort.empty() ) { @@ -1202,10 +1186,9 @@ int main( int argc, char** argv ) try { if ( !( 0 <= nPort && nPort <= 65535 ) ) nPort = -1; else - clog( VerbosityDebug, "main" ) - << cc::debug( "Got " ) - << cc::notice( strDescription ) + cc::debug( " from command line: " ) - << cc::num10( nPort ); + LOG( loggerDebug ) + << "Got " + << std::string( strDescription ) + " from command line: " << nPort; } } return nPort; @@ -1246,9 +1229,7 @@ int main( int argc, char** argv ) try { } if ( vm.count( "web3-trace" ) ) bTraceJsonRpcCalls = true; - clog( VerbosityDebug, "main" ) - << cc::info( "JSON RPC" ) << cc::debug( " trace logging mode is " ) - << cc::flag_ed( bTraceJsonRpcCalls ); + LOG( loggerDebug ) << "JSON RPC trace logging mode is " << flag_ed( bTraceJsonRpcCalls ); // First, get "special-rpc-trace" from config.json // Second, get it from command line parameter (higher priority source) @@ -1262,9 +1243,8 @@ int main( int argc, char** argv ) try { } if ( vm.count( "special-rpc-trace" ) ) bTraceJsonRpcSpecialCalls = true; - clog( VerbosityDebug, "main" ) - << cc::info( "Special JSON RPC" ) << cc::debug( " trace logging mode is " ) - << cc::flag_ed( bTraceJsonRpcSpecialCalls ); + LOG( loggerDebug ) << "Special JSON RPC" + << " trace logging mode is " << flag_ed( bTraceJsonRpcSpecialCalls ); // First, get "enable-personal-apis", "enable-admin-apis", "enable-debug-behavior-apis", // "enable-performance-tracker-apis" from config.json Second, get it from command line parameter @@ -1304,22 +1284,15 @@ int main( int argc, char** argv ) try { bEnabledAPIs_debug = true; if ( vm.count( "enable-performance-tracker-apis" ) ) bEnabledAPIs_performanceTracker = true; - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "enable-personal-apis" ) << cc::debug( " mode is " ) - << cc::flag_ed( bEnabledAPIs_personal ); - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "enable-admin-apis" ) << cc::debug( " mode is " ) - << cc::flag_ed( bEnabledAPIs_admin ); - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "enable-debug-behavior-apis" ) << cc::debug( " mode is " ) - << cc::flag_ed( bEnabledAPIs_debug ); - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "enable-performance-tracker-apis" ) << cc::debug( " mode is " ) - << cc::flag_ed( bEnabledAPIs_performanceTracker ); + LOG( loggerWarning ) << "Important notice: Programmatic enable-personal-apis mode is " + << flag_ed( bEnabledAPIs_personal ); + LOG( loggerWarning ) << "Important notice: Programmatic enable-admin-apis mode is " + << flag_ed( bEnabledAPIs_admin ); + LOG( loggerWarning ) << "Important notice: Programmatic enable-debug-behavior-apis mode is " + << flag_ed( bEnabledAPIs_debug ); + LOG( loggerWarning ) + << "Important notice: Programmatic enable-performance-tracker-apis mode is " + << flag_ed( bEnabledAPIs_performanceTracker ); // First, get "unsafe-transactions" from config.json // Second, get it from command line parameter (higher priority source) @@ -1333,10 +1306,8 @@ int main( int argc, char** argv ) try { } if ( vm.count( "unsafe-transactions" ) ) alwaysConfirm = false; - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "unsafe-transactions" ) << cc::debug( " mode is " ) - << cc::flag_ed( !alwaysConfirm ); + LOG( loggerWarning ) << "Important notice: Programmatic unsafe-transactions mode is " + << flag_ed( !alwaysConfirm ); // First, get "web3-shutdown" from config.json // Second, get it from command line parameter (higher priority source) @@ -1351,10 +1322,8 @@ int main( int argc, char** argv ) try { } if ( vm.count( "web3-shutdown" ) ) bEnabledShutdownViaWeb3 = true; - clog( VerbosityWarning, "main" ) - << cc::warn( "Important notice: " ) << cc::debug( "Programmatic " ) - << cc::info( "web3-shutdown" ) << cc::debug( " mode is " ) - << cc::flag_ed( bEnabledShutdownViaWeb3 ); + LOG( loggerWarning ) << "Important notice: Programmatic web3-shutdown mode is " + << flag_ed( bEnabledShutdownViaWeb3 ); // First, get "ipcpath" from config.json // Second, get it from command line parameter (higher priority source) @@ -1366,8 +1335,8 @@ int main( int argc, char** argv ) try { } catch ( ... ) { } } - clog( VerbosityDebug, "main" ) - << cc::notice( "IPC path" ) + cc::debug( " is: " ) << cc::p( strPathIPC ); + + LOG( loggerDebug ) << "IPC path is: " << strPathIPC; if ( vm.count( "ipcpath" ) ) strPathIPC = vm["ipcpath"].as< std::string >(); if ( !strPathIPC.empty() ) @@ -1385,16 +1354,14 @@ int main( int argc, char** argv ) try { } if ( vm.count( "db-path" ) ) strPathDB = vm["db-path"].as< std::string >(); - clog( VerbosityInfo, "main" ) << cc::notice( "DB path" ) + cc::debug( " is: " ) - << cc::p( strPathDB ); + LOG( loggerInfo ) << "DB path is: " << strPathDB; if ( !strPathDB.empty() ) setDataDir( strPathDB ); UnsafeRegion::init( getDataDir() ); if ( UnsafeRegion::isActive() ) { - clog( VerbosityError, "main" ) << "FATAL " - << "Previous skaled shutdown was too hard, need to repair!"; + LOG( loggerError ) << "FATAL Previous skaled shutdown was too hard, need to repair!"; return int( ExitHandler::ec_state_root_mismatch ); } // if bad exit @@ -1411,10 +1378,8 @@ int main( int argc, char** argv ) try { if ( vm.count( "block-rotation-period" ) ) clockDbRotationPeriodInSeconds = vm["block-rotation-period"].as< size_t >(); if ( clockDbRotationPeriodInSeconds > 0 ) - clog( VerbosityInfo, "main" ) - << cc::debug( "Timer-based " ) + cc::notice( "Block Rotation" ) + - cc::debug( " period is: " ) - << cc::size10( clockDbRotationPeriodInSeconds ); + LOG( loggerInfo ) << "Timer-based Block Rotation period is: " + << clockDbRotationPeriodInSeconds; ///////////////// CACHE PARAMS /////////////// @@ -1546,9 +1511,9 @@ int main( int argc, char** argv ) try { try { networkID = vm["network-id"].as< unsigned >(); } catch ( ... ) { - cerr << "Bad " - << "--network-id" - << " option: " << vm["network-id"].as< string >() << "\n"; + LOG( loggerError ) << "Bad " + << "--network-id" + << " option: " << vm["network-id"].as< string >(); return EX_USAGE; } if ( vm.count( "kill" ) ) @@ -1600,8 +1565,8 @@ int main( int argc, char** argv ) try { if ( vm.count( "no-snapshot-majority" ) ) { downloadSnapshotFlag = true; urlToDownloadSnapshotFrom = vm["no-snapshot-majority"].as< string >(); - clog( VerbosityInfo, "main" ) - << "Manually set url to download snapshot from: " << urlToDownloadSnapshotFrom; + LOG( loggerInfo ) << "Manually set url to download snapshot from: " + << urlToDownloadSnapshotFrom; } if ( chainParams.sChain.snapshotIntervalSec > 0 || downloadSnapshotFlag ) { @@ -1630,7 +1595,7 @@ int main( int argc, char** argv ) try { snapshotManager->isSnapshotHashPresent( 0 ); } catch ( SnapshotManager::SnapshotAbsent& ex ) { // sleep before send skale_getSnapshot again - will receive error - clog( VerbosityInfo, "main" ) + LOG( loggerInfo ) << std::string( "Will sleep for " ) << chainParams.sChain.snapshotDownloadInactiveTimeout + dev::rpc::Skale::snapshotDownloadFragmentMonitorThreadTimeout() @@ -1663,7 +1628,7 @@ int main( int argc, char** argv ) try { snapshotManager, chainParams, urlToDownloadSnapshotFrom, false ); snapshotManager->restoreSnapshot( 0 ); } catch ( SnapshotManager::SnapshotAbsent& ) { - clog( VerbosityWarning, "main" ) << "Snapshot for 0 block is not found"; + LOG( loggerWarning ) << "Snapshot for 0 block is not found"; } } } @@ -1686,7 +1651,7 @@ int main( int argc, char** argv ) try { if ( time( NULL ) < startTimestamp ) { statusAndControl->setSubsystemRunning( StatusAndControl::WaitingForTimestamp, true ); - std::cout << "\nWill start at localtime " << ctime( &startTimestamp ) << std::endl; + LOG( loggerInfo ) << "\nWill start at localtime " << ctime( &startTimestamp ); do sleep( 1 ); while ( time( NULL ) < startTimestamp ); @@ -1694,7 +1659,7 @@ int main( int argc, char** argv ) try { } if ( loggingOptions.verbosity > 0 ) - clog( VerbosityInfo, "main" ) << cc::attention( "skaled, a C++ Skale client" ) << "\n"; + LOG( loggerInfo ) << "skaled, a C++ Skale client"; m.execute(); @@ -1836,8 +1801,8 @@ int main( int argc, char** argv ) try { keyManager.create( std::string() ); } } catch ( ... ) { - cerr << "Error initializing key manager: " - << boost::current_exception_diagnostic_information() << "\n"; + LOG( loggerError ) << "Error initializing key manager: " + << boost::current_exception_diagnostic_information(); return 1; } @@ -1855,7 +1820,7 @@ int main( int argc, char** argv ) try { g_client->setNetworkId( networkID ); } - clog( VerbosityInfo, "main" ) << "Mining Beneficiary: " << g_client->author(); + LOG( loggerInfo ) << "Mining Beneficiary: " << g_client->author(); unique_ptr< rpc::SessionManager > sessionManager; unique_ptr< SimpleAccountHolder > accountHolder; @@ -1880,13 +1845,12 @@ int main( int argc, char** argv ) try { if ( strAA == "yes" || strAA == "no" || strAA == "always" ) autoAuthAnswer = strAA; else { - clog( VerbosityError, "main" ) << "Bad " - << "--aa" - << " option: " << strAA << "\n"; + LOG( loggerError ) << "Bad " + << "--aa" + << " option: " << strAA; return EX_USAGE; } - clog( VerbosityDebug, "main" ) - << cc::info( "Auto-answer" ) << cc::debug( " mode is set to: " ) << cc::info( strAA ); + LOG( loggerDebug ) << "Auto-answer mode is set to: " << strAA; } std::function< bool( TransactionSkeleton const&, bool ) > authenticator; @@ -1924,17 +1888,14 @@ int main( int argc, char** argv ) try { return r == "yes" || r == "always"; }; if ( chainParams.nodeInfo.ip.empty() ) { - clog( VerbosityWarning, "main" ) - << cc::info( "IPv4" ) - << cc::warn( " bind address is not set, will not start RPC on this protocol" ); + LOG( loggerWarning ) << "IPv4" + << " bind address is not set, will not start RPC on this protocol"; nExplicitPortHTTP4std = nExplicitPortHTTPS4std = nExplicitPortHTTP4nfo = nExplicitPortHTTPS4nfo = nExplicitPortWS4std = nExplicitPortWSS4std = nExplicitPortWS4nfo = nExplicitPortWSS4nfo = -1; } if ( chainParams.nodeInfo.ip6.empty() ) { - clog( VerbosityWarning, "main" ) - << cc::info( "IPv6" ) - << cc::warn( " bind address is not set, will not start RPC on this protocol" ); + LOG( loggerWarning ) << "IPv6 bind address is not set, will not start RPC on this protocol"; nExplicitPortHTTP6std = nExplicitPortHTTPS6std = nExplicitPortHTTP6nfo = nExplicitPortHTTPS6nfo = nExplicitPortWS6std = nExplicitPortWSS6std = nExplicitPortWS6nfo = nExplicitPortWSS6nfo = -1; @@ -2013,13 +1974,12 @@ int main( int argc, char** argv ) try { auto ipcConnector = new IpcServer( "geth" ); g_jsonrpcIpcServer->addConnector( ipcConnector ); if ( !ipcConnector->StartListening() ) { - clog( VerbosityError, "main" ) - << "Cannot start listening for RPC requests on ipc port: " - << strerror( errno ); + LOG( loggerError ) << "Cannot start listening for RPC requests on ipc port: " + << strerror( errno ); return EX_IOERR; } // error } catch ( const std::exception& ex ) { - clog( VerbosityError, "main" ) + LOG( loggerError ) << "Cannot start listening for RPC requests on ipc port: " << ex.what(); return EX_IOERR; } // catch @@ -2027,10 +1987,9 @@ int main( int argc, char** argv ) try { auto fnCheckPort = [&]( int& nPort, const char* strCommandLineKey ) -> bool { if ( nPort <= 0 || nPort >= 65536 ) { - clog( VerbosityError, "main" ) - << cc::error( "WARNING:" ) << cc::warn( " No valid port value provided with " ) - << cc::info( std::string( "--" ) + strCommandLineKey ) << cc::warn( "=" ) - << cc::info( "number" ); + LOG( loggerError ) << "WARNING: No valid port value provided with " + << std::string( "--" ) + strCommandLineKey << "=" + << "number"; return false; } return true; @@ -2089,8 +2048,7 @@ int main( int argc, char** argv ) try { nExplicitPortHTTPS6nfo > 0 || nExplicitPortWS4std > 0 || nExplicitPortWSS4std > 0 || nExplicitPortWS6std > 0 || nExplicitPortWSS6std > 0 || nExplicitPortWS4nfo > 0 || nExplicitPortWSS4nfo > 0 || nExplicitPortWS6nfo > 0 || nExplicitPortWSS6nfo > 0 ) { - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::attention( "RPC params" ) << cc::debug( ":" ); + LOG( loggerDebug ) << "....RPC params:"; // auto fnPrintPort = [&]( const int& nPort, const char* strDescription ) -> void { static const size_t nAlign = 35; @@ -2098,9 +2056,8 @@ int main( int argc, char** argv ) try { std::string strDots; for ( ; ( strDots.size() + nDescLen ) < nAlign; ) strDots += "."; - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::info( strDescription ) << cc::debug( strDots ) - << " " << ( ( nPort >= 0 ) ? cc::num10( nPort ) : cc::error( "off" ) ); + LOG( loggerDebug ) << "...." << strDescription << strDots << " " + << ( ( nPort >= 0 ) ? std::to_string( nPort ) : "off" ); }; fnPrintPort( nExplicitPortHTTP4std, "HTTP/4/std port" ); fnPrintPort( nExplicitPortHTTP4nfo, "HTTP/4/nfo port" ); @@ -2154,26 +2111,22 @@ int main( int argc, char** argv ) try { size_t maxItemCount = vm["performance-timeline-max-items"].as< size_t >(); pTracker->set_safe_max_item_count( maxItemCount ); } - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::info( "Performance timeline tracker" ) - << cc::debug( "............. " ) - << ( pTracker->is_enabled() ? cc::size10( pTracker->get_safe_max_item_count() ) : - cc::error( "off" ) ); + LOG( loggerDebug ) << "....Performance timeline tracker............. " + << ( pTracker->is_enabled() ? + std::to_string( pTracker->get_safe_max_item_count() ) : + "off" ); if ( !bHaveSSL ) nExplicitPortHTTPS4std = nExplicitPortHTTPS6std = nExplicitPortHTTPS4nfo = nExplicitPortHTTPS6nfo = nExplicitPortWSS4std = nExplicitPortWSS6std = nExplicitPortWSS4nfo = nExplicitPortWSS6nfo = -1; if ( bHaveSSL ) { - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::info( "SSL key is" ) - << cc::debug( "............................... " ) << cc::p( strPathSslKey ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "SSL certificate is" ) - << cc::debug( "....................... " ) << cc::p( strPathSslCert ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "SSL CA is" ) - << cc::debug( "................................ " ) << cc::p( strPathSslCA ); + LOG( loggerDebug ) + << "....SSL key is............................... " << strPathSslKey; + LOG( loggerDebug ) + << "....SSL certificate is....................... " << strPathSslCert; + LOG( loggerDebug ) + << "....SSL CA is................................ " << strPathSslCA; } // // @@ -2323,44 +2276,28 @@ int main( int argc, char** argv ) try { skutils::ws::g_eWSLL = skutils::ws::str2wsll( s ); } - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "WS mode" ) - << cc::debug( ".................................. " ) - << skutils::ws::nlws::srvmode2str( skutils::ws::nlws::g_default_srvmode ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "WS logging" ) - << cc::debug( "............................... " ) - << cc::info( skutils::ws::wsll2str( skutils::ws::g_eWSLL ) ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Max RPC connections" ) - << cc::debug( "...................... " ) - << ( ( maxConnections > 0 ) ? cc::size10( maxConnections ) : - cc::error( "disabled" ) ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Max HTTP queues" ) - << cc::debug( ".......................... " ) - << ( ( max_http_handler_queues > 0 ) ? cc::size10( max_http_handler_queues ) : - cc::notice( "default" ) ); - clog( VerbosityDebug, "main" ) << cc::debug( "...." ) + cc::info( "Asynchronous HTTP" ) - << cc::debug( "........................ " ) - << cc::yn( is_async_http_transfer_mode ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Proxygen threads" ) - << cc::debug( "......................... " ) << cc::num10( pg_threads ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Proxygen threads limit" ) - << cc::debug( "................... " ) << cc::num10( pg_threads_limit ); + LOG( loggerDebug ) << "....WS mode.................................. " + << skutils::ws::nlws::srvmode2str( + skutils::ws::nlws::g_default_srvmode ); + LOG( loggerDebug ) << "....WS logging............................... " + << skutils::ws::wsll2str( skutils::ws::g_eWSLL ); + LOG( loggerDebug ) << "....Max RPC connections...................... " + << ( ( maxConnections > 0 ) ? std::to_string( maxConnections ) : + "disabled" ); + LOG( loggerDebug ) << "....Max HTTP queues.......................... " + << ( ( max_http_handler_queues > 0 ) ? + std::to_string( max_http_handler_queues ) : + "default" ); + LOG( loggerDebug ) << "....Asynchronous HTTP........................ " + << ( is_async_http_transfer_mode ? "yes" : "no" ); + LOG( loggerDebug ) << "....Proxygen threads......................... " << pg_threads; + LOG( loggerDebug ) << "....Proxygen threads limit................... " + << pg_threads_limit; // - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Max count in batch JSON RPC request" ) - << cc::debug( "...... " ) << cc::size10( cntInBatch ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Parallel RPC connection acceptors" ) - << cc::debug( "........ " ) << cc::size10( cntServersStd ); - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) + cc::info( "Parallel informational RPC acceptors" ) - << cc::debug( "..... " ) << cc::size10( cntServersNfo ); + LOG( loggerDebug ) << "....Max count in batch JSON RPC request...... " << cntInBatch; + LOG( loggerDebug ) << "....Parallel RPC connection acceptors........ " << cntServersStd; + LOG( loggerDebug ) << "....Parallel informational RPC acceptors..... " << cntServersNfo; SkaleServerOverride::fn_binary_snapshot_download_t fn_binary_snapshot_download = [=]( const nlohmann::json& joRequest ) -> std::vector< uint8_t > { return pSkaleFace->impl_skale_downloadSnapshotFragmentBinary( joRequest ); @@ -2431,15 +2368,12 @@ int main( int argc, char** argv ) try { } if ( serverOpts.strEthErc20Address_.empty() ) throw std::runtime_error( "\"ethERC20Address\" was not found in config JSON" ); - clog( VerbosityDebug, "main" ) << ( cc::debug( "\"ethERC20Address\" is" ) + " " + - cc::info( serverOpts.strEthErc20Address_ ) ); + LOG( loggerDebug ) << "\"ethERC20Address\" is " + serverOpts.strEthErc20Address_; } catch ( ... ) { serverOpts.strEthErc20Address_ = "0xd3cdbc1b727b2ed91b8ad21333841d2e96f255af"; - clog( VerbosityError, "main" ) - << ( cc::error( "WARNING:" ) + " " + - cc::warn( - "\"ethERC20Address\" was not found in config JSON, assuming" ) + - " " + cc::info( serverOpts.strEthErc20Address_ ) ); + LOG( loggerWarning ) + << "WARNING: \"ethERC20Address\" was not found in config JSON, assuming " + + serverOpts.strEthErc20Address_; } auto skale_server_connector = new SkaleServerOverride( chainParams, g_client.get(), serverOpts ); @@ -2451,9 +2385,8 @@ int main( int argc, char** argv ) try { } else skale_server_connector->unddos_.get_settings(); // auto-init // - clog( VerbosityDebug, "main" ) - << cc::attention( "UN-DDOS" ) + cc::debug( " is using configuration" ) - << cc::j( skale_server_connector->unddos_.get_settings_json() ); + LOG( loggerDebug ) << "UN-DDOS is using configuration" + << cc::j( skale_server_connector->unddos_.get_settings_json() ); skale_server_connector->max_http_handler_queues_ = max_http_handler_queues; skale_server_connector->is_async_http_transfer_mode_ = is_async_http_transfer_mode; skale_server_connector->maxCountInBatchJsonRpcRequest_ = cntInBatch; @@ -2469,9 +2402,7 @@ int main( int argc, char** argv ) try { skale_server_connector->max_connection_set( maxConnections ); g_jsonrpcIpcServer->addConnector( skale_server_connector ); if ( !skale_server_connector->StartListening() ) { // TODO Will it delete itself? - clog( VerbosityError, "main" ) - << ( cc::fatal( "FATAL:" ) + " " + - cc::error( "Failed to start JSON RPC, will exit..." ) ); + LOG( loggerError ) << "FATAL: Failed to start JSON RPC, will exit..."; return EX_IOERR; } int nStatHTTP4std = skale_server_connector->getServerPortStatusProxygenHTTP( @@ -2514,9 +2445,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTP/4/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTP/4/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTP4std = skale_server_connector->getServerPortStatusProxygenHTTP( 4, e_server_mode_t::esm_standard ); @@ -2528,9 +2457,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTP/4/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTP/4/nfo start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTP4nfo = skale_server_connector->getServerPortStatusProxygenHTTP( 4, e_server_mode_t::esm_informational ); @@ -2542,9 +2469,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTP/6/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTP/6/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTP6std = skale_server_connector->getServerPortStatusProxygenHTTP( 6, e_server_mode_t::esm_standard ); @@ -2556,9 +2481,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTP/6/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTP/6/nfo start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTP6nfo = skale_server_connector->getServerPortStatusProxygenHTTP( 6, e_server_mode_t::esm_informational ); @@ -2570,9 +2493,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTPS/4/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTPS/4/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTPS4std = skale_server_connector->getServerPortStatusProxygenHTTPS( 4, e_server_mode_t::esm_standard ); @@ -2584,9 +2505,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTPS/4/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTPS/4/nfo start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTPS4nfo = skale_server_connector->getServerPortStatusProxygenHTTPS( 4, e_server_mode_t::esm_informational ); @@ -2598,9 +2517,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTPS/6/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTPS/6/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTPS6std = skale_server_connector->getServerPortStatusProxygenHTTPS( 6, e_server_mode_t::esm_standard ); @@ -2612,9 +2529,8 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "HTTPS/6/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for HTTPS/6/nfo" + << " start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatHTTPS6nfo = skale_server_connector->getServerPortStatusProxygenHTTPS( 6, e_server_mode_t::esm_informational ); @@ -2626,9 +2542,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WS/4/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WS/4/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatWS4std = skale_server_connector->getServerPortStatusWS( 4, e_server_mode_t::esm_standard ); @@ -2640,9 +2554,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WS/4/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WS/4/nfo start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatWS4nfo = skale_server_connector->getServerPortStatusWS( 4, e_server_mode_t::esm_informational ); @@ -2654,9 +2566,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WS/6/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WS/6/std start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatWS6std = skale_server_connector->getServerPortStatusWS( 6, e_server_mode_t::esm_standard ); @@ -2668,9 +2578,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WS/6/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WS/6/nfo start... "; std::this_thread::sleep_for( g_waitAttempt ); nStatWS6nfo = skale_server_connector->getServerPortStatusWS( 6, e_server_mode_t::esm_informational ); @@ -2682,9 +2590,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WSS/4/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WSS/4/std start... "; nStatWSS4std = skale_server_connector->getServerPortStatusWSS( 4, e_server_mode_t::esm_standard ); } @@ -2695,9 +2601,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WSS/4/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WSS/4/nfo start... "; nStatWSS4nfo = skale_server_connector->getServerPortStatusWSS( 4, e_server_mode_t::esm_informational ); } @@ -2708,9 +2612,7 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WSS/6/std" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WSS/6/std start... "; nStatWSS6std = skale_server_connector->getServerPortStatusWSS( 6, e_server_mode_t::esm_standard ); } @@ -2721,27 +2623,24 @@ int main( int argc, char** argv ) try { ( !ExitHandler::shouldExit() ); ++idxWaitAttempt ) { if ( idxWaitAttempt == 0 ) - clog( VerbosityDebug, "main" ) - << cc::debug( "Waiting for " ) + cc::info( "WSS/6/nfo" ) - << cc::debug( " start... " ); + LOG( loggerDebug ) << "Waiting for WSS/6/nfo start... "; nStatWSS6nfo = skale_server_connector->getServerPortStatusWSS( 6, e_server_mode_t::esm_informational ); } } - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::attention( "RPC status" ) << cc::debug( ":" ); - auto fnPrintStatus = []( const int& nPort, const int& nStat, + LOG( loggerDebug ) << "....RPC status:"; + auto fnPrintStatus = [&loggerDebug]( const int& nPort, const int& nStat, const char* strDescription ) -> void { static const size_t nAlign = 35; size_t nDescLen = strnlen( strDescription, 1024 ); std::string strDots; for ( ; ( strDots.size() + nDescLen ) < nAlign; ) strDots += "."; - clog( VerbosityDebug, "main" ) - << cc::debug( "...." ) << cc::info( strDescription ) << cc::debug( strDots ) - << ( ( nStat >= 0 ) ? ( ( nPort > 0 ) ? cc::num10( nStat ) : - cc::warn( "still starting..." ) ) : - cc::error( "off" ) ); + LOG( loggerDebug ) + << "...." << strDescription << strDots + << ( ( nStat >= 0 ) ? + ( ( nPort > 0 ) ? std::to_string( nStat ) : "still starting..." ) : + "off" ); }; fnPrintStatus( nExplicitPortHTTP4std, nStatHTTP4std, "HTTP/4std" ); fnPrintStatus( nExplicitPortHTTP4nfo, nStatHTTP4nfo, "HTTP/4nfo" ); @@ -2770,24 +2669,19 @@ int main( int argc, char** argv ) try { sessionManager->addSession( strJsonAdminSessionKey, rpc::SessionPermissions{ { rpc::Privilege::Admin } } ); - clog( VerbosityInfo, "main" ) - << cc::bright( "JSONRPC Admin Session Key: " ) << cc::sunny( strJsonAdminSessionKey ); + LOG( loggerInfo ) << "JSONRPC Admin Session Key: " << strJsonAdminSessionKey; } // if ( is_ipc || nExplicitPort... if ( bEnabledShutdownViaWeb3 ) { - clog( VerbosityWarning, "main" ) - << cc::warn( "Enabling programmatic shutdown via Web3..." ); + LOG( loggerWarning ) << "Enabling programmatic shutdown via Web3..."; dev::rpc::Skale::enableWeb3Shutdown( true ); dev::rpc::Skale::onShutdownInvoke( []() { ExitHandler::exitHandler( -1, ExitHandler::ec_web3_request ); } ); - clog( VerbosityWarning, "main" ) - << cc::warn( "Done, programmatic shutdown via Web3 is enabled" ); + LOG( loggerWarning ) << "Done, programmatic shutdown via Web3 is enabled"; } else { - clog( VerbosityDebug, "main" ) - << cc::debug( "Disabling programmatic shutdown via Web3..." ); + LOG( loggerDebug ) << "Disabling programmatic shutdown via Web3..."; dev::rpc::Skale::enableWeb3Shutdown( false ); - clog( VerbosityDebug, "main" ) - << cc::debug( "Done, programmatic shutdown via Web3 is disabled" ); + LOG( loggerDebug ) << "Done, programmatic shutdown via Web3 is disabled"; } if ( g_client ) { @@ -2820,23 +2714,20 @@ int main( int argc, char** argv ) try { g_client.reset( nullptr ); } - std::cerr << localeconv()->decimal_point << std::endl; + LOG( loggerError ) << localeconv()->decimal_point; std::string basename = "profile" + chainParams.nodeInfo.id.str(); MicroProfileDumpFileImmediately( ( basename + ".html" ).c_str(), ( basename + ".csv" ).c_str(), nullptr ); MicroProfileShutdown(); - // clog( VerbosityDebug, "main" ) << cc::debug( "Stopping task dispatcher..." ); - // skutils::dispatch::shutdown(); - // clog( VerbosityDebug, "main" ) << cc::debug( "Done, task dispatcher stopped" ); ExitHandler::exit_code_t ec = ExitHandler::requestedExitCode(); if ( ec != ExitHandler::ec_success ) { - clog( VerbosityError, "main" ) << cc::error( "Exiting main with code " ) - << cc::num10( int( ec ) ) << cc::error( "...\n" ); + LOG( loggerError ) << "Exiting main with code " << int( ec ) << "..."; } return int( ec ); } catch ( const Client::CreationException& ex ) { + // cannot use loggerError - not in scope clog( VerbosityError, "main" ) << dev::nested_exception_what( ex ); // TODO close microprofile!! g_client.reset( nullptr ); @@ -2848,16 +2739,12 @@ int main( int argc, char** argv ) try { return int( ExitHandler::ec_failure ); } catch ( const std::exception& ex ) { clog( VerbosityError, "main" ) << "CRITICAL " << dev::nested_exception_what( ex ); - clog( VerbosityError, "main" ) << "\n" - << skutils::signal::generate_stack_trace() << "\n" - << std::endl; + clog( VerbosityError, "main" ) << "\n" << skutils::signal::generate_stack_trace(); g_client.reset( nullptr ); return int( ExitHandler::ec_failure ); } catch ( ... ) { clog( VerbosityError, "main" ) << "CRITICAL unknown error"; - clog( VerbosityError, "main" ) << "\n" - << skutils::signal::generate_stack_trace() << "\n" - << std::endl; + clog( VerbosityError, "main" ) << "\n" << skutils::signal::generate_stack_trace(); g_client.reset( nullptr ); return int( ExitHandler::ec_failure ); } diff --git a/skaled_ssl_test/main.cpp b/skaled_ssl_test/main.cpp index 9dbe4de73..5b060efe8 100644 --- a/skaled_ssl_test/main.cpp +++ b/skaled_ssl_test/main.cpp @@ -79,20 +79,18 @@ void helper_ssl_cert_and_key_holder::auto_init() { if ( ( !strFilePathKey_.empty() ) && ( !strFilePathCert_.empty() ) && skutils::tools::file_exists( strFilePathKey_ ) && skutils::tools::file_exists( strFilePathCert_ ) ) { - std::cout << ( cc::success( "Using externally specified " ) + cc::p( strFilePathKey_ ) + - cc::success( " and " ) + cc::p( strFilePathCert_ ) + cc::success( "." ) + - "\n" ); + std::cout << "Using externally specified " + strFilePathKey_ + + " and " + strFilePathCert_ + ".\n" ; need_remove_files_ = false; return; } std::string strPrefix = skutils::tools::get_tmp_file_path(); strFilePathKey_ = strPrefix + ".key.pem"; strFilePathCert_ = strPrefix + ".cert.pem"; - std::cout << ( cc::info( "Will generate " ) + cc::p( strFilePathKey_ ) + cc::info( " and " ) + - cc::p( strFilePathCert_ ) + cc::info( "..." ) + "\n" ); - // - std::cout << ( cc::debug( "Will create " ) + cc::p( strFilePathKey_ ) + cc::debug( " and " ) + - cc::p( strFilePathCert_ ) + cc::debug( "..." ) + "\n" ); + std::cout << "Will generate " + strFilePathKey_ + " and " + + strFilePathCert_ + "...\n"; + std::cout << "Will create " + strFilePathKey_ + " and " + + strFilePathCert_ + "...\n"; std::string strCmd; strCmd += "openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj " @@ -108,8 +106,9 @@ void helper_ssl_cert_and_key_holder::auto_init() { std::cerr << g_err_msg << "\n"; throw std::runtime_error( g_err_msg ); } - std::cout << ( cc::success( "OKay created " ) + cc::p( strFilePathKey_ ) + - cc::success( " and " ) + cc::p( strFilePathCert_ ) + cc::success( "." ) + "\n" ); + + std::cout << "OKay created " + strFilePathKey_ + + " and " + strFilePathCert_ + ".\n"; need_remove_files_ = true; } @@ -161,18 +160,17 @@ void helper_server::run_parallel() { check_can_listen(); std::thread( [&]() -> void { thread_is_running_ = true; - std::cout << ( cc::info( strScheme_ ) + cc::debug( " network server thread started" ) + - "\n" ); + + std::cout << strScheme_ + " network server thread started\n" ; run(); - std::cout << ( cc::info( strScheme_ ) + cc::debug( " network server thread will exit" ) + - "\n" ); + + std::cout << strScheme_ + " network server thread will exit\n"; thread_is_running_ = false; } ) .detach(); while ( !thread_is_running_ ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); - std::cout << ( cc::debug( "Letting " ) + cc::info( strScheme_ ) + - cc::debug( " network server init..." ) ); + std::cout << "Letting " + strScheme_ + " network server init..."; std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); } @@ -183,10 +181,10 @@ void helper_server::wait_parallel() { void helper_server::stat_check_port_availability_to_start_listen( int ipVer, const char* strAddr, int nPort, const char* strScheme ) { - std::cout << ( cc::debug( "Will check port " ) + cc::num10( nPort ) + - cc::debug( "/IPv" + std::to_string( ipVer ) ) + - cc::debug( " availability for " ) + cc::info( strScheme ) + - cc::debug( " server..." ) + "\n" ); + std::cout << "Will check port " + std::to_string(nPort) + + "/IPv" + std::to_string( ipVer ) + + " availability for " + strScheme + + " server...\n"; skutils::network::sockaddr46 sa46; std::string strError = skutils::network::resolve_address_for_client_connection( ipVer, strAddr, sa46 ); @@ -204,9 +202,9 @@ void helper_server::stat_check_port_availability_to_start_listen( std::string( "\", port " ) + std::to_string( nPort ) + std::string( ", IPv" ) + std::to_string( ipVer ) + std::string( " - port is already listening" ) ); - std::cout << ( cc::notice( "Port " ) + cc::num10( nPort ) + - cc::notice( "/IPv" + std::to_string( ipVer ) ) + cc::notice( " is free for " ) + - cc::info( strScheme ) + cc::notice( " server to start" ) + "\n" ); + std::cout << "Port " + std::to_string(nPort) + + "/IPv" + std::to_string(ipVer) + " is free for " + + strScheme + " server to start\n"; } void helper_server::check_can_listen() { @@ -221,20 +219,20 @@ void helper_server::check_can_listen() { helper_ws_peer::helper_ws_peer( skutils::ws::server& srv, const skutils::ws::hdl_t& hdl ) : skutils::ws::peer( srv, hdl ) { strPeerQueueID_ = skutils::dispatch::generate_id( this, "relay_peer" ); - std::cout << ( desc() + cc::notice( " peer ctor" ) + "\n" ); + std::cout << desc() + " peer ctor\n" ; } helper_ws_peer::~helper_ws_peer() { - std::cout << ( desc() + cc::notice( " peer dtor" ) + "\n" ); + std::cout << desc() + " peer dtor\n"; skutils::dispatch::remove( strPeerQueueID_ ); } void helper_ws_peer::onPeerRegister() { - std::cout << ( desc() + cc::notice( " peer registered" ) + "\n" ); + std::cout << desc() + " peer registered\n"; skutils::ws::peer::onPeerRegister(); } void helper_ws_peer::onPeerUnregister() { // peer will no longer receive onMessage after call to // this - std::cout << ( desc() + cc::notice( " peer unregistered" ) + "\n" ); + std::cout << desc() + " peer unregistered\n"; skutils::ws::peer::onPeerUnregister(); } @@ -242,13 +240,11 @@ void helper_ws_peer::onMessage( const std::string& msg, skutils::ws::opcv eOpCod if ( eOpCode != skutils::ws::opcv::text ) throw std::runtime_error( "only ws text messages are supported" ); skutils::dispatch::async( strPeerQueueID_, [=]() -> void { - std::cout << ( cc::ws_rx_inv( - ">>> " + std::string( get_helper_server().strSchemeUC_ ) + "-RX >>> " ) + - desc() + cc::ws_rx( " >>> " ) + cc::j( msg ) + "\n" ); + std::cout << ">>> " + std::string( get_helper_server().strSchemeUC_ ) + "-RX >>> " + + desc() + " >>> " + msg + "\n"; std::string strResult = msg; - std::cout << ( cc::ws_tx_inv( - "<<< " + std::string( get_helper_server().strSchemeUC_ ) + "-TX <<< " ) + - desc() + cc::ws_tx( " <<< " ) + cc::j( strResult ) + "\n" ); + std::cout << "<<< " + std::string( get_helper_server().strSchemeUC_ ) + "-TX <<< " + + desc() + " <<< " + strResult + "\n"; sendMessage( strResult ); } ); skutils::ws::peer::onMessage( msg, eOpCode ); @@ -256,19 +252,21 @@ void helper_ws_peer::onMessage( const std::string& msg, skutils::ws::opcv eOpCod void helper_ws_peer::onClose( const std::string& reason, int local_close_code, const std::string& local_close_code_as_str ) { - std::cout << ( desc() + cc::warn( " peer close event with code=" ) + cc::c( local_close_code ) + - cc::debug( ", reason=" ) + cc::info( reason ) + "\n" ); + + std::cout << desc() + " peer close event with code=" + std::to_string(local_close_code) + + ", reason=" + reason + "\n"; skutils::ws::peer::onClose( reason, local_close_code, local_close_code_as_str ); } void helper_ws_peer::onFail() { - std::cout << ( desc() + cc::error( " peer fail event" ) + "\n" ); + + std::cout << desc() + " peer fail event\n"; skutils::ws::peer::onFail(); } void helper_ws_peer::onLogMessage( skutils::ws::e_ws_log_message_type_t eWSLMT, const std::string& msg ) { - std::cout << ( desc() + cc::debug( " peer log: " ) + msg + "\n" ); + std::cout << desc() + " peer log: " + msg + "\n"; skutils::ws::peer::onLogMessage( eWSLMT, msg ); } @@ -284,16 +282,15 @@ helper_server_ws_base::helper_server_ws_base( : helper_server( strScheme, nListenPort, strBindAddressServer ) { onPeerInstantiate_ = [&]( skutils::ws::server& srv, skutils::ws::hdl_t hdl ) -> skutils::ws::peer_ptr_t { - std::cout << ( cc::info( strScheme_ ) + cc::debug( " server will instantiate new peer" ) + - "\n" ); + std::cout << strScheme_ + " server will instantiate new peer\n"; return new helper_ws_peer( srv, hdl ); }; // onPeerRegister_ = // onPeerUnregister_ = } helper_server_ws_base::~helper_server_ws_base() { - std::cout << ( cc::debug( "Will close " ) + cc::info( strScheme_ ) + - cc::debug( " server, was running on port " ) + cc::c( nListenPort_ ) + "\n" ); + std::cout << "Will close " + strScheme_ + + " server, was running on port " + std::to_string(nListenPort_) + "\n"; stop(); } @@ -308,9 +305,8 @@ void helper_server_ws_base::stop() { } void helper_server_ws_base::run() { - std::cout << ( cc::debug( "Will start server on port " ) + cc::c( nListenPort_ ) + - cc::debug( " using " ) + cc::info( strScheme_ ) + cc::debug( " scheme" ) + - "\n" ); + std::cout << "Will start server on port " + std::to_string(nListenPort_) + + " using " + strScheme_ + " scheme\n"; std::atomic_bool bServerOpenComplete( false ); std::thread( [&]() { ws_server_thread_is_running_ = true; @@ -320,20 +316,18 @@ void helper_server_ws_base::run() { strPrivateKeyFile_ = ssl_info.strFilePathKey_; } if ( !open( strScheme_.c_str(), nListenPort_ ) ) { - std::cerr << ( cc::fatal( "Failed to start server" ) + "\n" ); + std::cerr << "Failed to start server\n"; throw std::runtime_error( "Failed to start server" ); } - std::cout << ( cc::sunny( "Server opened" ) + "\n" ); + std::cout << "Server opened\n"; bServerOpenComplete = true; if ( service_mode_supported() ) { - std::cout << ( cc::info( "Main loop" ) + - cc::debug( " will run in poll in service mode" ) + "\n" ); + std::cout << "Main loop will run in poll in service mode\n"; service( [&]() -> bool { return ( !/*skutils::signal::g_bStop*/ bStopFlag_ ) ? true : false; } ); } else { - std::cout << ( cc::info( "Main loop" ) + cc::debug( " will run in poll/reset mode" ) + - "\n" ); + std::cout << "Main loop will run in poll/reset mode\n"; for ( ; !bStopFlag_; ) { poll( [&]() -> bool { return ( !bStopFlag_ ) ? true : false; } ); if ( bStopFlag_ ) @@ -341,16 +335,14 @@ void helper_server_ws_base::run() { reset(); } // for( ; ! bStopFlag_; ) } - std::cout << ( cc::info( "Main loop" ) + cc::debug( " finish" ) + "\n" ); + std::cout << "Main loop finish\n"; ws_server_thread_is_running_ = false; } ) .detach(); - std::cout << ( cc::debug( "Waiting for " ) + cc::note( "server" ) + cc::debug( " open..." ) + - "\n" ); + std::cout << "Waiting for server open...\n"; while ( !bServerOpenComplete ) std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) ); - std::cout << ( cc::success( "Success, server " ) + cc::info( strScheme_ ) + - cc::success( " server started" ) + "\n" ); + std::cout << "Success, server " + strScheme_ + " server started\n"; } void helper_server_ws_base::onLogMessage( @@ -410,7 +402,7 @@ helper_server_http_base::helper_server_http_base( const char* strScheme, int nLi __SKUTILS_HTTP_DEFAULT_MAX_PARALLEL_QUEUES_COUNT__, is_async_http_transfer_mode ) ); pServer_->Options( "/", [&]( const skutils::http::request& /*req*/, skutils::http::response& res ) { - std::cout << ( cc::info( "OPTTIONS" ) + cc::debug( " request handler" ) + "\n" ); + std::cout << "OPTTIONS request handler\n"; // res.set_content( "", "text/plain" ); res.set_header( "access-control-allow-headers", "Content-Type" ); res.set_header( "access-control-allow-methods", "POST" ); @@ -422,15 +414,15 @@ helper_server_http_base::helper_server_http_base( const char* strScheme, int nLi "vary", "Origin, Access-Control-request-Method, Access-Control-request-Headers" ); } ); pServer_->Post( "/", [&]( const skutils::http::request& req, skutils::http::response& res ) { - std::cout << ( cc::ws_rx_inv( ">>> " + std::string( strSchemeUC_ ) + "-RX-POST >>> " ) + - cc::j( req.body_ ) + "\n" ); + std::cout << ">>> " + std::string( strSchemeUC_ ) + "-RX-POST >>> " + + req.body_ + "\n"; // // std::string strResult = req.body_; // // - std::cout << ( cc::ws_tx_inv( "<<< " + std::string( strSchemeUC_ ) + "-TX-POST <<< " ) + - cc::j( strResult ) + "\n" ); + std::cout << "<<< " + std::string( strSchemeUC_ ) + "-TX-POST <<< " + + strResult + "\n"; res.set_header( "access-control-allow-origin", "*" ); res.set_header( "vary", "Origin" ); res.set_content( strResult.c_str(), "application/json" ); @@ -494,10 +486,8 @@ nlohmann::json helper_client::call( const nlohmann::json& joMsg ) { nlohmann::json joAnswer = nlohmann::json::object(); if ( !call( joMsg, joAnswer ) ) { joAnswer = nlohmann::json::object(); - std::cerr << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::fatal( "RPC CALL FAILURE:" ) + - cc::error( " call failed on side of client " ) + cc::info( strClientName_ ) + - "\n" ); + std::cerr << strClientName_ + ": RPC CALL FAILURE: call failed on side of client " + strClientName_ + + "\n"; } return joAnswer; } @@ -520,55 +510,45 @@ helper_client_ws_base::helper_client_ws_base( const char* strClientName, int nTa nLocalCloseCode_ = local_close_code; strLocalCloseCode_ = local_close_code_as_str; strCloseReason_ = reason; - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::warn( "client got close event close with " ) + cc::info( "code" ) + - cc::warn( "=" ) + cc::c( local_close_code ) + - cc::warn( ", code explanation is " ) + - ( local_close_code_as_str.empty() ? cc::debug( "empty text" ) : - cc::info( local_close_code_as_str ) ) + - cc::warn( ", reason is " ) + - ( reason.empty() ? cc::debug( "empty text" ) : cc::info( reason ) ) + "\n" ); + + std::cout << strClientName_ + ": client got close event close with code = " + std::to_string(local_close_code) + + ", code explanation is " + + ( local_close_code_as_str.empty() ? "empty text" : + local_close_code_as_str ) + + ", reason is " + + ( reason.empty() ? "empty text" : reason ) + "\n"; }; onFail_ = [this]( skutils::ws::client::basic_socket&, skutils::ws::hdl_t ) -> void { ++cntFail_; - std::cerr << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::error( "client got fail event" ) + "\n" ); + std::cerr << strClientName_ + ": client got fail event\n"; }; - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::debug( "Will initalize client " ) + cc::info( strClientName_ ) + - cc::debug( "..." ) + "\n" ); + std::cout << strClientName_ + ": " + "Will initalize client " + strClientName_ + + "...\n"; enableRestartTimer( false ); std::string strServerUrl = skutils::tools::format( "%s://%s:%d", strScheme_.c_str(), strBindAddressClient_.c_str(), nTargetPort_ ); - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::debug( "client will connect to: " ) + cc::u( strServerUrl ) + - cc::debug( "..." ) + "\n" ); + std::cout << strClientName_ + ": client will connect to: " + strServerUrl + + "...\n"; size_t cnt = nConnectAttempts; if ( cnt < 1 ) cnt = 1; for ( size_t nClientConnectAttempt = 0; nClientConnectAttempt < cnt && ( !open( strServerUrl ) ); ++nClientConnectAttempt ) { - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::debug( "Attempt " ) + cc::size10( nClientConnectAttempt + 1 ) + - cc::debug( "..." ) + "\n" ); + std::cout << strClientName_ + ": Attempt " + std::to_string(nClientConnectAttempt + 1) + + "...\n"; std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); } - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + cc::success( "Success" ) + - cc::debug( ", client " ) + cc::info( strClientName_ ) + - cc::debug( " did connected to: " ) + cc::u( strServerUrl ) + cc::debug( "..." ) + - "\n" ); + std::cout << strClientName_ + ": Success, client " + strClientName_ + + " did connected to: " + strServerUrl + "...\n"; // std::this_thread::sleep_for( std::chrono::seconds(1) ); - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + cc::success( "Done" ) + - cc::notice( ", did initialized client " ) + cc::info( strClientName_ ) + "\n" ); + std::cout << strClientName_ + ": Done, did initialized client " + strClientName_ + "\n"; } helper_client_ws_base::~helper_client_ws_base() { stop(); } void helper_client_ws_base::stop() { - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::notice( "Will close client " ) + cc::info( strClientName_ ) + - cc::notice( "..." ) + "\n" ); + std::cout << ( strClientName_ ) + ": Will close client " + strClientName_ + "...\n"; pause_reading(); cancel(); // std::this_thread::sleep_for( std::chrono::seconds(1) ); @@ -577,8 +557,7 @@ void helper_client_ws_base::stop() { // skutils::ws::client::close_status::normal ); close(); // - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + cc::success( "Success" ) + - cc::debug( ", did closed client " ) + cc::info( strClientName_ ) + "\n" ); + std::cout << strClientName_ + ": Success, did closed client " + strClientName_ + "\n"; } void helper_client_ws_base::run() {} @@ -589,22 +568,22 @@ void helper_client_ws_base::onLogMessage( // case skutils::ws::e_ws_log_message_type_t::eWSLMT_debug: break; // case skutils::ws::e_ws_log_message_type_t::eWSLMT_info: break; case skutils::ws::e_ws_log_message_type_t::eWSLMT_warning: - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + msg + "\n" ); + std::cout << strClientName_ + ": " + msg + "\n"; return; case skutils::ws::e_ws_log_message_type_t::eWSLMT_error: - std::cerr << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + msg + "\n" ); + std::cerr << strClientName_ + ": " + msg + "\n"; return; default: break; } // switch( eWSLMT ) - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + msg + "\n" ); + std::cout << strClientName_ + ": " + msg + "\n"; } bool helper_client_ws_base::sendMessage( const std::string& msg, skutils::ws::opcv eOpCode /*= skutils::ws::opcv::text*/ ) { - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::ws_tx_inv( "RPC CALL Tx " + strClientName_ ) + cc::ws_tx( " <<< " ) + - cc::j( msg ) + "\n" ); + std::cout << strClientName_ + ": " + + "RPC CALL Tx " + strClientName_ + " <<< " + + msg + "\n"; strLastMessage_.clear(); bHaveAnswer_ = false; return skutils::ws::client::client::sendMessage( msg, eOpCode ); @@ -620,9 +599,8 @@ bool helper_client_ws_base::sendMessage( const nlohmann::json& joMsg ) { void helper_client_ws_base::onMessage( skutils::ws::hdl_t /*hdl*/, skutils::ws::opcv /*eOpCode*/, const std::string& msg ) { - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::ws_rx_inv( "RPC CALL Rx " + strClientName_ ) + cc::ws_rx( " >>> " ) + - cc::j( msg ) + "\n" ); + std::cout << strClientName_ + ": RPC CALL Rx " + strClientName_ + " >>> " + + msg + "\n"; strLastMessage_ = msg; bHaveAnswer_ = true; } @@ -746,15 +724,13 @@ bool helper_client_http_base::call( const std::string& strMsg, std::string& strA bool helper_client_http_base::call( const nlohmann::json& joMsg, nlohmann::json& joAnswer ) { joAnswer = nlohmann::json::object(); std::string strAnswer; - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::ws_tx_inv( "RPC CALL Tx " + strClientName_ ) + cc::ws_tx( " <<< " ) + - cc::j( joMsg ) + "\n" ); + std::cout << strClientName_ + ": RPC CALL Tx " + strClientName_ + " <<< " + + joMsg.dump() + "\n"; if ( !call( joMsg.dump(), strAnswer ) ) return false; joAnswer = nlohmann::json::parse( strAnswer ); - std::cout << ( cc::info( strClientName_ ) + cc::debug( ":" ) + " " + - cc::ws_rx_inv( "RPC CALL Rx " + strClientName_ ) + cc::ws_rx( " >>> " ) + - cc::j( joAnswer ) + "\n" ); + std::cout << strClientName_ + ": " + "RPC CALL Rx " + strClientName_ + " >>> " + + joAnswer.dump() + "\n"; return true; } @@ -894,12 +870,10 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, throw std::runtime_error( skutils::tools::format( "Failed to create IPv6 busy listener on port %d", nSocketListenPort ) ); } - std::cout << ( cc::debug( "Will execute " ) + cc::note( "busy port" ) + - cc::debug( " callback..." ) + "\n" ); + std::cout << "Will execute busy port callback...\n"; if ( fnWorker ) fnWorker(); - std::cout << ( cc::success( "Success, did executed " ) + cc::note( "busy port" ) + - cc::success( " callback" ) + "\n" ); + std::cout << "Success, did executed busy port callback\n"; } catch ( std::exception& ex ) { std::string strErrorDescription = ex.what(); bool isIgnoreError = false; @@ -907,9 +881,8 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, isIgnoreError = fnErrorHandler( strErrorDescription ); // returns true if errror should be ignored if ( !isIgnoreError ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "busy port" ) + cc::error( " callback: " ) + - cc::warn( strErrorDescription ) + "\n" ); + std::cerr << "FAILURE: Got exception from busy port callback: " + + strErrorDescription + "\n"; // assert( false ); } } catch ( ... ) { @@ -919,8 +892,7 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, isIgnoreError = fnErrorHandler( strErrorDescription ); // returns true if errror should be ignored if ( !isIgnoreError ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got unknown exception from " ) + - cc::note( "busy port" ) + cc::error( " callback" ) + "\n" ); + std::cerr << "FAILURE: Got unknown exception from busy port callback\n"; // assert( false ); } } @@ -954,25 +926,19 @@ void with_server( fn_with_server_t fn, const std::string& strServerUrlScheme, pServer.reset( new helper_server_http( nSocketListenPort, strBindAddressServer, false ) ); // assert( !pServer->isSSL() ); } else { - std::cerr << ( cc::error( "Unknown server type: " ) + cc::warn( strServerUrlScheme ) + - "\n" ); + std::cerr << "Unknown server type: " + strServerUrlScheme + "\n"; throw std::runtime_error( "Unknown server type: " + strServerUrlScheme ); } pServer->run_parallel(); try { - std::cout << ( cc::debug( "Will execute " ) + cc::note( "server" ) + - cc::debug( " callback..." ) + "\n" ); + std::cout << "Will execute server callback...\n"; fn( *pServer.get() ); - std::cout << ( cc::success( "Success, did executed " ) + cc::note( "server" ) + - cc::success( " callback" ) + "\n" ); + std::cout << "Success, did executed server callback\n"; } catch ( std::exception& ex ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "server" ) + cc::error( " callback: " ) + cc::warn( ex.what() ) + - "\n" ); + std::cerr << "FAILURE: Got exception from server callback: " + std::string(ex.what()) + "\n" ; // assert( false ); } catch ( ... ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got unknown exception from " ) + - cc::note( "server" ) + cc::error( " callback" ) + "\n" ); + std::cerr << "FAILURE: Got unknown exception from server callback\n"; // assert( false ); } pServer->stop(); @@ -985,19 +951,16 @@ void with_client( const size_t nConnectAttempts // = 10 ) { if ( runClientInOtherThread ) { - std::cout << ( cc::debug( "Starting client " ) + cc::info( strClientName ) + - cc::debug( " thread..." ) + "\n" ); + std::cout << "Starting client " + strClientName + " thread...\n"; std::atomic_bool bClientThreadFinished( false ); std::thread clientThread( [&]() { with_client( fn, strClientName, strServerUrlScheme, strBindAddressClient, nSocketListenPort, false, nConnectAttempts ); bClientThreadFinished = true; - std::cout << ( cc::debug( " client " ) + cc::info( strClientName ) + - cc::debug( " thread will exit" ) + "\n" ); + std::cout << " client " + strClientName + " thread will exit\n"; } ); - std::cout << ( cc::success( "Done, client " ) + cc::info( strClientName ) + - cc::success( " thread is running" ) + "\n" ); - std::cout << ( cc::debug( "Waiting for client thread to finish..." ) + "\n" ); + std::cout << "Done, client " + strClientName + " thread is running\n"; + std::cout << "Waiting for client thread to finish...\n"; while ( !bClientThreadFinished ) std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) ); try { @@ -1006,11 +969,10 @@ void with_client( } catch ( ... ) { } if ( clientThread.joinable() ) { - std::cerr << ( cc::fatal( "Client thread is still running" ) + "\n" ); + std::cerr << "Client thread is still running\n"; throw std::runtime_error( "Client thread is still running" ); } - std::cout << ( cc::success( "Done" ) + cc::debug( ", client " ) + - cc::info( strClientName ) + cc::debug( " thread is finished" ) + "\n" ); + std::cout << "Done, client " + strClientName + " thread is finished\n"; return; } // if( runClientInOtherThread ) @@ -1033,25 +995,20 @@ void with_client( new helper_client_http( strClientName.c_str(), nSocketListenPort, strBindAddressClient, nConnectAttempts ) ); // assert( !pClient->isSSL() ); } else { - std::cerr << ( cc::error( "Unknown client type: " ) + cc::warn( strServerUrlScheme ) + - "\n" ); + std::cerr << "Unknown client type: " + strServerUrlScheme + "\n"; throw std::runtime_error( "Unknown client type: " + strServerUrlScheme ); } try { - std::cerr << ( cc::debug( "Will execute client " ) + cc::info( pClient->strClientName_ ) + - cc::debug( " callback..." ) + "\n" ); + std::cerr << "Will execute client " + pClient->strClientName_ + " callback..." + "\n"; fn( *pClient.get() ); - std::cerr << ( cc::success( "Success, did executed client " ) + - cc::info( pClient->strClientName_ ) + cc::success( " callback" ) + "\n" ); + std::cerr << ( "Success, did executed client " ) + pClient->strClientName_ + " callback" + "\n"; } catch ( std::exception& ex ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from client " ) + - cc::info( pClient->strClientName_ ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) + "\n" ); + std::cerr << "FAILURE: Got exception from client " + + pClient->strClientName_ + " callback: " + ex.what() + "\n"; // assert( false ); } catch ( ... ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + - cc::error( " Got unknown exception from client " ) + - cc::info( pClient->strClientName_ ) + cc::error( " callback" ) + "\n" ); + std::cerr << "FAILURE: Got unknown exception from client " + + pClient->strClientName_ + " callback\n"; // assert( false ); } pClient->stop(); @@ -1074,16 +1031,16 @@ extern void with_clients( fn_with_client_t fn, const std::vector< std::string >& nConnectAttempts, &cntRunningThreads, &vecClientNames]() -> void { with_client( fn, vecClientNames[i], strServerUrlScheme, strBindAddressClient, nSocketListenPort, false, nConnectAttempts ); - std::cout << ( cc::debug( " client " ) + cc::info( vecClientNames[i] ) + - cc::debug( " thread will exit" ) + "\n" ); + std::cout << " client " + vecClientNames[i] + + " thread will exit\n"; --cntRunningThreads; } ) ); std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); for ( size_t idxWait = 0; cntRunningThreads > 0; ++idxWait ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); if ( idxWait % 1000 == 0 && idxWait != 0 ) - std::cout << ( cc::debug( "Waiting for " ) + cc::size10( cntRunningThreads ) + - cc::debug( " client thread(s)" ) + "\n" ); + std::cout << "Waiting for " + std::to_string(cntRunningThreads) + + " client thread(s)\n"; } for ( i = 0; i < cnt; ++i ) { try { @@ -1104,23 +1061,15 @@ void with_client_server( fn_with_client_server_t fn, const std::string& strClien with_client( [&]( helper_client& refClient ) -> void { try { - std::cout << ( cc::debug( "Will execute " ) + cc::note( "client-server" ) + - cc::debug( " callback..." ) + "\n" ); + std::cout << "Will execute client-server callback...\n"; fn( refServer, refClient ); - std::cout << ( cc::success( "Success, did executed " ) + - cc::note( "client-server" ) + cc::success( " callback" ) + - "\n" ); + std::cout << "Success, did executed client-server callback\n"; } catch ( std::exception& ex ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + - cc::error( " Got exception from " ) + - cc::note( "client-server" ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) + "\n" ); + std::cerr << "FAILURE: Got exception from client-server callback: " + + std::string(ex.what()) + "\n"; // assert( false ); } catch ( ... ) { - std::cerr << ( cc::fatal( "FAILURE:" ) + - cc::error( " Got unknown exception from " ) + - cc::note( "client-server" ) + cc::error( " callback" ) + - "\n" ); + std::cerr << "FAILURE: Got unknown exception from client-server callback\n"; // assert( false ); } }, @@ -1135,27 +1084,27 @@ void with_client_server( fn_with_client_server_t fn, const std::string& strClien void helper_protocol_busy_port( const char* strProtocol, const char* strBindAddressServer, int nPort ) { - std::cout << ( cc::debug( "Protocol busy port check" ) + "\n" ); + std::cout << "Protocol busy port check\n"; with_busy_tcp_port( [&]() -> void { // fn_with_busy_tcp_port_worker_t - std::cout << ( cc::sunny( "Busy port allocated" ) + "\n" ); + std::cout << "Busy port allocated\n"; with_server( [&]( helper_server & /*refServer*/ ) -> void { - std::cout << ( cc::sunny( "Server startup" ) + "\n" ); - std::cout << ( cc::sunny( "WE SHOULD NOT REACH THIS EXECUTION POINT" ) + "\n" ); + std::cout << "Server startup\n"; + std::cout << "WE SHOULD NOT REACH THIS EXECUTION POINT\n"; // assert( false ); }, strProtocol, strBindAddressServer, nPort ); - std::cout << ( cc::sunny( "Server finish" ) + "\n" ); + std::cout << "Server finish\n"; }, [&]( const std::string& strErrorDescription ) -> bool { // fn_with_busy_tcp_port_error_t - std::cout << ( cc::success( "Busy port detected with message: " ) + - cc::bright( strErrorDescription ) + "\n" ); - std::cout << ( cc::success( "SUCCESS - busy port handled" ) + "\n" ); + std::cout << "Busy port detected with message: " + + strErrorDescription + "\n"; + std::cout << "SUCCESS - busy port handled\n"; return true; // returns true if errror should be ignored }, strBindAddressServer, nPort ); - std::cout << ( cc::sunny( "Busy port de-allocated" ) + "\n" ); + std::cout << "Busy port de-allocated\n"; } void helper_protocol_rest_call( const char* strProtocol, const char* strBindAddressServer, @@ -1168,33 +1117,33 @@ void helper_protocol_rest_call( const char* strProtocol, const char* strBindAddr "{ \"id\": \"1234567\", \"method\": \"hello\", \"params\": {} }" ); nlohmann::json joCall = ensure_call_id_present_copy( nlohmann::json::parse( strCall ) ); - std::cout << ( cc::normal( "Startup" ) + "\n" ); + std::cout << "Startup\n"; std::string strURL = skutils::tools::format( "%s://%s:%d", strProtocol, strBindAddressClient, nPort ); skutils::url u( strURL ); skutils::rest::client restCall( u ); - std::cout << ( cc::info( "input" ) + cc::debug( "..........." ) + - cc::normal( joCall.dump() ) + "\n" ); + std::cout << "input..........." + + joCall.dump() + "\n"; skutils::rest::data_t dataOut = restCall.call( strCall ); // assert( ! dataOut.empty() ); nlohmann::json joResult = nlohmann::json::parse( dataOut.s_ ); - std::cout << ( cc::info( "output" ) + cc::debug( ".........." ) + - cc::normal( joResult.dump() ) + "\n" ); + std::cout << "output.........." + + joResult.dump() + "\n"; // assert( joCall.dump() == joResult.dump() ); end_reached = true; - std::cout << ( cc::success( "Finish" ) + "\n" ); + std::cout << "Finish\n"; if ( isAutoExitOnSuccess ) _exit( __EXIT_SUCCESS ); } catch ( std::exception& ex ) { std::string strErrorDescription = ex.what(); - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got in-test exception: " ) + - cc::warn( strErrorDescription ) + "\n" ); + std::cerr << "FAILURE: Got in-test exception: " + + strErrorDescription + "\n"; // assert( false ); _exit( __EXIT_ERROR_IN_TEST_EXCEPTOION ); } catch ( ... ) { std::string strErrorDescription = "unknown exception"; - std::cerr << ( cc::fatal( "FAILURE:" ) + cc::error( " Got in-test exception: " ) + - cc::warn( strErrorDescription ) + "\n" ); + std::cerr << "FAILURE: Got in-test exception: " + + strErrorDescription + "\n"; // assert( false ); _exit( __EXIT_ERROR_IN_TEST_UNKNOWN_EXCEPTOION ); } @@ -1207,7 +1156,7 @@ void helper_protocol_rest_call( const char* strProtocol, const char* strBindAddr void helper_protocol_echo_server( const char* strProtocol, const char* strBindAddressServer, int nPort ) { with_server( [&]( helper_server & /*refServer*/ ) -> void { - std::cout << ( cc::success( "Echo server started" ) + "\n" ); + std::cout << "Echo server started\n"; for( ; true; ) { std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); } diff --git a/storage_benchmark/main.cpp b/storage_benchmark/main.cpp index 9ee184e72..9abec6088 100644 --- a/storage_benchmark/main.cpp +++ b/storage_benchmark/main.cpp @@ -10,6 +10,7 @@ using namespace std; #include #include +#include #include @@ -128,7 +129,7 @@ void testState() { cout << "Balances reads:" << endl; cout << measure_performance( - [&state, &address]() { state.createStateCopyAndClearCaches().balance(address ); }, + [&state, &address]() { state.createStateCopyAndClearCaches().balance( address ); }, 100000 ) / 1e6 << " Mreads per second" << endl; @@ -150,7 +151,7 @@ void testState() { cout << "EVM storate reads:" << endl; cout << measure_performance( [&state, &address, &memory_address]() { - state.createReadOnlySnapBasedCopy().storage(address, memory_address ); + state.createReadOnlySnapBasedCopy().storage( address, memory_address ); memory_address = ( memory_address + 1 ) % 1024; }, 1000 ) / @@ -176,8 +177,9 @@ void testState() { cout << "EVM code reads:" << endl; cout << measure_performance( - [&state, &address]() { state.createReadOnlySnapBasedCopy().code(address ); }, 1000 ) / - 1e6 + [&state, &address]() { state.createReadOnlySnapBasedCopy().code( address ); }, + 1000 ) / + 1e6 << " Mreads per second" << endl; } diff --git a/test/tools/jsontests/vm.cpp b/test/tools/jsontests/vm.cpp index 765678a92..3e561419f 100644 --- a/test/tools/jsontests/vm.cpp +++ b/test/tools/jsontests/vm.cpp @@ -243,8 +243,8 @@ eth::OnOpFunc FakeExtVM::simpleTrace() const { for ( auto const& i : std::get< 2 >( ext.addresses.find( ext.myAddress )->second ) ) o << std::showbase << std::hex << i.first << ": " << i.second << "\n"; - LOG( ext.m_logger ) << o.str(); - LOG( ext.m_logger ) << " | " << std::dec << ext.depth << " | " << ext.myAddress << " | #" + LOG( ext.m_loggerTrace ) << o.str(); + LOG( ext.m_loggerTrace ) << " | " << std::dec << ext.depth << " | " << ext.myAddress << " | #" << steps << " | " << std::hex << std::setw( 4 ) << std::setfill( '0' ) << pc << " : " << instructionInfo( inst ).name << " | " << std::dec << gas << " | -" << std::dec << gasCost << " | " << newMemSize << "x32" diff --git a/test/tools/jsontests/vm.h b/test/tools/jsontests/vm.h index 4c0c510cd..eecadc3e6 100644 --- a/test/tools/jsontests/vm.h +++ b/test/tools/jsontests/vm.h @@ -94,7 +94,7 @@ class FakeExtVM : public eth::ExtVMFace { u256 gas; u256 execGas; - mutable Logger m_logger{createLogger( VerbosityTrace, "EVM" )}; + mutable Logger m_loggerTrace{createLogger( VerbosityTrace, "EVM" )}; }; class VmTestSuite : public TestSuite { diff --git a/test/tools/libtesteth/BlockChainHelper.cpp b/test/tools/libtesteth/BlockChainHelper.cpp index 3098b54e1..ad4c43903 100644 --- a/test/tools/libtesteth/BlockChainHelper.cpp +++ b/test/tools/libtesteth/BlockChainHelper.cpp @@ -198,7 +198,7 @@ void TestBlock::mine( TestBlockChain const& _bc ) { size_t transactionsOnImport = m_transactionQueue.topTransactions( 100 ).size(); block.sync( blockchain, m_transactionQueue, - gp ); //!!! Invalid transactions could be dropped from queue here!!! + gp ); //Invalid transactions could be dropped from queue here // if (transactionsOnImport > m_transactionQueue.topTransactions(1000).size()) // BOOST_ERROR(TestOutputHelper::get().testName() + " Dropped invalid Transactions before // mining!"); diff --git a/test/tools/libtesteth/ImportTest.cpp b/test/tools/libtesteth/ImportTest.cpp index 9555cec56..d78e50059 100644 --- a/test/tools/libtesteth/ImportTest.cpp +++ b/test/tools/libtesteth/ImportTest.cpp @@ -769,7 +769,7 @@ void ImportTest::traceStateDiff() { log << "trNetID: " << netIdToString( tr.netId ) << "\n"; log << "trDataInd: " << tr.dataInd << " tdGasInd: " << tr.gasInd << " trValInd: " << tr.valInd << "\n"; - LOG( m_logger ) << log.str(); + LOG( m_loggerInfo ) << log.str(); fillJsonWithStateChange( m_statePre, tr.postState, tr.changeLog ); // output std // log } diff --git a/test/tools/libtesteth/ImportTest.h b/test/tools/libtesteth/ImportTest.h index ed4f1c298..53e6c279a 100644 --- a/test/tools/libtesteth/ImportTest.h +++ b/test/tools/libtesteth/ImportTest.h @@ -112,7 +112,7 @@ class ImportTest { json_spirit::mObject const& m_testInputObject; json_spirit::mObject& m_testOutputObject; - Logger m_logger{createLogger( VerbosityInfo, "state" )}; + Logger m_loggerInfo{createLogger( VerbosityInfo, "state" )}; }; template < class T > diff --git a/test/unittests/libethereum/ClientTest.cpp b/test/unittests/libethereum/ClientTest.cpp index ade323edf..d49ea791b 100644 --- a/test/unittests/libethereum/ClientTest.cpp +++ b/test/unittests/libethereum/ClientTest.cpp @@ -179,35 +179,35 @@ class TestClientFixture : public TestOutputHelperFixture { std::string s = fastWriter.write( json ); nlohmann::json jo = nlohmann::json::parse( s ); clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Will compute status of transaction: " ) + cc::j( jo ) + cc::debug( " ..." ) ); + "Will compute status of transaction: " + jo.dump() + " ..."; } // block Transaction tx = tx_from_json(json); auto txHash = m_ethereum->importTransaction(tx); clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Mining transaction..." ) ); + "Mining transaction..."; dev::eth::mineTransaction(*(m_ethereum), 1); clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Getting transaction receipt..." ) ); + "Getting transaction receipt..."; Json::Value receipt = toJson(m_ethereum->localisedTransactionReceipt(txHash)); { // block Json::FastWriter fastWriter; std::string s = fastWriter.write( receipt ); nlohmann::json jo = nlohmann::json::parse( s ); clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Got transaction receipt: " ) + cc::j( jo ) + cc::debug( " ..." ) ); + "Got transaction receipt: " + jo.dump() + " ..."; } // block bool bStatusFlag = ( receipt["status"] == "0x1" ) ? true : false; if( bStatusFlag ) clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::success( "SUCCESS: Got positive transaction status" ) ); + "SUCCESS: Got positive transaction status"; else - cerr << "TestClientFixture::getTransactionStatus() ERROR:" << receipt["status"] << endl; + cerr << "TestClientFixture::getTransactionStatus() ERROR:" << receipt["status"] << '\n'; return bStatusFlag; } catch ( std::exception & ex ) { - cerr << "TestClientFixture::getTransactionStatus() ERROR:" << ex.what() << endl; + cerr << "TestClientFixture::getTransactionStatus() ERROR:" << ex.what() << '\n'; return false; } catch (...) { - cerr << "TestClientFixture::getTransactionStatus() Unknown exception" << endl; + cerr << "TestClientFixture::getTransactionStatus() Unknown exception" << '\n'; return false; } } diff --git a/test/unittests/libskutils/test_skutils_dispatch.cpp b/test/unittests/libskutils/test_skutils_dispatch.cpp index 1c011d6d9..7ed795fac 100644 --- a/test/unittests/libskutils/test_skutils_dispatch.cpp +++ b/test/unittests/libskutils/test_skutils_dispatch.cpp @@ -12,7 +12,6 @@ static std::string thread_prefix_str() { size_t nLen = strThreadID.length(); if ( nLen > g_nMaxThreadIdLen ) strThreadID = strThreadID.substr( nLen - g_nMaxThreadIdLen ); - strThreadID = cc::info( strThreadID ); // std::stringstream ssLoop; std::string strLoop; @@ -24,9 +23,8 @@ static std::string thread_prefix_str() { size_t nLen = strLoop.length(); if ( nLen > g_nMaxLoopIdLen ) strLoop = strLoop.substr( nLen - g_nMaxLoopIdLen ); - strLoop = cc::notice( strLoop ); } else - strLoop = cc::error( "~" ); + strLoop = "~"; // std::string strQueue; skutils::dispatch::queue_ptr_t pQueue = skutils::dispatch::queue::get_current(); @@ -38,12 +36,11 @@ static std::string thread_prefix_str() { size_t nLen = strQueue.length(); if ( nLen > g_nMaxQueueIdLen ) strQueue = strQueue.substr( nLen - g_nMaxQueueIdLen ); - strQueue = cc::attention( strQueue ); std::string strID = pQueue->get_id(); if ( !strID.empty() ) - strQueue += cc::debug( "-" ) + cc::sunny( strID ); + strQueue += "-" + strID; } else - strQueue = cc::error( "~" ); + strQueue = "~"; // std::stringstream ssDomain; std::string strDomain; @@ -55,15 +52,13 @@ static std::string thread_prefix_str() { size_t nLen = strDomain.length(); if ( nLen > g_nMaxDomainIdLen ) strDomain = strDomain.substr( nLen - g_nMaxDomainIdLen ); - strDomain = cc::notice( strDomain ); } else - strDomain = cc::error( "~" ); + strDomain = "~"; // thread / loop / queue / domain - return cc::debug( "TLQD/" ) + strThreadID + cc::debug( "/" ) + strLoop + cc::debug( "/" ) + - strQueue + cc::debug( "/" ) + strDomain + cc::debug( ": " ); + return "TLQD/" + strThreadID + "/" + strLoop + "/" + + strQueue + "/" + strDomain + ": "; } - BOOST_AUTO_TEST_SUITE( SkUtils ) BOOST_AUTO_TEST_SUITE( dispatch, *boost::unit_test::precondition( dev::test::option_all_tests ) ) @@ -73,58 +68,45 @@ BOOST_AUTO_TEST_SUITE( dispatch, *boost::unit_test::precondition( dev::test::opt BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { skutils::test::test_print_header_name( "SkUtils/dispatch/loop_functionality_alive" ); skutils::test::with_test_environment( [&]() { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "creating loop instance..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "creating loop instance..."); skutils::dispatch::loop_ptr_t pLoop( new skutils::dispatch::loop ); pLoop->on_job_will_add_ = [&]( const skutils::dispatch::job_id_t& id ) -> bool { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will " ) + - cc::success( "add" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "will add job " + id); return true; }; pLoop->on_job_was_added_ = [&]( const skutils::dispatch::job_id_t& id ) -> void { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "did " ) + - cc::success( "added" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "did added job " + id); }; pLoop->on_job_will_remove_ = [&]( const skutils::dispatch::job_id_t& id ) -> bool { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will " ) + - cc::error( "remove" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "will remove job " + id); return true; }; pLoop->on_job_did_removed_ = [&]( const skutils::dispatch::job_id_t& id ) -> void { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "did " ) + - cc::error( "removed" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "did removed job " + id); }; pLoop->on_job_will_execute_ = [&]( const skutils::dispatch::job_id_t& id ) -> bool { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will " ) + - cc::warn( "execute" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "will execute job " + id ); return true; }; pLoop->on_job_did_executed_ = [&]( const skutils::dispatch::job_id_t& id ) -> void { - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "did " ) + - cc::warn( "executed" ) + cc::debug( " job " ) + - cc::info( id ) ); + skutils::test::test_log_e( thread_prefix_str() + "did executed job " + id); }; pLoop->on_job_exception_ = [&]( const skutils::dispatch::job_id_t& id, std::exception* pe ) -> void { - skutils::test::test_log_e( thread_prefix_str() + cc::error( "exception in job " ) + - cc::info( id ) + cc::error( ", exception info: " ) + - cc::warn( ( pe ? pe->what() : "unknown exception" ) ) ); + skutils::test::test_log_e( thread_prefix_str() + "exception in job " + id + ", exception info: " + + ( pe ? pe->what() : "unknown exception" )); }; // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "starting loop thread..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "starting loop thread..." ); std::thread t( [&]() -> void { skutils::test::test_log_e( - thread_prefix_str() + cc::notice( "will run loop in thread..." ) ); + thread_prefix_str() + "will run loop in thread..." ); pLoop->run(); skutils::test::test_log_e( - thread_prefix_str() + cc::notice( "will exit loop thread..." ) ); + thread_prefix_str() + "will exit loop thread..." ); } ); skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "waiting loop to start finished..." ) ); + thread_prefix_str() + "waiting loop to start finished..." ); pLoop->wait_until_startup(); // static const size_t nSleepSeconds = 3; @@ -135,15 +117,15 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { [&]() -> void { ++nCallCountOnce; skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "--- once uppon a time job, invocation " ) + - cc::size10( nCallCountOnce - 1 ) ); + "--- once uppon a time job, invocation " + + std::to_string(nCallCountOnce - 1) ); }, skutils::dispatch::duration_from_milliseconds( nOnceJobTimeout ) ); // pLoop->job_add_once( "bad job", [&]() -> void { skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "bad job invoked, throwing someting" ) ); + thread_prefix_str() + "bad job invoked, throwing someting" ); // throw 12345; throw std::runtime_error( "exception thrown from bad job" ); }, @@ -155,29 +137,29 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { const size_t nExpectedCallCountPeriodical = ( nSleepSeconds * 1000 ) / nPeriodicJobTimeout - 1; // -1 for safety) skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "expecting periodical job to be invoked " ) + - cc::size10( nExpectedCallCountPeriodical ) + cc::debug( " time(s), at least" ) ); + thread_prefix_str() + "expecting periodical job to be invoked " + + std::to_string(nExpectedCallCountPeriodical) + " time(s), at least" ); pLoop->job_add_periodic( "some periodical work", [&]() -> void { ++nCallCountPeriodical; skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "--- periodical job, invocation " ) + - cc::size10( nCallCountPeriodical - 1 ) ); + "--- periodical job, invocation " + + std::to_string(nCallCountPeriodical - 1)); }, skutils::dispatch::duration_from_milliseconds( nPeriodicJobTimeout ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "will sleep " ) + - cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "will sleep " + + std::to_string(nSleepSeconds) + " second(s)..." ); sleep( nSleepSeconds ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will cancel loop..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "will cancel loop..." ); pLoop->cancel(); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will wait for loop..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "will wait for loop..." ); pLoop->wait(); try { if ( t.joinable() ) { skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "will wait for loop thread..." ) ); + thread_prefix_str() + "will wait for loop thread..." ); t.join(); } } catch ( ... ) { @@ -185,7 +167,7 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { BOOST_REQUIRE( nCallCountOnce == 1 ); BOOST_REQUIRE( nCallCountPeriodical >= nExpectedCallCountPeriodical ); // some number of calls should be performed - skutils::test::test_log_e( thread_prefix_str() + cc::info( "end of loop test" ) ); + skutils::test::test_log_e( thread_prefix_str() + "end of loop test" ); } ); } @@ -199,15 +181,14 @@ BOOST_AUTO_TEST_CASE( domain_functionality_alive ) { std::atomic_size_t nCallCounter( 0 ); { // block for domain skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "creating domain instance..." ) ); + thread_prefix_str() + "creating domain instance..." ); skutils::dispatch::domain_ptr_t pDomain( new skutils::dispatch::domain ); - // skutils::dispatch::domain_ptr_t pDomain( skutils::dispatch::default_domain() ); - // + size_t i; std::atomic_bool bInsideCall( false ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "expecting async job to be invoked " ) + - cc::size10( nExpectedCallCount ) + cc::debug( " time(s), at least" ) ); + thread_prefix_str() + "expecting async job to be invoked " + + std::to_string(nExpectedCallCount) + " time(s), at least"); for ( i = 0; i < nExpectedCallCount; ++i ) { skutils::dispatch::queue_ptr_t pQueue( pDomain->queue_get( skutils::dispatch::get_default_queue_id(), true ) ); @@ -218,8 +199,8 @@ BOOST_AUTO_TEST_CASE( domain_functionality_alive ) { if ( g_bShowDetailedJobLogs ) skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "--- async job in queue, invocation " ) + - cc::size10( size_t( nCallCounter ) - 1 ) ); + "--- async job in queue, invocation " + + std::to_string(size_t( nCallCounter ) - 1)); BOOST_REQUIRE( bool( bInsideCall ) ); bInsideCall = false; } ); @@ -229,25 +210,24 @@ BOOST_AUTO_TEST_CASE( domain_functionality_alive ) { static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string(nWaitRound+1) + + " of " + std::to_string(nWaitRoundCount) + + ", will sleep " + std::to_string(nSleepSeconds) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string(nSleepSeconds) + + " second(s), end of domain life time..." ); if( size_t( nExpectedCallCount ) == size_t( nCallCounter ) ) break; } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // - skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down domain..." ) ); + skutils::test::test_log_e(thread_prefix_str() + "shutting down domain..."); pDomain->shutdown(); } // block for domain BOOST_REQUIRE( nExpectedCallCount == nCallCounter ); // - skutils::test::test_log_e( thread_prefix_str() + cc::info( "end of domain alive test" ) ); + skutils::test::test_log_e( thread_prefix_str() + "end of domain alive test"); } ); } @@ -260,15 +240,15 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { size_t g_arrThreadCounts[] = {1, 2, 4 /*, 8, 16, 32, 64*/}; // tests with different count // of threads for ( const size_t& nThreadCount : g_arrThreadCounts ) { - skutils::test::test_log_e( cc::trace( + skutils::test::test_log_e( "# " - "-----------------------------------------------------------------------" ) ); - skutils::test::test_log_e( cc::trace( "# " ) + - cc::info( "job_priorities_alive with nThreadCount=" ) + - cc::size10( nThreadCount ) ); - skutils::test::test_log_e( cc::trace( + "-----------------------------------------------------------------------" ); + skutils::test::test_log_e( + "# " + "job_priorities_alive with nThreadCount=" + nThreadCount ); + skutils::test::test_log_e( "# " - "-----------------------------------------------------------------------" ) ); + "-----------------------------------------------------------------------" ); struct { skutils::dispatch::queue_id_t id_; const skutils::dispatch::priority_t priority_; @@ -294,7 +274,7 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { size_t idxPriority; { // block for domain skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "creating domain instance..." ) ); + thread_prefix_str() + "creating domain instance..." ); skutils::dispatch::domain_ptr_t pDomain( new skutils::dispatch::domain( nThreadCount ) ); // first parameter threads in pool, if not then then number // of CPUs @@ -303,15 +283,13 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { std::atomic_bool g_bStopSignalFlag( false ), g_bThreadStoppedFlag( false ); std::thread( [&]() { skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "test thread entered..." ) ); + thread_prefix_str() + "test thread entered..." ); // init queues with priorities for ( idxPriority = 0; idxPriority < cntPriorities; ++idxPriority ) { skutils::dispatch::priority_t pri = g_arrTestDataByPriority[idxPriority].priority_; skutils::dispatch::queue_id_t strQueueID = - g_arrTestDataByPriority[idxPriority].id_; // skutils::tools::format( - // "queue_id_%zu", - // size_t(pri) ); + g_arrTestDataByPriority[idxPriority].id_; skutils::dispatch::queue_ptr_t pQueue( pDomain->queue_get( strQueueID, true ) ); pQueue->priority( pri ); @@ -326,9 +304,7 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { // g_arrTestDataByPriority[idxPriority].priority_; skutils::dispatch::queue_id_t strQueueID = g_arrTestDataByPriority[idxPriority] - .id_; // skutils::tools::format( - // "queue_id_%zu", - // size_t(pri) ); + .id_; size_t push_count_at_step = g_arrTestDataByPriority[idxPriority].push_count_at_step_; for ( size_t j = 0; j < push_count_at_step; ++j ) { @@ -343,8 +319,7 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { strQueueID]() { std::atomic_bool& bInsideCall = g_arrTestDataByPriority[idxPriority].bInsideCall_; - // std::atomic_size_t & nSubmitCounter = - // g_arrTestDataByPriority[idxPriority].submit_counter_; + std::atomic_size_t& nCallCounter = g_arrTestDataByPriority[idxPriority].call_counter_; BOOST_REQUIRE( !bool( bInsideCall ) ); @@ -356,10 +331,10 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { if ( g_bShowDetailedJobLogs ) skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "--- async job in queue " ) + - cc::bright( strQueueID ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounter ) - 1 ) ); + "--- async job in queue " + + strQueueID + + ", invocation " + + std::to_string(size_t( nCallCounter ) - 1) ); BOOST_REQUIRE( bool( bInsideCall ) ); size_t sleep_milliseconds = g_arrTestDataByPriority[idxPriority].sleep_milliseconds_; @@ -376,8 +351,7 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { } // for( idxPriority = 0; idxPriority < cntPriorities; ++ idxPriority ) if ( g_bStopSignalFlag ) { skutils::test::test_log_e( - thread_prefix_str() + - cc::debug( "test thread got stop signal..." ) ); + thread_prefix_str() + "test thread got stop signal..." ); break; } std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); @@ -386,44 +360,37 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { // signal we are done g_bThreadStoppedFlag = true; skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "test thread is about to leave..." ) ); + thread_prefix_str() + "test thread is about to leave..." ); } ) .detach(); // // static const size_t nSleepMilliSeconds = 5000; - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "will sleep " ) + - cc::size10( nSleepMilliSeconds ) + - cc::warn( " millisecond(s)..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "will sleep " + + std::to_string(nSleepMilliSeconds) + + " millisecond(s)..."); std::this_thread::sleep_for( std::chrono::milliseconds( nSleepMilliSeconds ) ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepMilliSeconds ) + - cc::warn( " millisecond(s)" ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string(nSleepMilliSeconds) + + " millisecond(s)"); // skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "stopping test thread..." ) ); + thread_prefix_str() + "stopping test thread..." ); g_bStopSignalFlag = true; for ( ; !g_bThreadStoppedFlag; ) std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) ); skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "test thread was stopped, end of domain life time..." ) ); - // - // static const size_t nExtraSleepMilliSeconds = 1000; - // skutils::test::test_log_e( thread_prefix_str() + cc::warn("will additionally - // sleep ") + cc::size10(nExtraSleepMilliSeconds) + cc::warn(" millisecond(s) to - // lett all the work (probably done)...") ); std::this_thread::sleep_for( - // std::chrono::milliseconds(nExtraSleepMilliSeconds) ); - // + "test thread was stopped, end of domain life time..."); + skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down domain..." ) ); + thread_prefix_str() + "shutting down domain..."); pDomain->shutdown(); } // block for domain - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "analyzing results..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "analyzing results..." ); // for ( idxPriority = 0; idxPriority < cntPriorities; ++idxPriority ) { - // skutils::dispatch::priority_t pri = - // g_arrTestDataByPriority[idxPriority].priority_; + skutils::dispatch::queue_id_t strQueueID = g_arrTestDataByPriority[idxPriority].id_; // skutils::tools::format( // "queue_id_%zu", size_t(pri) ); @@ -444,24 +411,13 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { double lfPercentMiss = ( nSubmitCounter > 0 ) ? ( 100.0 - lfPercentHit ) : 0.0; std::string strHit = skutils::tools::format( "%.1lf", lfPercentHit ); std::string strMiss = skutils::tools::format( "%.1lf", lfPercentMiss ); - if ( lfPercentHit == 100.0 ) - strHit = cc::success( strHit ); - else if ( lfPercentHit > 10.0 ) - strHit = cc::warn( strHit ); - else - strHit = cc::error( strHit ); - if ( lfPercentMiss == 0.0 ) - strMiss = cc::success( strMiss ); - else if ( lfPercentMiss < 90.0 ) - strMiss = cc::warn( strMiss ); - else - strMiss = cc::error( strMiss ); + skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "queue " ) + cc::bright( strQueueID ) + - cc::debug( " was submitted " ) + cc::size10( size_t( nSubmitCounter ) ) + - cc::debug( " and called " ) + cc::size10( size_t( nCallCounter ) ) + - cc::debug( " time(s)" ) + cc::debug( ", hit " ) + strHit + cc::trace( "%" ) + - cc::debug( ", miss " ) + strMiss + cc::trace( "%" ) ); + thread_prefix_str() + "queue " + strQueueID + + " was submitted " + std::to_string(size_t( nSubmitCounter )) + + " and called " + std::to_string( size_t( nCallCounter ) ) + + " time(s)" + ", hit " + strHit + "%" + + ", miss " + strMiss + "%"); BOOST_REQUIRE( !bool( bInsideCall ) ); // if( bInsideCall ) { // int xxx = 0; @@ -487,8 +443,8 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { // skutils::test::test_log_e( thread_prefix_str() + - cc::info( "end of domain priorities test with nThreadCount=" ) + - cc::size10( nThreadCount ) ); + "end of domain priorities test with nThreadCount=" + + std::to_string(nThreadCount) ); } // for( const size_t & nThreadCount : g_arrThreadCounts ) } ); } @@ -519,73 +475,60 @@ BOOST_AUTO_TEST_CASE( domain_timing_functionality_alive ) { // { // block for domain skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "creating domain instance..." ) ); + thread_prefix_str() + "creating domain instance..." ); skutils::dispatch::domain_ptr_t pDomain( new skutils::dispatch::domain ); // skutils::dispatch::domain_ptr_t pDomain( skutils::dispatch::default_domain() ); skutils::dispatch::queue_ptr_t pQueue( pDomain->queue_get( skutils::dispatch::get_default_queue_id(), true ) ); skutils::dispatch::queue_ptr_t pQueueSync( pDomain->queue_get( sync_queue_id, true ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::notice( "once job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding once job to queue"); pQueue->job_add_once( [&]() { BOOST_REQUIRE( !bool( bInsideCallOnce ) ); bInsideCallOnce = true; ++nCallCounterOnce; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::notice( "once job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterOnce ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- once job, invocation " + + std::to_string(size_t( nCallCounterOnce ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallOnce ) ); bInsideCallOnce = false; }, skutils::dispatch::duration_from_seconds( 1 ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::warn( "periodic job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding periodic job to queue" ); pQueue->job_add_periodic( [&]() { BOOST_REQUIRE( !bool( bInsideCallPeriodic ) ); bInsideCallPeriodic = true; ++nCallCounterPeriodic; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::warn( "periodic job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterPeriodic ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- periodic job, invocation " + + std::to_string(size_t( nCallCounterPeriodic ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallPeriodic ) ); bInsideCallPeriodic = false; }, skutils::dispatch::duration_from_milliseconds( 500 ) // 0.5 seconds ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::note( "async job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding async job to queue"); pQueue->job_add( [&]() { BOOST_REQUIRE( !bool( bInsideCallAsync ) ); bInsideCallAsync = true; ++nCallCounterAsync; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::note( "async job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterAsync ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- async job, invocation " + + std::to_string(size_t( nCallCounterAsync ) - 1 ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will invoke " ) + - cc::attention( "sync job" ) ); + skutils::test::test_log_e( thread_prefix_str() + "will invoke sync job"); pQueueSync->job_run_sync( [&]() { BOOST_REQUIRE( !bool( bInsideCallSync ) ); bInsideCallSync = true; ++nCallCounterSync; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::attention( "sync job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterSync ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- sync job, invocation " + + std::to_string(size_t( nCallCounterSync ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallSync ) ); bInsideCallSync = false; } ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "did invoked " ) + - cc::attention( "sync job" ) ); + skutils::test::test_log_e(thread_prefix_str() + "did invoked sync job" ); // BOOST_REQUIRE( bool( bInsideCallAsync ) ); bInsideCallAsync = false; @@ -598,13 +541,13 @@ BOOST_AUTO_TEST_CASE( domain_timing_functionality_alive ) { static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string(nWaitRound+1) + + " of " + std::to_string(nWaitRoundCount) + + ", will sleep " + std::to_string(nSleepSeconds) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string(nSleepSeconds) + + " second(s), end of domain life time..." ); if( size_t( nCallCounterOnce ) >= 1 && size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) @@ -615,36 +558,36 @@ BOOST_AUTO_TEST_CASE( domain_timing_functionality_alive ) { // // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down domain..." ) ); + thread_prefix_str() + "shutting down domain..." ); pDomain->shutdown(); } // block for domain skutils::test::test_log_e( - cc::notice( "once job" ) + cc::debug( " expected exactly one call" ) + - cc::debug( ", was called " ) + cc::size10( size_t( nCallCounterOnce ) ) + - cc::debug( ", " ) + - ( ( size_t( nCallCounterOnce ) == 1 ) ? cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "once job expected exactly one call, was called " + + std::to_string( size_t( nCallCounterOnce ) ) + + ", " + + ( ( size_t( nCallCounterOnce ) == 1 ) ? "success" : + "fail")); skutils::test::test_log_e( - cc::warn( "periodic job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterPeriodicExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterPeriodic ) ) + cc::debug( ", " ) + + "periodic job expected call(s) at least " + + std::to_string( size_t( nCallCounterPeriodicExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterPeriodic ) ) + ", " + ( ( size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail") ); skutils::test::test_log_e( - cc::note( "async job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterAsyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterAsync ) ) + cc::debug( ", " ) + + "async job expected call(s) at least " + + std::to_string( size_t( nCallCounterAsyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterAsync ) ) + ", " + ( ( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); skutils::test::test_log_e( - cc::attention( "sync job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterSyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterSync ) ) + cc::debug( ", " ) + + "sync job expected call(s) at least " + + std::to_string( size_t( nCallCounterSyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterSync ) ) + ", " + ( ( size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); BOOST_REQUIRE( size_t( nCallCounterOnce ) == 1 ); BOOST_REQUIRE( size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) ); BOOST_REQUIRE( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ); @@ -652,7 +595,7 @@ BOOST_AUTO_TEST_CASE( domain_timing_functionality_alive ) { BOOST_REQUIRE( size_t( nCallCounterSync ) == size_t( nCallCounterAsync ) ); // skutils::test::test_log_e( - thread_prefix_str() + cc::info( "end of domain timing functionality test" ) ); + thread_prefix_str() + "end of domain timing functionality test" ); } ); } @@ -682,64 +625,53 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // // skutils::dispatch::add( sync_queue_id ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::notice( "once job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding once job to queue" ); skutils::dispatch::once( skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallOnce ) ); bInsideCallOnce = true; ++nCallCounterOnce; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::notice( "once job" ) + cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterOnce ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- once job, invocation " + + std::to_string( size_t( nCallCounterOnce ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallOnce ) ); bInsideCallOnce = false; }, skutils::dispatch::duration_from_seconds( 1 ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::warn( "periodic job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding periodic job to queue" ); skutils::dispatch::repeat( skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallPeriodic ) ); bInsideCallPeriodic = true; ++nCallCounterPeriodic; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::warn( "periodic job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterPeriodic ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- periodic job, invocation " + + std::to_string( size_t( nCallCounterPeriodic ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallPeriodic ) ); bInsideCallPeriodic = false; }, skutils::dispatch::duration_from_milliseconds( 500 ) // 0.5 seconds ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::note( "async job" ) + cc::debug( " to queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding async job to queue" ); skutils::dispatch::async( skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallAsync ) ); bInsideCallAsync = true; ++nCallCounterAsync; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::note( "async job" ) + cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterAsync ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- async job, invocation " + + std::to_string( size_t( nCallCounterAsync ) - 1 ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "will invoke " ) + - cc::attention( "sync job" ) ); + skutils::test::test_log_e( thread_prefix_str() + "will invoke sync job" ); skutils::dispatch::sync( sync_queue_id, [&]() { BOOST_REQUIRE( !bool( bInsideCallSync ) ); bInsideCallSync = true; ++nCallCounterSync; - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + - cc::attention( "sync job" ) + - cc::debug( ", invocation " ) + - cc::size10( size_t( nCallCounterSync ) - 1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- sync job, invocation " + + std::to_string( size_t( nCallCounterSync ) - 1 ) ); BOOST_REQUIRE( bool( bInsideCallSync ) ); bInsideCallSync = false; } ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "did invoked " ) + - cc::attention( "sync job" ) ); + skutils::test::test_log_e( thread_prefix_str() + "did invoked sync job" ); // BOOST_REQUIRE( bool( bInsideCallAsync ) ); bInsideCallAsync = false; @@ -752,13 +684,13 @@ BOOST_AUTO_TEST_CASE( simple_api ) { static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string( nWaitRound+1 ) + + " of " + std::to_string( nWaitRoundCount ) + + ", will sleep " + std::to_string( nSleepSeconds ) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string( nSleepSeconds ) + + " second(s), end of domain life time..." ); if( size_t( nCallCounterOnce ) == 1 && size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) @@ -769,44 +701,43 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down default domain..." ) ); + thread_prefix_str() + "shutting down default domain..." ); skutils::dispatch::shutdown(); // // skutils::test::test_log_e( - cc::notice( "once job" ) + cc::debug( " expected exactly one call" ) + - cc::debug( ", was called " ) + cc::size10( size_t( nCallCounterOnce ) ) + - cc::debug( ", " ) + - ( ( size_t( nCallCounterOnce ) == 1 ) ? cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "once job expected exactly one call, was called " + + std::to_string( size_t( nCallCounterOnce ) ) + + ", " + ( ( size_t( nCallCounterOnce ) == 1 ) ? "success" : + "fail" ) ); skutils::test::test_log_e( - cc::warn( "periodic job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterPeriodicExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterPeriodic ) ) + cc::debug( ", " ) + + "periodic job expected call(s) at least " + + std::to_string( size_t( nCallCounterPeriodicExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterPeriodic ) ) + ", " + ( ( size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); skutils::test::test_log_e( - cc::note( "async job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterAsyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterAsync ) ) + cc::debug( ", " ) + + "async job expected call(s) at least " + + std::to_string( size_t( nCallCounterAsyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterAsync ) ) + ", " + ( ( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); skutils::test::test_log_e( - cc::attention( "sync job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterSyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterSync ) ) + cc::debug( ", " ) + + "sync job expected call(s) at least " + + std::to_string( size_t( nCallCounterSyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterSync ) ) + ", " + ( ( size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); BOOST_REQUIRE( size_t( nCallCounterOnce ) == 1 ); BOOST_REQUIRE( size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) ); BOOST_REQUIRE( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ); BOOST_REQUIRE( size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ); BOOST_REQUIRE( size_t( nCallCounterSync ) == size_t( nCallCounterAsync ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::info( "end of simple API test" ) ); + skutils::test::test_log_e( thread_prefix_str() + "end of simple API test" ); } ); } @@ -827,28 +758,26 @@ BOOST_AUTO_TEST_CASE( auto_queues ) { // // skutils::dispatch::add( sync_queue_id ); // - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + - cc::note( "async periodical job" ) + - cc::debug( " to auto queue" ) ); + skutils::test::test_log_e( thread_prefix_str() + "adding async periodical job to auto queue" ); skutils::dispatch::job_id_t async_job_id0; skutils::dispatch::job_id_t async_job_id1; skutils::dispatch::job_id_t async_job_id2; auto fn = [&]() { ++nCallCounterAsync; skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "--- " ) + cc::note( "async periodical job" ) + - cc::debug( ", invocation " ) + cc::size10( size_t( nCallCounterAsync ) - 1 ) ); + thread_prefix_str() + "--- async periodical job, invocation " + + std::to_string( size_t( nCallCounterAsync ) - 1 ) ); // skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "will invoke " ) + cc::attention( "sync job" ) ); + thread_prefix_str() + "will invoke " + "sync job" ); skutils::dispatch::sync( sync_queue_id, [&]() { ++nCallCounterSync; skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "--- " ) + cc::attention( "sync job" ) + - cc::debug( ", invocation " ) + cc::size10( size_t( nCallCounterSync ) - 1 ) ); + thread_prefix_str() + "--- sync job" + + ", invocation " + std::to_string( size_t( nCallCounterSync ) - 1 ) ); } ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "did invoked " ) + cc::attention( "sync job" ) ); + thread_prefix_str() + "did invoked sync job" ); // }; skutils::dispatch::async( fn, @@ -856,40 +785,33 @@ BOOST_AUTO_TEST_CASE( auto_queues ) { skutils::dispatch::duration_from_milliseconds( 1500 ), // 1.5 seconds &async_job_id0 ); BOOST_REQUIRE( !async_job_id0.empty() ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "done, did added " ) + - cc::note( "async periodical job" ) + - cc::debug( " to auto queue, job id is " ) + - cc::bright( async_job_id0 ) ); + skutils::test::test_log_e( thread_prefix_str() + "done, did added async periodical job to auto queue, job id is " + + async_job_id0 ); skutils::dispatch::async( fn, skutils::dispatch::duration_from_seconds( 2 ), // 2 seconds skutils::dispatch::duration_from_milliseconds( 1500 ), // 1.5 seconds &async_job_id1 ); BOOST_REQUIRE( !async_job_id1.empty() ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "done, did added " ) + - cc::note( "async periodical job" ) + - cc::debug( " to auto queue, job id is " ) + - cc::bright( async_job_id1 ) ); + skutils::test::test_log_e( thread_prefix_str() + "done, did added async periodical job to auto queue, job id is " + + async_job_id1 ); skutils::dispatch::async( fn, skutils::dispatch::duration_from_seconds( 2 ), // 2 seconds skutils::dispatch::duration_from_milliseconds( 1500 ), // 1.5 seconds &async_job_id2 ); BOOST_REQUIRE( !async_job_id2.empty() ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "done, did added " ) + - cc::note( "async periodical job" ) + - cc::debug( " to auto queue, job id is " ) + - cc::bright( async_job_id2 ) ); + skutils::test::test_log_e( thread_prefix_str() + "done, did added async periodical job to auto queue, job id is " + async_job_id2 ); // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string( nWaitRound+1 ) + + " of " + std::to_string( nWaitRoundCount ) + + ", will sleep " + std::to_string( nSleepSeconds ) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string( nSleepSeconds ) + + " second(s), end of domain life time..." ); if( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) && size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) @@ -900,17 +822,16 @@ BOOST_AUTO_TEST_CASE( auto_queues ) { } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // - skutils::test::test_log_e( thread_prefix_str() + - cc::warn( "stopping async periodical job " ) + - cc::bright( async_job_id0 ) + cc::debug( "..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "stopping async periodical job " + + async_job_id0 + "..."); skutils::dispatch::stop( async_job_id0 ); skutils::test::test_log_e( thread_prefix_str() + - cc::warn( "stopping async periodical job " ) + - cc::bright( async_job_id1 ) + cc::debug( "..." ) ); + "stopping async periodical job " + + async_job_id1 + "..." ); skutils::dispatch::stop( async_job_id1 ); skutils::test::test_log_e( thread_prefix_str() + - cc::warn( "stopping async periodical job " ) + - cc::bright( async_job_id2 ) + cc::debug( "..." ) ); + "stopping async periodical job " + + async_job_id2 + "..." ); skutils::dispatch::stop( async_job_id2 ); // skutils::dispatch::set_queue_ids_t setQueueIDs; @@ -923,28 +844,28 @@ BOOST_AUTO_TEST_CASE( auto_queues ) { BOOST_REQUIRE( setQueueIDs.size() == 0 ); // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down default domain..." ) ); + thread_prefix_str() + "shutting down default domain..." ); skutils::dispatch::shutdown(); // skutils::test::test_log_e( - cc::note( "async job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterAsyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterAsync ) ) + cc::debug( ", " ) + + "async job expected call(s) at least " + + std::to_string( size_t( nCallCounterAsyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterAsync ) ) + ", " + ( ( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); skutils::test::test_log_e( - cc::attention( "sync job" ) + cc::debug( " expected call(s) at least " ) + - cc::size10( size_t( nCallCounterSyncExpected ) ) + cc::debug( ", was called " ) + - cc::size10( size_t( nCallCounterSync ) ) + cc::debug( ", " ) + + "sync job expected call(s) at least " + + std::to_string( size_t( nCallCounterSyncExpected ) ) + ", was called " + + std::to_string( size_t( nCallCounterSync ) ) + ", " + ( ( size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ) ? - cc::success( "success" ) : - cc::fatal( "fail" ) ) ); + "success" : + "fail" ) ); BOOST_REQUIRE( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) ); BOOST_REQUIRE( size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ); BOOST_REQUIRE( size_t( nCallCounterSync ) >= size_t( nCallCounterAsync ) ); // - skutils::test::test_log_e( thread_prefix_str() + cc::info( "end of auto_queues test" ) ); + skutils::test::test_log_e( thread_prefix_str() + "end of auto_queues test" ); } ); } @@ -972,8 +893,8 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { skutils::dispatch::queue_id_t id_queue_next = skutils::tools::format( "queue_%zu", j ); if ( g_bShowDetailedJobLogs ) skutils::test::test_log_e( thread_prefix_str() + - cc::debug( "...will add async job to queue " ) + - cc::bright( id_queue_current ) + cc::debug( "..." ) ); + "...will add async job to queue " + + id_queue_current + "..." ); skutils::dispatch::async( id_queue_current, [&vecInside, &vecCallCount, i, j, id_queue_current, id_queue_next]() { BOOST_REQUIRE( !bool( vecInside[i] ) ); @@ -982,9 +903,9 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { vecCallCount[i]++; if ( i != 0 ) { // condition to avoid chained lock skutils::test::test_log_e( - thread_prefix_str() + cc::ws_tx( "-->" ) + cc::debug( " worker " ) + - cc::bright( id_queue_current ) + cc::debug( " will invoke " ) + - cc::bright( id_queue_next ) ); + thread_prefix_str() + "--> worker " + + id_queue_current + " will invoke " + + id_queue_next ); skutils::dispatch::sync( id_queue_next, [&vecInside, &vecCallCount, i, j, id_queue_current, id_queue_next]() { BOOST_REQUIRE( !bool( vecInside[j] ) ); @@ -992,22 +913,22 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { BOOST_REQUIRE( bool( vecInside[j] ) ); vecCallCount[j]++; skutils::test::test_log_e( - thread_prefix_str() + cc::ws_rx( "<--" ) + cc::debug( " worker " ) + - cc::bright( id_queue_next ) + cc::debug( " invoked from " ) + - cc::bright( id_queue_current ) ); + thread_prefix_str() + "<-- worker " + + id_queue_next + " invoked from " + + id_queue_current ); BOOST_REQUIRE( bool( vecInside[j] ) ); vecInside[j] = false; BOOST_REQUIRE( !bool( vecInside[j] ) ); } ); } else { skutils::test::test_log_e( - thread_prefix_str() + cc::ws_tx( "-->" ) + cc::debug( " worker " ) + - cc::bright( id_queue_current ) + cc::debug( " will invoke " ) + - cc::bright( id_queue_next ) + cc::warn( "(emulation)" ) ); + thread_prefix_str() + "--> worker " + + id_queue_current + " will invoke " + + id_queue_next + "(emulation)" ); skutils::test::test_log_e( - thread_prefix_str() + cc::ws_rx( "<--" ) + cc::debug( " worker " ) + - cc::bright( id_queue_next ) + cc::debug( " invoked from " ) + - cc::bright( id_queue_current ) + cc::warn( "(emulation)" ) ); + thread_prefix_str() + "<-- worker " + + id_queue_next + " invoked from " + + id_queue_current + "(emulation)" ); vecCallCount[j]++; // invocation emilation } BOOST_REQUIRE( bool( vecInside[i] ) ); @@ -1021,25 +942,25 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string( nWaitRound+1 ) + + " of " + std::to_string( nWaitRoundCount ) + + ", will sleep " + std::to_string( nSleepSeconds ) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string( nSleepSeconds ) + + " second(s), end of domain life time..." ); // // // pre-liminary attempt to find out everything is OKay skutils::test::test_log_e( - thread_prefix_str() + cc::info( "performing preliminary state test..." ) ); + thread_prefix_str() + "performing preliminary state test..." ); isEverythingOKay = true; // assume good thing for ( i = 0; i < nQueueCount; ++i ) { bool bInside = bool( vecInside[i] ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "queue " ) + cc::size10( i ) + - cc::debug( " is " ) + - ( ( !bInside ) ? cc::success( "OKay" ) : cc::fatal( "STILL WORKING - FAIL" ) ) ); + thread_prefix_str() + "queue " + std::to_string( i ) + + " is " + + ( ( !bInside ) ? "OKay" : "STILL WORKING - FAIL" ) ); if ( bInside ) { isEverythingOKay = false; break; @@ -1051,15 +972,15 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { size_t nQueueJobCount = pQueue->async_job_count(); // BOOST_REQUIRE( nQueueJobCount == 0 ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "worker " ) + cc::bright( id_queue_current ) + - cc::debug( " has " ) + cc::size10( nQueueJobCount ) + - cc::debug( " job(s) unfinished " ) + - ( ( nQueueJobCount == 0 ) ? cc::success( "OKay" ) : - cc::fatal( "FAIL, MUST BE ZERO" ) ) ); + thread_prefix_str() + "worker " + id_queue_current + + " has " + std::to_string( nQueueJobCount ) + + " job(s) unfinished " + + ( ( nQueueJobCount == 0 ) ? "OKay" : + "FAIL, MUST BE ZERO" ) ); } skutils::test::test_log_e( - thread_prefix_str() + cc::info( "done preliminary state test - " ) + - ( isEverythingOKay ? cc::success( "PASSED" ) : cc::fatal( "FAILED" ) ) ); + thread_prefix_str() + "done preliminary state test - " + + ( isEverythingOKay ? "PASSED" : "FAILED" ) ); if( isEverythingOKay ) break; } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) @@ -1067,25 +988,25 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { // if ( !isEverythingOKay ) { static const size_t nSleepSecondsExtraAttempt = 10; - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "will sleep additional " ) + - cc::size10( nSleepSecondsExtraAttempt ) + - cc::warn( " second(s)..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "will sleep additional " + + std::to_string( nSleepSecondsExtraAttempt ) + + " second(s)..." ); sleep( nSleepSecondsExtraAttempt ); skutils::test::test_log_e( thread_prefix_str() + - cc::warn( "done sleeping additional " ) + - cc::size10( nSleepSecondsExtraAttempt ) + - cc::warn( " second(s), end of domain life time..." ) ); + "done sleeping additional " + + std::to_string( nSleepSecondsExtraAttempt ) + + " second(s), end of domain life time..." ); } // // final test skutils::test::test_log_e( - thread_prefix_str() + cc::info( "performing final state test..." ) ); + thread_prefix_str() + "performing final state test..." ); for ( i = 0; i < nQueueCount; ++i ) { bool bInside = bool( vecInside[i] ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "queue " ) + cc::size10( i ) + - cc::debug( " is " ) + - ( ( !bInside ) ? cc::success( "OKay" ) : cc::fatal( "STILL WORKING - FAIL" ) ) ); + thread_prefix_str() + "queue " + std::to_string( i ) + + " is " + + ( ( !bInside ) ? "OKay" : "STILL WORKING - FAIL") ); BOOST_REQUIRE( !bInside ); skutils::dispatch::queue_id_t id_queue_current = skutils::tools::format( "queue_%zu", i ); @@ -1094,17 +1015,16 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { size_t nQueueJobCount = pQueue->async_job_count(); // BOOST_REQUIRE( nQueueJobCount == 0 ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "worker " ) + cc::bright( id_queue_current ) + - cc::debug( " has " ) + cc::size10( nQueueJobCount ) + - cc::debug( " job(s) unfinished " ) + - ( ( nQueueJobCount == 0 ) ? cc::success( "OKay" ) : - cc::fatal( "FAIL, MUST BE ZERO" ) ) ); + thread_prefix_str() + "worker " + id_queue_current + + " has " + std::to_string( nQueueJobCount ) + + " job(s) unfinished " + + ( ( nQueueJobCount == 0 ) ? "OKay" : + "FAIL, MUST BE ZERO" ) ); } - skutils::test::test_log_e( thread_prefix_str() + cc::info( "done final state test - " + - cc::success( "PASSED" ) ) ); + skutils::test::test_log_e( thread_prefix_str() + "done final state test - PASSED" ); // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down default domain..." ) ); + thread_prefix_str() + "shutting down default domain..." ); skutils::dispatch::shutdown(); // for ( i = 0; i < nQueueCount; ++i ) { @@ -1112,9 +1032,9 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { skutils::dispatch::queue_id_t id_queue_current = skutils::tools::format( "queue_%zu", i ); skutils::test::test_log_e( - thread_prefix_str() + cc::attention( "worker " ) + cc::bright( id_queue_current ) + - cc::attention( " was invoked " ) + cc::size10( vecCallCount[i] ) + - cc::attention( " time(s)" ) ); + thread_prefix_str() + "worker " + id_queue_current + + " was invoked " + std::to_string( vecCallCount[i] ) + + " time(s)" ); } size_t nCallCountFirst = vecCallCount.front(); BOOST_REQUIRE( nCallCountFirst > 0 ); @@ -1123,7 +1043,7 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { BOOST_REQUIRE( vecCallCount[i] == nCallCountFirst ); } // - skutils::test::test_log_e( thread_prefix_str() + cc::info( "end of cross_jobs test" ) ); + skutils::test::test_log_e( thread_prefix_str() + "end of cross_jobs test" ); } ); } @@ -1142,7 +1062,7 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { auto fnLog = [&]( const char* s ) -> void { lock_type lock( mtx ); log_sequence.push_back( s ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + cc::info( s ) ); + skutils::test::test_log_e( thread_prefix_str() + "--- " + s ); }; auto fnLogSequenceSize = [&]( ) -> size_t { lock_type lock( mtx ); @@ -1270,10 +1190,10 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { BOOST_REQUIRE( !bool( bInside_ShortWork_2 ) ); BOOST_REQUIRE( !bool( bInside_SyncWork ) ); } ); - skutils::test::test_log_e( thread_prefix_str() + cc::debug( "awaiting 500 milliseconds" ) ); + skutils::test::test_log_e( thread_prefix_str() + "awaiting 500 milliseconds" ); std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "done, finished awaiting 500 milliseconds" ) ); + thread_prefix_str() + "done, finished awaiting 500 milliseconds" ); skutils::dispatch::sync( id_my_queue, [&]() { BOOST_REQUIRE( !bool( bInside_LengthyWork ) ); BOOST_REQUIRE( !bool( bInside_ShortWork_0 ) ); @@ -1306,13 +1226,13 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + + "waiting for test to complete in round " + std::to_string( nWaitRound+1 ) + + " of " + std::to_string( nWaitRoundCount ) + + ", will sleep " + std::to_string( nSleepSeconds ) + " second(s)..." ); sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); + skutils::test::test_log_e( thread_prefix_str() + "done sleeping " + + std::to_string( nSleepSeconds ) + + " second(s), end of domain life time..." ); size_t n = fnLogSequenceSize(); if( n >= 10 ) break; @@ -1320,12 +1240,12 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { // // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "shutting down default domain..." ) ); + thread_prefix_str() + "shutting down default domain..." ); skutils::dispatch::shutdown(); // // skutils::test::test_log_e( - thread_prefix_str() + cc::warn( "analyzing expected results..." ) ); + thread_prefix_str() + "analyzing expected results..." ); BOOST_REQUIRE( log_sequence.size() >= 10 ); BOOST_REQUIRE( log_sequence[0] == g_strLogText_LengthyWork_begin ); BOOST_REQUIRE( log_sequence[1] == g_strLogText_LengthyWork_end ); @@ -1339,7 +1259,7 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { BOOST_REQUIRE( log_sequence[9] == g_strLogText_ShortWork_2_end ); // skutils::test::test_log_e( - thread_prefix_str() + cc::info( "end of enqueue_while_busy test" ) ); + thread_prefix_str() + "end of enqueue_while_busy test"); } ); } diff --git a/test/unittests/libskutils/test_skutils_helper.cpp b/test/unittests/libskutils/test_skutils_helper.cpp index df1737a5c..18ef11841 100644 --- a/test/unittests/libskutils/test_skutils_helper.cpp +++ b/test/unittests/libskutils/test_skutils_helper.cpp @@ -41,7 +41,7 @@ std::string test_log_prefix_reformat( if ( i == 0 && isInsertTime ) { strResult += cc::time2string( cc::default_clock_t::now(), false ); strResult += " "; - strResult += cc::debug( "N/A" ); // instead of message class + strResult += "N/A"; // instead of message class strResult += ": "; } strResult += ( *itWalk ); @@ -82,119 +82,119 @@ std::string test_log_caption( const std::string& strPrefix, const char* strSuffi void test_log_e( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::debug( test_log_caption( nullptr, nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( nullptr, nullptr ) + " ", strMessage ) ); } // test environment log void test_log_ew( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( nullptr, "W" ) ) + " ", strMessage ) ); + true, test_log_caption( nullptr, "W" ) + " ", strMessage ) ); } // test environment warning log void test_log_ee( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( nullptr, "E" ) ) + " ", strMessage ) ); + true, test_log_caption( nullptr, "E" ) + " ", strMessage ) ); } // test environment error log void test_log_ef( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( nullptr, "F" ) ) + " ", strMessage ) ); + true, test_log_caption( nullptr, "F" ) + " ", strMessage ) ); } // test environment fatal log void test_log_s( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::attention( test_log_caption( "SERVER", nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( "SERVER", nullptr ) + " ", strMessage ) ); } // server-side log void test_log_ss( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::attention( test_log_caption( "SERVER", "N" ) ) + " ", strMessage ) ); + true, test_log_caption( "SERVER", "N" ) + " ", strMessage ) ); } // server-side web socket log void test_log_sw( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( "SERVER", "W" ) ) + " ", strMessage ) ); + true, test_log_caption( "SERVER", "W" ) + " ", strMessage ) ); } // server-side warning log void test_log_se( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( "SERVER", "E" ) ) + " ", strMessage ) ); + true, test_log_caption( "SERVER", "E" ) + " ", strMessage ) ); } // server-side error log void test_log_sf( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( "SERVER", "F" ) ) + " ", strMessage ) ); + true, test_log_caption( "SERVER", "F" ) + " ", strMessage ) ); } // server-side fatal log void test_log_c( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::bright( test_log_caption( "CLIENT", nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( "CLIENT", nullptr ) + " ", strMessage ) ); } // client-side log void test_log_c( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::bright( test_log_caption( strClient, nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, nullptr ) + " ", strMessage ) ); } // client-side log void test_log_cs( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::bright( test_log_caption( "CLIENT", "N" ) ) + " ", strMessage ) ); + true, test_log_caption( "CLIENT", "N" ) + " ", strMessage ) ); } // client-side web socket log void test_log_cs( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::bright( test_log_caption( strClient, "N" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "N" ) + " ", strMessage ) ); } // client-side web socket log void test_log_cw( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( "CLIENT", "W" ) ) + " ", strMessage ) ); + true, test_log_caption( "CLIENT", "W" ) + " ", strMessage ) ); } // client-side warning log void test_log_cw( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( strClient, "W" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "W" ) + " ", strMessage ) ); } // client-side warning log void test_log_ce( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( "CLIENT", "E" ) ) + " ", strMessage ) ); + true, test_log_caption( "CLIENT", "E" ) + " ", strMessage ) ); } // client-side error log void test_log_ce( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( strClient, "E" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "E" ) + " ", strMessage ) ); } // client-side error log void test_log_cf( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( "CLIENT", "F" ) ) + " ", strMessage ) ); + true, test_log_caption( "CLIENT", "F" ) + " ", strMessage ) ); } // client-side fatal log void test_log_cf( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( strClient, "F" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "F" ) + " ", strMessage ) ); } // client-side fatal log void test_log_p( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::sunny( test_log_caption( "PEER", nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( "PEER", nullptr ) + " ", strMessage ) ); } // peer-side log void test_log_p( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::sunny( test_log_caption( strClient, nullptr ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, nullptr ) + " ", strMessage ) ); } // peer-side log void test_log_ps( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::sunny( test_log_caption( "PEER", "N" ) ) + " ", strMessage ) ); + true, test_log_caption( "PEER", "N" ) + " ", strMessage ) ); } // peer-side web socket log void test_log_ps( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::sunny( test_log_caption( strClient, "N" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "N" ) + " ", strMessage ) ); } // peer-side web socket log void test_log_pw( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( "PEER", "W" ) ) + " ", strMessage ) ); + true, test_log_caption( "PEER", "W" ) + " ", strMessage ) ); } // peer-side warning log void test_log_pw( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::warn( test_log_caption( strClient, "W" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "W" ) + " ", strMessage ) ); } // peer-side warning log void test_log_pe( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( "PEER", "E" ) ) + " ", strMessage ) ); + true, test_log_caption( "PEER", "E" ) + " ", strMessage ) ); } // peer-side error log void test_log_pe( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::error( test_log_caption( strClient, "E" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "E" ) + " ", strMessage ) ); } // peer-side error log void test_log_pf( const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( "PEER", "F" ) ) + " ", strMessage ) ); + true, test_log_caption( "PEER", "F" ) + " ", strMessage ) ); } // peer-side fatal log void test_log_pf( const std::string& strClient, const std::string& strMessage ) { test_log_output( test_log_prefix_reformat( - true, cc::fatal( test_log_caption( strClient, "F" ) ) + " ", strMessage ) ); + true, test_log_caption( strClient, "F" ) + " ", strMessage ) ); } // peer-side fatal log ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -254,8 +254,7 @@ test_ssl_cert_and_key_holder::test_ssl_cert_and_key_holder() { strFilePathKey_ = strPrefix + ".key.pem"; strFilePathCert_ = strPrefix + ".cert.pem"; // - test_log_e( cc::debug( "Will create " ) + cc::p( strFilePathKey_ ) + cc::debug( " and " ) + - cc::p( strFilePathCert_ ) + cc::debug( "..." ) ); + test_log_e( "Will create " + strFilePathKey_ + " and " + strFilePathCert_ + "..." ); std::string strCmd; strCmd += "openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj " @@ -271,8 +270,8 @@ test_ssl_cert_and_key_holder::test_ssl_cert_and_key_holder() { test_log_ee( g_err_msg ); throw std::runtime_error( g_err_msg ); } - test_log_s( cc::success( "OKay created " ) + cc::p( strFilePathKey_ ) + cc::success( " and " ) + - cc::p( strFilePathCert_ ) + cc::success( "." ) ); + test_log_s( "OKay created " + strFilePathKey_ + " and " + + strFilePathCert_ + "." ); } test_ssl_cert_and_key_holder::~test_ssl_cert_and_key_holder() { if ( !strFilePathKey_.empty() ) { @@ -312,16 +311,16 @@ void test_server::run_parallel() { check_can_listen(); std::thread( [&]() -> void { thread_is_running_ = true; - test_log_s( cc::info( strScheme_ ) + cc::debug( " network server thread started" ) ); + test_log_s( strScheme_ + " network server thread started" ); run(); - test_log_s( cc::info( strScheme_ ) + cc::debug( " network server thread will exit" ) ); + test_log_s( strScheme_ + " network server thread will exit" ); thread_is_running_ = false; } ) .detach(); while ( !thread_is_running_ ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); test_log_s( - cc::debug( "Letting " ) + cc::info( strScheme_ ) + cc::debug( " network server init..." ) ); + "Letting " + strScheme_ + " network server init..." ); std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); } @@ -332,9 +331,9 @@ void test_server::wait_parallel() { void test_server::stat_check_port_availability_to_start_listen( int ipVer, const char* strAddr, int nPort, const char* strScheme ) { - test_log_s( cc::debug( "Will check port " ) + cc::num10( nPort ) + - cc::debug( "/IPv" + std::to_string( ipVer ) ) + cc::debug( " availability for " ) + - cc::info( strScheme ) + cc::debug( " server..." ) ); + test_log_s( "Will check port " + std::to_string(nPort) + + "/IPv" + std::to_string( ipVer ) + " availability for " + + strScheme + " server..." ); skutils::network::sockaddr46 sa46; std::string strError = skutils::network::resolve_address_for_client_connection( ipVer, strAddr, sa46 ); @@ -352,9 +351,9 @@ void test_server::stat_check_port_availability_to_start_listen( std::string( "\", port " ) + std::to_string( nPort ) + std::string( ", IPv" ) + std::to_string( ipVer ) + std::string( " - port is already listening" ) ); - test_log_s( cc::notice( "Port " ) + cc::num10( nPort ) + - cc::notice( "/IPv" + std::to_string( ipVer ) ) + cc::notice( " is free for " ) + - cc::info( strScheme ) + cc::notice( " server to start" ) ); + test_log_s( "Port " + std::to_string(nPort) + + "/IPv" + std::to_string( ipVer ) + " is free for " + + strScheme + " server to start" ); } void test_server::check_can_listen() { @@ -369,19 +368,19 @@ void test_server::check_can_listen() { test_ws_peer::test_ws_peer( skutils::ws::server& srv, const skutils::ws::hdl_t& hdl ) : skutils::ws::peer( srv, hdl ) { strPeerQueueID_ = skutils::dispatch::generate_id( this, "relay_peer" ); - test_log_p( desc() + cc::notice( " peer ctor" ) ); + test_log_p( desc() + " peer ctor" ); } test_ws_peer::~test_ws_peer() { - test_log_p( desc() + cc::notice( " peer dtor" ) ); + test_log_p( desc() + " peer dtor" ); skutils::dispatch::remove( strPeerQueueID_ ); } void test_ws_peer::onPeerRegister() { - test_log_p( desc() + cc::notice( " peer registered" ) ); + test_log_p( desc() + " peer registered" ); skutils::ws::peer::onPeerRegister(); } void test_ws_peer::onPeerUnregister() { // peer will no longer receive onMessage after call to this - test_log_p( desc() + cc::notice( " peer unregistered" ) ); + test_log_p( desc() + " peer unregistered" ); skutils::ws::peer::onPeerUnregister(); } @@ -390,16 +389,16 @@ void test_ws_peer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode throw std::runtime_error( "only ws text messages are supported" ); skutils::dispatch::async( strPeerQueueID_, [=]() -> void { test_log_p( - cc::ws_rx_inv( ">>> " + std::string( get_test_server().strSchemeUC_ ) + "-RX >>> " ) + - desc() + cc::ws_rx( " >>> " ) + cc::j( msg ) ); + ">>> " + std::string( get_test_server().strSchemeUC_ ) + "-RX >>> " + + desc() + " >>> " + msg ); // // std::string strResult = msg; // // test_log_p( - cc::ws_tx_inv( "<<< " + std::string( get_test_server().strSchemeUC_ ) + "-TX <<< " ) + - desc() + cc::ws_tx( " <<< " ) + cc::j( strResult ) ); + "<<< " + std::string( get_test_server().strSchemeUC_ ) + "-TX <<< " + + desc() + " <<< " + strResult ); sendMessage( strResult ); } ); skutils::ws::peer::onMessage( msg, eOpCode ); @@ -407,19 +406,19 @@ void test_ws_peer::onMessage( const std::string& msg, skutils::ws::opcv eOpCode void test_ws_peer::onClose( const std::string& reason, int local_close_code, const std::string& local_close_code_as_str ) { - test_log_p( desc() + cc::warn( " peer close event with code=" ) + cc::c( local_close_code ) + - cc::debug( ", reason=" ) + cc::info( reason ) ); + test_log_p( desc() + " peer close event with code=" + std::to_string(local_close_code) + + ", reason=" + reason ); skutils::ws::peer::onClose( reason, local_close_code, local_close_code_as_str ); } void test_ws_peer::onFail() { - test_log_p( desc() + cc::error( " peer fail event" ) ); + test_log_p( desc() + " peer fail event" ); skutils::ws::peer::onFail(); } void test_ws_peer::onLogMessage( skutils::ws::e_ws_log_message_type_t eWSLMT, const std::string& msg ) { - test_log_p( desc() + cc::debug( " peer log: " ) + msg ); + test_log_p( desc() + " peer log: " + msg ); skutils::ws::peer::onLogMessage( eWSLMT, msg ); } @@ -434,15 +433,15 @@ test_server_ws_base::test_server_ws_base( const char* strScheme, int nListenPort : test_server( strScheme, nListenPort ) { onPeerInstantiate_ = [&]( skutils::ws::server& srv, skutils::ws::hdl_t hdl ) -> skutils::ws::peer_ptr_t { - test_log_s( cc::info( strScheme_ ) + cc::debug( " server will instantiate new peer" ) ); + test_log_s( strScheme_ + " server will instantiate new peer" ); return new test_ws_peer( srv, hdl ); }; // onPeerRegister_ = // onPeerUnregister_ = } test_server_ws_base::~test_server_ws_base() { - test_log_s( cc::debug( "Will close " ) + cc::info( strScheme_ ) + - cc::debug( " server, was running on port " ) + cc::c( nListenPort_ ) ); + test_log_s( "Will close " + strScheme_ + + " server, was running on port " + std::to_string(nListenPort_) ); stop(); } @@ -457,8 +456,8 @@ void test_server_ws_base::stop() { } void test_server_ws_base::run() { - test_log_s( cc::debug( "Will start server on port " ) + cc::c( nListenPort_ ) + - cc::debug( " using " ) + cc::info( strScheme_ ) + cc::debug( " scheme" ) ); + test_log_s( "Will start server on port " + std::to_string(nListenPort_) + + " using " + strScheme_ + " scheme" ); std::atomic_bool bServerOpenComplete( false ); std::thread( [&]() { ws_server_thread_is_running_ = true; @@ -468,16 +467,16 @@ void test_server_ws_base::run() { strPrivateKeyFile_ = ssl_info.strFilePathKey_; } BOOST_REQUIRE( open( strScheme_.c_str(), nListenPort_ ) ); - test_log_s( cc::sunny( "Server opened" ) ); + test_log_s( "Server opened" ); bServerOpenComplete = true; if ( service_mode_supported() ) { test_log_s( - cc::info( "Main loop" ) + cc::debug( " will run in poll in service mode" ) ); + "Main loop will run in poll in service mode" ); service( [&]() -> bool { return ( !/*skutils::signal::g_bStop*/ bStopFlag_ ) ? true : false; } ); } else { - test_log_s( cc::info( "Main loop" ) + cc::debug( " will run in poll/reset mode" ) ); + test_log_s( "Main loop will run in poll/reset mode" ); for ( ; !bStopFlag_; ) { poll( [&]() -> bool { return ( !bStopFlag_ ) ? true : false; } ); if ( bStopFlag_ ) @@ -485,15 +484,14 @@ void test_server_ws_base::run() { reset(); } // for( ; ! bStopFlag_; ) } - test_log_s( cc::info( "Main loop" ) + cc::debug( " finish" ) ); + test_log_s( "Main loop finish" ); ws_server_thread_is_running_ = false; } ) .detach(); - test_log_s( cc::debug( "Waiting for " ) + cc::note( "test server" ) + cc::debug( " open..." ) ); + test_log_s( "Waiting for test server open..." ); while ( !bServerOpenComplete ) std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) ); - test_log_s( cc::success( "Success, test server " ) + cc::info( strScheme_ ) + - cc::success( " server started" ) ); + test_log_s( "Success, test server " + strScheme_ + " server started"); } void test_server_ws_base::onLogMessage( @@ -549,7 +547,7 @@ test_server_http_base::test_server_http_base( __SKUTILS_HTTP_DEFAULT_MAX_PARALLEL_QUEUES_COUNT__, is_async_http_transfer_mode ) ); pServer_->Options( "/", [&]( const skutils::http::request& /*req*/, skutils::http::response& res ) { - test_log_s( cc::info( "OPTTIONS" ) + cc::debug( " request handler" ) ); + test_log_s( "OPTTIONS request handler"); // res.set_content( "", "text/plain" ); res.set_header( "access-control-allow-headers", "Content-Type" ); res.set_header( "access-control-allow-methods", "POST" ); @@ -561,15 +559,13 @@ test_server_http_base::test_server_http_base( "vary", "Origin, Access-Control-request-Method, Access-Control-request-Headers" ); } ); pServer_->Post( "/", [&]( const skutils::http::request& req, skutils::http::response& res ) { - test_log_p( cc::ws_rx_inv( ">>> " + std::string( strSchemeUC_ ) + "-RX-POST >>> " ) + - cc::ws_rx( " >>> " ) + cc::j( req.body_ ) ); + test_log_p( ">>> " + std::string( strSchemeUC_ ) + "-RX-POST >>> >>> " + req.body_ ); // // std::string strResult = req.body_; // // - test_log_p( cc::ws_tx_inv( "<<< " + std::string( strSchemeUC_ ) + "-TX-POST <<< " ) + - cc::ws_tx( " <<< " ) + cc::j( strResult ) ); + test_log_p( "<<< " + std::string( strSchemeUC_ ) + "-TX-POST <<< <<< " + strResult ); res.set_header( "access-control-allow-origin", "*" ); res.set_header( "vary", "Origin" ); res.set_content( strResult.c_str(), "application/json" ); @@ -682,7 +678,7 @@ skutils::result_of_http_request test_server_proxygen::implHandleHttpRequest( const std::string& /*strDstAddress*/, int /*nDstPort*/ ) { - test_log_p( cc::ws_tx_inv( "<<< PROXYGEN-TX-POST <<< " ) + cc::u( strOrigin ) + cc::ws_tx( " <<< " ) + cc::j( joIn ) ); + test_log_p( "<<< PROXYGEN-TX-POST <<< " + strOrigin + " <<< " + joIn.dump() ); skutils::result_of_http_request rslt; rslt.isBinary_ = false; rslt.joOut_ = joIn; @@ -703,9 +699,8 @@ nlohmann::json test_client::call( const nlohmann::json& joMsg ) { nlohmann::json joAnswer = nlohmann::json::object(); if ( !call( joMsg, joAnswer ) ) { joAnswer = nlohmann::json::object(); - test_log_ce( strClientName_, cc::fatal( "RPC CALL FAILURE:" ) + - cc::error( " call failed on side of client " ) + - cc::info( strClientName_ ) ); + test_log_ce( strClientName_, "RPC CALL FAILURE: call failed on side of client " + + strClientName_ ); } return joAnswer; } @@ -729,50 +724,48 @@ test_client_ws_base::test_client_ws_base( const char* strClientName, int nTarget strLocalCloseCode_ = local_close_code_as_str; strCloseReason_ = reason; test_log_cw( strClientName_, - cc::warn( "client got close event close with " ) + cc::info( "code" ) + - cc::warn( "=" ) + cc::c( local_close_code ) + cc::warn( ", code explanation is " ) + - ( local_close_code_as_str.empty() ? cc::debug( "empty text" ) : - cc::info( local_close_code_as_str ) ) + - cc::warn( ", reason is " ) + - ( reason.empty() ? cc::debug( "empty text" ) : cc::info( reason ) ) ); + "client got close event close with code = " + std::to_string(local_close_code) + ", code explanation is " + + ( local_close_code_as_str.empty() ? "empty text" : + local_close_code_as_str ) + + ", reason is " + + ( reason.empty() ? "empty text" : reason) ); }; onFail_ = [this]( skutils::ws::client::basic_socket&, skutils::ws::hdl_t ) -> void { ++cntFail_; - test_log_cf( strClientName_, cc::error( "client got fail event" ) ); + test_log_cf( strClientName_, "client got fail event" ); }; - test_log_c( strClientName_, cc::debug( "Will initalize test client " ) + - cc::info( strClientName_ ) + cc::debug( "..." ) ); + test_log_c( strClientName_, "Will initalize test client " + + strClientName_ + "..." ); enableRestartTimer( false ); static const char g_strLocalHostName[] = "localhost"; // "127.0.0.1" // "::1" // "localhost" std::string strServerUrl = skutils::tools::format( "%s://%s:%d", strScheme_.c_str(), g_strLocalHostName, nTargetPort_ ); test_log_c( strClientName_, - cc::debug( "test client will connect to: " ) + cc::u( strServerUrl ) + cc::debug( "..." ) ); + "test client will connect to: " + strServerUrl + "..." ); size_t cnt = nConnectAttempts; if ( cnt < 1 ) cnt = 1; for ( size_t nClientConnectAttempt = 0; nClientConnectAttempt < cnt && ( !open( strServerUrl ) ); ++nClientConnectAttempt ) { - test_log_c( strClientName_, cc::debug( "Attempt " ) + - cc::size10( nClientConnectAttempt + 1 ) + - cc::debug( "..." ) ); + test_log_c( strClientName_, "Attempt " + + std::to_string( nClientConnectAttempt + 1 ) + + "..." ); std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); } test_log_c( strClientName_, - cc::success( "Success" ) + cc::debug( ", test client " ) + cc::info( strClientName_ ) + - cc::debug( " did connected to: " ) + cc::u( strServerUrl ) + cc::debug( "..." ) ); + "Success, test client " + strClientName_ + + " did connected to: " + strServerUrl + "..." ); // std::this_thread::sleep_for( std::chrono::seconds(1) ); - test_log_c( strClientName_, cc::success( "Done" ) + - cc::notice( ", did initialized test client " ) + - cc::info( strClientName_ ) ); + test_log_c( strClientName_, "Done, did initialized test client " + + strClientName_ ); } test_client_ws_base::~test_client_ws_base() { stop(); } void test_client_ws_base::stop() { - test_log_c( strClientName_, cc::notice( "Will close test client " ) + - cc::info( strClientName_ ) + cc::notice( "..." ) ); + test_log_c( strClientName_, "Will close test client " + + strClientName_ + "..." ); pause_reading(); cancel(); // std::this_thread::sleep_for( std::chrono::seconds(1) ); @@ -780,9 +773,8 @@ void test_client_ws_base::stop() { // wsClient.close( "test is about to close", skutils::ws::client::close_status::normal ); close(); // - test_log_c( strClientName_, cc::success( "Success" ) + - cc::debug( ", did closed test client " ) + - cc::info( strClientName_ ) ); + test_log_c( strClientName_, "Success, did closed test client " + + strClientName_ ); } void test_client_ws_base::run() {} @@ -806,8 +798,8 @@ void test_client_ws_base::onLogMessage( bool test_client_ws_base::sendMessage( const std::string& msg, skutils::ws::opcv eOpCode /*= skutils::ws::opcv::text*/ ) { - test_log_c( strClientName_, cc::ws_tx_inv( "TEST RPC CALL Tx " + strClientName_ ) + - cc::ws_tx( " <<< " ) + cc::j( msg ) ); + test_log_c( strClientName_, "TEST RPC CALL Tx " + strClientName_ + + " <<< " + msg ); strLastMessage_.clear(); bHaveAnswer_ = false; return skutils::ws::client::client::sendMessage( msg, eOpCode ); @@ -823,8 +815,8 @@ bool test_client_ws_base::sendMessage( const nlohmann::json& joMsg ) { void test_client_ws_base::onMessage( skutils::ws::hdl_t /*hdl*/, skutils::ws::opcv /*eOpCode*/, const std::string& msg ) { - test_log_c( strClientName_, cc::ws_rx_inv( "TEST RPC CALL Rx " + strClientName_ ) + - cc::ws_rx( " >>> " ) + cc::j( msg ) ); + test_log_c( strClientName_, "TEST RPC CALL Rx " + strClientName_ + + " >>> " + msg ); strLastMessage_ = msg; bHaveAnswer_ = true; } @@ -948,13 +940,13 @@ bool test_client_http_base::call( const std::string& strMsg, std::string& strAns bool test_client_http_base::call( const nlohmann::json& joMsg, nlohmann::json& joAnswer ) { joAnswer = nlohmann::json::object(); std::string strAnswer; - test_log_c( strClientName_, cc::ws_tx_inv( "TEST RPC CALL Tx " + strClientName_ ) + - cc::ws_tx( " <<< " ) + cc::j( joMsg ) ); + test_log_c( strClientName_, "TEST RPC CALL Tx " + strClientName_ + + " <<< " + joMsg.dump() ); if ( !call( joMsg.dump(), strAnswer ) ) return false; joAnswer = nlohmann::json::parse( strAnswer ); - test_log_c( strClientName_, cc::ws_rx_inv( "TEST RPC CALL Rx " + strClientName_ ) + - cc::ws_rx( " >>> " ) + cc::j( joAnswer ) ); + test_log_c( strClientName_, "TEST RPC CALL Rx " + strClientName_ + + " >>> " + joAnswer.dump() ); return true; } @@ -996,8 +988,7 @@ void with_test_environment( fn_with_test_environment_t fn ) { // eWSLL_detailed // cc::_default_json_indent_ = 4; //???::g_nPeerStatsLoggingFlags = __???_PEER_STATS_ALL; - test_log_e( - cc::debug( "Will initialize " ) + cc::note( "test environment" ) + cc::debug( "..." ) ); + test_log_e( "Will initialize test environment..." ); // SSL_library_init(); OpenSSL_add_all_ciphers(); @@ -1006,25 +997,21 @@ void with_test_environment( fn_with_test_environment_t fn ) { OpenSSL_add_all_algorithms(); // // - test_log_e( cc::success( "Done" ) + cc::debug( ", " ) + cc::note( "test environment" ) + - cc::debug( " initialized" ) ); + test_log_e( "Done, test environment initialized" ); } // if( ! g_b_test_environment_initilized ) try { - test_log_e( cc::debug( "Will execute " ) + cc::note( "test environment" ) + - cc::debug( " callback..." ) ); + test_log_e( "Will execute test environment callback..." ); fn(); - test_log_e( cc::success( "Success, did executed " ) + cc::note( "test environment" ) + - cc::success( " callback" ) ); + test_log_e( "Success, did executed test environment callback" ); } catch ( std::exception& ex ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "test environment" ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) ); + test_log_ef( "FAILURE: Got exception from test environment callback: " + + std::string(ex.what()) ); BOOST_REQUIRE( false ); } catch ( ... ) { // XXX HACK For test passing - // test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got unknown exception from " ) + // test_log_ef( "FAILURE: Got unknown exception from " // + - // cc::note( "test environment" ) + cc::error( " callback" ) ); + // "test environment callback" ); // BOOST_REQUIRE( false ); } } @@ -1132,12 +1119,10 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, throw std::runtime_error( skutils::tools::format( "Failed to create IPv6 busy test listener on port %d", nSocketListenPort ) ); } - test_log_e( - cc::debug( "Will execute " ) + cc::note( "busy port" ) + cc::debug( " callback..." ) ); + test_log_e( "Will execute busy port callback..." ); if ( fnWorker ) fnWorker(); - test_log_e( cc::success( "Success, did executed " ) + cc::note( "busy port" ) + - cc::success( " callback" ) ); + test_log_e( "Success, did executed busy port callback" ); } catch ( std::exception& ex ) { std::string strErrorDescription = ex.what(); bool isIgnoreError = false; @@ -1145,9 +1130,8 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, isIgnoreError = fnErrorHandler( strErrorDescription ); // returns true if errror should be ignored if ( !isIgnoreError ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "busy port" ) + cc::error( " callback: " ) + - cc::warn( strErrorDescription ) ); + test_log_ef( "FAILURE: Got exception from busy port callback: " + + strErrorDescription ); BOOST_REQUIRE( false ); } } catch ( ... ) { @@ -1157,8 +1141,7 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, isIgnoreError = fnErrorHandler( strErrorDescription ); // returns true if errror should be ignored if ( !isIgnoreError ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got unknown exception from " ) + - cc::note( "busy port" ) + cc::error( " callback" ) ); + test_log_ef( "FAILURE: Got unknown exception from busy port callback" ); BOOST_REQUIRE( false ); } } @@ -1197,24 +1180,20 @@ void with_test_server( 0, 0 ) ); } else { - test_log_se( cc::error( "Unknown server type: " ) + cc::warn( strServerUrlScheme ) ); + test_log_se( "Unknown server type: " + strServerUrlScheme ); throw std::runtime_error( "Unknown server type: " + strServerUrlScheme ); } pServer->run_parallel(); try { - test_log_e( cc::debug( "Will execute " ) + cc::note( "Test server" ) + - cc::debug( " callback..." ) ); + test_log_e( "Will execute Test server callback..." ); fn( *pServer.get() ); - test_log_e( cc::success( "Success, did executed " ) + cc::note( "Test server" ) + - cc::success( " callback" ) ); + test_log_e( "Success, did executed Test server callback"); } catch ( std::exception& ex ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "Test server" ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) ); + test_log_ef( "FAILURE: Got exception from Test server callback: " + + std::string(ex.what())); BOOST_REQUIRE( false ); } catch ( ... ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got unknown exception from " ) + - cc::note( "Test server" ) + cc::error( " callback" ) ); + test_log_ef( "FAILURE: Got unknown exception from Test server callback" ); BOOST_REQUIRE( false ); } pServer->stop(); @@ -1226,19 +1205,17 @@ void with_test_client( fn_with_test_client_t fn, const std::string& strTestClien const size_t nConnectAttempts // = 10 ) { if ( runClientInOtherThread ) { - test_log_e( cc::debug( "Starting test client " ) + cc::info( strTestClientName ) + - cc::debug( " thread..." ) ); + test_log_e( "Starting test client " + strTestClientName + + " thread..." ); std::atomic_bool bClientThreadFinished( false ); std::thread clientThread( [&]() { with_test_client( fn, strTestClientName, strServerUrlScheme, nSocketListenPort, false, nConnectAttempts ); bClientThreadFinished = true; - test_log_e( cc::debug( " test client " ) + cc::info( strTestClientName ) + - cc::debug( " thread will exit" ) ); + test_log_e( " test client " + strTestClientName + " thread will exit" ); } ); - test_log_e( cc::success( "Done, test client " ) + cc::info( strTestClientName ) + - cc::success( " thread is running" ) ); - test_log_e( cc::debug( "Waiting for client thread to finish..." ) ); + test_log_e( "Done, test client " + strTestClientName + " thread is running" ); + test_log_e( "Waiting for client thread to finish..." ); while ( !bClientThreadFinished ) std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) ); try { @@ -1247,8 +1224,7 @@ void with_test_client( fn_with_test_client_t fn, const std::string& strTestClien } catch ( ... ) { } BOOST_REQUIRE( !clientThread.joinable() ); - test_log_e( cc::success( "Done" ) + cc::debug( ", test client " ) + - cc::info( strTestClientName ) + cc::debug( " thread is finished" ) ); + test_log_e( "Done, test client " + strTestClientName + " thread is finished" ); return; } // if( runClientInOtherThread ) @@ -1271,24 +1247,23 @@ void with_test_client( fn_with_test_client_t fn, const std::string& strTestClien strTestClientName.c_str(), nSocketListenPort, nConnectAttempts ) ); BOOST_REQUIRE( !pClient->isSSL() ); } else { - test_log_se( cc::error( "Unknown client type: " ) + cc::warn( strServerUrlScheme ) ); + test_log_se( "Unknown client type: " + strServerUrlScheme ); throw std::runtime_error( "Unknown client type: " + strServerUrlScheme ); } try { - test_log_e( cc::debug( "Will execute test client " ) + cc::info( pClient->strClientName_ ) + - cc::debug( " callback..." ) ); + test_log_e( "Will execute test client " + pClient->strClientName_ + + " callback..." ); fn( *pClient.get() ); - test_log_e( cc::success( "Success, did executed test client " ) + - cc::info( pClient->strClientName_ ) + cc::success( " callback" ) ); + test_log_e( "Success, did executed test client " + + pClient->strClientName_ + " callback" ); } catch ( std::exception& ex ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from test client " ) + - cc::info( pClient->strClientName_ ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) ); + test_log_ef( "FAILURE: Got exception from test client " + + pClient->strClientName_ + " callback: " + + ex.what() ); BOOST_REQUIRE( false ); } catch ( ... ) { - test_log_ef( cc::fatal( "FAILURE:" ) + - cc::error( " Got unknown exception from test client " ) + - cc::info( pClient->strClientName_ ) + cc::error( " callback" ) ); + test_log_ef( "FAILURE: Got unknown exception from test client " + + pClient->strClientName_ + " callback" ); BOOST_REQUIRE( false ); } pClient->stop(); @@ -1311,16 +1286,16 @@ extern void with_test_clients( &cntRunningThreads, &vecTestClientNames]() -> void { with_test_client( fn, vecTestClientNames[i], strServerUrlScheme, nSocketListenPort, false, nConnectAttempts ); - test_log_e( cc::debug( " test client " ) + cc::info( vecTestClientNames[i] ) + - cc::debug( " thread will exit" ) ); + test_log_e( " test client " + vecTestClientNames[i] + + " thread will exit" ); --cntRunningThreads; } ) ); std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); for ( size_t idxWait = 0; cntRunningThreads > 0; ++idxWait ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); if ( idxWait % 1000 == 0 && idxWait != 0 ) - test_log_e( cc::debug( "Waiting for " ) + cc::size10( cntRunningThreads ) + - cc::debug( " client thread(s)" ) ); + test_log_e( "Waiting for " + std::to_string( cntRunningThreads ) + + " client thread(s)" ); } for ( i = 0; i < cnt; ++i ) { try { @@ -1340,20 +1315,15 @@ void with_test_client_server( fn_with_test_client_server_t fn, const std::string with_test_client( [&]( test_client& refClient ) -> void { try { - test_log_e( cc::debug( "Will execute " ) + cc::note( "client-server" ) + - cc::debug( " callback..." ) ); + test_log_e( "Will execute client-server callback..." ); fn( refServer, refClient ); - test_log_e( cc::success( "Success, did executed " ) + - cc::note( "client-server" ) + cc::success( " callback" ) ); + test_log_e( "Success, did executed client-server callback" ); } catch ( std::exception& ex ) { - test_log_ef( cc::fatal( "FAILURE:" ) + cc::error( " Got exception from " ) + - cc::note( "client-server" ) + cc::error( " callback: " ) + - cc::warn( ex.what() ) ); + test_log_ef( "FAILURE: Got exception from client-server callback: " + + std::string(ex.what()) ); BOOST_REQUIRE( false ); } catch ( ... ) { - test_log_ef( cc::fatal( "FAILURE:" ) + - cc::error( " Got unknown exception from " ) + - cc::note( "client-server" ) + cc::error( " callback" ) ); + test_log_ef( "FAILURE: Got unknown exception from client-server callback" ); BOOST_REQUIRE( false ); } }, @@ -1374,9 +1344,9 @@ void test_print_header_name( const char* s ) { static const char g_strLine[] = "==========================================================================================" "======"; - test_log_e( cc::attention( g_strLine ) ); - test_log_e( " " + cc::sunny( s ) ); - test_log_e( cc::attention( g_strLine ) ); + test_log_e( g_strLine ); + test_log_e( " " + std::string(s) ); + test_log_e( g_strLine ); cc::_on_ = bPrev; } @@ -1396,7 +1366,7 @@ void test_protocol_server_startup( const char* strProto, int nPort ) { skutils::test::with_test_server( [&]( skutils::test::test_server & /*refServer*/ ) -> void { was_started = true; - skutils::test::test_log_e( cc::success( "WE ARE HERE, SERVER ALIVE" ) ); + skutils::test::test_log_e( "WE ARE HERE, SERVER ALIVE" ); }, strProto, nPort ); } ); @@ -1428,12 +1398,12 @@ void test_protocol_serial_calls( // multiple clients serial server calls std::atomic_size_t cnt_actions_performed = 0, cnt_clients = vecClientNames.size(), wait_time_step_ms = 500; - skutils::test::test_log_e( cc::debug( "Protocol serial calls test with " ) + - cc::size10( size_t( cnt_clients ) ) + cc::debug( " client(s)" ) ); + skutils::test::test_log_e( "Protocol serial calls test with " + + std::to_string( size_t( cnt_clients ) ) + " client(s)" ); skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( [&]( skutils::test::test_server & /*refServer*/ ) -> void { - skutils::test::test_log_e( cc::sunny( "Server startup" ) ); + skutils::test::test_log_e( "Server startup" ); for ( size_t i = 0; i < cnt_clients; ++i ) { std::this_thread::sleep_for( std::chrono::milliseconds( size_t( wait_time_step_ms ) ) ); @@ -1441,20 +1411,20 @@ void test_protocol_serial_calls( [&, i]( skutils::test::test_client& refClient ) -> void { // std::this_thread::sleep_for( // std::chrono::milliseconds( size_t( wait_time_step_ms ) * i ) ); - skutils::test::test_log_e( cc::bright( "Client " ) + cc::size10( i ) + - cc::bright( " begin" ) ); + skutils::test::test_log_e( "Client " + std::to_string( i ) + + " begin" ); std::string strCall( "{ \"method\": \"hello\", \"params\": {} }" ); nlohmann::json joCall = skutils::test::ensure_call_id_present_copy( nlohmann::json::parse( strCall ) ); nlohmann::json joResult = refClient.call( joCall ); BOOST_REQUIRE( joCall.dump() == joResult.dump() ); ++cnt_actions_performed; - skutils::test::test_log_e( cc::bright( "Client " ) + cc::size10( i ) + - cc::bright( " finish" ) ); + skutils::test::test_log_e( "Client " + std::to_string( i ) + + " finish" ); }, vecClientNames[i], strProto, nPort, true ); } - skutils::test::test_log_e( cc::sunny( "Server finish" ) ); + skutils::test::test_log_e( "Server finish" ); }, strProto, nPort ); } ); @@ -1463,11 +1433,11 @@ void test_protocol_serial_calls( size_t( cnt_actions_performed ) < size_t( cnt_clients ); ++idxWaitAttempt ) { skutils::test::test_log_e( - cc::debug( "Waiting for test to complete, step " ) + - cc::size10( size_t( idxWaitAttempt ) ) + cc::debug( " of " ) + - cc::size10( size_t( cntWaitAttempts ) ) + cc::debug( ", performed " ) + - cc::size10( size_t( cnt_actions_performed ) ) + cc::debug( " action(s) of " ) + - cc::size10( size_t( cnt_clients ) ) + cc::debug( " expeted ..." ) ); + "Waiting for test to complete, step " + + std::to_string( size_t( idxWaitAttempt ) ) + " of " + + std::to_string( size_t( cntWaitAttempts ) ) + ", performed " + + std::to_string( size_t( cnt_actions_performed ) ) + " action(s) of " + + std::to_string( size_t( cnt_clients ) ) + " expeted ..." ); std::this_thread::sleep_for( std::chrono::milliseconds( size_t( wait_time_step_ms ) ) ); } BOOST_REQUIRE( cnt_actions_performed == cnt_clients ); @@ -1479,12 +1449,12 @@ void test_protocol_parallel_calls( std::atomic_size_t cnt_actions_performed = 0, cnt_clients = vecClientNames.size(), wait_time_step_ms = 500, parallel_client_indexer = 0; std::mutex mtxClientIndexer; - skutils::test::test_log_e( cc::debug( "Protocol parallel calls test with " ) + - cc::size10( size_t( cnt_clients ) ) + cc::debug( " client(s)" ) ); + skutils::test::test_log_e( "Protocol parallel calls test with " + + std::to_string( size_t( cnt_clients ) ) + " client(s)" ); skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( [&]( skutils::test::test_server & /*refServer*/ ) -> void { - skutils::test::test_log_e( cc::sunny( "Server startup" ) ); + skutils::test::test_log_e( "Server startup" ); skutils::test::with_test_clients( [&]( skutils::test::test_client& refClient ) -> void { size_t i = 0; @@ -1494,7 +1464,7 @@ void test_protocol_parallel_calls( ++parallel_client_indexer; } // block skutils::test::test_log_e( - cc::bright( "Client " ) + cc::size10( i ) + cc::bright( " begin" ) ); + "Client " + std::to_string( i ) + " begin" ); std::string strCall( "{ \"method\": \"hello\", \"params\": {} }" ); nlohmann::json joCall = skutils::test::ensure_call_id_present_copy( nlohmann::json::parse( strCall ) ); @@ -1519,54 +1489,54 @@ void test_protocol_parallel_calls( // ++cnt_actions_performed; skutils::test::test_log_e( - cc::bright( "Client " ) + cc::size10( i ) + cc::bright( " finish" ) ); + "Client " + std::to_string( i ) + " finish" ); }, vecClientNames, strProto, nPort, true ); }, strProto, nPort ); - skutils::test::test_log_e( cc::sunny( "Server finish" ) ); + skutils::test::test_log_e( "Server finish" ); } ); size_t idxWaitAttempt, cntWaitAttempts = size_t( cnt_clients ) + 1; for ( idxWaitAttempt = 0; size_t( idxWaitAttempt ) < size_t( cntWaitAttempts ) && size_t( cnt_actions_performed ) < size_t( cnt_clients ); ++idxWaitAttempt ) { skutils::test::test_log_e( - cc::debug( "Waiting for test to complete, step " ) + - cc::size10( size_t( idxWaitAttempt ) ) + cc::debug( " of " ) + - cc::size10( size_t( cntWaitAttempts ) ) + cc::debug( ", performed " ) + - cc::size10( size_t( cnt_actions_performed ) ) + cc::debug( " action(s) of " ) + - cc::size10( size_t( cnt_clients ) ) + cc::debug( " expeted ..." ) ); + "Waiting for test to complete, step " + + std::to_string( size_t( idxWaitAttempt ) ) + " of " + + std::to_string( size_t( cntWaitAttempts ) ) + ", performed " + + std::to_string( size_t( cnt_actions_performed ) ) + " action(s) of " + + std::to_string( size_t( cnt_clients ) ) + " expeted ..." ); std::this_thread::sleep_for( std::chrono::milliseconds( size_t( wait_time_step_ms ) ) ); } BOOST_REQUIRE( cnt_actions_performed == cnt_clients ); } void test_protocol_busy_port( const char* strProto, int nPort ) { - skutils::test::test_log_e( cc::debug( "Protocol busy port test" ) ); + skutils::test::test_log_e( "Protocol busy port test" ); skutils::test::with_test_environment( [&]() -> void { skutils::test::with_busy_tcp_port( [&]() -> void { // fn_with_busy_tcp_port_worker_t - skutils::test::test_log_e( cc::sunny( "Busy port allocated" ) ); + skutils::test::test_log_e( "Busy port allocated" ); skutils::test::with_test_server( [&]( skutils::test::test_server & /*refServer*/ ) -> void { - skutils::test::test_log_e( cc::sunny( "Server startup" ) ); + skutils::test::test_log_e( "Server startup" ); skutils::test::test_log_sf( - cc::sunny( "WE SHOULD NOT REACH THIS EXECUTION POINT" ) ); + "WE SHOULD NOT REACH THIS EXECUTION POINT" ); BOOST_REQUIRE( false ); }, strProto, nPort ); - skutils::test::test_log_e( cc::sunny( "Server finish" ) ); + skutils::test::test_log_e( "Server finish" ); }, [&]( const std::string& strErrorDescription ) -> bool { // fn_with_busy_tcp_port_error_t - skutils::test::test_log_e( cc::success( "Busy port detected with message: " ) + - cc::bright( strErrorDescription ) ); - skutils::test::test_log_ss( cc::success( "SUCCESS - busy port handled" ) ); + skutils::test::test_log_e( "Busy port detected with message: " + + strErrorDescription ); + skutils::test::test_log_ss( "SUCCESS - busy port handled" ); BOOST_REQUIRE( true ); return true; // returns true if errror should be ignored }, nPort ); - skutils::test::test_log_e( cc::sunny( "Busy port de-allocated" ) ); + skutils::test::test_log_e( "Busy port de-allocated" ); } ); } @@ -1579,33 +1549,33 @@ void test_protocol_rest_call( const char* strProto, int nPort, bool tt, bool ft nlohmann::json joCall = skutils::test::ensure_call_id_present_copy( nlohmann::json::parse( strCall ) ); if( tt ) { - skutils::test::test_log_e( cc::normal( "\"True test\" part startup" ) ); + skutils::test::test_log_e( "\"True test\" part startup" ); std::string strURL = skutils::tools::format( "%s://127.0.0.1:%d", strProto, nPort ); skutils::url u( strURL ); skutils::rest::client restCall( u ); skutils::rest::data_t dataOut = restCall.call( strCall ); BOOST_REQUIRE( ! dataOut.empty() ); nlohmann::json joResult = nlohmann::json::parse( dataOut.s_ ); - skutils::test::test_log_e( cc::info( "input" ) + cc::debug( "..........." ) + cc::normal( joCall.dump() ) ); - skutils::test::test_log_e( cc::info( "output" ) + cc::debug( ".........." ) + cc::normal( joResult.dump() ) ); + skutils::test::test_log_e( "input ..........." + joCall.dump() ); + skutils::test::test_log_e( "output .........." + joResult.dump() ); BOOST_REQUIRE( joCall.dump() == joResult.dump() ); end_1_reached = true; - skutils::test::test_log_e( cc::success( "\"True test\" part finish" ) ); + skutils::test::test_log_e( "\"True test\" part finish" ); } if( ft ) { - skutils::test::test_log_e( cc::normal( "\"False test\" part startup" ) ); + skutils::test::test_log_e( "\"False test\" part startup" ); std::string strURL = skutils::tools::format( "%s://127.0.0.1:%d", strProto, nPort + 123 ); // incorrect port skutils::url u( strURL ); skutils::rest::client restCall( u ); skutils::rest::data_t dataOut = restCall.call( strCall ); - skutils::test::test_log_e( cc::info( "error type" ) + cc::debug( "......" ) + cc::num10( int( dataOut.ei_.et_ ) ) ); - skutils::test::test_log_e( cc::info( "error code" ) + cc::debug( "......" ) + cc::num10( int( dataOut.ei_.ec_ ) ) ); - skutils::test::test_log_e( cc::info( "error text" ) + cc::debug( "......" ) + cc::normal( dataOut.ei_.strError_ ) ); + skutils::test::test_log_e( "error type ......" + int( dataOut.ei_.et_ ) ); + skutils::test::test_log_e( "error code ......" + int( dataOut.ei_.ec_ ) ); + skutils::test::test_log_e( "error text ......" + dataOut.ei_.strError_ ); BOOST_REQUIRE( dataOut.empty() ); BOOST_REQUIRE( dataOut.ei_.et_ != skutils::http::common_network_exception::error_type::et_no_error ); BOOST_REQUIRE( ! dataOut.ei_.strError_.empty() ); end_2_reached = true; - skutils::test::test_log_e( cc::success( "\"False test\" part finish" ) ); + skutils::test::test_log_e( "\"False test\" part finish" ); } }, strProto, nPort ); diff --git a/utils/json_spirit/json_spirit_reader_template.h b/utils/json_spirit/json_spirit_reader_template.h index aa3305360..08402a7d9 100644 --- a/utils/json_spirit/json_spirit_reader_template.h +++ b/utils/json_spirit/json_spirit_reader_template.h @@ -9,9 +9,6 @@ #include "json_spirit_error_position.h" #include "json_spirit_value.h" -//#define BOOST_SPIRIT_THREADSAFE // uncomment for multithreaded use, requires linking to -// boost.thread - #include #include #include