summaryrefslogtreecommitdiffstats
path: root/include/ruby/backward/util.h
diff options
context:
space:
mode:
Diffstat (limited to 'include/ruby/backward/util.h')
0 files changed, 0 insertions, 0 deletions
d='n67' href='#n67'>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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
/*
    Copyright (C) 2009  Jiri Moskovcak (jmoskovc@redhat.com)
    Copyright (C) 2009  RedHat inc.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    */
#include "abrtlib.h"
#include "CrashWatcher.h"
#include <iostream>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <sstream>
#include <cstring>
#include "ABRTException.h"

#define VAR_RUN_LOCK_FILE   VAR_RUN"/abrt.lock"
#define VAR_RUN_PIDFILE     VAR_RUN"/abrt.pid"

/* just a helper function
template< class T >
std::string
to_string( T x )
{
    std::ostringstream o;
    o << x;
    return o.str();
}
*/

/* Is it "." or ".."? */
/* abrtlib candidate */
static bool dot_or_dotdot(const char *filename)
{
    if (filename[0] != '.') return false;
    if (filename[1] == '\0') return true;
    if (filename[1] != '.') return false;
    if (filename[2] == '\0') return true;
    return false;
}

static double GetDirSize(const std::string &pPath);

gboolean CCrashWatcher::handle_event_cb(GIOChannel *gio, GIOCondition condition, gpointer daemon)
{
    GIOError err;
    char *buf = new char[INOTIFY_BUFF_SIZE];
    gsize len;
    gsize i = 0;
    err = g_io_channel_read(gio, buf, INOTIFY_BUFF_SIZE, &len);
    CCrashWatcher *cc = (CCrashWatcher*)daemon;
    if (err != G_IO_ERROR_NONE)
    {
        cc->Warning("Error reading inotify fd.");
        delete[] buf;
        return FALSE;
    }
    /* reconstruct each event and send message to the dbus */
    while (i < len)
    {
        const char *name = NULL;
        struct inotify_event *event;

        event = (struct inotify_event *) &buf[i];
        if (event->len)
            name = &buf[i] + sizeof (struct inotify_event);
        i += sizeof (struct inotify_event) + event->len;

        cc->Debug(std::string("Created file: ") + name);

        /* we want to ignore the lock files */
        if (event->mask & IN_ISDIR)
        {
            if (GetDirSize(DEBUG_DUMPS_DIR) / (1024*1024) < cc->m_pSettings->GetMaxCrashReportsSize())
            {
                //std::string sName = name;
                map_crash_info_t crashinfo;
                try
                {
                    CMiddleWare::mw_result_t res;
                    res = cc->m_pMW->SaveDebugDump(std::string(DEBUG_DUMPS_DIR) + "/" + name, crashinfo);
                    switch (res)
                    {
                        case CMiddleWare::MW_OK:
                            cc->Warning("New crash, saving...");
                            cc->m_pMW->RunActionsAndReporters(crashinfo[CD_MWDDD][CD_CONTENT]);
                            /* send message to dbus */
                            cc->m_pCommLayer->Crash(crashinfo[CD_PACKAGE][CD_CONTENT]);
                            break;
                        case CMiddleWare::MW_REPORTED:
                        case CMiddleWare::MW_OCCURED:
                            /* send message to dbus */
                            cc->Warning("Already saved crash, deleting...");
                            cc->m_pCommLayer->Crash(crashinfo[CD_PACKAGE][CD_CONTENT]);
                            cc->m_pMW->DeleteDebugDumpDir(std::string(DEBUG_DUMPS_DIR) + "/" + name);
                            break;
                        case CMiddleWare::MW_BLACKLISTED:
                        case CMiddleWare::MW_CORRUPTED:
                        case CMiddleWare::MW_PACKAGE_ERROR:
                        case CMiddleWare::MW_GPG_ERROR:
                        case CMiddleWare::MW_IN_DB:
                        case CMiddleWare::MW_FILE_ERROR:
                        default:
                            cc->Warning("Corrupted or bad crash, deleting...");
                            cc->m_pMW->DeleteDebugDumpDir(std::string(DEBUG_DUMPS_DIR) + "/" + name);
                            break;
                    }
                }
                catch (CABRTException& e)
                {
                    cc->Warning(e.what());
                    if (e.type() == EXCEP_FATAL)
                    {
                        delete[] buf;
                        return -1;
                    }
                }
                catch (...)
                {
                    delete[] buf;
                    throw;
                }
            }
            else
            {
                cc->Debug(std::string("DebugDumps size has exceeded the limit, deleting the last dump: ") + name);
                cc->m_pMW->DeleteDebugDumpDir(std::string(DEBUG_DUMPS_DIR) + "/" + name);
            }
        }
        else
        {
            cc->Debug("Some file created, ignoring...");
        }
    }
    delete[] buf;
    return TRUE;
}

void *CCrashWatcher::create_report(void *arg){
    thread_data_t *thread_data = (thread_data_t *) arg;
    map_crash_info_t crashReport;
    thread_data->daemon->Debug("Creating report...");
    try
    {
        CMiddleWare::mw_result_t res;
        res = thread_data->daemon->m_pMW->CreateCrashReport(thread_data->UUID,thread_data->UID,crashReport);
        switch (res)
        {
            case CMiddleWare::MW_OK:
                break;
            case CMiddleWare::MW_IN_DB_ERROR:
                thread_data->daemon->Warning(std::string("Did not find crash with UUID ")+thread_data->UUID+ " in database.");
                break;
            case CMiddleWare::MW_CORRUPTED:
            case CMiddleWare::MW_FILE_ERROR:
            default:
                {
                    std::string debugDumpDir;
                    thread_data->daemon->Warning(std::string("Corrupted crash with UUID ")+thread_data->UUID+", deleting.");
                    debugDumpDir = thread_data->daemon->m_pMW->DeleteCrashInfo(thread_data->UUID, thread_data->UID);
                    thread_data->daemon->m_pMW->DeleteDebugDumpDir(debugDumpDir);
                }
                break;
        }
        /* only one thread can write */
        pthread_mutex_lock(&(thread_data->daemon->m_pJobsMutex));
        thread_data->daemon->pending_jobs[std::string(thread_data->UID)][thread_data->thread_id] = crashReport;
        pthread_mutex_unlock(&(thread_data->daemon->m_pJobsMutex));
        thread_data->daemon->m_pCommLayer->JobDone(thread_data->dest, thread_data->thread_id);
    }
    catch (CABRTException& e)
    {
        if (e.type() == EXCEP_FATAL)
        {
            /* free strduped strings */
            free(thread_data->UUID);
            free(thread_data->UID);
            free(thread_data->dest);
            free(thread_data);
            throw e;
        }
        thread_data->daemon->Warning(e.what());
    }
    /* free strduped strings */
    free(thread_data->UUID);
    free(thread_data->UID);
    free(thread_data->dest);
    free(thread_data);
}

gboolean CCrashWatcher::cron_activation_periodic_cb(gpointer data)
{
    cron_callback_data_t* cronPeriodicCallbackData = static_cast<cron_callback_data_t*>(data);
    cronPeriodicCallbackData->m_pCrashWatcher->Debug("Activating plugin: " + cronPeriodicCallbackData->m_sPluginName);
    cronPeriodicCallbackData->m_pCrashWatcher->m_pMW->RunAction(cronPeriodicCallbackData->m_pCrashWatcher->m_sTarget,
                                                                cronPeriodicCallbackData->m_sPluginName,
                                                                cronPeriodicCallbackData->m_sPluginArgs);
    return TRUE;
}
gboolean CCrashWatcher::cron_activation_one_cb(gpointer data)
{
    cron_callback_data_t* cronOneCallbackData = static_cast<cron_callback_data_t*>(data);
    cronOneCallbackData->m_pCrashWatcher->Debug("Activating plugin: " + cronOneCallbackData->m_sPluginName);
    cronOneCallbackData->m_pCrashWatcher->m_pMW->RunAction(cronOneCallbackData->m_pCrashWatcher->m_sTarget,
                                                           cronOneCallbackData->m_sPluginName,
                                                           cronOneCallbackData->m_sPluginArgs);
    return FALSE;
}
gboolean CCrashWatcher::cron_activation_reshedule_cb(gpointer data)
{
    cron_callback_data_t* cronResheduleCallbackData = static_cast<cron_callback_data_t*>(data);
    cronResheduleCallbackData->m_pCrashWatcher->Debug("Rescheduling plugin: " + cronResheduleCallbackData->m_sPluginName);
    cron_callback_data_t* cronPeriodicCallbackData = new cron_callback_data_t(cronResheduleCallbackData->m_pCrashWatcher,
                                                                              cronResheduleCallbackData->m_sPluginName,
                                                                              cronResheduleCallbackData->m_sPluginArgs,
                                                                              cronResheduleCallbackData->m_nTimeout);
    g_timeout_add_seconds_full(G_PRIORITY_DEFAULT,
                               cronPeriodicCallbackData->m_nTimeout,
                               cron_activation_periodic_cb,
                               static_cast<gpointer>(cronPeriodicCallbackData),
                               cron_delete_callback_data_cb);


    return FALSE;
}

void CCrashWatcher::cron_delete_callback_data_cb(gpointer data)
{
    cron_callback_data_t* cronDeleteCallbackData = static_cast<cron_callback_data_t*>(data);
    delete cronDeleteCallbackData;
}

void CCrashWatcher::SetUpMW()
{
    m_pMW->SetOpenGPGCheck(m_pSettings->GetOpenGPGCheck());
    m_pMW->SetDatabase(m_pSettings->GetDatabase());
    CSettings::set_strings_t openGPGPublicKeys = m_pSettings->GetOpenGPGPublicKeys();
    CSettings::set_strings_t::iterator it_k;
    for (it_k = openGPGPublicKeys.begin(); it_k != openGPGPublicKeys.end(); it_k++)
    {
        m_pMW->AddOpenGPGPublicKey(*it_k);
    }
    CSettings::set_strings_t blackList = m_pSettings->GetBlackList();
    CSettings::set_strings_t::iterator it_b;
    for (it_b = blackList.begin(); it_b != blackList.end(); it_b++)
    {
        m_pMW->AddBlackListedPackage(*it_b);
    }
    CSettings::set_strings_t enabledPlugins = m_pSettings->GetEnabledPlugins();
    CSettings::set_strings_t::iterator it_p;
    for (it_p = enabledPlugins.begin(); it_p != enabledPlugins.end(); it_p++)
    {
        m_pMW->RegisterPlugin(*it_p);
    }
    CSettings::vector_pair_strings_t actionsAndReporters = m_pSettings->GetActionsAndReporters();
    CSettings::vector_pair_strings_t::iterator it_ar;
    for (it_ar = actionsAndReporters.begin(); it_ar != actionsAndReporters.end(); it_ar++)
    {
        m_pMW->AddActionOrReporter((*it_ar).first, (*it_ar).second);
    }

    CSettings::map_analyzer_actions_and_reporters_t analyzerActionsAndReporters = m_pSettings->GetAnalyzerActionsAndReporters();
    CSettings::map_analyzer_actions_and_reporters_t::iterator it_aar;
    for (it_aar = analyzerActionsAndReporters.begin(); it_aar != analyzerActionsAndReporters.end(); it_aar++)
    {
        CSettings::vector_pair_strings_t::iterator it_ar;
        for (it_ar = it_aar->second.begin(); it_ar != it_aar->second.end(); it_ar++)
        {
            m_pMW->AddAnalyzerActionOrReporter(it_aar->first, (*it_ar).first, (*it_ar).second);
        }
    }
}

void CCrashWatcher::SetUpCron()
{
    CSettings::map_cron_t cron = m_pSettings->GetCron();
    CSettings::map_cron_t::iterator it_c;
    for (it_c = cron.begin(); it_c != cron.end(); it_c++)
    {
        std::string::size_type pos = it_c->first.find(":");
        int timeout = 0;
        int nH = -1;
        int nM = -1;
        int nS = -1;

        if (pos != std::string::npos)
        {
            std::string sH = "";
            std::string sM = "";

            sH = it_c->first.substr(0, pos);
            nH = atoi(sH.c_str());
            nH = nH > 23 ? 23 : nH;
            nH = nH < 0 ? 0 : nH;
            nM = nM > 59 ? 59 : nM;
            nM = nM < 0 ? 0 : nM;
            timeout += nH * 60 * 60;
            sM = it_c->first.substr(pos + 1);
            nM = atoi(sM.c_str());
            timeout += nM * 60;
        }
        else
        {
            std::string sS = "";

            sS = it_c->first;
            nS = atoi(sS.c_str());
            nS = nS < 0 ? 0 : nS;
            timeout = nS;
        }

        if (nS != -1)
        {
            CSettings::vector_pair_strings_t::iterator it_ar;
            for (it_ar = it_c->second.begin(); it_ar != it_c->second.end(); it_ar++)
            {

                cron_callback_data_t* cronPeriodicCallbackData = new cron_callback_data_t(this, (*it_ar).first, (*it_ar).second, timeout);
                g_timeout_add_seconds_full(G_PRIORITY_DEFAULT,
                                           timeout ,
                                           cron_activation_periodic_cb,
                                           static_cast<gpointer>(cronPeriodicCallbackData),
                                           cron_delete_callback_data_cb);
            }
        }
        else
        {
            time_t actTime = time(NULL);
            if (actTime == ((time_t)-1))
            {
                throw CABRTException(EXCEP_FATAL, "CCrashWatcher::SetUpCron(): Cannot get time.");
            }
            struct tm locTime;
            if (localtime_r(&actTime, &locTime) == NULL)
            {
                throw CABRTException(EXCEP_FATAL, "CCrashWatcher::SetUpCron(): Cannot get local time.");
            }
            locTime.tm_hour = nH;
            locTime.tm_min = nM;
            locTime.tm_sec = 0;
            time_t nextTime = mktime(&locTime);
            if (nextTime == ((time_t)-1))
            {
                throw CABRTException(EXCEP_FATAL, "CCrashWatcher::SetUpCron(): Cannot set up time.");
            }
            if (actTime > nextTime)
            {
                timeout = 24*60*60 + (nextTime - actTime);
            }
            else
            {
                timeout = nextTime - actTime;
            }
            CSettings::vector_pair_strings_t::iterator it_ar;
            for (it_ar = it_c->second.begin(); it_ar != it_c->second.end(); it_ar++)
            {

                cron_callback_data_t* cronOneCallbackData = new cron_callback_data_t(this, (*it_ar).first, (*it_ar).second, timeout);
                g_timeout_add_seconds_full(G_PRIORITY_DEFAULT,
                                           timeout,
                                           cron_activation_one_cb,
                                           static_cast<gpointer>(cronOneCallbackData),
                                           cron_delete_callback_data_cb);
                cron_callback_data_t* cronResheduleCallbackData = new cron_callback_data_t(this, (*it_ar).first, (*it_ar).second, 24 * 60 * 60);
                g_timeout_add_seconds_full(G_PRIORITY_DEFAULT,
                                           timeout,
                                           cron_activation_reshedule_cb,
                                           static_cast<gpointer>(cronResheduleCallbackData),
                                           cron_delete_callback_data_cb);
            }
        }
    }
}

void CCrashWatcher::Status(const std::string& pMessage, const std::string& pDest)
{
    std::cout << "Update: " + pMessage << std::endl;
    //FIXME: send updates only to job owner
    if(m_pCommLayer != NULL)
       m_pCommLayer->Update(pDest,pMessage);
}

void CCrashWatcher::Warning(const std::string& pMessage, const std::string& pDest)
{
    std::cerr << "Warning: " + pMessage << std::endl;
    if(m_pCommLayer != NULL)
       m_pCommLayer->Warning(pDest,pMessage);
}

void CCrashWatcher::Debug(const std::string& pMessage, const std::string& pDest)
{
    //some logic to add logging levels?
    std::cout << "Debug: " + pMessage << std::endl;
}

static double GetDirSize(const std::string &pPath)
{
    double size = 0;
    struct dirent *ep;
    struct stat stats;
    DIR *dp;

    dp = opendir(pPath.c_str());
    if (dp != NULL)
    {
        while ((ep = readdir(dp)) != NULL)
        {
            if (dot_or_dotdot(ep->d_name))
                continue;
            std::string dname = pPath + "/" + ep->d_name;
            if (lstat(dname.c_str(), &stats) == 0)
            {
                if (S_ISDIR(stats.st_mode))
                {
                    size += GetDirSize(dname);
                }
                else if (S_ISREG(stats.st_mode))
                {
                    size += stats.st_size;
                }
            }
        }
        closedir(dp);
    }
    else
    {
        throw CABRTException(EXCEP_FATAL, std::string(__func__) + ": Init Failed");
    }
    return size;
}

CCrashWatcher::CCrashWatcher(const std::string& pPath)
{
    int watch = 0;
    m_sTarget = pPath;

    // TODO: initialize object according parameters -w -d
    // status has to be always created.
    m_pCommLayer = NULL;
    m_pCommLayerInner = new CCommLayerInner(this, true, true);
    comm_layer_inner_init(m_pCommLayerInner);

    m_pSettings = new CSettings();
    m_pSettings->LoadSettings(std::string(CONF_DIR) + "/abrt.conf");

    m_pMainloop = g_main_loop_new(NULL,FALSE);
    m_pMW = new CMiddleWare(PLUGINS_CONF_DIR,PLUGINS_LIB_DIR);
    if (pthread_mutex_init(&m_pJobsMutex, NULL) != 0)
    {
        throw CABRTException(EXCEP_FATAL, "CCrashWatcher::CCrashWatcher(): Can't init mutex!");
    }
    try
    {
        SetUpMW();
        SetUpCron();
        FindNewDumps(pPath);
#ifdef ENABLE_DBUS
        m_pCommLayer = new CCommLayerServerDBus();
#elif ENABLE_SOCKET
        m_pCommLayer = new CCommLayerServerSocket();
#endif
//      m_pCommLayer = new CCommLayerServerDBus();
//      m_pCommLayer = new CCommLayerServerSocket();
        m_pCommLayer->Attach(this);