Skip to content
This repository
branch: externalresolv…
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 423 lines (388 sloc) 12.633 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#include "playdar/application.h"

#include <sstream>
#include <boost/foreach.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/filesystem.hpp>

#include "playdar/resolver.h"

#include "playdar/rs_local_library.h"
#include "playdar/rs_script.h"
#include "playdar/library.h"

// PDL stuff:
#include <DynamicLoader.hpp>
#include <DynamicClass.hpp>
#include <DynamicLibrary.hpp>
#include <DynamicLibraryManager.hpp>
#include <LoaderException.hpp>
#include <platform.h>
// end PDL stuff


Resolver::Resolver(MyApplication * app)
    :m_app(app), m_exiting(false)
{
    m_id_counter = 0;
    cout << "Resolver starting..." << endl;
    
    m_t = new boost::thread(boost::bind(&Resolver::dispatch_runner, this));
    
    // set up io_service with work so it never ends:
    m_io_service = new boost::asio::io_service();
    m_work = new boost::asio::io_service::work(*m_io_service);
    m_iothr = new boost::thread(boost::bind(
                    &boost::asio::io_service::run,
                    m_io_service));
             
    // Initialize built-in local library resolver:
    load_library_resolver();

    // Load all non built-in resolvers:
    try
    {
        load_resolver_scripts(); // external processes
        load_resolver_plugins(); // DLL plugins
    }
    catch(...)
    {
        cout << "Error loading resolver plugins." << endl;
    }
    // sort the list of resolvers by weight, descending:
    boost::function<bool (const loaded_rs &, const loaded_rs &)> sortfun =
        boost::bind(&Resolver::loaded_rs_sorter, this, _1, _2);
    sort(m_resolvers.begin(), m_resolvers.end(), sortfun);
    cout << endl;
    cout << "Loaded resolvers (" << m_resolvers.size() << ")" << endl;
    BOOST_FOREACH( loaded_rs & lrs, m_resolvers )
    {
        cout << "RESOLVER w:" << lrs.weight << "\tt:" << lrs.targettime
             << "\t[" << (lrs.script?"script":"plugin") << "] "
             << lrs.rs->name() << endl;
    }
    cout << endl;
}

void
Resolver::load_library_resolver()
{
    loaded_rs cr;
    cr.rs = new RS_local_library();
    // local library resolver is special, it gets a handle to app:
    ((RS_local_library *)cr.rs)->set_app(m_app);
    cr.weight = cr.rs->weight();
    cr.targettime = cr.rs->target_time();
    cr.rs->init(m_app->conf(), this);
    m_resolvers.push_back( cr );
}


Resolver::~Resolver()
{
    m_exiting = true;
    m_cond.notify_one();
    m_t->join();
    delete(m_work);
    m_io_service->stop();
    m_iothr->join();
}

bool
Resolver::loaded_rs_sorter(const loaded_rs & lhs, const loaded_rs & rhs)
{
    return lhs.weight > rhs.weight;
}

/// spawn resolver scripts:
void
Resolver::load_resolver_scripts()
{
    cout << "Loading resolver scripts:" << endl;
    typedef map<string,string> st;
    vector< st > scripts = app()->conf()->get_scriptlist();
    BOOST_FOREACH( st & p, scripts )
    {
        cout << "-> Loading: " << p["path"] << endl;
        try
        {
            loaded_rs cr;
            cr.script = true;
            cr.rs = new playdar::resolvers::rs_script();
            // custom init method for scripts:
            ((playdar::resolvers::rs_script *)cr.rs)->init(app()->conf(), this, p["path"]);
            if(p.find("targettime")!=p.end())
                cr.targettime = boost::lexical_cast<int>(p["targettime"]);
            else
                cr.targettime = cr.rs->target_time();
                
            if(p.find("weight")!=p.end())
                cr.weight = boost::lexical_cast<int>(p["weight"]);
            else
                cr.weight = cr.rs->weight();
            
            if(cr.weight > 0)
            {
                m_resolvers.push_back( cr );
                cout << "-> OK [w:" << cr.weight << " t:" << cr.targettime
                     << "] " << cr.rs->name() << endl;
            }
        }
        catch(...)
        {
            cout << "Error initializing script" << endl;
        }
    }
}

/// dynamically load resolver plugins:
void
Resolver::load_resolver_plugins()
{
    namespace bfs = boost::filesystem;
    bfs::directory_iterator end_itr;
    //bfs::path appdir = bfs::initial_path();
    //bfs::path p(appdir.string() +"/plugins/");
    bfs::path p("plugins");
    cout << "Loading resolver plugins from: "
         << p.string() << endl;
    for(bfs::directory_iterator itr( p ); itr != end_itr; ++itr)
    {
        if ( bfs::is_directory(itr->status()) ) continue;
        string pluginfile = itr->string();
        if(bfs::extension(pluginfile)!=".resolver")
        {
            //cerr << "Skipping '" << pluginfile
            // << "' from plugins directory" << endl;
            continue;
        }
        string classname = bfs::basename(pluginfile);
        string confopt = "resolvers.";
        confopt += classname;
        confopt += ".enabled";
        if(app()->conf()->get<string>(confopt, "yes") == "no")
        {
            cout << "Skipping '" << classname
                 <<"' - disabled in config file." << endl;
            continue;
        }
        try
        {
            PDL::DynamicLoader & dynamicLoader =
                PDL::DynamicLoader::Instance();
            cout << "Loading resolver: " << pluginfile << endl;
            ResolverService * instance =
                dynamicLoader.GetClassInstance< ResolverService >
                    ( pluginfile.c_str(), classname.c_str() );
            instance->init(app()->conf(), this);
            // does this plugin handle any URLs?
            vector<string> handlers = instance->get_http_handlers();
            if(handlers.size())
            {
                cout << "-> Registering " << handlers.size() << " HTTP handlers" << endl;
                //typedef pair<string, http_req_cb> pair_t;
                BOOST_FOREACH(string url, handlers)
                {
                    cout << "-> " << url << endl;
                    m_http_handlers[url] = instance;
                }
            }
            loaded_rs cr;
            cr.script = false;
            cr.rs = instance;
            string rsopt = "resolvers.";
            confopt += classname;
            cr.weight = app()->conf()->get<int>(rsopt + ".weight",
                                                instance->weight());
            cr.targettime = app()->conf()->get<int>(rsopt + ".targettime",
                                                    instance->target_time());
            m_resolvers.push_back( cr );
            cout << "-> OK [w:" << cr.weight << " t:" << cr.targettime << "] "
                 << instance->name() << endl;
        }
        catch( PDL::LoaderException & ex )
        {
            cerr << "-> Error: " << ex.what() << endl;
        }
    }
}

ResolverService *
Resolver::get_url_handler(string url)
{
    if(m_http_handlers.find(url)==m_http_handlers.end()) return 0;
    return m_http_handlers[url];
}

/// start resolving! (non-blocking)
/// returns a query_uid so you can check status of this query later
query_uid
Resolver::dispatch(boost::shared_ptr<ResolverQuery> rq)
{
    rq_callback_t null_cb;
    return dispatch(rq, null_cb);
}

query_uid
Resolver::dispatch(boost::shared_ptr<ResolverQuery> rq,
                    rq_callback_t cb)
{
    if(!rq->valid())
    {
        // probably malformed, eg no track name specified.
        throw;
    }
    boost::mutex::scoped_lock lk(m_mutex);
    if(!add_new_query(rq))
    {
        // already running
        return rq->id();
    }
    if(cb) rq->register_callback(cb);
    m_pending.push_front( pair<rq_ptr, unsigned short>(rq, 999) );
    m_cond.notify_one();
    
    return rq->id();
}

/// thread that loops forever dispatching stuff in the queue
void
Resolver::dispatch_runner()
{
    try
    {
        pair<rq_ptr, unsigned short> p;
        while(true)
        {
            {
                boost::mutex::scoped_lock lk(m_mutex);
                if(m_pending.size() == 0) m_cond.wait(lk);
                if(m_exiting) break;
                p = m_pending.back();
                m_pending.pop_back();
            }
            run_pipeline( p.first, p.second );
        }
    }
    catch(...)
    {
        cout << "Error exiting Resolver::dispatch_runner" << endl;
    }
    cout << "Resolver dispatch_runner terminating" << endl;
}

/// go thru list of resolversservices and dispatch in order
/// lastweight is the weight of the last resolver we dispatched to.
void
Resolver::run_pipeline( rq_ptr rq, unsigned short lastweight )
{
    unsigned short atweight;
    unsigned int mintime;
    bool started = false;
    BOOST_FOREACH( loaded_rs & lrs, m_resolvers )
    {
        if(lrs.weight >= lastweight) continue;
        if(!started)
        {
            atweight = lrs.weight;
            mintime = lrs.targettime;
            started = true;
            cout << "Pipeline at weight: " << atweight << endl;
        }
        if(lrs.weight != atweight)
        {
            // we've dispatched to everything of weight "atweight"
            // and the shortest targettime at that weight is "mintime"
            // so schedule a callaback after mintime to carry on down the
            // chain and dispatch to the next lowest weighted resolver services.
            cout << "Will continue pipeline after " << mintime << "ms." << endl;
            boost::shared_ptr<boost::asio::deadline_timer>
                t(new boost::asio::deadline_timer( m_work->get_io_service() ));
            t->expires_from_now(boost::posix_time::milliseconds(mintime));
            // pass the timer pointer to the handler so it doesnt autodestruct:
            t->async_wait(boost::bind(&Resolver::run_pipeline_cont, this,
                                      rq, atweight, t));
            break;
        }
        if(lrs.targettime < mintime) mintime = lrs.targettime;
        // dispatch to this resolver:
        cout << "Pipeline dispatching to " << lrs.rs->name()
             << " (lastweight: " << lastweight << ")" << endl;
        lrs.rs->start_resolving(rq);
    }
}

void
Resolver::run_pipeline_cont( rq_ptr rq,
                        unsigned short lastweight,
                        boost::shared_ptr<boost::asio::deadline_timer> oldtimer)
{
    cout << "Pipeline continues.." << endl;
    if(rq->solved())
    {
        cout << "Bailing from pipeline: SOLVED @ lastweight: " << lastweight
             << endl;
    }
    else
    {
        boost::mutex::scoped_lock lk(m_mutex);
        m_pending.push_front( pair<rq_ptr, unsigned short>(rq, lastweight) );
        m_cond.notify_one();
    }
}

// a resolver will report results here
// false means give up on this query, it's over
// true means carry on as normal
bool
Resolver::add_results(query_uid qid, vector< pi_ptr > results, string via)
{
    if(results.size()==0)
    {
        return true;
    }
    boost::mutex::scoped_lock lock(m_mut_results);
    if(!query_exists(qid)) return false; // query was deleted
    // add these new results to the ResolverQuery object
    BOOST_FOREACH(boost::shared_ptr<PlayableItem> pip, results)
    {
        m_queries[qid]->add_result(pip);
        // update map of source id -> playable item
        m_pis[pip->id()] = pip;
    }
    return true;
}

// gets all the current results for a query
// but leaves query active. (ie, results may change later)
vector< pi_ptr >
Resolver::get_results(query_uid qid)
{
    vector< pi_ptr > ret;
    boost::mutex::scoped_lock lock(m_mut_results);
    if(!query_exists(qid)) return ret; // query was deleted
    return m_queries[qid]->results();
}

void
Resolver::end_query(query_uid qid)
{
    //boost::mutex::scoped_lock lock(m_mut);
    //m_queries.erase(qid);
}

// check how many results we found for this query id
int
Resolver::num_results(query_uid qid)
{
    {
        boost::mutex::scoped_lock lock(m_mut_results);
        if(query_exists(qid))
        {
            return m_queries[qid]->results().size();
        }
    }
    cerr << "Query id '"<< qid <<"' does not exist" << endl;
    return 0;
}

// does this qid still exist?
bool
Resolver::query_exists(const query_uid & qid)
{
    return (m_queries.find(qid) != m_queries.end());
}

// true on success, false if it already exists.
bool
Resolver::add_new_query(boost::shared_ptr<ResolverQuery> rq)
{
    if(query_exists(rq->id())) return false;
    m_queries[rq->id()] = rq;
    m_qidlist.push_front(rq->id());
    return true;
}

boost::shared_ptr<ResolverQuery>
Resolver::rq(query_uid qid)
{
    return m_queries[qid];
}

size_t
Resolver::num_seen_queries()
{
    return m_queries.size();
}

boost::shared_ptr<PlayableItem>
Resolver::get_pi(source_uid sid)
{
    return m_pis[sid];
}
Something went wrong with that request. Please try again.