Changeset c5ec0c8 in nscp


Ignore:
Timestamp:
01/31/12 22:20:51 (16 months ago)
Author:
Michael Medin <michael@…>
Branches:
master, 0.4.0, 0.4.1, 0.4.2
Children:
a06e6af
Parents:
56724a4
Message:
  • Fixed issue with parsing "invalid external commands". If parsing fails it will notify you but use the legacy split string method instead.
  • LuaScript? module is now modern (ie. works with 0.4.0) Should be 99% compatible (function needs to be defined before registration) but all old scripts should work now (I think)
  • LuaScript? module has been modernized The new API is very similar to Python Concepts are working but not all commands have been implements (and no testcases either) The old API will still work
  • Fixed issue with
  • Changed CheckCounter format option to take a coma separated list of keyword from the below list:

nocap100: Counter values above 100 (for example, counter values measuring the processor load on multiprocessor computers) will not be reset to 100. The default behavior is that counter values are capped at a value of 100.
1000: Multiply the actual value by 1000.
noscale: Do not apply the default scaling factor.
So format=nocap100,noscale would combine the two aspects above.

  • Fixed issue with parsing multiple performance data items (internally)
  • Added option to CheckCounter format=nocap100 to not cap counters at 100% (for multi cpu machines)
  • Fixed help when specifying invalid options on command line
  • Eradicated a potential memory leak in the NSCA encryption library
Files:
1 added
17 edited

Legend:

Unmodified
Added
Removed
  • changelog

    r8013c0c rc5ec0c8  
    55 * Fixa dependonservice LanManWorkStation (old win) 
    66 * Fix RtlStringFromGUID problem on NT4 
     7 
     82012-01-31 MickeM 
     9 * Fixed issue with parsing "invalid external commands". 
     10   If parsing falies it will notify you but use the legacy split string method instead. 
     11 * LuaScript module is now modern (ie. works with 0.4.0) 
     12   Should be 99% compatbile (function needs to be defined before registration) but all old scripts should work now (I think) 
     13 * LuaScript module has been modernized 
     14   The new API is very similar to Python 
     15   Concepts are working but not all commands have beenh implementes (and no testcases either) 
     16   The old API will still work 
     17 * Fixed issue with  
     18 
     192012-01-27 MickeM 
     20 * Changed CheckCounter format option to take a coma separated list of keyword from the below list: 
     21   nocap100: Counter values above 100 (for example, counter values measuring the processor load on multiprocessor computers) will not be reset to 100. The default behavior is that counter values are capped at a value of 100. 
     22   1000: Multiply the actual value by 1000. 
     23   noscale: Do not apply the default scaling factor. 
     24   So format=nocap100,noscale would combine the two aspects above. 
     25 
     262012-01-26 MickeM 
     27 * Fixed issue with parsing multiple performance data items (internally) 
     28 * Added option to CheckCounter format=nocap100 to not cap counters at 100% (for multi cpu machines) 
     29 
     302012-01-22 MickeM 
     31 * Fixed help when specifying invalid options on command line 
     32 * Eradicated a potential memoryleakin the NSCA encryption library 
    733 
    8342012-01-22 MickeM 
  • include/luna.h

    r1ff950c rc5ec0c8  
    5050 
    5151    // fill method table with methods from class T 
    52     for (RegType *l = T::methods; l->name; l++) { 
     52    for (const RegType *l = T::methods; l->name; l++) { 
    5353    /* edited by Snaily: shouldn't it be const RegType *l ... ? */ 
    5454      lua_pushstring(L, l->name); 
  • include/nsca/nsca_enrypt.hpp

    r2ec2eb6 rc5ec0c8  
    159159    class any_encryption { 
    160160    public: 
     161      virtual ~any_encryption() {} 
    161162      virtual void init(std::string password, std::string iv) = 0; 
    162163      virtual void encrypt(std::string &buffer) = 0; 
     
    180181      cryptopp_encryption() : keysize_(TMethod::DEFAULT_KEYLENGTH) {} 
    181182      cryptopp_encryption(int keysize) : keysize_(keysize) {} 
     183      virtual ~cryptopp_encryption() {} 
    182184      int get_keySize() { 
    183185        return keysize_; 
     
    188190 
    189191      virtual void init(std::string password, std::string iv) { 
    190         init(password, (unsigned char*)&*iv.begin(), iv.size()); 
    191  
    192       } 
    193       void init(std::string password, unsigned char *transmitted_iv, int iv_size) { 
    194         /* generate an encryption/description key using the password */ 
     192        int blocksize = get_blockSize(); 
     193        if(blocksize>iv.size()) 
     194          throw encryption_exception("IV size for crypto algorithm exceeds limits"); 
     195 
     196        // Generate key buffer 
    195197        std::string::size_type keysize=get_keySize(); 
    196  
    197         unsigned char *key = new unsigned char[keysize+1]; 
    198         if (key == NULL){ 
     198        char *key = new char[keysize+1]; 
     199        if (key == NULL) 
    199200          throw encryption_exception("Could not allocate memory for encryption/decryption key"); 
    200         } 
    201201        memset(key, 0, keysize); 
    202202        using namespace std; 
    203203        memcpy(key,password.c_str(),min(keysize,password.length())); 
    204  
    205  
    206         /* determine size of IV buffer for this algorithm */ 
    207         int blocksize = get_blockSize(); 
    208         if(blocksize>iv_size){ 
    209           throw encryption_exception("IV size for crypto algorithm exceeds limits"); 
    210         } 
    211  
    212         /* allocate memory for IV buffer */ 
    213         unsigned char *iv = new unsigned char[blocksize+1]; 
    214         if (iv == NULL){ 
    215           throw encryption_exception("Could not allocate memory for IV buffer"); 
    216         } 
    217         memset(iv, 0, blocksize); 
    218  
    219         /* fill IV buffer with first bytes of IV that is going to be used to crypt (determined by server) */ 
    220         memcpy(iv, transmitted_iv, sizeof(unsigned char)*blocksize); 
     204        std::string skey(key, keysize); 
     205        delete [] key; 
    221206 
    222207        try { 
    223           cipher_.SetKey(key, keysize); 
    224           crypto_.SetCipherWithIV(cipher_, iv, 1); 
    225           decrypto_.SetCipherWithIV(cipher_, iv, 1); 
     208          cipher_.SetKey((const byte*)skey.c_str(), keysize); 
     209          crypto_.SetCipherWithIV(cipher_, (const byte*)iv.c_str(), 1); 
     210          decrypto_.SetCipherWithIV(cipher_, (const byte*)iv.c_str(), 1); 
    226211        } catch (...) { 
    227212          throw encryption_exception("Unknown exception when trying to setup crypto"); 
    228213        } 
    229         delete [] iv; 
    230         delete [] key; 
    231214      } 
    232215      void encrypt(std::string &buffer) { 
     
    439422        throw encryption_exception("Failed to get encryption module for: " + boost::lexical_cast<std::string>(encryption_method)); 
    440423 
    441       /* server generates IV used for encryption */ 
     424      // server generates IV used for encryption  
    442425      if (received_iv.empty()) { 
    443426        std::string iv = generate_transmitted_iv(); 
    444427        core_->init(password, iv); 
    445       } else  /* client receives IV from server */ 
     428      } else  // client receives IV from server 
    446429        core_->init(password, received_iv); 
    447430    } 
  • include/nsca/nsca_socket.hpp

    r2ec2eb6 rc5ec0c8  
    1616  private: 
    1717    boost::shared_ptr<tcp::socket> socket_; 
     18    boost::asio::io_service &io_service_; 
    1819    nsca_encrypt crypt_inst; 
    1920  public: 
     
    2122 
    2223  public: 
    23     socket(boost::asio::io_service &io_service) { 
    24       socket_.reset(new tcp::socket(io_service)); 
     24    socket(boost::asio::io_service &io_service) : io_service_(io_service) { 
     25      socket_.reset(new tcp::socket(io_service_)); 
    2526    } 
    26     socket() {} 
    27  
    28     virtual boost::asio::io_service& get_io_service() { 
    29       return socket_->get_io_service(); 
    30     } 
    31     virtual basic_socket_type& get_socket() { 
    32       return *socket_; 
     27    ~socket() { 
     28      if (socket_) 
     29        socket_->close(); 
     30      socket_.reset(); 
    3331    } 
    3432 
    3533    virtual void connect(std::string host, std::string port) { 
    3634      NSC_DEBUG_MSG(_T("Connecting to: ") + to_wstring(host) + _T(" (") + to_wstring(port) + _T(")")); 
    37       tcp::resolver resolver(get_io_service()); 
     35      tcp::resolver resolver(io_service_); 
    3836      tcp::resolver::query query(host, port); 
    3937 
     
    4442      while (error && endpoint_iterator != end) { 
    4543        tcp::resolver::endpoint_type ep = *endpoint_iterator; 
    46         get_socket().close(); 
    47         get_socket().lowest_layer().connect(*endpoint_iterator++, error); 
     44        socket_->close(); 
     45        socket_->connect(*endpoint_iterator++, error); 
    4846        NSC_DEBUG_MSG(_T("Connected to: ") + to_wstring(ep.address().to_string())); 
    4947      } 
    50       if (error) 
     48      if (error) { 
     49        NSC_DEBUG_MSG(_T("Failed to connect to:") + utf8::to_unicode(host)); 
    5150        throw boost::system::system_error(error); 
     51      } 
    5252    } 
    5353 
    54     ~socket() { 
    55       get_socket().close(); 
    56     } 
    5754 
    5855    virtual void shutdown() { 
     
    6057      // Initiate graceful connection closure. 
    6158      boost::system::error_code ignored_ec; 
    62       get_socket().lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); 
     59      if (socket_) 
     60        socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); 
     61    }; 
     62    virtual void close() { 
     63      if (socket_) 
     64        socket_->close(); 
     65      socket_.reset(); 
    6366    }; 
    6467 
    6568    virtual void send_nsca(const nsca::packet &packet, const boost::posix_time::seconds timeout) { 
    66       if (!get_socket().is_open()) { 
    67         NSC_DEBUG_MSG(_T("is closed...")); 
     69      if (!socket_ || !socket_->is_open()) { 
     70        NSC_LOG_ERROR_STD(_T("Socket was closed when trying to send data...")); 
    6871        return; 
    6972      } 
     
    7578    } 
    7679    virtual bool recv_iv(std::string password, int encryption_method, boost::posix_time::seconds timeout) { 
    77       if (!get_socket().is_open()) { 
    78         NSC_DEBUG_MSG(_T("is closed...")); 
     80      if (!socket_ || !socket_->is_open()) { 
     81        NSC_LOG_ERROR_STD(_T("Socket was closed when trying to read data...")); 
    7982        return false; 
    8083      } 
     
    8588        return false; 
    8689      } 
    87       std::string tmp = std::string(buf.begin(), buf.end()); 
    88       nsca::iv_packet iv_packet(tmp); 
     90      nsca::iv_packet iv_packet(std::string(buf.begin(), buf.end())); 
    8991      std::string iv = iv_packet.get_iv(); 
    9092      NSC_DEBUG_MSG(_T("Encrypting using when sending: ") + utf8::cvt<std::wstring>(nsca::nsca_encrypt::helpers::encryption_to_string(encryption_method)) + _T(" and ") + utf8::cvt<std::wstring>(password)); 
     
    9395    } 
    9496    virtual bool read_with_timeout(std::vector<char> &buf, boost::posix_time::seconds timeout) { 
    95       return socket_helpers::io::read_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout); 
     97      return socket_helpers::io::read_with_timeout(*socket_, *socket_, boost::asio::buffer(buf), timeout); 
    9698    } 
    9799    virtual void write_with_timeout(std::string &buf, boost::posix_time::seconds timeout) { 
    98       socket_helpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout); 
     100      socket_helpers::io::write_with_timeout(*socket_, *socket_, boost::asio::buffer(buf), timeout); 
    99101    } 
    100102  }; 
  • include/nscapi/functions.hpp

    r8013c0c rc5ec0c8  
    788788        } else { 
    789789          chunk = perf.substr(0, p); 
     790          p = perf.find_first_not_of(tokenizer_data.perf_separator, p); 
    790791          perf = perf.substr(p); 
    791792        } 
  • include/pdh/collectors.hpp

    rd66ccee rc5ec0c8  
    121121    virtual __int64 get_int64() = 0; 
    122122    virtual double get_average(int backlog) = 0; 
     123    virtual void set_extra_format(DWORD format) = 0; 
    123124  }; 
    124125 
     
    135136    std::wstring lastError_; 
    136137    const PDH::PDHCounter *parent_; 
    137   public: 
    138     StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL) {} 
     138    DWORD extra_format; 
     139  public: 
     140    StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL), extra_format(0) {} 
    139141    virtual void collect(const PDH::PDHCounter &counter) { 
    140142      PDHCounterMutexHandler mutex(&mutex_); 
     
    154156      return value_; 
    155157    } 
     158    void set_extra_format(DWORD format) { 
     159      extra_format = format; 
     160    } 
    156161    DWORD getFormat() const { 
    157       return format_double; 
     162      return format_double|extra_format; 
    158163    } 
    159164  public: 
     
    184189    bool hasValue_; 
    185190    const PDH::PDHCounter *parent_; 
    186   public: 
    187     StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL) {} 
     191    DWORD extra_format; 
     192  public: 
     193    StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL), extra_format(0) {} 
    188194    virtual void collect(const PDH::PDHCounter &counter) { 
    189195      PDHCounterMutexHandler mutex(&mutex_); 
     
    203209      return value_; 
    204210    } 
     211    void set_extra_format(DWORD format) { 
     212      extra_format = format; 
     213    } 
    205214    DWORD getFormat() const { 
    206       return format_long; 
     215      return format_long|extra_format; 
    207216    } 
    208217    inline std::wstring get_string() { 
     
    232241    bool hasValue_; 
    233242    const PDH::PDHCounter *parent_; 
    234   public: 
    235     StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL) {} 
     243    DWORD extra_format; 
     244  public: 
     245    StaticPDHCounterListener() : value_(0), hasValue_(false), parent_(NULL), extra_format(0) {} 
    236246    virtual void collect(const PDH::PDHCounter &counter) { 
    237247      PDHCounterMutexHandler mutex(&mutex_); 
     
    251261      return value_; 
    252262    } 
     263    void set_extra_format(DWORD format) { 
     264      extra_format = format; 
     265    } 
    253266    DWORD getFormat() const { 
    254       return format_large; 
     267      return format_large|extra_format; 
    255268    } 
    256269    inline std::wstring get_string() { 
     
    284297    const PDH::PDHCounter *parent_; 
    285298  public: 
    286     RoundINTPDHBufferListenerImpl() : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL) {} 
     299    DWORD extra_format; 
     300    RoundINTPDHBufferListenerImpl() : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL), extra_format(0) {} 
    287301    RoundINTPDHBufferListenerImpl(int length_) : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL) { 
    288302      resize(length_); 
     
    293307        return; 
    294308      delete [] buffer; 
     309    } 
     310 
     311    virtual void set_extra_format(DWORD format) { 
     312      extra_format = format; 
    295313    } 
    296314 
     
    396414    } 
    397415    virtual DWORD getFormat() const { 
    398       return format_double; 
     416      return format_double|extra_format; 
    399417    } 
    400418  }; 
     
    410428    } 
    411429    virtual DWORD getFormat() const { 
    412       return format_long; 
     430      return format_long|extra_format; 
    413431    } 
    414432  }; 
     
    424442    } 
    425443    virtual DWORD getFormat() const { 
    426       return format_large; 
     444      return format_large|extra_format; 
    427445    } 
    428446  }; 
  • modules/CheckExternalScripts/CheckExternalScripts.h

    r98113da rc5ec0c8  
    2929  struct command_data { 
    3030    command_data() {} 
    31     command_data(std::wstring command_, std::wstring arguments_) : command(command_) { 
     31    command_data(std::wstring alias, std::wstring command_, std::wstring arguments_) : alias(alias), command(command_) { 
    3232      parser_arguments(arguments_); 
    3333    } 
    3434    void parser_arguments(std::wstring args) { 
    35       boost::tokenizer<boost::escaped_list_separator<wchar_t>, std::wstring::const_iterator, std::wstring>  
    36         tok(args, boost::escaped_list_separator<wchar_t>(L'\\', L' ', L'\"')); 
    37       BOOST_FOREACH(std::wstring s, tok) { 
    38         arguments.push_back(s); 
     35      try { 
     36        boost::tokenizer<boost::escaped_list_separator<wchar_t>, std::wstring::const_iterator, std::wstring>  
     37          tok(args, boost::escaped_list_separator<wchar_t>(L'\\', L' ', L'\"')); 
     38        BOOST_FOREACH(std::wstring s, tok) { 
     39          arguments.push_back(s); 
     40        } 
     41      } catch (const std::exception &e) { 
     42        NSC_LOG_ERROR(_T("Failed to parse arguments for command '") + alias + _T("', using old split string method: ") + utf8::to_unicode(e.what())); 
     43        strEx::splitList list = strEx::splitEx(args, _T(" ")); 
     44        BOOST_FOREACH(std::wstring s, list) { 
     45          arguments.push_back(s); 
     46        } 
    3947      } 
    4048    } 
     
    4957    } 
    5058 
     59    std::wstring alias; 
    5160    std::wstring command; 
    5261    std::list<std::wstring> arguments; 
     
    119128    strEx::token tok = strEx::getToken(command, ' ', true); 
    120129    boost::to_lower(key); 
    121     command_data cd = command_data(tok.first, tok.second); 
     130    command_data cd = command_data(key, tok.first, tok.second); 
    122131    commands[key.c_str()] = cd; 
    123132    register_command(key.c_str(), alias); 
     
    126135    strEx::token tok = strEx::getToken(command, ' ', true); 
    127136    boost::to_lower(key); 
    128     command_data cd = command_data(tok.first, tok.second); 
     137    command_data cd = command_data(key, tok.first, tok.second); 
    129138    alias[key.c_str()] = cd; 
    130139    register_command(key.c_str(), _T("Alias for: ") + cd.to_string()); 
  • modules/CheckSystem/CheckSystem.cpp

    r330af36 rc5ec0c8  
    12271227  bool bExpandIndex = false; 
    12281228  bool bForceReload = false; 
     1229  std::wstring extra_format; 
    12291230 
    12301231  MAP_OPTIONS_BEGIN(arguments) 
     
    12371238    MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData) 
    12381239    MAP_OPTIONS_STR(_T("Alias"), tmpObject.data) 
     1240    MAP_OPTIONS_STR(_T("format"), extra_format) 
    12391241    MAP_OPTIONS_SHOWALL(tmpObject) 
    12401242    MAP_OPTIONS_BOOL_EX(_T("Averages"), bCheckAverages, _T("true"), _T("false")) 
     
    12951297        ptr_lsnr_type cDouble(new PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE>()); 
    12961298        //boost::shared_ptr<PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> > cDouble; 
     1299        if (!extra_format.empty()) { 
     1300          boost::char_separator<wchar_t> sep(_T(",")); 
     1301 
     1302          boost::tokenizer< boost::char_separator<wchar_t>, std::wstring::const_iterator, std::wstring > tokens(extra_format, sep); 
     1303          DWORD flags = 0; 
     1304          BOOST_FOREACH(std::wstring t, tokens) { 
     1305            if (extra_format == _T("nocap100")) 
     1306              flags |= PDH_FMT_NOCAP100; 
     1307            else if (extra_format == _T("1000")) 
     1308              flags |= PDH_FMT_1000; 
     1309            else if (extra_format == _T("noscale")) 
     1310              flags |= PDH_FMT_NOSCALE; 
     1311            else { 
     1312              NSC_LOG_ERROR_STD(_T("Unsupported extrta format: ") + extra_format); 
     1313            } 
     1314          } 
     1315          cDouble->set_extra_format(flags); 
     1316        } 
    12971317        pdh.addCounter(counter.data, cDouble); 
    12981318        pdh.open(); 
     
    13121332        msg += strEx::itos(static_cast<float>(value)); 
    13131333      } else { 
    1314         std::wcout << _T("perf data: ") << bPerfData << std::endl; 
    13151334        counter.perfData = bPerfData; 
    13161335        counter.setDefault(tmpObject); 
  • modules/LUAScript/LUAScript.cpp

    r81e420c rc5ec0c8  
    3030 
    3131 
    32 LUAScript::LUAScript() { 
     32LUAScript::LUAScript() : registry(new lua_wrappers::lua_registry()) { 
    3333} 
    3434LUAScript::~LUAScript() { 
     
    6868    BOOST_FOREACH(script_container &script, scripts_) { 
    6969      try { 
    70         boost::shared_ptr<script_wrapper::lua_script> instance = boost::shared_ptr<script_wrapper::lua_script>(new script_wrapper::lua_script(script)); 
    71         instance->pre_load(this); 
     70        boost::shared_ptr<script_wrapper::lua_script> instance = script_wrapper::lua_script::create_instance(get_core(), get_id(), registry, script.alias, script.script.string()); 
     71        instance->pre_load(); 
    7272        instances_.push_back(instance); 
    73       } catch (script_wrapper::LUAException e) { 
     73      } catch (const lua_wrappers::LUAException &e) { 
    7474        NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + e.getMessage()); 
     75      } catch (const std::exception &e) { 
     76        NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + utf8::to_unicode(e.what())); 
    7577      } 
    7678    } 
     
    7981    //    NSC_LOG_ERROR_STD(_T("Exception caught: ") + e.what()); 
    8082    //    return false; 
     83  } catch (const std::exception &e) { 
     84    NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what())); 
     85    return false; 
    8186  } catch (...) { 
    8287    NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); 
    8388    return false; 
    8489  } 
    85   return true; 
    8690 
    8791//  std::list<std::wstring>::const_iterator it; 
     
    9094//  } 
    9195  return true; 
    92 } 
    93  
    94 void LUAScript::register_command(script_wrapper::lua_script* script, std::wstring command, std::wstring function) { 
    95   NSC_LOG_MESSAGE(_T("Script loading: ") + script->get_wscript() + _T(": ") + command); 
    96   commands_[command] = lua_func(script, function); 
    9796} 
    9897 
     
    135134bool LUAScript::unloadModule() { 
    136135  instances_.clear(); 
     136  scripts_.clear(); 
    137137  return true; 
    138138} 
     
    148148bool LUAScript::reload(std::wstring &message) { 
    149149  bool error = false; 
    150   commands_.clear(); 
     150  registry->clear(); 
    151151  for (script_list::const_iterator cit = instances_.begin(); cit != instances_.end() ; ++cit) { 
    152152    try { 
    153       (*cit)->reload(this); 
    154     } catch (script_wrapper::LUAException e) { 
     153      (*cit)->reload(); 
     154    } catch (const lua_wrappers::LUAException &e) { 
    155155      error = true; 
    156156      message += _T("Exception when reloading script: ") + (*cit)->get_wscript() + _T(": ") + e.getMessage(); 
     
    173173    return reload(message)?NSCAPI::returnOK:NSCAPI::returnCRIT; 
    174174  } 
    175   cmd_list::const_iterator cit = commands_.find(command); 
    176   if (cit == commands_.end()) 
     175  if (!registry->has_command(command)) 
    177176    return NSCAPI::returnIgnored; 
    178   return (*cit).second.handleCommand(this, command.c_str(), arguments, message, perf); 
     177  return registry->on_query(target, command, arguments, message, perf); 
     178    // const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf 
    179179} 
    180180 
  • modules/LUAScript/LUAScript.def

    r8b206ee rc5ec0c8  
    44  NSModuleHelperInit 
    55  NSLoadModule 
     6  NSLoadModuleEx 
    67  NSGetModuleName 
    78  NSGetModuleVersion 
     
    1213  NSUnloadModule 
    1314  NSGetModuleDescription 
     15  NSDeleteBuffer 
    1416 
  • modules/LUAScript/LUAScript.h

    ra78a985 rc5ec0c8  
    3131 
    3232 
    33 class LUAScript : public nscapi::impl::simple_command_handler, public script_wrapper::lua_handler, public nscapi::impl::simple_plugin { 
     33class LUAScript : public nscapi::impl::simple_command_handler, public nscapi::impl::simple_plugin { 
    3434private: 
    3535 
    36   class lua_func { 
    37   public: 
    38     lua_func(script_wrapper::lua_script* script_, std::wstring function_) : script(script_), function(function_) {} 
    39     lua_func() : script(NULL) {} 
    40     script_wrapper::lua_script* script; 
    41     std::wstring function; 
    42  
    43     NSCAPI::nagiosReturn handleCommand(lua_handler *handler, std::wstring command, std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf) const { 
    44       return script->handleCommand(handler, function, command, arguments, msg, perf); 
    45     } 
    46   }; 
    47  
     36  boost::shared_ptr<lua_wrappers::lua_registry> registry; 
    4837  script_container::list_type scripts_; 
    49  
    50   typedef std::map<std::wstring,lua_func> cmd_list; 
    5138  typedef std::list<boost::shared_ptr<script_wrapper::lua_script> > script_list; 
    52  
    53   cmd_list commands_; 
    5439  script_list instances_; 
    5540  boost::filesystem::wpath root_; 
     
    8469  //NSCAPI::nagiosReturn extract_return(Lua_State &L, int arg_count,  std::wstring &message, std::wstring &perf); 
    8570 
    86   //script_wrapper::lua_handler 
    87   void register_command(script_wrapper::lua_script* script, std::wstring command, std::wstring function); 
    88  
    89 private: 
    90   typedef checkHolders::CheckContainer<checkHolders::MaxMinBoundsDiscSize> PathContainer; 
    91   typedef checkHolders::CheckContainer<checkHolders::MaxMinPercentageBoundsDiskSize> DriveContainer; 
    9271}; 
  • modules/LUAScript/script_wrapper.hpp

    r8013c0c rc5ec0c8  
    11#pragma once 
    22 
     3#include <boost/enable_shared_from_this.hpp> 
     4#include <boost/shared_ptr.hpp> 
    35#include <map> 
    46 
    5 extern "C" { 
    6 #include <lua.h> 
    7 #include "lauxlib.h" 
    8 #include "lualib.h" 
    9 } 
    10 #include "luna.h" 
     7#include "lua_wrappers.hpp" 
    118 
    129#include <scripts/functions.hpp> 
     
    1411namespace script_wrapper { 
    1512 
    16   class Lua_State { 
    17     lua_State *L; 
    18   public: 
    19     Lua_State() : L(lua_open()) { } 
    20  
    21     ~Lua_State() { 
    22       lua_close(L); 
    23     } 
    24  
    25     // implicitly act as a lua_State pointer 
    26     inline operator lua_State*() { 
    27       return L; 
    28     } 
    29   }; 
    30  
    31   class LUAException { 
    32     std::wstring error_; 
    33   public: 
    34     LUAException(std::wstring error) : error_(error) {} 
    35  
    36     std::wstring getMessage() const { 
    37       return error_; 
    38     } 
    39  
    40   }; 
    41  
    42   inline std::string w2s(std::wstring s) { 
    43     return strEx::wstring_to_string(s); 
    44   } 
    45   inline std::wstring s2w(std::string s) { 
    46     return strEx::string_to_wstring(s); 
    47   } 
    48   typedef std::pair<std::wstring,int> where_type; 
    49   where_type where(lua_State *L, int level = 1) { 
    50     lua_Debug ar; 
    51     if (lua_getstack(L, level, &ar)) {  /* check function at level */ 
    52       lua_getinfo(L, "Sl", &ar);  /* get info about it */ 
    53       if (ar.currentline > 0) {  /* is there info? */ 
    54         return where_type(s2w(ar.short_src), ar.currentline); 
    55       } 
    56     } 
    57     return where_type(_T("unknown"),0); 
    58   } 
    59   std::wstring extract_string(lua_State *L) { 
    60     int top = lua_gettop(L); 
    61     if (lua_isstring(L, top)) 
    62       return strEx::string_to_wstring(lua_tostring( L, lua_gettop( L ) )); 
    63     return _T("<NOT_A_STRING>"); 
    64   } 
    65   std::wstring pop_string(lua_State *L) { 
    66     std::wstring ret; 
    67     int top = lua_gettop(L); 
    68     if (lua_isstring(L, top)) 
    69       ret = strEx::string_to_wstring(lua_tostring( L, top)); 
    70     else if (lua_isnil(L, top)) 
    71       ret = _T("<NIL>"); 
    72     else if (lua_istable(L, top)) 
    73       ret = _T("<TABLE>"); 
    74     else if (lua_isnumber(L, top)) 
    75       ret = _T("<NUMBER>"); 
    76     else if (lua_iscfunction(L, top)) 
    77       ret = _T("<C-FUNCTION>"); 
    78     else 
    79       ret = _T("<UNKNOWN>"); 
    80     lua_pop(L, 1); 
    81     return ret; 
    82   } 
    83   NSCAPI::nagiosReturn extract_code(lua_State *L) { 
    84     std::string str; 
    85     switch (lua_type( L, lua_gettop( L ) )) { 
    86   case LUA_TNUMBER:  
    87     return static_cast<int>(lua_tonumber(L, lua_gettop(L))); 
    88   case LUA_TTABLE: 
    89     NSC_LOG_ERROR_STD(_T("Incorect return from script: should be error, ok, warning or unknown")); 
    90     return NSCAPI::returnUNKNOWN; 
    91   case LUA_TSTRING: 
    92     str = lua_tostring(L, lua_gettop(L)); 
    93     if ((str == "critical")||(str == "crit")||(str == "error")) { 
    94       return NSCAPI::returnCRIT; 
    95     } else if ((str == "warning")||(str == "warn")) { 
    96       return NSCAPI::returnWARN; 
    97     } else if (str == "ok") { 
    98       return NSCAPI::returnOK; 
    99     } else if (str == "unknown") { 
    100       return NSCAPI::returnUNKNOWN; 
    101     } else { 
    102       NSC_LOG_ERROR_STD(_T("Incorect return from script: should be ok, warning, critical or unknown not: ") + strEx::string_to_wstring(str) ); 
    103       return NSCAPI::returnUNKNOWN; 
    104     } 
    105   case LUA_TBOOLEAN: 
    106     return lua_toboolean( L, lua_gettop( L ) )?NSCAPI::returnOK:NSCAPI::returnCRIT; 
    107     } 
    108     NSC_LOG_ERROR_STD(_T("Incorect return from script: should be error, ok, warning or unknown")); 
    109     return NSCAPI::returnUNKNOWN; 
    110   } 
    111   void push_code(lua_State *L, NSCAPI::nagiosReturn  code) { 
    112     if (code == NSCAPI::returnOK) 
    113       lua_pushstring(L, strEx::wstring_to_string(_T("ok")).c_str()); 
    114     else if (code == NSCAPI::returnWARN) 
    115       lua_pushstring(L, strEx::wstring_to_string(_T("warning")).c_str()); 
    116     else if (code == NSCAPI::returnCRIT) 
    117       lua_pushstring(L, strEx::wstring_to_string(_T("critical")).c_str()); 
    118     else 
    119     lua_pushstring(L, strEx::wstring_to_string(_T("unknown")).c_str()); 
    120   } 
    121   void push_string(lua_State *L, std::wstring s) { 
    122     lua_pushstring(L, strEx::wstring_to_string(s).c_str()); 
    123   } 
    124   void push_array(lua_State *L, std::list<std::wstring> &arr) { 
    125     lua_createtable(L, 0, arr.size()); 
    126     int i=0; 
    127     for (std::list<std::wstring>::const_iterator cit=arr.begin(); cit != arr.end(); ++cit) { 
    128       lua_pushnumber(L,i++); 
    129       lua_pushstring(L,strEx::wstring_to_string(*cit).c_str()); 
    130       lua_settable(L,-3); 
    131     } 
    132   } 
    133  
    134   class lua_script; 
    135   class lua_handler { 
    136   public: 
    137     virtual void register_command(lua_script* script, std::wstring command, std::wstring function) = 0; 
    138  
    139   }; 
    140   class lua_manager { 
    141     typedef std::map<double,lua_handler*> handler_type; 
    142     typedef std::map<double,lua_script*> script_type; 
    143     static handler_type handlers; 
    144     static script_type scripts; 
    145     static double last_value; 
    146     static char handler_key[]; 
    147     static char script_key[]; 
    148   public: 
    149     static lua_handler* get_handler(lua_State *L) { 
    150       handler_type::const_iterator cit = handlers.find(get_id(L, handler_key)); 
    151       if (cit == handlers.end()) 
    152         throw LUAException(_T("Could not find handler reference")); 
    153       return (*cit).second; 
    154     } 
    155     static void set_handler(lua_State *L, lua_handler* handler) { 
    156       double id = get_id(L, handler_key); 
    157       handlers[id] = handler; 
    158     } 
    159     static lua_script* get_script(lua_State *L) { 
    160       script_type::const_iterator cit = scripts.find(get_id(L, script_key)); 
    161       if (cit == scripts.end()) 
    162         throw LUAException(_T("Could not find script reference")); 
    163       return (*cit).second; 
    164     } 
    165     static void set_script(lua_State *L, lua_script* script) { 
    166       double id = get_id(L, script_key); 
    167       scripts[id] = script; 
    168     } 
    169     static double get_id(lua_State *L, char *key) { 
    170       /* retrieve a number */ 
    171       lua_pushstring(L, key); 
    172       //lua_pushlightuserdata(L, (void*)&key);  /* push address */ 
    173       lua_gettable(L, LUA_REGISTRYINDEX);  /* retrieve value */ 
    174       double v = 0; 
    175       v = lua_tonumber(L, -1);  /* convert to number */ 
    176       lua_pop(L,1); 
    177       if (v <= 0) { 
    178         v = ++last_value; 
    179         lua_pushstring(L, key); 
    180         //lua_pushlightuserdata(L, reinterpret_cast<void*>(&key));  /* push address */ 
    181         lua_pushnumber(L, v);  /* push value */ 
    182         /* registry[&Key] = myNumber */ 
    183         lua_settable(L, LUA_REGISTRYINDEX); 
    184       } 
    185       return v; 
    186  
    187     } 
    188  
    189   }; 
     13  typedef lua_wrappers::lua_wrapper lua_wrapper; 
     14  typedef lua_wrappers::lua_script_instance script_instance; 
     15  typedef lua_wrappers::lua_instance_manager instance_manager; 
     16 
     17 
     18  class base_script_object : boost::noncopyable { 
     19  private: 
     20    instance_manager::script_instance_type instance; 
     21 
     22  public: 
     23    base_script_object(lua_State *L) { 
     24      instance = instance_manager::get_script(L); 
     25    } 
     26    instance_manager::script_instance_type get_instance() { 
     27      if (!instance) 
     28        throw lua_wrappers::LUAException("Invalid instance"); 
     29      return instance; 
     30    } 
     31  }; 
     32 
     33  class core_wrapper : public base_script_object { 
     34  public: 
     35    core_wrapper(lua_State *L) : base_script_object(L) { 
     36      NSC_DEBUG_MSG(_T("get: ")); 
     37    } 
     38 
     39    static const char className[]; 
     40    static const Luna<core_wrapper>::RegType methods[]; 
     41 
     42    int simple_query(lua_State *L) { 
     43      lua_wrappers::lua_wrapper lua(L); 
     44      try { 
     45        int nargs = lua.size(); 
     46        if (nargs == 0) 
     47          return lua.error("nscp.execute requires at least 1 argument!"); 
     48        const unsigned int argLen = nargs-1; 
     49        std::list<std::wstring> arguments; 
     50        for (unsigned int i=argLen; i>0; i--) { 
     51          if (lua.is_table()) { 
     52            std::list<std::wstring> table = lua.pop_array(); 
     53            arguments.insert(arguments.begin(), table.begin(), table.end()); 
     54          } else { 
     55            arguments.push_front(lua.pop_string()); 
     56          } 
     57        } 
     58        std::wstring command = lua.pop_string(); 
     59        std::wstring message; 
     60        std::wstring perf; 
     61        NSCAPI::nagiosReturn ret = get_instance()->get_core()->simple_query(command, arguments, message, perf); 
     62        lua.push_code(ret); 
     63        lua.push_string(message); 
     64        lua.push_string(perf); 
     65        return lua.size(); 
     66      } catch (...) { 
     67        return lua.error("Unknown exception in: simple_query"); 
     68      } 
     69    } 
     70    int query(lua_State *L) { 
     71      lua_wrappers::lua_wrapper lua(L); 
     72      NSC_LOG_ERROR_STD(_T("Unsupported API called: query")); 
     73      return lua.error("Unsupported API called: query"); 
     74    } 
     75    int simple_exec(lua_State *L) { 
     76      NSC_DEBUG_MSG(_T("s_q")); 
     77      return 0; 
     78    } 
     79    int exec(lua_State *L) { 
     80      lua_wrappers::lua_wrapper lua(L); 
     81      NSC_LOG_ERROR_STD(_T("Unsupported API called: exec")); 
     82      return lua.error("Unsupported API called: exec"); 
     83    } 
     84    int simple_submit(lua_State *L) { 
     85      NSC_DEBUG_MSG(_T("s_q")); 
     86      return 0; 
     87    } 
     88    int submit(lua_State *L) { 
     89      lua_wrappers::lua_wrapper lua(L); 
     90      NSC_LOG_ERROR_STD(_T("Unsupported API called: submit")); 
     91      return lua.error("Unsupported API called: submit"); 
     92    } 
     93    int reload(lua_State *L) { 
     94      lua_wrappers::lua_wrapper lua(L); 
     95      if (lua.size() > 1) 
     96        return lua.error("Incorrect syntax: reload([<module>]);"); 
     97      std::wstring module = _T("module"); 
     98      if (lua.size() == 1) 
     99        module = lua.pop_string(); 
     100      get_instance()->get_core()->reload(module); 
     101      return 0; 
     102    } 
     103  }; 
     104 
     105  const char core_wrapper::className[] = "Core"; 
     106  const Luna<core_wrapper>::RegType core_wrapper::methods[] = { 
     107    { "simple_query", &core_wrapper::simple_query }, 
     108    { "query", &core_wrapper::query }, 
     109    { "simple_exec", &core_wrapper::simple_exec }, 
     110    { "exec", &core_wrapper::exec }, 
     111    { "simple_submit", &core_wrapper::simple_submit }, 
     112    { "submit", &core_wrapper::submit }, 
     113    { "reload", &core_wrapper::reload }, 
     114    { 0 } 
     115  }; 
     116 
     117  class registry_wrapper : public base_script_object { 
     118  private: 
     119    //registry_wrapper(const registry_wrapper &other) {} 
     120    //registry_wrapper& operator=(const registry_wrapper &other) {} 
     121 
     122  public: 
     123 
     124    registry_wrapper(lua_State *L) : base_script_object(L) { 
     125      NSC_DEBUG_MSG(_T("create (from LUA)")); 
     126    } 
     127    /* 
     128    registry_wrapper(nscapi::core_wrapper* core, unsigned int plugin_id) : core(core), plugin_id(plugin_id) { 
     129      NSC_DEBUG_MSG(_T("create (from c++)")); 
     130    } 
     131    static boost::shared_ptr<registry_wrapper> create(unsigned int plugin_id) { 
     132      return boost::shared_ptr<registry_wrapper>(new registry_wrapper(nscapi::plugin_singleton->get_core(), plugin_id)); 
     133    } 
     134    */ 
     135 
     136    static const char className[]; 
     137    static const Luna<registry_wrapper>::RegType methods[]; 
     138 
     139    int register_function(lua_State *L) { 
     140      NSC_DEBUG_MSG(_T("register_function")); 
     141      return 0; 
     142    } 
     143    int register_simple_function(lua_State *L) { 
     144      NSC_DEBUG_MSG(_T("register_simple_function")); 
     145      lua_wrapper lua(L); 
     146      std::wstring description; 
     147      if (lua.size() > 2) 
     148        description = lua.pop_string(); 
     149      std::wstring name; 
     150      if (lua.is_string()) { 
     151        name = lua.pop_string(); 
     152        lua_getglobal(L, utf8::cvt<std::string>(name).c_str()); 
     153      } 
     154      if (!lua.is_function()) 
     155        return lua.error("Invalid argument not a function: " + utf8::cvt<std::string>(name)); 
     156 
     157      int func_ref = luaL_ref(L, LUA_REGISTRYINDEX); 
     158 
     159      if (func_ref == 0) 
     160        return lua.error("Invalid function: " + utf8::cvt<std::string>(name)); 
     161      std::wstring script = lua.pop_string(); 
     162      if (description.empty())  
     163        description = _T("Lua script: ") + script; 
     164      get_instance()->get_core()->registerCommand(get_instance()->get_plugin_id(), script, description); 
     165      get_instance()->get_registry()->register_query(script, get_instance(), func_ref); 
     166      return 0; 
     167    } 
     168    int register_cmdline(lua_State *L) { 
     169      NSC_DEBUG_MSG(_T("register_cmdline")); 
     170      return 0; 
     171    } 
     172    int register_simple_cmdline(lua_State *L) { 
     173      NSC_DEBUG_MSG(_T("register_simple_cmdline")); 
     174      return 0; 
     175    } 
     176    int subscription(lua_State *L) { 
     177      NSC_DEBUG_MSG(_T("subscription")); 
     178      return 0; 
     179    } 
     180    int simple_subscription(lua_State *L) { 
     181      NSC_DEBUG_MSG(_T("simple_subscription")); 
     182      return 0; 
     183    } 
     184  }; 
     185 
     186  const char registry_wrapper::className[] = "Registry"; 
     187  const Luna<registry_wrapper>::RegType registry_wrapper::methods[] = { 
     188    { "function", &registry_wrapper::register_function }, 
     189    { "simple_function", &registry_wrapper::register_simple_function }, 
     190    { "cmdline", &registry_wrapper::register_cmdline }, 
     191    { "simple_cmdline", &registry_wrapper::register_simple_cmdline }, 
     192    { "subscription", &registry_wrapper::subscription }, 
     193    { "simple_subscription", &registry_wrapper::simple_subscription }, 
     194    { 0 } 
     195  }; 
     196 
     197 
     198 
     199  class settings_wrapper : public base_script_object { 
     200  public: 
     201 
     202    settings_wrapper(lua_State *L) : base_script_object(L) { 
     203      NSC_DEBUG_MSG(_T("create")); 
     204    } 
     205 
     206    static const char className[]; 
     207    static const Luna<settings_wrapper>::RegType methods[]; 
     208 
     209 
     210 
     211    int get_section(lua_State *L) { 
     212      lua_wrapper lua(L); 
     213      int nargs = lua.size(); 
     214      if (nargs > 1) 
     215        return lua.error("Incorrect syntax: get_section([<section>]);"); 
     216      std::wstring v; 
     217      if (nargs > 0) 
     218        v = lua.pop_string(); 
     219      try { 
     220        lua.push_array(get_instance()->get_core()->getSettingsSection(v)); 
     221      } catch (...) { 
     222        return lua.error("Unknown exception getting section"); 
     223      } 
     224      return 1; 
     225    } 
     226    int get_string(lua_State *L) { 
     227      lua_wrapper lua(L); 
     228      int nargs = lua.size(); 
     229//      if (nargs < 2 || nargs > 3) { 
     230//        return lua.error("Incorrect syntax: get_string(<section>, <key>[, <default value>]);" + utf8::cvt<std::string>(lua.dump_stack())); 
     231//      } 
     232      std::wstring v; 
     233      if (nargs > 2) 
     234        v = lua.pop_string(); 
     235      std::wstring k = lua.pop_string(); 
     236      std::wstring s = lua.pop_string(); 
     237      if (nargs > 1) 
     238        lua.pop_string(); 
     239      lua.push_string(get_instance()->get_core()->getSettingsString(s, k, v)); 
     240      return 1; 
     241    } 
     242    int set_string(lua_State *L) { 
     243      NSC_DEBUG_MSG(_T("set_string")); 
     244      return 0; 
     245    } 
     246    int get_bool(lua_State *L) { 
     247      lua_wrapper lua(L); 
     248      int nargs = lua.size(); 
     249      if (nargs < 2 || nargs > 3) 
     250        return lua.error("Incorrect syntax: get_string(<section>, <key>[, <default value>]);"); 
     251      bool v; 
     252      if (nargs > 2) 
     253        v = lua.pop_boolean(); 
     254      std::wstring k = lua.pop_string(); 
     255      std::wstring s = lua.pop_string(); 
     256      lua.push_boolean(get_instance()->get_core()->getSettingsInt(s, k, v?1:0)==1); 
     257      return 1; 
     258    } 
     259    int set_bool(lua_State *L) { 
     260      NSC_DEBUG_MSG(_T("set_bool")); 
     261      return 0; 
     262    } 
     263    int get_int(lua_State *L) { 
     264      NSC_DEBUG_MSG(_T("get_int")); 
     265      return 0; 
     266    } 
     267    int set_int(lua_State *L) { 
     268      NSC_DEBUG_MSG(_T("set_int")); 
     269      return 0; 
     270    } 
     271    int save(lua_State *L) { 
     272      NSC_DEBUG_MSG(_T("save")); 
     273      return 0; 
     274    } 
     275    int register_path(lua_State *L) { 
     276      NSC_DEBUG_MSG(_T("register_path")); 
     277      return 0; 
     278    } 
     279    int register_key(lua_State *L) { 
     280      NSC_DEBUG_MSG(_T("register_key")); 
     281      return 0; 
     282    } 
     283     
     284  }; 
     285 
     286  const char settings_wrapper::className[] = "Settings"; 
     287  const Luna<settings_wrapper>::RegType settings_wrapper::methods[] = { 
     288    { "get_section", &settings_wrapper::get_section }, 
     289    { "get_string", &settings_wrapper::get_string }, 
     290    { "set_string", &settings_wrapper::set_string }, 
     291    { "get_bool", &settings_wrapper::get_bool }, 
     292    { "set_bool", &settings_wrapper::set_bool }, 
     293    { "get_int", &settings_wrapper::get_int }, 
     294    { "set_int", &settings_wrapper::set_int }, 
     295    { "save", &settings_wrapper::save }, 
     296    { "register_path", &settings_wrapper::register_path }, 
     297    { "register_key", &settings_wrapper::register_key }, 
     298    { 0 } 
     299  }; 
     300 
    190301  class nsclient_wrapper { 
    191302  public: 
     
    193304    static int execute (lua_State *L) { 
    194305      try { 
    195         int nargs = lua_gettop( L ); 
    196         if (nargs == 0) { 
    197           return luaL_error(L, "nscp.execute requires at least 1 argument!"); 
    198         } 
     306        lua_wrapper lua(L); 
     307        int nargs = lua.size(); 
     308        if (nargs == 0) 
     309          return lua.error("nscp.execute requires at least 1 argument!"); 
    199310        unsigned int argLen = nargs-1; 
    200311        std::list<std::wstring> arguments; 
    201         for (unsigned int i=argLen;i>0;i--) { 
    202           arguments.push_front(extract_string(L)); 
    203           lua_pop(L, 1); 
    204         } 
    205         std::wstring command = extract_string(L); 
    206         lua_pop(L, 1); 
     312        for (unsigned int i=argLen; i>0; i--) 
     313          arguments.push_front(lua.pop_string()); 
     314        std::wstring command = lua.pop_string(); 
    207315        std::wstring message; 
    208316        std::wstring perf; 
    209317        NSCAPI::nagiosReturn ret = GET_CORE()->simple_query(command, arguments, message, perf); 
    210         push_code(L, ret); 
    211         lua_pushstring(L, strEx::wstring_to_string(message).c_str()); 
    212         lua_pushstring(L, strEx::wstring_to_string(perf).c_str()); 
     318        lua.push_code(ret); 
     319        lua.push_string(message); 
     320        lua.push_string(perf); 
    213321        return 3; 
    214322      } catch (...) { 
     
    218326 
    219327    static int register_command(lua_State *L) { 
    220       try { 
    221         lua_handler *handler = lua_manager::get_handler(L); 
    222         lua_script *script = lua_manager::get_script(L); 
    223         int nargs = lua_gettop( L ); 
    224         if (nargs != 2) 
    225           return luaL_error(L, "Incorrect syntax: nscp.register(<key>, <function>);"); 
    226         handler->register_command(script, pop_string(L), pop_string(L)); 
    227         return 0; 
    228       } catch (LUAException e) { 
    229         return luaL_error(L, std::string("Error in nscp.register: " + w2s(e.getMessage())).c_str()); 
    230       } catch (...) { 
    231         return luaL_error(L, "Unknown exception in: nscp.register"); 
    232       } 
     328      registry_wrapper registry(L); 
     329      return registry.register_simple_function(L); 
    233330    } 
    234331 
    235332    static int getSetting (lua_State *L) { 
    236       int nargs = lua_gettop( L ); 
    237       if (nargs < 2 || nargs > 3) 
    238         return luaL_error(L, "Incorrect syntax: nscp.getSetting(<section>, <key>[, <default value>]);"); 
    239       std::wstring v; 
    240       if (nargs > 2) 
    241         v = pop_string(L); 
    242       std::wstring k = pop_string(L); 
    243       std::wstring s = pop_string(L); 
    244       push_string(L, GET_CORE()->getSettingsString(s, k, v)); 
    245       return 1; 
     333      settings_wrapper sw(L); 
     334      return sw.get_string(L); 
    246335    } 
    247336    static int getSection (lua_State *L) { 
    248       int nargs = lua_gettop( L ); 
    249       if (nargs > 1) 
    250         return luaL_error(L, "Incorrect syntax: nscp.getSection([<section>]);"); 
    251       std::wstring v; 
    252       if (nargs > 0) 
    253         v = pop_string(L); 
    254       try { 
    255         std::list<std::wstring> list = GET_CORE()->getSettingsSection(v); 
    256         push_array(L, list); 
    257       } catch (...) { 
    258         return luaL_error(L, "Unknown exception getting section"); 
    259       } 
    260       return 1; 
     337      settings_wrapper sw(L); 
     338      return sw.get_section(L); 
    261339    } 
    262340    static int info (lua_State *L) { 
     
    267345    } 
    268346    static int log_any(lua_State *L, int mode) { 
    269       where_type w = where(L); 
    270       int nargs = lua_gettop( L ); 
     347      lua_wrapper lua(L); 
     348      lua_wrapper::stack_trace trace = lua.get_stack_trace(); 
     349      int nargs = lua.size(); 
    271350      std::wstring str; 
    272351      for (int i=0;i<nargs;i++) { 
    273         str += pop_string(L); 
    274       } 
    275       GET_CORE()->log(mode, utf8::cvt<std::string>(w.first), w.second, str); 
     352        str += lua.pop_string(); 
     353      } 
     354      GET_CORE()->log(mode, utf8::cvt<std::string>(trace.first), trace.second, str); 
    276355      return 0; 
    277356    } 
     
    279358    static const luaL_Reg my_funcs[]; 
    280359 
    281     static int luaopen(lua_State *L) { 
     360    static void luaopen(lua_State *L) { 
    282361      luaL_register(L, "nscp", my_funcs); 
    283       return 1; 
    284     } 
    285  
     362      lua_pop(L, 1); 
     363      Luna<core_wrapper>::Register(L); 
     364      Luna<registry_wrapper>::Register(L); 
     365      Luna<settings_wrapper>::Register(L); 
     366    } 
    286367 
    287368  }; 
     
    297378  }; 
    298379 
    299   lua_manager::handler_type lua_manager::handlers; 
    300   lua_manager::script_type lua_manager::scripts; 
    301   double lua_manager::last_value = 0; 
    302   char lua_manager::handler_key[] = "registry.key.handler"; 
    303   char lua_manager::script_key[] = "registry.key.script"; 
    304  
    305   class lua_script { 
    306     Lua_State L; 
    307     std::string script_; 
    308     std::string alias_; 
    309   public: 
    310     lua_script(const script_container &script) : script_(utf8::cvt<std::string>(script.script.string())), alias_(utf8::cvt<std::string>(script.alias)) { 
     380  class lua_script : public script_instance, public boost::enable_shared_from_this<lua_script>  { 
     381    lua_script(nscapi::core_wrapper* core, const int plugin_id, boost::shared_ptr<lua_wrappers::lua_registry> registry, const std::string alias, const std::string script)  
     382      : script_instance(core, plugin_id, registry, alias, script) { 
    311383      load(); 
    312384    } 
     385  public: 
     386 
     387    static boost::shared_ptr<lua_script> create_instance(nscapi::core_wrapper* core, const int plugin_id, boost::shared_ptr<lua_wrappers::lua_registry> registry, const std::wstring alias, const std::wstring script) { 
     388      boost::shared_ptr<lua_script> instance(new lua_script(core, plugin_id, registry, utf8::cvt<std::string>(alias), utf8::cvt<std::string>(script))); 
     389      if (instance) 
     390        instance->init(); 
     391      return instance; 
     392    } 
     393    void init() { 
     394      lua_wrappers::lua_instance_manager::set_script(get_lua_state(), shared_from_this()); 
     395    } 
     396 
    313397    void load() { 
    314       luaL_openlibs(L); 
    315       nsclient_wrapper::luaopen(L); 
    316       if (luaL_loadfile(L, script_.c_str()) != 0) { 
    317         throw LUAException(_T("Failed to load script: ") + get_wscript() + _T(": ") + s2w(lua_tostring(L, -1))); 
    318       } 
    319  
     398      int i = lua_gettop(get_lua_state()); 
     399      luaL_openlibs(get_lua_state()); 
     400      i = lua_gettop(get_lua_state()); 
     401      nsclient_wrapper::luaopen(get_lua_state()); 
     402      i = lua_gettop(get_lua_state()); 
     403      if (luaL_loadfile(get_lua_state(), get_script().c_str()) != 0) { 
     404        throw lua_wrappers::LUAException(_T("Failed to load script: ") + get_wscript() + _T(": ") + utf8::cvt<std::wstring>(lua_tostring(get_lua_state(), -1))); 
     405      } 
    320406    } 
    321407    std::wstring get_wscript() const { 
    322       return utf8::cvt<std::wstring>(script_); 
    323     } 
    324     std::string get_script() const { 
    325       return script_; 
     408      return utf8::cvt<std::wstring>(get_script()); 
    326409    } 
    327410    void unload() {} 
    328     void reload(lua_handler *handler) { 
     411    void reload() { 
    329412      unload(); 
    330413      load(); 
    331       pre_load(handler); 
    332     } 
    333     void pre_load(lua_handler *handler) { 
    334       lua_manager::set_handler(L, handler); 
    335       lua_manager::set_script(L, this); 
    336       if (lua_pcall(L, 0, 0, 0) != 0) { 
    337         throw LUAException(_T("Failed to parse script: ") + get_wscript() + _T(": ") + s2w(lua_tostring(L, -1))); 
    338       } 
    339     } 
    340  
    341  
    342     NSCAPI::nagiosReturn extract_return(Lua_State &L, int arg_count,  std::wstring &message, std::wstring &perf) { 
    343       // code, message, performance data 
    344       if (arg_count > 3) { 
    345         NSC_LOG_ERROR_STD(_T("Too many arguments return from script (only using last 3)")); 
    346         lua_pop(L, arg_count-3); 
    347       } 
    348       if (arg_count > 2) { 
    349         perf = extract_string(L); 
    350         lua_pop( L, 1 ); 
    351       } 
    352       if (arg_count > 1) { 
    353         message = extract_string(L); 
    354         lua_pop( L, 1 ); 
    355       } 
    356       if (arg_count > 0) { 
    357         int ret = extract_code(L); 
    358         lua_pop( L, 1 ); 
    359         return ret; 
    360       } 
    361       NSC_LOG_ERROR_STD(_T("No arguments returned from script.")); 
    362       return NSCAPI::returnUNKNOWN; 
    363     } 
    364  
     414      pre_load(); 
     415    } 
     416    void pre_load() { 
     417      if (lua_pcall(get_lua_state(), 0, 0, 0) != 0) { 
     418        throw lua_wrappers::LUAException(_T("Failed to parse script: ") + get_wscript() + _T(": ") + utf8::cvt<std::wstring>(lua_tostring(get_lua_state(), -1))); 
     419      } 
     420    } 
     421 
     422 
     423/* 
    365424    NSCAPI::nagiosReturn handleCommand(lua_handler *handler, std::wstring function, std::wstring cmd, std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf) { 
    366425      lua_manager::set_handler(L, handler); 
    367426      lua_manager::set_script(L, this); 
    368       int nargs = lua_gettop( L ); 
    369       lua_getglobal(L, w2s(function).c_str()); 
     427      lua_wrapper lua(L); 
     428      int nargs = lua.size(); 
     429      lua_getglobal(L, utf8::cvt<std::string>(function).c_str()); 
    370430      if (!lua_isfunction(L, -1)) { 
    371431        lua_pop(L, 1); // remove function from LUA stack 
    372         throw LUAException(_T("Failed to run script: ") + get_wscript() + _T(": Function not found: handle")); 
    373       } 
    374       lua_pushstring(L, w2s(cmd).c_str());  
    375  
    376       lua_createtable(L, 0, arguments.size()); 
    377       int i=0; 
    378       BOOST_FOREACH(std::wstring arg, arguments) { 
    379         lua_pushnumber(L,i++); 
    380         lua_pushstring(L,strEx::wstring_to_string(arg).c_str()); 
    381         lua_settable(L,-3); 
    382       } 
     432        throw lua_wrappers::LUAException(_T("Failed to run script: ") + get_wscript() + _T(": Function not found: handle")); 
     433      } 
     434      lua.push_string(cmd);  
     435      lua.push_array(arguments); 
    383436 
    384437      if (lua_pcall(L, 2, LUA_MULTRET, 0) != 0) { 
    385         std::wstring err = strEx::string_to_wstring(lua_tostring(L, -1)); 
     438        std::wstring err = lua.pop_string(); 
    386439        NSC_LOG_ERROR_STD(_T("Failed to call main function in script: ") + get_wscript() + _T(": ") + err); 
    387         lua_pop(L, 1); // remove error message 
    388440        return NSCAPI::returnUNKNOWN; 
    389441      } 
    390       return extract_return(L, lua_gettop( L )-nargs, msg, perf); 
    391     } 
     442      return extract_return(L, lua.size(), msg, perf); 
     443    } 
     444    */ 
    392445  }; 
    393446 
  • modules/NSCAClient/NSCAClient.cpp

    r8013c0c rc5ec0c8  
    283283 
    284284void NSCAAgent::setup(client::configuration &config) { 
    285   boost::shared_ptr<clp_handler_impl> handler = boost::shared_ptr<clp_handler_impl>(new clp_handler_impl(this)); 
     285  boost::shared_ptr<clp_handler_impl> handler(new clp_handler_impl(this)); 
    286286  add_local_options(config.local, config.data); 
    287287 
  • modules/NSCAServer/handler_impl.cpp

    r98113da rc5ec0c8  
    1717 
    1818  } 
    19   std::wstring perf = _T(""); // @todo fix this! 
    20  
    2119  NSC_DEBUG_MSG(_T("Got response: ") + response); 
    2220} 
  • service/cli_parser.hpp

    r8013c0c rc5ec0c8  
    3333    root.add_options() 
    3434      ("help", po::bool_switch(&help), "produce help message") 
     35      /* 
    3536      ("settings-help", "Produce help message for the various settings related options") 
    3637      ("service-help", "Produce help message for the various settings related service management") 
    3738      ("client-help", "Produce help message for the various settings related client") 
    3839      ("test-help", "Produce help message for the various settings related client") 
     40      */ 
    3941/* 
    4042      ("settings", "Enter settings mode and handle settings related commands") 
     
    107109  } 
    108110 
    109  
    110  
    111   int parse(int argc, wchar_t* argv[]) { 
    112  
    113     typedef boost::function<int(int, wchar_t**)> handler_function; 
    114     typedef std::map<std::string,handler_function> handler_map; 
    115     typedef std::map<std::string,std::string> alias_map; 
     111  typedef boost::function<int(int, wchar_t**)> handler_function; 
     112  typedef std::map<std::string,handler_function> handler_map; 
     113  typedef std::map<std::string,std::string> alias_map; 
     114 
     115  handler_map get_handlers() { 
    116116    handler_map handlers; 
    117     alias_map aliases; 
    118117    handlers["settings"] = boost::bind(&cli_parser::parse_settings, this, _1, _2); 
    119118    handlers["service"] = boost::bind(&cli_parser::parse_service, this, _1, _2); 
    120119    handlers["client"] = boost::bind(&cli_parser::parse_client, this, _1, _2, _T("")); 
    121120    handlers["test"] = boost::bind(&cli_parser::parse_test, this, _1, _2); 
    122  
     121    handlers["help"] = boost::bind(&cli_parser::parse_help, this, _1, _2); 
     122    return handlers; 
     123  } 
     124 
     125  alias_map get_aliases() { 
     126    alias_map aliases; 
    123127    aliases["nrpe"] = "NRPEClient"; 
    124128    aliases["nscp"] = "NSCPClient"; 
     
    129133    aliases["lua"] = "LuaScript"; 
    130134    aliases["syslog"] = "SyslogClient"; 
     135    return aliases; 
     136  } 
     137 
     138  int parse(int argc, wchar_t* argv[]) { 
    131139 
    132140    if (argc > 1 && argv[1][0] != L'-') { 
     141      handler_map handlers = get_handlers(); 
     142      alias_map aliases = get_aliases(); 
     143 
    133144      std::string mod = utf8::cvt<std::string>(argv[1]); 
    134145      handler_map::const_iterator it = handlers.find(mod); 
     
    140151        return parse_client(argc-1, &argv[1], utf8::cvt<std::wstring>(alias_it->second)); 
    141152 
     153      parse_help(argc, argv); 
    142154      std::cerr << "Invalid module specified: " << mod << std::endl; 
    143       std::cerr << "Available modules are: "; 
     155      return 1; 
     156    } 
     157    return parse_help(argc, argv); 
     158  } 
     159  int parse_help(int argc, wchar_t* argv[]) { 
     160    try { 
     161 
     162      po::options_description all("Allowed options"); 
     163      all.add(root).add(common).add(service).add(settings).add(client); 
     164      std::cout << all << std::endl; 
     165 
     166      std::cerr << "First argument has to be one of the following: "; 
     167      handler_map handlers = get_handlers(); 
    144168      BOOST_FOREACH(const handler_map::value_type &itm, handlers) { 
    145169        std::cerr << itm.first << ", "; 
    146170      } 
     171      std::cerr << std::endl; 
     172      std::cerr << "Or on of the following client aliases: "; 
     173      alias_map aliases = get_aliases(); 
    147174      BOOST_FOREACH(const alias_map::value_type &itm, aliases) { 
    148175        std::cerr << itm.first << ", "; 
     
    150177      std::cerr << std::endl; 
    151178      return 1; 
    152     } 
    153  
    154     try { 
    155       po::options_description all("Allowed options"); 
    156       all.add(root).add(common).add(service).add(settings).add(client); 
    157  
    158       po::variables_map vm; 
    159       po::wparsed_options parsed =  
    160         po::wcommand_line_parser((argc>2)?2:argc, argv).options(root).run(); 
    161  
    162       po::store(parsed, vm); 
    163       po::notify(vm); 
    164  
    165       BOOST_FOREACH(handler_map::value_type &it, handlers) { 
    166         if (vm.count(it.first)) { 
    167           return it.second(argc-1, &argv[1]); 
    168         } 
    169       } 
    170       std::cerr << "First argument has to be one of the following: " << std::endl; 
    171       std::cout << root << std::endl; 
    172       return 1; 
    173179    } catch(std::exception & e) { 
    174180      std::cerr << "Unable to parse root option: " << e.what() << std::endl; 
     
    178184      return 1; 
    179185    } 
    180     return 0; 
    181186  } 
    182187 
  • version.hpp

    r8013c0c rc5ec0c8  
    11#ifndef VERSION_HPP 
    22#define VERSION_HPP 
    3 #define PRODUCTVER     0,4,0,129 
    4 #define STRPRODUCTVER  "0,4,0,129" 
    5 #define STRPRODUCTDATE "2012-01-21" 
     3#define PRODUCTVER     0,4,0,130 
     4#define STRPRODUCTVER  "0,4,0,130" 
     5#define STRPRODUCTDATE "2012-01-26" 
    66#endif // VERSION_HPP 
  • version.txt

    r8013c0c rc5ec0c8  
    11version=0.4.0 
    2 build=129 
    3 date=2012-01-21 
     2build=130 
     3date=2012-01-26 
Note: See TracChangeset for help on using the changeset viewer.