2
Copyright (C) 2010 Zimin
4
This program is free software; you can redistribute it and/or
5
modify it under the terms of the GNU General Public License
6
as published by the Free Software Foundation; either version 2
7
of the License, or (at your option) any later version.
9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
GNU General Public License for more details.
14
You should have received a copy of the GNU General Public License
15
along with this program; if not, write to the Free Software
16
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
#include <drizzled/field.h>
21
#include <drizzled/field/blob.h>
22
#include <drizzled/field/timestamp.h>
23
#include <drizzled/error.h>
24
#include <drizzled/table.h>
25
#include <drizzled/session.h>
26
#include "drizzled/internal/my_sys.h"
27
#include <google/protobuf/io/zero_copy_stream.h>
28
#include <google/protobuf/io/zero_copy_stream_impl.h>
30
#include "filesystem_engine.h"
40
#include <boost/algorithm/string.hpp>
43
using namespace drizzled;
45
#define FILESYSTEM_EXT ".FST"
47
/* Stuff for shares */
48
pthread_mutex_t filesystem_mutex;
50
static const char *ha_filesystem_exts[] = {
55
class FilesystemEngine : public drizzled::plugin::StorageEngine
58
typedef std::map<string, FilesystemTableShare*> FilesystemMap;
59
FilesystemMap fs_open_tables;
61
FilesystemEngine(const string& name_arg)
62
: drizzled::plugin::StorageEngine(name_arg,
64
HTON_SKIP_STORE_LOCK |
65
HTON_CAN_INDEX_BLOBS |
69
table_definition_ext= FILESYSTEM_EXT;
70
pthread_mutex_init(&filesystem_mutex, MY_MUTEX_INIT_FAST);
72
virtual ~FilesystemEngine()
74
pthread_mutex_destroy(&filesystem_mutex);
77
virtual Cursor *create(TableShare &table)
79
return new FilesystemCursor(*this, table);
82
const char **bas_ext() const {
83
return ha_filesystem_exts;
86
bool validateCreateTableOption(const std::string &key, const std::string &state);
88
int doCreateTable(Session &,
90
const drizzled::TableIdentifier &identifier,
91
drizzled::message::Table&);
93
int doGetTableDefinition(Session& ,
94
const drizzled::TableIdentifier &,
95
drizzled::message::Table &);
97
int doDropTable(Session&, const TableIdentifier &);
99
/* operations on FilesystemTableShare */
100
FilesystemTableShare *findOpenTable(const string table_name);
101
void addOpenTable(const string &table_name, FilesystemTableShare *);
102
void deleteOpenTable(const string &table_name);
104
uint32_t max_keys() const { return 0; }
105
uint32_t max_key_parts() const { return 0; }
106
uint32_t max_key_length() const { return 0; }
107
bool doDoesTableExist(Session& , const TableIdentifier &);
108
int doRenameTable(Session&, const TableIdentifier &, const TableIdentifier &);
109
void doGetTableIdentifiers(drizzled::CachedDirectory &directory,
110
const drizzled::SchemaIdentifier &schema_identifier,
111
drizzled::TableIdentifiers &set_of_identifiers);
113
void getTableNamesFromFilesystem(drizzled::CachedDirectory &directory,
114
const drizzled::SchemaIdentifier &schema_identifier,
115
drizzled::plugin::TableNameList *set_of_names,
116
drizzled::TableIdentifiers *set_of_identifiers);
119
void FilesystemEngine::getTableNamesFromFilesystem(drizzled::CachedDirectory &directory,
120
const drizzled::SchemaIdentifier &schema_identifier,
121
drizzled::plugin::TableNameList *set_of_names,
122
drizzled::TableIdentifiers *set_of_identifiers)
124
drizzled::CachedDirectory::Entries entries= directory.getEntries();
126
for (drizzled::CachedDirectory::Entries::iterator entry_iter= entries.begin();
127
entry_iter != entries.end();
130
drizzled::CachedDirectory::Entry *entry= *entry_iter;
131
const string *filename= &entry->filename;
133
assert(not filename->empty());
135
string::size_type suffix_pos= filename->rfind('.');
137
if (suffix_pos != string::npos &&
138
boost::iequals(filename->substr(suffix_pos), FILESYSTEM_EXT) &&
139
filename->compare(0, strlen(TMP_FILE_PREFIX), TMP_FILE_PREFIX))
141
char uname[NAME_LEN + 1];
142
uint32_t file_name_len;
144
file_name_len= TableIdentifier::filename_to_tablename(filename->c_str(), uname, sizeof(uname));
145
uname[file_name_len - sizeof(FILESYSTEM_EXT) + 1]= '\0';
147
set_of_names->insert(uname);
148
if (set_of_identifiers)
149
set_of_identifiers->push_back(TableIdentifier(schema_identifier, uname));
154
void FilesystemEngine::doGetTableIdentifiers(drizzled::CachedDirectory &directory,
155
const drizzled::SchemaIdentifier &schema_identifier,
156
drizzled::TableIdentifiers &set_of_identifiers)
158
getTableNamesFromFilesystem(directory, schema_identifier, NULL, &set_of_identifiers);
161
int FilesystemEngine::doDropTable(Session &, const TableIdentifier &identifier)
163
string new_path(identifier.getPath());
164
new_path+= FILESYSTEM_EXT;
165
int err= unlink(new_path.c_str());
173
bool FilesystemEngine::doDoesTableExist(Session &, const TableIdentifier &identifier)
175
string proto_path(identifier.getPath());
176
proto_path.append(FILESYSTEM_EXT);
178
if (access(proto_path.c_str(), F_OK))
186
FilesystemTableShare *FilesystemEngine::findOpenTable(const string table_name)
188
FilesystemMap::iterator find_iter=
189
fs_open_tables.find(table_name);
191
if (find_iter != fs_open_tables.end())
192
return (*find_iter).second;
197
void FilesystemEngine::addOpenTable(const string &table_name, FilesystemTableShare *share)
199
fs_open_tables[table_name]= share;
202
void FilesystemEngine::deleteOpenTable(const string &table_name)
204
fs_open_tables.erase(table_name);
207
static int parseTaggedFile(const FormatInfo &fi, vector< map<string, string> > &v)
209
int filedesc= ::open(fi.getFileName().c_str(), O_RDONLY);
213
boost::scoped_ptr<TransparentFile> filebuffer(new TransparentFile);
214
filebuffer->init_buff(filedesc);
216
bool last_line_empty= false;
217
map<string, string> kv;
222
char ch= filebuffer->get_value(pos);
225
if (!last_line_empty)
234
if (!fi.isRowSeparator(ch))
240
// if we have a new empty line,
241
// it means we got the end of a section, push it to vector
244
if (!last_line_empty)
249
last_line_empty= true;
254
vector<string> sv, svcopy;
255
boost::split(sv, line, boost::is_any_of(fi.getColSeparator()));
256
for (vector<string>::iterator iter= sv.begin();
261
svcopy.push_back(*iter);
264
// the first splitted string as key,
265
// and the second splitted string as value.
266
string key(svcopy[0]);
268
if (svcopy.size() >= 2)
270
string value(svcopy[1]);
274
else if (svcopy.size() >= 1)
277
last_line_empty= false;
284
int FilesystemEngine::doGetTableDefinition(Session &,
285
const drizzled::TableIdentifier &identifier,
286
drizzled::message::Table &table_proto)
288
string new_path(identifier.getPath());
289
new_path.append(FILESYSTEM_EXT);
291
int fd= ::open(new_path.c_str(), O_RDONLY);
295
google::protobuf::io::ZeroCopyInputStream* input=
296
new google::protobuf::io::FileInputStream(fd);
299
return HA_ERR_CRASHED_ON_USAGE;
301
if (not table_proto.ParseFromZeroCopyStream(input))
305
if (not table_proto.IsInitialized())
307
my_error(ER_CORRUPT_TABLE_DEFINITION, MYF(0),
308
table_proto.InitializationErrorString().c_str());
309
return ER_CORRUPT_TABLE_DEFINITION;
312
return HA_ERR_CRASHED_ON_USAGE;
316
// if the file is a tagged file such as /proc/meminfo
317
// then columns of this table are added dynamically here.
319
format.parseFromTable(&table_proto);
320
if (!format.isTagFormat() || !format.isFileGiven()) {
325
vector< map<string, string> > vm;
326
if (parseTaggedFile(format, vm) != 0) {
331
if (vm.size() == 0) {
336
// we don't care what user provides, just clear them all
337
table_proto.clear_field();
338
// we take the first section as sample
339
map<string, string> kv= vm[0];
340
for (map<string, string>::iterator iter= kv.begin();
344
// add columns to table proto
345
message::Table::Field *field= table_proto.add_field();
346
field->set_name(iter->first);
347
field->set_type(drizzled::message::Table::Field::VARCHAR);
348
message::Table::Field::StringFieldOptions *stringoption= field->mutable_string_options();
349
stringoption->set_length(iter->second.length() + 1);
356
FilesystemTableShare::FilesystemTableShare(const string table_name_arg)
357
: use_count(0), table_name(table_name_arg),
358
update_file_opened(false),
363
FilesystemTableShare::~FilesystemTableShare()
365
pthread_mutex_destroy(&mutex);
368
FilesystemTableShare *FilesystemCursor::get_share(const char *table_name)
370
Guard g(filesystem_mutex);
372
FilesystemEngine *a_engine= static_cast<FilesystemEngine *>(engine);
373
share= a_engine->findOpenTable(table_name);
376
If share is not present in the hash, create a new share and
377
initialize its members.
381
share= new (nothrow) FilesystemTableShare(table_name);
387
share->format.parseFromTable(table->getShare()->getTableProto());
388
if (!share->format.isFileGiven())
393
* for taggered file such as /proc/meminfo,
394
* we pre-process it first, and store the parsing result in a map.
396
if (share->format.isTagFormat())
398
if (parseTaggedFile(share->format, share->vm) != 0)
403
a_engine->addOpenTable(share->table_name, share);
405
pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
412
void FilesystemCursor::free_share()
414
Guard g(filesystem_mutex);
416
if (!--share->use_count){
417
FilesystemEngine *a_engine= static_cast<FilesystemEngine *>(engine);
418
a_engine->deleteOpenTable(share->table_name);
419
pthread_mutex_destroy(&share->mutex);
424
void FilesystemCursor::critical_section_enter()
426
if (sql_command_type == SQLCOM_ALTER_TABLE ||
427
sql_command_type == SQLCOM_UPDATE ||
428
sql_command_type == SQLCOM_DELETE ||
429
sql_command_type == SQLCOM_INSERT ||
430
sql_command_type == SQLCOM_INSERT_SELECT ||
431
sql_command_type == SQLCOM_REPLACE ||
432
sql_command_type == SQLCOM_REPLACE_SELECT)
433
share->filesystem_lock.scan_update_begin();
435
share->filesystem_lock.scan_begin();
437
thread_locked = true;
440
void FilesystemCursor::critical_section_exit()
442
if (sql_command_type == SQLCOM_ALTER_TABLE ||
443
sql_command_type == SQLCOM_UPDATE ||
444
sql_command_type == SQLCOM_DELETE ||
445
sql_command_type == SQLCOM_INSERT ||
446
sql_command_type == SQLCOM_INSERT_SELECT ||
447
sql_command_type == SQLCOM_REPLACE ||
448
sql_command_type == SQLCOM_REPLACE_SELECT)
449
share->filesystem_lock.scan_update_end();
451
share->filesystem_lock.scan_end();
453
thread_locked = false;
456
FilesystemCursor::FilesystemCursor(drizzled::plugin::StorageEngine &engine_arg, TableShare &table_arg)
457
: Cursor(engine_arg, table_arg),
458
file_buff(new TransparentFile),
463
int FilesystemCursor::doOpen(const drizzled::TableIdentifier &identifier, int, uint32_t)
465
if (!(share= get_share(identifier.getPath().c_str())))
468
file_desc= ::open(share->format.getFileName().c_str(), O_RDONLY);
472
return ER_CANT_OPEN_FILE;
475
ref_length= sizeof(off_t);
479
int FilesystemCursor::close(void)
481
int err= ::close(file_desc);
488
int FilesystemCursor::doStartTableScan(bool)
490
sql_command_type = session_sql_command(table->getSession());
493
critical_section_exit();
494
critical_section_enter();
496
if (share->format.isTagFormat())
505
if (share->needs_reopen)
507
file_desc= ::open(share->format.getFileName().c_str(), O_RDONLY);
509
return HA_ERR_CRASHED_ON_USAGE;
510
share->needs_reopen= false;
512
file_buff->init_buff(file_desc);
516
int FilesystemCursor::find_current_row(unsigned char *buf)
518
ptrdiff_t row_offset= buf - table->record[0];
520
next_position= current_position;
523
bool line_done= false;
524
bool line_blank= true;
525
Field **field= table->getFields();
526
for (; !line_done && *field; ++next_position)
528
char ch= file_buff->get_value(next_position);
530
return HA_ERR_END_OF_FILE;
532
if (share->format.isEscapedChar(ch))
534
// read next character
535
ch= file_buff->get_value(++next_position);
537
return HA_ERR_END_OF_FILE;
539
content.push_back(FormatInfo::getEscapedChar(ch));
544
// if we find separator
545
bool is_row= share->format.isRowSeparator(ch);
546
bool is_col= share->format.isColSeparator(ch);
549
if (share->format.isSeparatorModeGeneral() && is_row && line_blank)
551
if (share->format.isSeparatorModeWeak() && is_col)
555
if (is_row || is_col)
557
(*field)->move_field_offset(row_offset);
558
if (!content.empty())
560
(*field)->set_notnull();
561
if ((*field)->isReadSet() || (*field)->isWriteSet())
563
(*field)->setWriteSet();
564
(*field)->store(content.c_str(),
565
(uint32_t)content.length(),
570
(*field)->set_default();
573
(*field)->set_null();
574
(*field)->move_field_offset(-row_offset);
585
content.push_back(ch);
589
for (; *field; ++field)
591
(*field)->move_field_offset(row_offset);
592
(*field)->set_notnull();
593
(*field)->set_default();
594
(*field)->move_field_offset(-row_offset);
599
// eat up characters when line_done
602
char ch= file_buff->get_value(next_position);
603
if (share->format.isRowSeparator(ch))
611
int FilesystemCursor::rnd_next(unsigned char *buf)
613
ha_statistic_increment(&system_status_var::ha_read_rnd_next_count);
614
if (share->format.isTagFormat())
616
if (tag_depth >= share->vm.size())
617
return HA_ERR_END_OF_FILE;
619
ptrdiff_t row_offset= buf - table->record[0];
620
for (Field **field= table->getFields(); *field; field++)
622
string key((*field)->field_name);
623
string content= share->vm[tag_depth][key];
625
(*field)->move_field_offset(row_offset);
626
if (!content.empty())
628
(*field)->set_notnull();
629
if ((*field)->isReadSet() || (*field)->isWriteSet())
631
(*field)->setWriteSet();
632
(*field)->store(content.c_str(),
633
(uint32_t)content.length(),
639
(*field)->set_default();
644
(*field)->set_null();
646
(*field)->move_field_offset(-row_offset);
652
current_position= next_position;
653
return find_current_row(buf);
656
void FilesystemCursor::position(const unsigned char *)
658
*reinterpret_cast<off_t *>(ref)= current_position;
661
int FilesystemCursor::rnd_pos(unsigned char * buf, unsigned char *pos)
663
ha_statistic_increment(&system_status_var::ha_read_rnd_count);
664
current_position= *reinterpret_cast<off_t *>(pos);
665
return find_current_row(buf);
668
int FilesystemCursor::info(uint32_t)
670
if (stats.records < 2)
675
int FilesystemCursor::openUpdateFile()
677
if (!share->update_file_opened)
680
if (stat(share->format.getFileName().c_str(), &st) < 0)
682
update_file_name= share->format.getFileName();
683
update_file_name.append(".UPDATE");
684
unlink(update_file_name.c_str());
685
update_file_desc= ::open(update_file_name.c_str(),
686
O_RDWR | O_CREAT | O_TRUNC,
688
if (update_file_desc < 0)
692
share->update_file_opened= true;
697
int FilesystemCursor::doEndTableScan()
699
sql_command_type = session_sql_command(table->getSession());
701
if (share->format.isTagFormat())
704
critical_section_exit();
708
if (slots.size() == 0)
711
critical_section_exit();
716
sort(slots.begin(), slots.end());
717
vector< pair<off_t, off_t> >::iterator slot_iter= slots.begin();
718
off_t write_start= 0;
720
off_t file_buffer_start= 0;
722
pthread_mutex_lock(&share->mutex);
724
file_buff->init_buff(file_desc);
725
if (openUpdateFile() < 0)
728
while (file_buffer_start != -1)
732
write_end= file_buff->end();
733
if (slot_iter != slots.end() &&
734
write_end >= slot_iter->first)
736
write_end= slot_iter->first;
740
off_t write_length= write_end - write_start;
741
if (write_in_all(update_file_desc,
742
file_buff->ptr() + (write_start - file_buff->start()),
743
write_length) != write_length)
748
while (file_buff->end() <= slot_iter->second && file_buffer_start != -1)
749
file_buffer_start= file_buff->read_next();
750
write_start= slot_iter->second;
754
write_start= write_end;
756
if (write_end == file_buff->end())
757
file_buffer_start= file_buff->read_next();
760
if (::fsync(update_file_desc) ||
761
::close(update_file_desc))
763
share->update_file_opened= false;
765
// close current file
766
if (::close(file_desc))
768
if (::rename(update_file_name.c_str(), share->format.getFileName().c_str()))
771
share->needs_reopen= true;
775
pthread_mutex_unlock(&share->mutex);
778
critical_section_exit();
783
void FilesystemCursor::recordToString(string& output)
786
drizzled::String attribute;
787
for (Field **field= table->getFields(); *field; ++field)
795
output.append(share->format.getColSeparatorHead());
798
if (not (*field)->is_null())
800
(*field)->setReadSet();
801
(*field)->val_str(&attribute, &attribute);
803
output.append(attribute.ptr(), attribute.length());
810
output.append(share->format.getRowSeparatorHead());
813
int FilesystemCursor::doInsertRecord(unsigned char * buf)
817
if (share->format.isTagFormat())
820
sql_command_type = session_sql_command(table->getSession());
822
critical_section_enter();
828
recordToString(output_line);
830
int fd= ::open(share->format.getFileName().c_str(), O_WRONLY | O_APPEND);
833
critical_section_exit();
837
err_write= write_in_all(fd, output_line.c_str(), output_line.length());
843
err_close= ::close(fd);
847
critical_section_exit();
856
int FilesystemCursor::doUpdateRecord(const unsigned char *, unsigned char *)
858
if (share->format.isTagFormat())
860
if (openUpdateFile())
863
// get the update information
867
if (write_in_all(update_file_desc, str.c_str(), str.length()) < 0)
875
void FilesystemCursor::addSlot()
877
if (slots.size() > 0 && slots.back().second == current_position)
878
slots.back().second= next_position;
880
slots.push_back(make_pair(current_position, next_position));
883
int FilesystemCursor::doDeleteRecord(const unsigned char *)
885
if (share->format.isTagFormat())
891
int FilesystemEngine::doRenameTable(Session&, const TableIdentifier &from, const TableIdentifier &to)
893
if (rename_file_ext(from.getPath().c_str(), to.getPath().c_str(), FILESYSTEM_EXT))
898
bool FilesystemEngine::validateCreateTableOption(const std::string &key,
899
const std::string &state)
901
return FormatInfo::validateOption(key, state);
904
int FilesystemEngine::doCreateTable(Session &,
906
const drizzled::TableIdentifier &identifier,
907
drizzled::message::Table &proto)
910
format.parseFromTable(&proto);
911
if (format.isFileGiven())
913
int err= ::open(format.getFileName().c_str(), O_RDONLY);
918
string new_path(identifier.getPath());
919
new_path+= FILESYSTEM_EXT;
920
fstream output(new_path.c_str(), ios::out | ios::binary);
925
if (! proto.SerializeToOstream(&output))
928
unlink(new_path.c_str());
935
static FilesystemEngine *filesystem_engine= NULL;
937
static int filesystem_init_func(drizzled::module::Context &context)
939
filesystem_engine= new FilesystemEngine("FILESYSTEM");
940
context.add(filesystem_engine);
945
DRIZZLE_DECLARE_PLUGIN
953
filesystem_init_func, /* Plugin Init */
954
NULL, /* system variables */
955
NULL /* config options */
957
DRIZZLE_DECLARE_PLUGIN_END;