Skip to content
This repository
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 437 lines (351 sloc) 12.521 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
#include "settings.h"

#include <cerrno>
#include <fstream>
#include <sstream>

#include <boost/crc.hpp>
#include <boost/cstdint.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <sys/stat.h>
#include <libxml/xmlIO.h>

#include "xscript/tag.h"
#include "xscript/util.h"
#include "xscript/string_utils.h"
#include "xscript/xml_util.h"
#include "xscript/param.h"
#include "xscript/tagged_block.h"
#include "xscript/logger.h"
#include "xscript/config.h"
#include "xscript/context.h"
#include "xscript/doc_cache_strategy.h"
#include "xscript/doc_cache.h"

#ifdef HAVE_DMALLOC_H
#include <dmalloc.h>
#endif

namespace xscript {

class TaggedKeyDisk : public TagKey {
public:
    TaggedKeyDisk(const Context *ctx, const TaggedBlock *block);

    boost::uint32_t number() const;
    virtual const std::string& asString() const;
    const std::string& filename() const;

private:
    std::string value_;
    std::string filename_;
    boost::uint32_t number_;
};

class DocCacheDisk :
            public Component<DocCacheDisk>,
            public DocCacheStrategy {
public:
    DocCacheDisk();
    virtual ~DocCacheDisk();

    virtual void init(const Config *config);

    virtual time_t minimalCacheTime() const;

    virtual std::auto_ptr<TagKey> createKey(const Context *ctx, const TaggedBlock *block) const;

protected:
    virtual bool loadDocImpl(const TagKey *key, Tag &tag, XmlDocHelper &doc);
    virtual bool saveDocImpl(const TagKey *key, const Tag &tag, const XmlDocHelper &doc);
private:

    static void makeDir(const std::string &name);
    static void createDir(const std::string &name);

    static bool load(const std::string &path, const std::string &key, Tag &tag, std::vector<char> &doc_data);
    static bool save(const std::string &path, const std::string &key, const Tag &tag, const XmlDocHelper &doc);


    static const time_t DEFAULT_CACHE_TIME;
    static const boost::uint32_t VERSION_SIGNATURE_UNMARKED;
    static const boost::uint32_t VERSION_SIGNATURE_MARKED;
    static const boost::uint32_t DOC_SIGNATURE_START;
    static const boost::uint32_t DOC_SIGNATURE_END;

    class WriteFile {
    public:
        WriteFile(FILE *f);
        ~WriteFile();

        void write(const void *ptr, size_t size) const;

    private:
        FILE *f_;
    };

private:
    time_t min_time_;
    std::string root_;
    //boost::mutex mutexes_[256];
};

const time_t DocCacheDisk::DEFAULT_CACHE_TIME = 5; // sec
const boost::uint32_t DocCacheDisk::VERSION_SIGNATURE_UNMARKED = 0xdfc00201;
const boost::uint32_t DocCacheDisk::VERSION_SIGNATURE_MARKED = 0xdfc00202;
const boost::uint32_t DocCacheDisk::DOC_SIGNATURE_START = 0x0a0b0d0a;
const boost::uint32_t DocCacheDisk::DOC_SIGNATURE_END = 0x0a0e0d0a;

TaggedKeyDisk::TaggedKeyDisk(const Context *ctx, const TaggedBlock *block) {
    assert(NULL != ctx);
    assert(NULL != block);

    const std::string& xslt = block->xsltName();
    if (!xslt.empty()) {
        value_.assign(xslt);
        value_.push_back('|');
        
        namespace fs = boost::filesystem;
        fs::path path(xslt);
        if (fs::exists(path) && !fs::is_directory(path)) {
            value_.append(boost::lexical_cast<std::string>(fs::last_write_time(path)));
            value_.push_back('|');
        }
        else {
            throw std::runtime_error("Cannot stat stylesheet " + xslt);
        }
    }
    value_.append(block->canonicalMethod(ctx));

    boost::uint32_t method_sum = HashUtils::crc32(value_);

    std::string param_str;
    const std::vector<Param*> &params = block->params();
    for (unsigned int i = 0, n = params.size(); i < n; ++i) {
        param_str.append(1, ':').append(params[i]->asString(ctx));
    }

    const std::vector<Param*> &xslt_params = block->xsltParams();
    for (unsigned int i = 0, n = xslt_params.size(); i < n; ++i) {
        param_str.append(1, ':').append(xslt_params[i]->id());
        param_str.append(1, ':').append(xslt_params[i]->asString(ctx));
    }

    boost::uint32_t params_sum = HashUtils::crc32(param_str);

    char buf[255];
    boost::uint32_t common = method_sum ^ params_sum;

    number_ = common & 0xFF;
    snprintf(buf, sizeof(buf), "%02x/%08x%08x", number_, method_sum, params_sum);

    filename_.assign(buf);
    value_.append(param_str);
}

boost::uint32_t
TaggedKeyDisk::number() const {
    return number_;
}

const std::string&
TaggedKeyDisk::asString() const {
    return value_;
}

const std::string&
TaggedKeyDisk::filename() const {
    return filename_;
}


DocCacheDisk::WriteFile::WriteFile(FILE *f) : f_(f) {
}

DocCacheDisk::WriteFile::~WriteFile() {
    if (f_) {
        fclose(f_);
    }
}

void DocCacheDisk::WriteFile::write(const void *ptr, size_t size) const {
    size_t sz = ::fwrite(ptr, 1, size, f_);
    if (sz != size) {
        char buf[60];
        snprintf(buf, sizeof(buf), "file write error size: %llu, written: %llu", (unsigned long long)size, (unsigned long long)sz);
        throw std::runtime_error(&buf[0]);
    }
}


DocCacheDisk::DocCacheDisk() :
        min_time_(DEFAULT_CACHE_TIME) {
    statBuilder_.setName("tagged-cache-disk");
    DocCache::instance()->addStrategy(this, "disk");
}

DocCacheDisk::~DocCacheDisk() {
}

void
DocCacheDisk::init(const Config *config) {
    DocCacheStrategy::init(config);

    root_ = config->as<std::string>("/xscript/tagged-cache-disk/root-dir", "").append("/");
    min_time_ = config->as<time_t>("/xscript/tagged-cache-disk/min-cache-time", DEFAULT_CACHE_TIME);
    if (min_time_ <= 0) {
        min_time_ = DEFAULT_CACHE_TIME;
    }
}

time_t
DocCacheDisk::minimalCacheTime() const {
    return min_time_;
}

bool
DocCacheDisk::loadDocImpl(const TagKey *key, Tag &tag, XmlDocHelper &doc) {

    const TaggedKeyDisk *dkey = dynamic_cast<const TaggedKeyDisk*>(key);
    assert(NULL != dkey);

    std::string path(root_);
    path.append(dkey->filename());

    const std::string &key_str = key->asString();
    std::vector<char> vec;
    try {
        //boost::mutex::scoped_lock sl(mutexes_[dkey->number()]);
        if (!load(path, key_str, tag, vec)) {
            return false;
        }
    }
    catch (const std::exception &e) {
        log()->error("error while loading doc from cache: %s", e.what());
        return false;
    }

    try {
        doc = XmlDocHelper(xmlParseMemory(&vec[0], vec.size()));
        XmlUtils::throwUnless(NULL != doc.get());
        return true;
    }
    catch (const std::exception &e) {
        log()->error("error while parsing doc from cache: %s", e.what());
        return false;
    }
}

bool
DocCacheDisk::saveDocImpl(const TagKey *key, const Tag &tag, const XmlDocHelper &doc) {

    const TaggedKeyDisk *dkey = dynamic_cast<const TaggedKeyDisk*>(key);
    assert(NULL != dkey);

    const std::string &key_str = key->asString();

    if (NULL == xmlDocGetRootElement(doc.get())) {
        log()->error("skip saving empty doc, key: %s", key_str.c_str());
        return false;
    }

    std::string path(root_);
    path.append(dkey->filename());

    try {
        createDir(path);

        char buf[path.length() + 8];
        buf[0] = 0;
        strcat(buf, path.c_str());
        strcat(buf, ".XXXXXX");
        int fd = mkstemp(buf);

        if (fd == -1) {
            log()->error("can not create filename: %s", buf);
            return false;
        }

        close(fd);

        if (!save(buf, key_str, tag, doc)) {
            log()->error("can not create doc: %s, key: %s", path.c_str(), key_str.c_str());
            return false;
        }

        if (rename(buf, path.c_str()) == 0) {
            return true;
        }

        log()->error("error while saving doc to cache: %d, key: %s", errno, key_str.c_str());
        return false;
    }
    catch (const std::exception &e) {
        log()->error("error while saving doc to cache: %s, key: %s", e.what(), key_str.c_str());
        return false;
    }
}

std::auto_ptr<TagKey>
DocCacheDisk::createKey(const Context *ctx, const TaggedBlock *block) const {
    return std::auto_ptr<TagKey>(new TaggedKeyDisk(ctx, block));
}

void
DocCacheDisk::makeDir(const std::string &name) {
    int res = mkdir(name.c_str(), 0777);
    if (-1 == res && EEXIST != errno) {
        std::stringstream stream;
        StringUtils::report("failed to create dir: ", errno, stream);
        throw std::runtime_error(stream.str());
    }
}

void
DocCacheDisk::createDir(const std::string &path) {

    std::string::size_type pos = 0;
    while (true) {
        pos = path.find('/', pos + 1);
        if (std::string::npos == pos) {
            break;
        }
        makeDir(path.substr(0, pos));
    }
}

bool
DocCacheDisk::load(const std::string &path, const std::string &key, Tag &tag, std::vector<char> &doc_data) {

    std::fstream is(path.c_str(), std::ios::in | std::ios::out);
    if (!is) {
        log()->debug("can not find cached doc");
        return false;
    }
    is.exceptions(std::ios::badbit | std::ios::eofbit);

    try {
        boost::uint32_t sig = 0, doclen = 0, key_size = 0;
        std::ifstream::pos_type size = 0;
        if (!is.seekg(0, std::ios::end)) {
            throw std::runtime_error("seek error");
        }
        size = is.tellg();
        if (!is.seekg(0, std::ios::beg)) {
            throw std::runtime_error("seek error");
        }

        is.read((char*) &sig, sizeof(boost::uint32_t));
        if (VERSION_SIGNATURE_MARKED != sig && VERSION_SIGNATURE_UNMARKED != sig) {
            throw std::runtime_error("bad signature");
        }
        is.read((char*) &tag.expire_time, sizeof(time_t));
        if (tag.expired()) {
            log()->info("tag expired");
            return false;
        }
        is.read((char*) &tag.last_modified, sizeof(time_t));

        time_t stored_time;
        is.read((char*) &stored_time, sizeof(time_t));

        if (VERSION_SIGNATURE_UNMARKED == sig && tag.needPrefetch(stored_time)) {
            log()->info("need prefetch doc");
            is.seekg(0, std::ios::beg);
            is.write((const char*) &VERSION_SIGNATURE_MARKED, sizeof(boost::uint32_t));
            return false;
        }

        is.read((char*) &key_size, sizeof(boost::uint32_t));

        std::string key_str;
        key_str.resize(key_size);
        is.read((char*) &key_str[0], key_size);
        if (key != key_str) {
            log()->info("tag key clashes with other one");
            return false;
        }

        is.read((char*) &sig, sizeof(boost::uint32_t));
        if (DOC_SIGNATURE_START != sig) {
            throw std::runtime_error("bad doc start signature");
        }
        size -= ((3 * sizeof(time_t)) + (3 * sizeof(boost::uint32_t)) + key_size);
        if (size < (std::ifstream::pos_type)(sizeof(boost::uint32_t))) {
            throw std::runtime_error("can not find doc end signature");
        }
        doclen = (boost::uint32_t)(size) - sizeof(boost::uint32_t);
        doc_data.resize(doclen);
        is.read(&doc_data[0], doclen);
        is.exceptions(std::ios::badbit);
        is.read((char*) &sig, sizeof(boost::uint32_t));
        if (DOC_SIGNATURE_END != sig) {
            throw std::runtime_error("bad doc end signature");
        }

        return true;
    }
    catch (const std::exception &e) {
        is.close();
        unlink(path.c_str());
        throw;
    }
}

bool
DocCacheDisk::save(const std::string &path, const std::string &key, const Tag &tag, const XmlDocHelper &doc) {

    log()->debug("saving %s, key: %s", path.c_str(), key.c_str());

    try {
        FILE *f = fopen(path.c_str(), "w");
        if (NULL == f) {
            return false;
        }
        WriteFile wf(f);
        wf.write(&VERSION_SIGNATURE_UNMARKED, sizeof(boost::uint32_t));
        wf.write(&tag.expire_time, sizeof(time_t));
        wf.write(&tag.last_modified, sizeof(time_t));

        const time_t now = time(NULL);
        wf.write(&now, sizeof(time_t));

        boost::uint32_t key_size = key.size();
        wf.write(&key_size, sizeof(boost::uint32_t));
        wf.write(key.data(), key_size);

        wf.write(&DOC_SIGNATURE_START, sizeof(boost::uint32_t));
        xmlDocDump(f, doc.get());
        wf.write(&DOC_SIGNATURE_END, sizeof(boost::uint32_t));

        return true;
    }
    catch (const std::exception &e) {
        unlink(path.c_str());
        throw;
    }
}

//REGISTER_COMPONENT(DocCacheDisk);
//static ComponentRegisterer<DocCacheDisk> reg_(new DocCacheDisk());
namespace {
static DocCacheDisk cache;
}

} // namespace xscript
Something went wrong with that request. Please try again.