<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 *  Effective License of whole file:
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 *  Parts "Copyright by Sun Microsystems, Inc" prior to August 2011:
 *
 *    The Contents of this file are made available subject to the terms of
 *    the GNU Lesser General Public License Version 2.1
 *
 *    Copyright: 2000 by Sun Microsystems, Inc.
 *
 *    Contributor(s): Joerg Budischewski
 *
 *  All parts contributed on or after August 2011:
 *
 *    Version: MPL 1.1 / GPLv3+ / LGPLv2.1+
 *
 *    The contents of this file are subject to the Mozilla Public License Version
 *    1.1 (the "License"); you may not use this file except in compliance with
 *    the License or as specified alternatively below. You may obtain a copy of
 *    the License at http://www.mozilla.org/MPL/
 *
 *    Software distributed under the License is distributed on an "AS IS" basis,
 *    WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 *    for the specific language governing rights and limitations under the
 *    License.
 *
 *    Major Contributor(s):
 *    [ Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> ]
 *
 *    All Rights Reserved.
 *
 *    For minor contributions see the git repository.
 *
 *    Alternatively, the contents of this file may be used under the terms of
 *    either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 *    the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"),
 *    in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable
 *    instead of those above.
 *
 ************************************************************************/

#include <stdio.h>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/implementationentry.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>

#include "pq_driver.hxx"

using rtl::OUString;
using rtl::OUStringToOString;
using osl::MutexGuard;

using cppu::WeakComponentImplHelper2;

using com::sun::star::lang::XSingleComponentFactory;
using com::sun::star::lang::XServiceInfo;
using com::sun::star::lang::XComponent;

using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Exception;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::Any;

using com::sun::star::beans::PropertyValue;
using com::sun::star::beans::XPropertySet;

using com::sun::star::sdbc::XConnection;
using com::sun::star::sdbc::SQLException;
using com::sun::star::sdbc::DriverPropertyInfo;

using com::sun::star::sdbcx::XTablesSupplier;

namespace pq_sdbc_driver
{
#define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )

OUString DriverGetImplementationName()
{
    static OUString *p;
    if (! p )
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        static OUString instance(
            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) );
        p = &instance;
    }
    return *p;
}

Sequence< OUString > DriverGetSupportedServiceNames()
{
    static Sequence< OUString > *p;
    if( ! p )
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) );
        static Sequence< OUString > instance( &tmp,1 );
        p = &instance;
    }
    return *p;
}

Reference< XConnection > Driver::connect(
    const OUString& url,const Sequence< PropertyValue >& info )
    throw (SQLException, RuntimeException)
{
    if( ! acceptsURL( url ) )  // XDriver spec tells me to do so ...
        return Reference< XConnection > ();

    Sequence< Any > seq ( 2 );
    seq[0] <<= url;
    seq[1] <<= info;
    return Reference< XConnection> (
        m_smgr->createInstanceWithArgumentsAndContext(
            OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ),
            seq, m_ctx ),
        UNO_QUERY );
}

sal_Bool Driver::acceptsURL( const ::rtl::OUString& url )
    throw (SQLException, RuntimeException)
{
    return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) );
}

Sequence< DriverPropertyInfo > Driver::getPropertyInfo(
    const OUString& url,const Sequence< PropertyValue >& info )
    throw (SQLException, RuntimeException)
{
    (void)url; (void)info;
    return Sequence< DriverPropertyInfo > ();
}

sal_Int32  Driver::getMajorVersion(  ) throw (RuntimeException)
{
    return PQ_SDBC_MAJOR;
}

sal_Int32 Driver::getMinorVersion(  ) throw (RuntimeException)
{
    return PQ_SDBC_MINOR;
}

    // XServiceInfo
OUString SAL_CALL Driver::getImplementationName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return DriverGetImplementationName();
}

sal_Bool Driver::supportsService(const OUString& ServiceName)
    throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< OUString > serviceNames = DriverGetSupportedServiceNames();
    for( int i = 0 ; i < serviceNames.getLength() ; i ++ )
        if( serviceNames[i] == ServiceName )
            return sal_True;
    return sal_False;
}

Sequence< OUString > Driver::getSupportedServiceNames(void)
    throw(::com::sun::star::uno::RuntimeException)
{
    return DriverGetSupportedServiceNames();
}

// XComponent
void Driver::disposing()
{

}

Reference< XTablesSupplier > Driver::getDataDefinitionByConnection(
    const Reference< XConnection >& connection )
        throw (SQLException, RuntimeException)
{
     return Reference< XTablesSupplier >( connection , UNO_QUERY );
}

Reference< XTablesSupplier > Driver::getDataDefinitionByURL(
    const ::rtl::OUString& url, const Sequence< PropertyValue >& info )
        throw (SQLException, RuntimeException)
{
    return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY );
}

Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx )
{
    Reference< XInterface >  ret = * new Driver( ctx );
    return ret;
}

class OOneInstanceComponentFactory :
    public MutexHolder,
    public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >
{
public:
    OOneInstanceComponentFactory(
        const OUString & rImplementationName_,
        cppu::ComponentFactoryFunc fptr,
        const Sequence< OUString > & serviceNames,
        const Reference< XComponentContext > & defaultContext) :
        WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ),
        m_create( fptr ),
        m_serviceNames( serviceNames ),
        m_implName( rImplementationName_ ),
        m_defaultContext( defaultContext )
    {
    }

    // XSingleComponentFactory
    virtual Reference< XInterface > SAL_CALL createInstanceWithContext(
        Reference< XComponentContext > const & xContext )
        throw (Exception, RuntimeException);
    virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext(
        Sequence< Any > const & rArguments,
        Reference< XComponentContext > const & xContext )
        throw (Exception, RuntimeException);

    // XServiceInfo
    OUString SAL_CALL getImplementationName()
        throw(::com::sun::star::uno::RuntimeException)
    {
        return m_implName;
    }
    sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
        throw(::com::sun::star::uno::RuntimeException)
    {
        for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ )
            if( m_serviceNames[i] == ServiceName )
                return sal_True;
        return sal_False;
    }
    Sequence< OUString > SAL_CALL getSupportedServiceNames(void)
        throw(::com::sun::star::uno::RuntimeException)
    {
        return m_serviceNames;
    }

    // XComponent
    virtual void SAL_CALL disposing();

private:
    cppu::ComponentFactoryFunc     m_create;
    Sequence< OUString >           m_serviceNames;
    OUString                       m_implName;
    Reference< XInterface >        m_theInstance;
    Reference< XComponentContext > m_defaultContext;
};

Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext(
    Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx )
    throw( RuntimeException, Exception )
{
    (void)rArguments;
    return createInstanceWithContext( ctx );
}

Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext(
    const Reference< XComponentContext > & ctx )
    throw( RuntimeException, Exception )
{
    if( ! m_theInstance.is() )
    {
        // work around the problem in sdbc
        Reference< XComponentContext > useCtx = ctx;
        if( ! useCtx.is() )
            useCtx = m_defaultContext;
        Reference< XInterface > theInstance = m_create( useCtx );
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        if( ! m_theInstance.is () )
        {
            m_theInstance = theInstance;
        }
    }
    return m_theInstance;
}

void OOneInstanceComponentFactory::disposing()
{
    Reference< XComponent > rComp;
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        rComp = Reference< XComponent >( m_theInstance, UNO_QUERY );
        m_theInstance.clear();
    }
    if( rComp.is() )
        rComp->dispose();
}

//  Reference< XSingleComponentFactory > createOneInstanceComponentFactory(
//      cppu::ComponentFactoryFunc fptr,
//      ::rtl::OUString const & rImplementationName,
//      ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,
//      rtl_ModuleCount * pModCount = 0 )
//      SAL_THROW(())
//  {
//      return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames);
//  }

}

static struct cppu::ImplementationEntry g_entries[] =
{
    {
        pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName,
        pq_sdbc_driver::DriverGetSupportedServiceNames, 0,
        0 , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{

void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * )
{
    // need to extract the defaultcontext, because the way, sdbc
    // bypasses the servicemanager, does not allow to use the
    // XSingleComponentFactory interface ...
    void * pRet = 0;
    Reference< XSingleComponentFactory > xFactory;
    Reference< XInterface > xSmgr( (XInterface * ) pServiceManager );

    for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ )
    {
        OUString implName = g_entries[i].getImplementationName();
        if( 0 == implName.compareToAscii( pImplName ) )
        {
            Reference< XComponentContext > defaultContext;
            Reference< XPropertySet > propSet( xSmgr, UNO_QUERY );
            if( propSet.is() )
            {
                try
                {
                    propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext;
                }
                catch( com::sun::star::uno::Exception &e )
                {
                    // if there is no default context, ignore it
                }
            }
            xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory(
                implName,
                g_entries[i].create,
                g_entries[i].getSupportedServiceNames(),
                defaultContext );
        }
    }

    if( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }
    return pRet;
}

}
<commit_msg>WaE: unreferenced local variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 *  Effective License of whole file:
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 *  Parts "Copyright by Sun Microsystems, Inc" prior to August 2011:
 *
 *    The Contents of this file are made available subject to the terms of
 *    the GNU Lesser General Public License Version 2.1
 *
 *    Copyright: 2000 by Sun Microsystems, Inc.
 *
 *    Contributor(s): Joerg Budischewski
 *
 *  All parts contributed on or after August 2011:
 *
 *    Version: MPL 1.1 / GPLv3+ / LGPLv2.1+
 *
 *    The contents of this file are subject to the Mozilla Public License Version
 *    1.1 (the "License"); you may not use this file except in compliance with
 *    the License or as specified alternatively below. You may obtain a copy of
 *    the License at http://www.mozilla.org/MPL/
 *
 *    Software distributed under the License is distributed on an "AS IS" basis,
 *    WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 *    for the specific language governing rights and limitations under the
 *    License.
 *
 *    Major Contributor(s):
 *    [ Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> ]
 *
 *    All Rights Reserved.
 *
 *    For minor contributions see the git repository.
 *
 *    Alternatively, the contents of this file may be used under the terms of
 *    either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 *    the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"),
 *    in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable
 *    instead of those above.
 *
 ************************************************************************/

#include <stdio.h>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/implementationentry.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>

#include "pq_driver.hxx"

using rtl::OUString;
using rtl::OUStringToOString;
using osl::MutexGuard;

using cppu::WeakComponentImplHelper2;

using com::sun::star::lang::XSingleComponentFactory;
using com::sun::star::lang::XServiceInfo;
using com::sun::star::lang::XComponent;

using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Exception;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::Any;

using com::sun::star::beans::PropertyValue;
using com::sun::star::beans::XPropertySet;

using com::sun::star::sdbc::XConnection;
using com::sun::star::sdbc::SQLException;
using com::sun::star::sdbc::DriverPropertyInfo;

using com::sun::star::sdbcx::XTablesSupplier;

namespace pq_sdbc_driver
{
#define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )

OUString DriverGetImplementationName()
{
    static OUString *p;
    if (! p )
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        static OUString instance(
            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) );
        p = &instance;
    }
    return *p;
}

Sequence< OUString > DriverGetSupportedServiceNames()
{
    static Sequence< OUString > *p;
    if( ! p )
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) );
        static Sequence< OUString > instance( &tmp,1 );
        p = &instance;
    }
    return *p;
}

Reference< XConnection > Driver::connect(
    const OUString& url,const Sequence< PropertyValue >& info )
    throw (SQLException, RuntimeException)
{
    if( ! acceptsURL( url ) )  // XDriver spec tells me to do so ...
        return Reference< XConnection > ();

    Sequence< Any > seq ( 2 );
    seq[0] <<= url;
    seq[1] <<= info;
    return Reference< XConnection> (
        m_smgr->createInstanceWithArgumentsAndContext(
            OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ),
            seq, m_ctx ),
        UNO_QUERY );
}

sal_Bool Driver::acceptsURL( const ::rtl::OUString& url )
    throw (SQLException, RuntimeException)
{
    return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) );
}

Sequence< DriverPropertyInfo > Driver::getPropertyInfo(
    const OUString& url,const Sequence< PropertyValue >& info )
    throw (SQLException, RuntimeException)
{
    (void)url; (void)info;
    return Sequence< DriverPropertyInfo > ();
}

sal_Int32  Driver::getMajorVersion(  ) throw (RuntimeException)
{
    return PQ_SDBC_MAJOR;
}

sal_Int32 Driver::getMinorVersion(  ) throw (RuntimeException)
{
    return PQ_SDBC_MINOR;
}

    // XServiceInfo
OUString SAL_CALL Driver::getImplementationName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return DriverGetImplementationName();
}

sal_Bool Driver::supportsService(const OUString& ServiceName)
    throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< OUString > serviceNames = DriverGetSupportedServiceNames();
    for( int i = 0 ; i < serviceNames.getLength() ; i ++ )
        if( serviceNames[i] == ServiceName )
            return sal_True;
    return sal_False;
}

Sequence< OUString > Driver::getSupportedServiceNames(void)
    throw(::com::sun::star::uno::RuntimeException)
{
    return DriverGetSupportedServiceNames();
}

// XComponent
void Driver::disposing()
{

}

Reference< XTablesSupplier > Driver::getDataDefinitionByConnection(
    const Reference< XConnection >& connection )
        throw (SQLException, RuntimeException)
{
     return Reference< XTablesSupplier >( connection , UNO_QUERY );
}

Reference< XTablesSupplier > Driver::getDataDefinitionByURL(
    const ::rtl::OUString& url, const Sequence< PropertyValue >& info )
        throw (SQLException, RuntimeException)
{
    return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY );
}

Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx )
{
    Reference< XInterface >  ret = * new Driver( ctx );
    return ret;
}

class OOneInstanceComponentFactory :
    public MutexHolder,
    public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >
{
public:
    OOneInstanceComponentFactory(
        const OUString & rImplementationName_,
        cppu::ComponentFactoryFunc fptr,
        const Sequence< OUString > & serviceNames,
        const Reference< XComponentContext > & defaultContext) :
        WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ),
        m_create( fptr ),
        m_serviceNames( serviceNames ),
        m_implName( rImplementationName_ ),
        m_defaultContext( defaultContext )
    {
    }

    // XSingleComponentFactory
    virtual Reference< XInterface > SAL_CALL createInstanceWithContext(
        Reference< XComponentContext > const & xContext )
        throw (Exception, RuntimeException);
    virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext(
        Sequence< Any > const & rArguments,
        Reference< XComponentContext > const & xContext )
        throw (Exception, RuntimeException);

    // XServiceInfo
    OUString SAL_CALL getImplementationName()
        throw(::com::sun::star::uno::RuntimeException)
    {
        return m_implName;
    }
    sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
        throw(::com::sun::star::uno::RuntimeException)
    {
        for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ )
            if( m_serviceNames[i] == ServiceName )
                return sal_True;
        return sal_False;
    }
    Sequence< OUString > SAL_CALL getSupportedServiceNames(void)
        throw(::com::sun::star::uno::RuntimeException)
    {
        return m_serviceNames;
    }

    // XComponent
    virtual void SAL_CALL disposing();

private:
    cppu::ComponentFactoryFunc     m_create;
    Sequence< OUString >           m_serviceNames;
    OUString                       m_implName;
    Reference< XInterface >        m_theInstance;
    Reference< XComponentContext > m_defaultContext;
};

Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext(
    Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx )
    throw( RuntimeException, Exception )
{
    (void)rArguments;
    return createInstanceWithContext( ctx );
}

Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext(
    const Reference< XComponentContext > & ctx )
    throw( RuntimeException, Exception )
{
    if( ! m_theInstance.is() )
    {
        // work around the problem in sdbc
        Reference< XComponentContext > useCtx = ctx;
        if( ! useCtx.is() )
            useCtx = m_defaultContext;
        Reference< XInterface > theInstance = m_create( useCtx );
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        if( ! m_theInstance.is () )
        {
            m_theInstance = theInstance;
        }
    }
    return m_theInstance;
}

void OOneInstanceComponentFactory::disposing()
{
    Reference< XComponent > rComp;
    {
        MutexGuard guard( osl::Mutex::getGlobalMutex() );
        rComp = Reference< XComponent >( m_theInstance, UNO_QUERY );
        m_theInstance.clear();
    }
    if( rComp.is() )
        rComp->dispose();
}

//  Reference< XSingleComponentFactory > createOneInstanceComponentFactory(
//      cppu::ComponentFactoryFunc fptr,
//      ::rtl::OUString const & rImplementationName,
//      ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,
//      rtl_ModuleCount * pModCount = 0 )
//      SAL_THROW(())
//  {
//      return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames);
//  }

}

static struct cppu::ImplementationEntry g_entries[] =
{
    {
        pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName,
        pq_sdbc_driver::DriverGetSupportedServiceNames, 0,
        0 , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{

void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * )
{
    // need to extract the defaultcontext, because the way, sdbc
    // bypasses the servicemanager, does not allow to use the
    // XSingleComponentFactory interface ...
    void * pRet = 0;
    Reference< XSingleComponentFactory > xFactory;
    Reference< XInterface > xSmgr( (XInterface * ) pServiceManager );

    for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ )
    {
        OUString implName = g_entries[i].getImplementationName();
        if( 0 == implName.compareToAscii( pImplName ) )
        {
            Reference< XComponentContext > defaultContext;
            Reference< XPropertySet > propSet( xSmgr, UNO_QUERY );
            if( propSet.is() )
            {
                try
                {
                    propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext;
                }
                catch( com::sun::star::uno::Exception & )
                {
                    // if there is no default context, ignore it
                }
            }
            xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory(
                implName,
                g_entries[i].create,
                g_entries[i].getSupportedServiceNames(),
                defaultContext );
        }
    }

    if( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }
    return pRet;
}

}
<|endoftext|>


<commit_before>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>

namespace gg
{

VideoSourceVLC::VideoSourceVLC(const std::string path)
    : _vlc_inst(nullptr)
    , _vlc_mp(nullptr)
    , _video_buffer(nullptr)
    , _data_length(0)
    , _cols(0)
    , _rows(0)
    , _sub(nullptr)
    , _path(path)
{
    this->init_vlc();
    this->run_vlc();
}

VideoSourceVLC::~VideoSourceVLC()
{
    stop_vlc();
    release_vlc();
}

bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
    ///\todo mutex

    if(this->_cols == 0 || this->_rows == 0)
        return false;

    width = this->_cols;
    height = this->_rows;
    return true;
}

bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
    throw VideoSourceError("VLC video source supports only I420 colour space");

    // TODO

    ///\todo mutex

    if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
        return false;

    // allocate and fill the image
    if (_cols * _rows * 4 == this->_data_length)
        frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
    else
        throw VideoSourceError("VLC video source does not support padded images");

    return true;
}

bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
    if (_data_length > 0)
    {
        // TODO manage data?
        frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
        return true;
    }
    else
        return false;

    // TODO #86
}

double VideoSourceVLC::get_frame_rate()
{
    //return libvlc_media_player_get_rate( m_mp );
    return libvlc_media_player_get_fps(_vlc_mp);
    //throw std::runtime_error("get_frame_rate to be implemented");
    //return 0.0;
}

void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
    // TODO mutex?

    if (x >= _full.x and x + width <= _full.x + _full.width and
        y >= _full.y and y + height <= _full.y + _full.height)
    {
        stop_vlc();
        release_vlc();
        if (_sub == nullptr) _sub = new FrameBox;
        _sub->x = x;
        _sub->y = y;
        _sub->width = width;
        _sub->height = height;
        init_vlc();
        run_vlc();
    }
}

void VideoSourceVLC::get_full_frame()
{
    // TODO mutex?
    stop_vlc();
    release_vlc();
    init_vlc();
    run_vlc();
}

void VideoSourceVLC::init_vlc()
{
    // VLC pointers
    libvlc_media_t * vlc_media = nullptr;

    // VLC options
    char smem_options[512];

    sprintf(smem_options, "#");
    if (_sub != nullptr)
    {
        unsigned int croptop = _sub->y,
                     cropbottom = _full.height - (_sub->y + _sub->height),
                     cropleft = _sub->x,
                     cropright = _full.width - (_sub->x + _sub->width);
        sprintf(smem_options,
                "%stranscode{vcodec=I420,vfilter=croppadd{",
                smem_options);
        sprintf(smem_options,
                "%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:",
                smem_options,
                croptop, cropbottom, cropleft, cropright);
    }
    sprintf(smem_options,
            "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
            smem_options,
            (long long int)(intptr_t)(void*) this,
            (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
            (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );

    const char * const vlc_args[] = {
        "-I", "dummy", // Don't use any interface
        "--ignore-config", // Don't use VLC's config
        "--extraintf=logger", // Log anything
        // TODO - what about the options below?
        //"--verbose=2", // Be much more verbose then normal for debugging purpose
        //"--clock-jitter=0",
        //"--file-caching=150",
        "--no-audio",
        "--sout", smem_options // Stream to memory
    };

    // We launch VLC
    _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
    if (_vlc_inst == nullptr)
        throw VideoSourceError("Could not create VLC engine");

    // If path contains a colon (:), it will be treated as a
    // URL. Else, it will be considered as a local path.
    if (_path.find(":") == std::string::npos)
        vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
    else
        vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
    if (vlc_media == nullptr)
        throw VideoSourceError(std::string("Could not open ").append(_path));

    libvlc_media_add_option(vlc_media, ":noaudio");
    libvlc_media_add_option(vlc_media, ":no-video-title-show");

    // Create a media player playing environement
    _vlc_mp = libvlc_media_player_new_from_media(vlc_media);
    if (_vlc_mp == nullptr)
        throw VideoSourceError("Could not create VLC media player");

    // No need to keep the media now
    libvlc_media_release( vlc_media );
}

void VideoSourceVLC::run_vlc()
{
    // play the media_player
    if (libvlc_media_player_play(_vlc_mp) != 0)
        throw VideoSourceError("Could not start VLC media player");

    // empirically determined value that allows for initialisation
    // to succeed before any API functions are called on this object
    std::this_thread::sleep_for(std::chrono::milliseconds(350));
    unsigned int width, height;
    if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
        throw VideoSourceError("Could not get video dimensions");

    _full.x = 0;
    _full.y = 0;
    _full.width = width;
    _full.height = height;
}

void VideoSourceVLC::stop_vlc()
{
    if (libvlc_media_player_is_playing(_vlc_mp) == 1)
        // stop playing
        libvlc_media_player_stop(_vlc_mp);
}

void VideoSourceVLC::release_vlc()
{
    // free media player
    libvlc_media_player_release(_vlc_mp);

    // free engine
    libvlc_release(_vlc_inst);

    // free buffer
    if (_video_buffer != nullptr)
        delete[] _video_buffer;
    _data_length = 0;
    _cols = 0;
    _rows = 0;

    // free sub-frame
    if (_sub != nullptr)
    {
        delete _sub;
        _sub = nullptr;
    }
}

void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
                                   uint8_t ** pp_pixel_buffer,
                                   size_t size)
{
    ///\todo create mutex guard

    unsigned int width, height;
    if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0)
        return;
    p_video_data->_cols = width;
    p_video_data->_rows = height;

    if (size > p_video_data->_data_length)
        p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
                    realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
                    );
    p_video_data->_data_length = size;

    *pp_pixel_buffer = p_video_data->_video_buffer;
}

void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
                                  uint8_t * p_pixel_buffer,
                                  size_t cols,
                                  size_t rows,
                                  size_t colour_depth,
                                  size_t size)
{
    // TODO: explain how data should be handled (see #86)
    // TODO: Unlock the mutex
}

std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height)
{
    std::string psz_geometry;
    psz_geometry.append(std::to_string(width)).append("x")
                .append(std::to_string(height))
                .append("+").append(std::to_string(x))
                .append("+").append(std::to_string(y));
    return psz_geometry;
}

}
<commit_msg>Issue #83: removed is-playing check on VLC player in stop_vlc function<commit_after>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>

namespace gg
{

VideoSourceVLC::VideoSourceVLC(const std::string path)
    : _vlc_inst(nullptr)
    , _vlc_mp(nullptr)
    , _video_buffer(nullptr)
    , _data_length(0)
    , _cols(0)
    , _rows(0)
    , _sub(nullptr)
    , _path(path)
{
    this->init_vlc();
    this->run_vlc();
}

VideoSourceVLC::~VideoSourceVLC()
{
    stop_vlc();
    release_vlc();
}

bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
    ///\todo mutex

    if(this->_cols == 0 || this->_rows == 0)
        return false;

    width = this->_cols;
    height = this->_rows;
    return true;
}

bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
    throw VideoSourceError("VLC video source supports only I420 colour space");

    // TODO

    ///\todo mutex

    if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
        return false;

    // allocate and fill the image
    if (_cols * _rows * 4 == this->_data_length)
        frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
    else
        throw VideoSourceError("VLC video source does not support padded images");

    return true;
}

bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
    if (_data_length > 0)
    {
        // TODO manage data?
        frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
        return true;
    }
    else
        return false;

    // TODO #86
}

double VideoSourceVLC::get_frame_rate()
{
    //return libvlc_media_player_get_rate( m_mp );
    return libvlc_media_player_get_fps(_vlc_mp);
    //throw std::runtime_error("get_frame_rate to be implemented");
    //return 0.0;
}

void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
    // TODO mutex?

    if (x >= _full.x and x + width <= _full.x + _full.width and
        y >= _full.y and y + height <= _full.y + _full.height)
    {
        stop_vlc();
        release_vlc();
        if (_sub == nullptr) _sub = new FrameBox;
        _sub->x = x;
        _sub->y = y;
        _sub->width = width;
        _sub->height = height;
        init_vlc();
        run_vlc();
    }
}

void VideoSourceVLC::get_full_frame()
{
    // TODO mutex?
    stop_vlc();
    release_vlc();
    init_vlc();
    run_vlc();
}

void VideoSourceVLC::init_vlc()
{
    // VLC pointers
    libvlc_media_t * vlc_media = nullptr;

    // VLC options
    char smem_options[512];

    sprintf(smem_options, "#");
    if (_sub != nullptr)
    {
        unsigned int croptop = _sub->y,
                     cropbottom = _full.height - (_sub->y + _sub->height),
                     cropleft = _sub->x,
                     cropright = _full.width - (_sub->x + _sub->width);
        sprintf(smem_options,
                "%stranscode{vcodec=I420,vfilter=croppadd{",
                smem_options);
        sprintf(smem_options,
                "%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:",
                smem_options,
                croptop, cropbottom, cropleft, cropright);
    }
    sprintf(smem_options,
            "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
            smem_options,
            (long long int)(intptr_t)(void*) this,
            (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
            (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );

    const char * const vlc_args[] = {
        "-I", "dummy", // Don't use any interface
        "--ignore-config", // Don't use VLC's config
        "--extraintf=logger", // Log anything
        // TODO - what about the options below?
        //"--verbose=2", // Be much more verbose then normal for debugging purpose
        //"--clock-jitter=0",
        //"--file-caching=150",
        "--no-audio",
        "--sout", smem_options // Stream to memory
    };

    // We launch VLC
    _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
    if (_vlc_inst == nullptr)
        throw VideoSourceError("Could not create VLC engine");

    // If path contains a colon (:), it will be treated as a
    // URL. Else, it will be considered as a local path.
    if (_path.find(":") == std::string::npos)
        vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
    else
        vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
    if (vlc_media == nullptr)
        throw VideoSourceError(std::string("Could not open ").append(_path));

    libvlc_media_add_option(vlc_media, ":noaudio");
    libvlc_media_add_option(vlc_media, ":no-video-title-show");

    // Create a media player playing environement
    _vlc_mp = libvlc_media_player_new_from_media(vlc_media);
    if (_vlc_mp == nullptr)
        throw VideoSourceError("Could not create VLC media player");

    // No need to keep the media now
    libvlc_media_release( vlc_media );
}

void VideoSourceVLC::run_vlc()
{
    // play the media_player
    if (libvlc_media_player_play(_vlc_mp) != 0)
        throw VideoSourceError("Could not start VLC media player");

    // empirically determined value that allows for initialisation
    // to succeed before any API functions are called on this object
    std::this_thread::sleep_for(std::chrono::milliseconds(350));
    unsigned int width, height;
    if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
        throw VideoSourceError("Could not get video dimensions");

    _full.x = 0;
    _full.y = 0;
    _full.width = width;
    _full.height = height;
}

void VideoSourceVLC::stop_vlc()
{
    // stop playing
    libvlc_media_player_stop(_vlc_mp);
}

void VideoSourceVLC::release_vlc()
{
    // free media player
    libvlc_media_player_release(_vlc_mp);

    // free engine
    libvlc_release(_vlc_inst);

    // free buffer
    if (_video_buffer != nullptr)
        delete[] _video_buffer;
    _data_length = 0;
    _cols = 0;
    _rows = 0;

    // free sub-frame
    if (_sub != nullptr)
    {
        delete _sub;
        _sub = nullptr;
    }
}

void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
                                   uint8_t ** pp_pixel_buffer,
                                   size_t size)
{
    ///\todo create mutex guard

    unsigned int width, height;
    if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0)
        return;
    p_video_data->_cols = width;
    p_video_data->_rows = height;

    if (size > p_video_data->_data_length)
        p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
                    realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
                    );
    p_video_data->_data_length = size;

    *pp_pixel_buffer = p_video_data->_video_buffer;
}

void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
                                  uint8_t * p_pixel_buffer,
                                  size_t cols,
                                  size_t rows,
                                  size_t colour_depth,
                                  size_t size)
{
    // TODO: explain how data should be handled (see #86)
    // TODO: Unlock the mutex
}

std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height)
{
    std::string psz_geometry;
    psz_geometry.append(std::to_string(width)).append("x")
                .append(std::to_string(height))
                .append("+").append(std::to_string(x))
                .append("+").append(std::to_string(y));
    return psz_geometry;
}

}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "VirtualMachinePool.h"
#include "VirtualMachineHook.h"

#include "NebulaLog.h"

#include <sstream>

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

time_t VirtualMachinePool::_monitor_expiration;
bool   VirtualMachinePool::_submit_on_hold;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

VirtualMachinePool::VirtualMachinePool(
        SqlDB *                     db,
        vector<const Attribute *>   hook_mads,
        const string&               hook_location,
        const string&               remotes_location,
        vector<const Attribute *>&  restricted_attrs,
        time_t                      expire_time,
        bool                        on_hold)
    : PoolSQL(db, VirtualMachine::table, false)
{
    const VectorAttribute * vattr;

    string name;
    string on;
    string cmd;
    string arg;
    bool   remote;

    bool state_hook = false;

    _monitor_expiration = expire_time;
    _submit_on_hold = on_hold;

    if ( _monitor_expiration == 0 )
    {
        clean_all_monitoring();
    }

    for (unsigned int i = 0 ; i < hook_mads.size() ; i++ )
    {
        vattr = static_cast<const VectorAttribute *>(hook_mads[i]);

        name = vattr->vector_value("NAME");
        on   = vattr->vector_value("ON");
        cmd  = vattr->vector_value("COMMAND");
        arg  = vattr->vector_value("ARGUMENTS");
        vattr->vector_value("REMOTE", remote);

        transform (on.begin(),on.end(),on.begin(),(int(*)(int))toupper);

        if ( on.empty() || cmd.empty() )
        {
            ostringstream oss;

            oss << "Empty ON or COMMAND attribute in VM_HOOK. Hook "
                << "not registered!";
            NebulaLog::log("VM",Log::WARNING,oss);

            continue;
        }

        if ( name.empty() )
        {
            name = cmd;
        }

        if (cmd[0] != '/')
        {
            ostringstream cmd_os;

            if ( remote )
            {
                cmd_os << hook_location << "/" << cmd;
            }
            else
            {
                cmd_os << remotes_location << "/hooks/" << cmd;
            }

            cmd = cmd_os.str();
        }

        if ( on == "CREATE" )
        {
            AllocateHook * hook;

            hook = new AllocateHook(name, cmd, arg, false);

            add_hook(hook);
        }
        else if ( on == "PROLOG" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                           VirtualMachine::PROLOG, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "RUNNING" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                           VirtualMachine::RUNNING, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "SHUTDOWN" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::EPILOG, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "STOP" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::STOPPED);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "DONE" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::DONE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "FAILED" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::FAILED);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "UNKNOWN" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::UNKNOWN, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "CUSTOM" )
        {
            VirtualMachineStateHook * hook;

            string lcm_str = vattr->vector_value("LCM_STATE");
            string vm_str  = vattr->vector_value("STATE");

            VirtualMachine::LcmState lcm_state;
            VirtualMachine::VmState vm_state;

            if ( VirtualMachine::lcm_state_from_str(lcm_str, lcm_state) != 0 )
            {
                ostringstream oss;
                oss << "Wrong LCM_STATE: "<< lcm_str <<". Hook not registered!";

                NebulaLog::log("VM",Log::WARNING,oss);
                continue;
            }

            if ( VirtualMachine::vm_state_from_str(vm_str, vm_state) != 0 )
            {
                ostringstream oss;
                oss << "Wrong STATE: "<< vm_str <<". Hook not registered!";

                NebulaLog::log("VM",Log::WARNING,oss);
                continue;
            }

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                    lcm_state, vm_state);

            add_hook(hook);

            state_hook = true;
        }
        else
        {
            ostringstream oss;

            oss << "Unknown VM_HOOK " << on << ". Hook not registered!";
            NebulaLog::log("VM",Log::WARNING,oss);
        }
    }

    if ( state_hook )
    {
        VirtualMachineUpdateStateHook * hook;

        hook = new VirtualMachineUpdateStateHook();

        add_hook(hook);
    }

    // Set restricted attributes
    VirtualMachineTemplate::set_restricted_attributes(restricted_attrs);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::allocate (
    int            uid,
    int            gid,
    const string&  uname,
    const string&  gname,
    int            umask,
    VirtualMachineTemplate * vm_template,
    int *          oid,
    string&        error_str,
    bool           on_hold)
{
    VirtualMachine * vm;

    // ------------------------------------------------------------------------
    // Build a new Virtual Machine object
    // ------------------------------------------------------------------------
    vm = new VirtualMachine(-1, uid, gid, uname, gname, umask, vm_template);

    if ( _submit_on_hold == true || on_hold )
    {
        vm->state = VirtualMachine::HOLD;
    }
    else
    {
        vm->state = VirtualMachine::PENDING;
    }

    // ------------------------------------------------------------------------
    // Insert the Object in the pool
    // ------------------------------------------------------------------------

    *oid = PoolSQL::allocate(vm, error_str);

    return *oid;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::get_running(
    vector<int>&    oids,
    int             vm_limit,
    time_t          last_poll)
{
    ostringstream   os;
    string          where;

    os << "last_poll <= " << last_poll << " and"
       << " state = " << VirtualMachine::ACTIVE
       << " and ( lcm_state = " << VirtualMachine::RUNNING
       << " or lcm_state = " << VirtualMachine::UNKNOWN << " )"
       << " ORDER BY last_poll ASC LIMIT " << vm_limit;

    where = os.str();

    return PoolSQL::search(oids,VirtualMachine::table,where);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::get_pending(
    vector<int>&    oids)
{
    ostringstream   os;
    string          where;

    os << "state = " << VirtualMachine::PENDING;

    where = os.str();

    return PoolSQL::search(oids,VirtualMachine::table,where);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::dump_acct(ostringstream& oss,
                                  const string&  where,
                                  int            time_start,
                                  int            time_end)
{
    ostringstream cmd;

    cmd << "SELECT " << History::table << ".body FROM " << History::table
        << " INNER JOIN " << VirtualMachine::table
        << " WHERE vid=oid";

    if ( !where.empty() )
    {
        cmd << " AND " << where;
    }

    if ( time_start != -1 || time_end != -1 )
    {
        if ( time_start != -1 )
        {
            cmd << " AND (etime > " << time_start << " OR  etime = 0)";
        }

        if ( time_end != -1 )
        {
            cmd << " AND stime < " << time_end;
        }
    }

    cmd << " GROUP BY vid,seq";

    return PoolSQL::dump(oss, "HISTORY_RECORDS", cmd);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::clean_expired_monitoring()
{
    if ( _monitor_expiration == 0 )
    {
        return 0;
    }

    time_t          max_last_poll;
    int             rc;
    ostringstream   oss;

    max_last_poll = time(0) - _monitor_expiration;

    oss << "DELETE FROM " << VirtualMachine::monit_table
        << " WHERE last_poll < " << max_last_poll;

    rc = db->exec(oss);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::clean_all_monitoring()
{
    ostringstream   oss;
    int             rc;

    oss << "DELETE FROM " << VirtualMachine::monit_table;

    rc = db->exec(oss);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::dump_monitoring(
        ostringstream& oss,
        const string&  where)
{
    ostringstream cmd;

    cmd << "SELECT " << VirtualMachine::monit_table << ".body FROM "
        << VirtualMachine::monit_table
        << " INNER JOIN " << VirtualMachine::table
        << " WHERE vmid = oid";

    if ( !where.empty() )
    {
        cmd << " AND " << where;
    }

    cmd << " ORDER BY vmid, " << VirtualMachine::monit_table << ".last_poll;";

    return PoolSQL::dump(oss, "MONITORING_DATA", cmd);
}
<commit_msg>Bug #2700: SQL query for VirtualMachinePool accounting now has ORDER BY instead of GROUP BY (which was a typo)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "VirtualMachinePool.h"
#include "VirtualMachineHook.h"

#include "NebulaLog.h"

#include <sstream>

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

time_t VirtualMachinePool::_monitor_expiration;
bool   VirtualMachinePool::_submit_on_hold;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

VirtualMachinePool::VirtualMachinePool(
        SqlDB *                     db,
        vector<const Attribute *>   hook_mads,
        const string&               hook_location,
        const string&               remotes_location,
        vector<const Attribute *>&  restricted_attrs,
        time_t                      expire_time,
        bool                        on_hold)
    : PoolSQL(db, VirtualMachine::table, false)
{
    const VectorAttribute * vattr;

    string name;
    string on;
    string cmd;
    string arg;
    bool   remote;

    bool state_hook = false;

    _monitor_expiration = expire_time;
    _submit_on_hold = on_hold;

    if ( _monitor_expiration == 0 )
    {
        clean_all_monitoring();
    }

    for (unsigned int i = 0 ; i < hook_mads.size() ; i++ )
    {
        vattr = static_cast<const VectorAttribute *>(hook_mads[i]);

        name = vattr->vector_value("NAME");
        on   = vattr->vector_value("ON");
        cmd  = vattr->vector_value("COMMAND");
        arg  = vattr->vector_value("ARGUMENTS");
        vattr->vector_value("REMOTE", remote);

        transform (on.begin(),on.end(),on.begin(),(int(*)(int))toupper);

        if ( on.empty() || cmd.empty() )
        {
            ostringstream oss;

            oss << "Empty ON or COMMAND attribute in VM_HOOK. Hook "
                << "not registered!";
            NebulaLog::log("VM",Log::WARNING,oss);

            continue;
        }

        if ( name.empty() )
        {
            name = cmd;
        }

        if (cmd[0] != '/')
        {
            ostringstream cmd_os;

            if ( remote )
            {
                cmd_os << hook_location << "/" << cmd;
            }
            else
            {
                cmd_os << remotes_location << "/hooks/" << cmd;
            }

            cmd = cmd_os.str();
        }

        if ( on == "CREATE" )
        {
            AllocateHook * hook;

            hook = new AllocateHook(name, cmd, arg, false);

            add_hook(hook);
        }
        else if ( on == "PROLOG" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                           VirtualMachine::PROLOG, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "RUNNING" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                           VirtualMachine::RUNNING, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "SHUTDOWN" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::EPILOG, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "STOP" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::STOPPED);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "DONE" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::DONE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "FAILED" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::LCM_INIT, VirtualMachine::FAILED);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "UNKNOWN" )
        {
            VirtualMachineStateHook * hook;

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                            VirtualMachine::UNKNOWN, VirtualMachine::ACTIVE);
            add_hook(hook);

            state_hook = true;
        }
        else if ( on == "CUSTOM" )
        {
            VirtualMachineStateHook * hook;

            string lcm_str = vattr->vector_value("LCM_STATE");
            string vm_str  = vattr->vector_value("STATE");

            VirtualMachine::LcmState lcm_state;
            VirtualMachine::VmState vm_state;

            if ( VirtualMachine::lcm_state_from_str(lcm_str, lcm_state) != 0 )
            {
                ostringstream oss;
                oss << "Wrong LCM_STATE: "<< lcm_str <<". Hook not registered!";

                NebulaLog::log("VM",Log::WARNING,oss);
                continue;
            }

            if ( VirtualMachine::vm_state_from_str(vm_str, vm_state) != 0 )
            {
                ostringstream oss;
                oss << "Wrong STATE: "<< vm_str <<". Hook not registered!";

                NebulaLog::log("VM",Log::WARNING,oss);
                continue;
            }

            hook = new VirtualMachineStateHook(name, cmd, arg, remote,
                    lcm_state, vm_state);

            add_hook(hook);

            state_hook = true;
        }
        else
        {
            ostringstream oss;

            oss << "Unknown VM_HOOK " << on << ". Hook not registered!";
            NebulaLog::log("VM",Log::WARNING,oss);
        }
    }

    if ( state_hook )
    {
        VirtualMachineUpdateStateHook * hook;

        hook = new VirtualMachineUpdateStateHook();

        add_hook(hook);
    }

    // Set restricted attributes
    VirtualMachineTemplate::set_restricted_attributes(restricted_attrs);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::allocate (
    int            uid,
    int            gid,
    const string&  uname,
    const string&  gname,
    int            umask,
    VirtualMachineTemplate * vm_template,
    int *          oid,
    string&        error_str,
    bool           on_hold)
{
    VirtualMachine * vm;

    // ------------------------------------------------------------------------
    // Build a new Virtual Machine object
    // ------------------------------------------------------------------------
    vm = new VirtualMachine(-1, uid, gid, uname, gname, umask, vm_template);

    if ( _submit_on_hold == true || on_hold )
    {
        vm->state = VirtualMachine::HOLD;
    }
    else
    {
        vm->state = VirtualMachine::PENDING;
    }

    // ------------------------------------------------------------------------
    // Insert the Object in the pool
    // ------------------------------------------------------------------------

    *oid = PoolSQL::allocate(vm, error_str);

    return *oid;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::get_running(
    vector<int>&    oids,
    int             vm_limit,
    time_t          last_poll)
{
    ostringstream   os;
    string          where;

    os << "last_poll <= " << last_poll << " and"
       << " state = " << VirtualMachine::ACTIVE
       << " and ( lcm_state = " << VirtualMachine::RUNNING
       << " or lcm_state = " << VirtualMachine::UNKNOWN << " )"
       << " ORDER BY last_poll ASC LIMIT " << vm_limit;

    where = os.str();

    return PoolSQL::search(oids,VirtualMachine::table,where);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::get_pending(
    vector<int>&    oids)
{
    ostringstream   os;
    string          where;

    os << "state = " << VirtualMachine::PENDING;

    where = os.str();

    return PoolSQL::search(oids,VirtualMachine::table,where);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::dump_acct(ostringstream& oss,
                                  const string&  where,
                                  int            time_start,
                                  int            time_end)
{
    ostringstream cmd;

    cmd << "SELECT " << History::table << ".body FROM " << History::table
        << " INNER JOIN " << VirtualMachine::table
        << " WHERE vid=oid";

    if ( !where.empty() )
    {
        cmd << " AND " << where;
    }

    if ( time_start != -1 || time_end != -1 )
    {
        if ( time_start != -1 )
        {
            cmd << " AND (etime > " << time_start << " OR  etime = 0)";
        }

        if ( time_end != -1 )
        {
            cmd << " AND stime < " << time_end;
        }
    }

    cmd << " ORDER BY vid,seq";

    return PoolSQL::dump(oss, "HISTORY_RECORDS", cmd);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::clean_expired_monitoring()
{
    if ( _monitor_expiration == 0 )
    {
        return 0;
    }

    time_t          max_last_poll;
    int             rc;
    ostringstream   oss;

    max_last_poll = time(0) - _monitor_expiration;

    oss << "DELETE FROM " << VirtualMachine::monit_table
        << " WHERE last_poll < " << max_last_poll;

    rc = db->exec(oss);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::clean_all_monitoring()
{
    ostringstream   oss;
    int             rc;

    oss << "DELETE FROM " << VirtualMachine::monit_table;

    rc = db->exec(oss);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePool::dump_monitoring(
        ostringstream& oss,
        const string&  where)
{
    ostringstream cmd;

    cmd << "SELECT " << VirtualMachine::monit_table << ".body FROM "
        << VirtualMachine::monit_table
        << " INNER JOIN " << VirtualMachine::table
        << " WHERE vmid = oid";

    if ( !where.empty() )
    {
        cmd << " AND " << where;
    }

    cmd << " ORDER BY vmid, " << VirtualMachine::monit_table << ".last_poll;";

    return PoolSQL::dump(oss, "MONITORING_DATA", cmd);
}
<|endoftext|>


<commit_before><commit_msg>Prediction: extract trajectory from semantic_LSTM<commit_after><|endoftext|>


<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Core/Stopwatch.h>
#include <vw/Plate/Index.h>
#include <vw/Plate/Amqp.h>
#include <vw/Plate/ProtoBuffers.pb.h>
#include <vw/Plate/common.h>
#include <vw/Plate/RpcServices.h>
#include <vw/Plate/IndexService.h>
#include <signal.h>

#include <google/protobuf/descriptor.h>

#ifdef VW_HAVE_PKG_TCMALLOC
#include <google/heap-checker.h>
#else
class HeapLeakChecker {
    public:
        explicit HeapLeakChecker(const char* name) {std::cerr << "Using fake leak checker: " << name << std::endl;}
        bool NoLeaks() {return true;}
        ssize_t BytesLeaked() const {return 0;}
};
#endif

#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;

// Global variable.  (Makes signal handling a lot easier...)
boost::shared_ptr<IndexServiceImpl> g_service;

// ------------------------------ SIGNAL HANDLER -------------------------------

volatile bool process_messages = true;
volatile bool force_sync = false;

void sig_unexpected_shutdown(int sig_num) {
  signal(sig_num, SIG_IGN);
  process_messages = false;
  signal(sig_num, sig_unexpected_shutdown);
}

void sig_sync(int sig_num) {
  signal(sig_num, SIG_IGN);
  force_sync = true;
  signal(sig_num, sig_sync);
}

// ------------------------------    MAIN LOOP   -------------------------------

class ServerTask {
  boost::shared_ptr<AmqpRpcServer> m_server;

public:

  ServerTask(boost::shared_ptr<AmqpRpcServer> server) : m_server(server) {}

  void operator()() {
    std::cout << "\t--> Listening for messages.\n";
    m_server->run();
  }

  void kill() { m_server->shutdown(); }
};

// ------------------------------      MAIN      -------------------------------

int main(int argc, char** argv) {
  std::string queue_name, root_directory;
  std::string hostname;
  int port;

  po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:");
  general_options.add_options()
    ("queue_name,q", po::value<std::string>(&queue_name)->default_value("index"),
     "Specify the name of the AMQP queue to create and listen to for mosaicking requests. (Defaults to the \"ngt_mosaic_worker\" queue.")
    ("hostname,h", po::value<std::string>(&hostname)->default_value("localhost"),
     "Specify the hostname of the AMQP server to use for remote procedure calls (RPCs).")
    ("port,p", po::value<int>(&port)->default_value(5672),
     "Specify the port of the AMQP server to use for remote procedure calls (RPCs).")
    ("debug", "Output debug messages.")
    ("help", "Display this help message");

  po::options_description hidden_options("");
  hidden_options.add_options()
    ("root-directory", po::value<std::string>(&root_directory));

  po::options_description options("Allowed Options");
  options.add(general_options).add(hidden_options);

  po::positional_options_description p;
  p.add("root-directory", -1);

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
  po::notify( vm );

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [-q <queue name>] root_directory" <<std::endl << std::endl;
  usage << general_options << std::endl;

  if( vm.count("help") ) {
    std::cout << usage.str();
    return 0;
  }

  if( vm.count("root-directory") != 1 ) {
    std::cerr << "Error: must specify a root directory that contains plate files!"
              << std::endl << std::endl;
    std::cout << usage.str();
    return 1;
  }

  boost::shared_ptr<AmqpConnection> connection( new AmqpConnection(hostname, port) );
  boost::shared_ptr<AmqpRpcServer> server( new AmqpRpcServer(connection, INDEX_EXCHANGE,
                                                             queue_name, vm.count("debug")) );
  g_service.reset( new IndexServiceImpl(root_directory) );
  server->bind_service(g_service, "index");

  // Start the server task in another thread
  boost::shared_ptr<ServerTask> server_task( new ServerTask(server) );
  Thread server_thread( server_task );

  // Install Unix Signal Handlers.  These will help us to gracefully
  // recover and salvage the index under most unexpected error
  // conditions.
  signal(SIGINT,  sig_unexpected_shutdown);
  signal(SIGUSR1, sig_sync);

  std::cout << "\n\n";
  long long t0 = Stopwatch::microtime();

  HeapLeakChecker checker_end("testing_at_end");

  {
  HeapLeakChecker checker_sync("testing_force_sync");

  while(process_messages) {
    if (force_sync) {
      std::cout << "Syncing." << std::endl;
      g_service->sync();
      if (!checker_sync.NoLeaks())
          std::cout << "Leaked " << checker_sync.BytesLeaked() << " bytes" << std::endl;
      force_sync = false;
    }
    int queries = server->queries_processed();
    size_t bytes = server->bytes_processed();
    int n_outstanding_messages = server->incoming_message_queue_size();
    server->reset_stats();

    float dt = float(Stopwatch::microtime() - t0) / 1e6;
    t0 = Stopwatch::microtime();

    std::cout << "[index_server] : "
              << float(queries/dt) << " qps    "
              << float(bytes/dt)/1000.0 << " kB/sec    "
              << n_outstanding_messages << " outstanding messages                          \r"
              << std::flush;
    sleep(1.0);
  }
  }

  std::cout << "\nShutting down the index service safely.\n";
  g_service->sync();

  if (!checker_end.NoLeaks())
      std::cout << "Leaked " << checker_end.BytesLeaked() << " bytes at end" << std::endl;

  return 0;
}

<commit_msg>NoLeaks does its own printing.<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Core/Stopwatch.h>
#include <vw/Plate/Index.h>
#include <vw/Plate/Amqp.h>
#include <vw/Plate/ProtoBuffers.pb.h>
#include <vw/Plate/common.h>
#include <vw/Plate/RpcServices.h>
#include <vw/Plate/IndexService.h>
#include <signal.h>

#include <google/protobuf/descriptor.h>

#ifdef VW_HAVE_PKG_TCMALLOC
#include <google/heap-checker.h>
#else
class HeapLeakChecker {
    public:
        explicit HeapLeakChecker(const char* name) {std::cerr << "Using fake leak checker: " << name << std::endl;}
        bool NoLeaks() {return true;}
        ssize_t BytesLeaked() const {return 0;}
};
#endif

#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;

// Global variable.  (Makes signal handling a lot easier...)
boost::shared_ptr<IndexServiceImpl> g_service;

// ------------------------------ SIGNAL HANDLER -------------------------------

volatile bool process_messages = true;
volatile bool force_sync = false;

void sig_unexpected_shutdown(int sig_num) {
  signal(sig_num, SIG_IGN);
  process_messages = false;
  signal(sig_num, sig_unexpected_shutdown);
}

void sig_sync(int sig_num) {
  signal(sig_num, SIG_IGN);
  force_sync = true;
  signal(sig_num, sig_sync);
}

// ------------------------------    MAIN LOOP   -------------------------------

class ServerTask {
  boost::shared_ptr<AmqpRpcServer> m_server;

public:

  ServerTask(boost::shared_ptr<AmqpRpcServer> server) : m_server(server) {}

  void operator()() {
    std::cout << "\t--> Listening for messages.\n";
    m_server->run();
  }

  void kill() { m_server->shutdown(); }
};

// ------------------------------      MAIN      -------------------------------

int main(int argc, char** argv) {
  std::string queue_name, root_directory;
  std::string hostname;
  int port;

  po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:");
  general_options.add_options()
    ("queue_name,q", po::value<std::string>(&queue_name)->default_value("index"),
     "Specify the name of the AMQP queue to create and listen to for mosaicking requests. (Defaults to the \"ngt_mosaic_worker\" queue.")
    ("hostname,h", po::value<std::string>(&hostname)->default_value("localhost"),
     "Specify the hostname of the AMQP server to use for remote procedure calls (RPCs).")
    ("port,p", po::value<int>(&port)->default_value(5672),
     "Specify the port of the AMQP server to use for remote procedure calls (RPCs).")
    ("debug", "Output debug messages.")
    ("help", "Display this help message");

  po::options_description hidden_options("");
  hidden_options.add_options()
    ("root-directory", po::value<std::string>(&root_directory));

  po::options_description options("Allowed Options");
  options.add(general_options).add(hidden_options);

  po::positional_options_description p;
  p.add("root-directory", -1);

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
  po::notify( vm );

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [-q <queue name>] root_directory" <<std::endl << std::endl;
  usage << general_options << std::endl;

  if( vm.count("help") ) {
    std::cout << usage.str();
    return 0;
  }

  if( vm.count("root-directory") != 1 ) {
    std::cerr << "Error: must specify a root directory that contains plate files!"
              << std::endl << std::endl;
    std::cout << usage.str();
    return 1;
  }

  boost::shared_ptr<AmqpConnection> connection( new AmqpConnection(hostname, port) );
  boost::shared_ptr<AmqpRpcServer> server( new AmqpRpcServer(connection, INDEX_EXCHANGE,
                                                             queue_name, vm.count("debug")) );
  g_service.reset( new IndexServiceImpl(root_directory) );
  server->bind_service(g_service, "index");

  // Start the server task in another thread
  boost::shared_ptr<ServerTask> server_task( new ServerTask(server) );
  Thread server_thread( server_task );

  // Install Unix Signal Handlers.  These will help us to gracefully
  // recover and salvage the index under most unexpected error
  // conditions.
  signal(SIGINT,  sig_unexpected_shutdown);
  signal(SIGUSR1, sig_sync);

  std::cout << "\n\n";
  long long t0 = Stopwatch::microtime();

  HeapLeakChecker checker_end("testing_at_end");

  {
  HeapLeakChecker checker_sync("testing_force_sync");

  while(process_messages) {
    if (force_sync) {
      std::cout << "Syncing." << std::endl;
      g_service->sync();
      checker_sync.NoLeaks();
      force_sync = false;
    }
    int queries = server->queries_processed();
    size_t bytes = server->bytes_processed();
    int n_outstanding_messages = server->incoming_message_queue_size();
    server->reset_stats();

    float dt = float(Stopwatch::microtime() - t0) / 1e6;
    t0 = Stopwatch::microtime();

    std::cout << "[index_server] : "
              << float(queries/dt) << " qps    "
              << float(bytes/dt)/1000.0 << " kB/sec    "
              << n_outstanding_messages << " outstanding messages                          \r"
              << std::flush;
    sleep(1.0);
  }
  }

  std::cout << "\nShutting down the index service safely.\n";
  g_service->sync();

  checker_end.NoLeaks();

  return 0;
}

<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Copyright (C) 2007,  Simon Kagstrom
 *
 * Filename:      emit.hh
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Emitter
 *
 * $Id:$
 *
 ********************************************************************/
#ifndef __EMIT_HH__
#define __EMIT_HH__

#include <stdint.h>
#include <registerallocator.hh>

class Emit
{
public:
  Emit();

  void bc_comment(const char *what) { this->output("; "); this->write((char*)what); }

  void bc_generic(const char *what, ...);

  void bc_generic_insn(const char *what) { this->writeIndent(what); }

  void bc_label(const char *what, ...);

  void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); }

  void bc_goto(const char *where) { this->writeIndent("goto %s", where); }

  void bc_condbranch(const char *what, ...);

  void bc_pushconst(int32_t nr);

  void bc_pushconst_u(uint32_t nr);

  void bc_pushregister(MIPS_register_t reg);

  void bc_popregister(MIPS_register_t reg);

  void bc_pushindex(MIPS_register_t reg, int32_t extra);

  void bc_pushaddress(MIPS_register_t reg, int32_t extra);

  void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); }

  void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); }

  void bc_iload(int n);

  void bc_istore(int n);

  void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); }

  void bc_iadd() { this->writeIndent("iadd"); }

  void bc_iinc(MIPS_register_t reg, int extra);

  void bc_isub() { this->writeIndent("isub"); }

  void bc_invokestatic(const char *what, ...);

  void bc_lookupswitch(int n, uint32_t *table, const char *def);

  void bc_iushr() { this->writeIndent("iushr"); }

  void bc_lushr() { this->writeIndent("lushr"); }

  void bc_imul() { this->writeIndent("imul"); }

  void bc_idiv() { this->writeIndent("idiv"); }

  void bc_irem() { this->writeIndent("irem"); }

  void bc_ineg() { this->writeIndent("ineg"); }

  void bc_ior() { this->writeIndent("ior"); }

  void bc_ixor() { this->writeIndent("ixor"); }

  void bc_lmul() { this->writeIndent("lmul"); }

  void bc_dup() { this->writeIndent("dup"); }

  void bc_dup2() { this->writeIndent("dup2"); }

  void bc_pop() { this->writeIndent("pop"); }

  void bc_pop2() { this->writeIndent("pop2"); }

  void bc_i2l() { this->writeIndent("i2l"); }

  void bc_l2i() { this->writeIndent("l2i"); }

  void bc_swap() { this->writeIndent("swap"); }

  void bc_iaload() { this->writeIndent("iaload"); }

  void bc_iastore() { this->writeIndent("iastore"); }

  void bc_ireturn() { this->writeIndent("ireturn"); }

  void bc_return() { this->writeIndent("return"); }

  void error(const char *dst, ...);

  void warning(const char *dst, ...);

  void setOutputFile(FILE *fp);

private:
  void bc_load_store_helper(const char *type, int nr);

  void write(const char *dst, ...);

  void writeIndent(const char *dst, ...);

  void output(char *what);

  FILE *fp;
};

extern Emit *emit;

#endif /* !__EMIT_HH__ */
<commit_msg>include stdio.h<commit_after>/*********************************************************************
 *
 * Copyright (C) 2007,  Simon Kagstrom
 *
 * Filename:      emit.hh
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Emitter
 *
 * $Id:$
 *
 ********************************************************************/
#ifndef __EMIT_HH__
#define __EMIT_HH__

#include <stdio.h>
#include <stdint.h>
#include <registerallocator.hh>

class Emit
{
public:
  Emit();

  void bc_comment(const char *what) { this->output("; "); this->write((char*)what); }

  void bc_generic(const char *what, ...);

  void bc_generic_insn(const char *what) { this->writeIndent(what); }

  void bc_label(const char *what, ...);

  void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); }

  void bc_goto(const char *where) { this->writeIndent("goto %s", where); }

  void bc_condbranch(const char *what, ...);

  void bc_pushconst(int32_t nr);

  void bc_pushconst_u(uint32_t nr);

  void bc_pushregister(MIPS_register_t reg);

  void bc_popregister(MIPS_register_t reg);

  void bc_pushindex(MIPS_register_t reg, int32_t extra);

  void bc_pushaddress(MIPS_register_t reg, int32_t extra);

  void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); }

  void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); }

  void bc_iload(int n);

  void bc_istore(int n);

  void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); }

  void bc_iadd() { this->writeIndent("iadd"); }

  void bc_iinc(MIPS_register_t reg, int extra);

  void bc_isub() { this->writeIndent("isub"); }

  void bc_invokestatic(const char *what, ...);

  void bc_lookupswitch(int n, uint32_t *table, const char *def);

  void bc_iushr() { this->writeIndent("iushr"); }

  void bc_lushr() { this->writeIndent("lushr"); }

  void bc_imul() { this->writeIndent("imul"); }

  void bc_idiv() { this->writeIndent("idiv"); }

  void bc_irem() { this->writeIndent("irem"); }

  void bc_ineg() { this->writeIndent("ineg"); }

  void bc_ior() { this->writeIndent("ior"); }

  void bc_ixor() { this->writeIndent("ixor"); }

  void bc_lmul() { this->writeIndent("lmul"); }

  void bc_dup() { this->writeIndent("dup"); }

  void bc_dup2() { this->writeIndent("dup2"); }

  void bc_pop() { this->writeIndent("pop"); }

  void bc_pop2() { this->writeIndent("pop2"); }

  void bc_i2l() { this->writeIndent("i2l"); }

  void bc_l2i() { this->writeIndent("l2i"); }

  void bc_swap() { this->writeIndent("swap"); }

  void bc_iaload() { this->writeIndent("iaload"); }

  void bc_iastore() { this->writeIndent("iastore"); }

  void bc_ireturn() { this->writeIndent("ireturn"); }

  void bc_return() { this->writeIndent("return"); }

  void error(const char *dst, ...);

  void warning(const char *dst, ...);

  void setOutputFile(FILE *fp);

private:
  void bc_load_store_helper(const char *type, int nr);

  void write(const char *dst, ...);

  void writeIndent(const char *dst, ...);

  void output(char *what);

  FILE *fp;
};

extern Emit *emit;

#endif /* !__EMIT_HH__ */
<|endoftext|>