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(Table &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::TableIdentifier::vector &set_of_identifiers);
113
void getTableNamesFromFilesystem(drizzled::CachedDirectory &directory,
114
const drizzled::SchemaIdentifier &schema_identifier,
115
drizzled::plugin::TableNameList *set_of_names,
116
drizzled::TableIdentifier::vector *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::TableIdentifier::vector *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::TableIdentifier::vector &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 (not format.isTagFormat() || not format.isFileGiven())
326
std::vector< std::map<std::string, std::string> > vm;
327
if (parseTaggedFile(format, vm) != 0)
333
if (vm.size() == 0) {
338
// we don't care what user provides, just clear them all
339
table_proto.clear_field();
340
// we take the first section as sample
341
std::map<string, string> kv= vm[0];
342
for (std::map<string, string>::iterator iter= kv.begin();
346
// add columns to table proto
347
message::Table::Field *field= table_proto.add_field();
348
field->set_name(iter->first);
349
field->set_type(drizzled::message::Table::Field::VARCHAR);
350
message::Table::Field::StringFieldOptions *stringoption= field->mutable_string_options();
351
stringoption->set_length(iter->second.length() + 1);
358
FilesystemTableShare::FilesystemTableShare(const string table_name_arg)
359
: use_count(0), table_name(table_name_arg),
360
update_file_opened(false),
365
FilesystemTableShare::~FilesystemTableShare()
367
pthread_mutex_destroy(&mutex);
370
FilesystemTableShare *FilesystemCursor::get_share(const char *table_name)
372
Guard g(filesystem_mutex);
374
FilesystemEngine *a_engine= static_cast<FilesystemEngine *>(getEngine());
375
share= a_engine->findOpenTable(table_name);
378
If share is not present in the hash, create a new share and
379
initialize its members.
383
share= new (nothrow) FilesystemTableShare(table_name);
389
share->format.parseFromTable(getTable()->getShare()->getTableProto());
390
if (!share->format.isFileGiven())
395
* for taggered file such as /proc/meminfo,
396
* we pre-process it first, and store the parsing result in a map.
398
if (share->format.isTagFormat())
400
if (parseTaggedFile(share->format, share->vm) != 0)
405
a_engine->addOpenTable(share->table_name, share);
407
pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
414
void FilesystemCursor::free_share()
416
Guard g(filesystem_mutex);
418
if (!--share->use_count){
419
FilesystemEngine *a_engine= static_cast<FilesystemEngine *>(getEngine());
420
a_engine->deleteOpenTable(share->table_name);
421
pthread_mutex_destroy(&share->mutex);
426
void FilesystemCursor::critical_section_enter()
428
if (sql_command_type == SQLCOM_ALTER_TABLE ||
429
sql_command_type == SQLCOM_UPDATE ||
430
sql_command_type == SQLCOM_DELETE ||
431
sql_command_type == SQLCOM_INSERT ||
432
sql_command_type == SQLCOM_INSERT_SELECT ||
433
sql_command_type == SQLCOM_REPLACE ||
434
sql_command_type == SQLCOM_REPLACE_SELECT)
435
share->filesystem_lock.scan_update_begin();
437
share->filesystem_lock.scan_begin();
439
thread_locked = true;
442
void FilesystemCursor::critical_section_exit()
444
if (sql_command_type == SQLCOM_ALTER_TABLE ||
445
sql_command_type == SQLCOM_UPDATE ||
446
sql_command_type == SQLCOM_DELETE ||
447
sql_command_type == SQLCOM_INSERT ||
448
sql_command_type == SQLCOM_INSERT_SELECT ||
449
sql_command_type == SQLCOM_REPLACE ||
450
sql_command_type == SQLCOM_REPLACE_SELECT)
451
share->filesystem_lock.scan_update_end();
453
share->filesystem_lock.scan_end();
455
thread_locked = false;
458
FilesystemCursor::FilesystemCursor(drizzled::plugin::StorageEngine &engine_arg, Table &table_arg)
459
: Cursor(engine_arg, table_arg),
460
file_buff(new TransparentFile),
465
int FilesystemCursor::doOpen(const drizzled::TableIdentifier &identifier, int, uint32_t)
467
if (!(share= get_share(identifier.getPath().c_str())))
470
file_desc= ::open(share->format.getFileName().c_str(), O_RDONLY);
474
return ER_CANT_OPEN_FILE;
477
ref_length= sizeof(off_t);
481
int FilesystemCursor::close(void)
483
int err= ::close(file_desc);
490
int FilesystemCursor::doStartTableScan(bool)
492
sql_command_type = session_sql_command(getTable()->getSession());
495
critical_section_exit();
496
critical_section_enter();
498
if (share->format.isTagFormat())
507
if (share->needs_reopen)
509
file_desc= ::open(share->format.getFileName().c_str(), O_RDONLY);
511
return HA_ERR_CRASHED_ON_USAGE;
512
share->needs_reopen= false;
514
file_buff->init_buff(file_desc);
518
int FilesystemCursor::find_current_row(unsigned char *buf)
520
ptrdiff_t row_offset= buf - getTable()->record[0];
522
next_position= current_position;
525
bool line_done= false;
526
bool line_blank= true;
527
Field **field= getTable()->getFields();
528
for (; !line_done && *field; ++next_position)
530
char ch= file_buff->get_value(next_position);
532
return HA_ERR_END_OF_FILE;
534
if (share->format.isEscapedChar(ch))
536
// read next character
537
ch= file_buff->get_value(++next_position);
539
return HA_ERR_END_OF_FILE;
541
content.push_back(FormatInfo::getEscapedChar(ch));
546
// if we find separator
547
bool is_row= share->format.isRowSeparator(ch);
548
bool is_col= share->format.isColSeparator(ch);
551
if (share->format.isSeparatorModeGeneral() && is_row && line_blank)
553
if (share->format.isSeparatorModeWeak() && is_col)
557
if (is_row || is_col)
559
(*field)->move_field_offset(row_offset);
560
if (!content.empty())
562
(*field)->set_notnull();
563
if ((*field)->isReadSet() || (*field)->isWriteSet())
565
(*field)->setWriteSet();
566
(*field)->store_and_check(CHECK_FIELD_WARN,
568
(uint32_t)content.length(),
573
(*field)->set_default();
577
(*field)->set_null();
578
(*field)->move_field_offset(-row_offset);
589
content.push_back(ch);
593
for (; *field; ++field)
595
(*field)->move_field_offset(row_offset);
596
(*field)->set_notnull();
597
(*field)->set_default();
598
(*field)->move_field_offset(-row_offset);
603
// eat up characters when line_done
606
char ch= file_buff->get_value(next_position);
607
if (share->format.isRowSeparator(ch))
615
int FilesystemCursor::rnd_next(unsigned char *buf)
617
ha_statistic_increment(&system_status_var::ha_read_rnd_next_count);
618
if (share->format.isTagFormat())
620
if (tag_depth >= share->vm.size())
621
return HA_ERR_END_OF_FILE;
623
ptrdiff_t row_offset= buf - getTable()->record[0];
624
for (Field **field= getTable()->getFields(); *field; field++)
626
string key((*field)->field_name);
627
string content= share->vm[tag_depth][key];
629
(*field)->move_field_offset(row_offset);
630
if (!content.empty())
632
(*field)->set_notnull();
633
if ((*field)->isReadSet() || (*field)->isWriteSet())
635
(*field)->setWriteSet();
636
(*field)->store_and_check(CHECK_FIELD_WARN,
638
(uint32_t)content.length(),
643
(*field)->set_default();
648
(*field)->set_null();
650
(*field)->move_field_offset(-row_offset);
656
current_position= next_position;
657
return find_current_row(buf);
660
void FilesystemCursor::position(const unsigned char *)
662
*reinterpret_cast<off_t *>(ref)= current_position;
665
int FilesystemCursor::rnd_pos(unsigned char * buf, unsigned char *pos)
667
ha_statistic_increment(&system_status_var::ha_read_rnd_count);
668
current_position= *reinterpret_cast<off_t *>(pos);
669
return find_current_row(buf);
672
int FilesystemCursor::info(uint32_t)
674
if (stats.records < 2)
679
int FilesystemCursor::openUpdateFile()
681
if (!share->update_file_opened)
684
if (stat(share->format.getFileName().c_str(), &st) < 0)
686
update_file_name= share->format.getFileName();
687
update_file_name.append(".UPDATE");
688
unlink(update_file_name.c_str());
689
update_file_desc= ::open(update_file_name.c_str(),
690
O_RDWR | O_CREAT | O_TRUNC,
692
if (update_file_desc < 0)
696
share->update_file_opened= true;
701
int FilesystemCursor::doEndTableScan()
703
sql_command_type = session_sql_command(getTable()->getSession());
705
if (share->format.isTagFormat())
708
critical_section_exit();
712
if (slots.size() == 0)
715
critical_section_exit();
720
sort(slots.begin(), slots.end());
721
vector< pair<off_t, off_t> >::iterator slot_iter= slots.begin();
722
off_t write_start= 0;
724
off_t file_buffer_start= 0;
726
pthread_mutex_lock(&share->mutex);
728
file_buff->init_buff(file_desc);
729
if (openUpdateFile() < 0)
732
while (file_buffer_start != -1)
736
write_end= file_buff->end();
737
if (slot_iter != slots.end() &&
738
write_end >= slot_iter->first)
740
write_end= slot_iter->first;
744
off_t write_length= write_end - write_start;
745
if (write_in_all(update_file_desc,
746
file_buff->ptr() + (write_start - file_buff->start()),
747
write_length) != write_length)
752
while (file_buff->end() <= slot_iter->second && file_buffer_start != -1)
753
file_buffer_start= file_buff->read_next();
754
write_start= slot_iter->second;
758
write_start= write_end;
760
if (write_end == file_buff->end())
761
file_buffer_start= file_buff->read_next();
764
if (::fsync(update_file_desc) ||
765
::close(update_file_desc))
767
share->update_file_opened= false;
769
// close current file
770
if (::close(file_desc))
772
if (::rename(update_file_name.c_str(), share->format.getFileName().c_str()))
775
share->needs_reopen= true;
779
pthread_mutex_unlock(&share->mutex);
782
critical_section_exit();
787
void FilesystemCursor::recordToString(string& output)
790
drizzled::String attribute;
791
for (Field **field= getTable()->getFields(); *field; ++field)
799
output.append(share->format.getColSeparatorHead());
802
if (not (*field)->is_null())
804
(*field)->setReadSet();
805
(*field)->val_str(&attribute, &attribute);
807
output.append(attribute.ptr(), attribute.length());
814
output.append(share->format.getRowSeparatorHead());
817
int FilesystemCursor::doInsertRecord(unsigned char * buf)
821
if (share->format.isTagFormat())
824
sql_command_type = session_sql_command(getTable()->getSession());
826
critical_section_enter();
832
recordToString(output_line);
834
int fd= ::open(share->format.getFileName().c_str(), O_WRONLY | O_APPEND);
837
critical_section_exit();
841
err_write= write_in_all(fd, output_line.c_str(), output_line.length());
847
err_close= ::close(fd);
851
critical_section_exit();
860
int FilesystemCursor::doUpdateRecord(const unsigned char *, unsigned char *)
862
if (share->format.isTagFormat())
864
if (openUpdateFile())
867
// get the update information
871
if (write_in_all(update_file_desc, str.c_str(), str.length()) < 0)
879
void FilesystemCursor::addSlot()
881
if (slots.size() > 0 && slots.back().second == current_position)
882
slots.back().second= next_position;
884
slots.push_back(make_pair(current_position, next_position));
887
int FilesystemCursor::doDeleteRecord(const unsigned char *)
889
if (share->format.isTagFormat())
895
int FilesystemEngine::doRenameTable(Session&, const TableIdentifier &from, const TableIdentifier &to)
897
if (rename_file_ext(from.getPath().c_str(), to.getPath().c_str(), FILESYSTEM_EXT))
902
bool FilesystemEngine::validateCreateTableOption(const std::string &key,
903
const std::string &state)
905
return FormatInfo::validateOption(key, state);
908
int FilesystemEngine::doCreateTable(Session &,
910
const drizzled::TableIdentifier &identifier,
911
drizzled::message::Table &proto)
914
format.parseFromTable(&proto);
915
if (format.isFileGiven())
917
int err= ::open(format.getFileName().c_str(), O_RDONLY);
922
string new_path(identifier.getPath());
923
new_path+= FILESYSTEM_EXT;
924
fstream output(new_path.c_str(), ios::out | ios::binary);
929
if (! proto.SerializeToOstream(&output))
932
unlink(new_path.c_str());
939
static FilesystemEngine *filesystem_engine= NULL;
941
static int filesystem_init_func(drizzled::module::Context &context)
943
filesystem_engine= new FilesystemEngine("FILESYSTEM");
944
context.add(filesystem_engine);
949
DRIZZLE_DECLARE_PLUGIN
957
filesystem_init_func, /* Plugin Init */
958
NULL, /* system variables */
959
NULL /* config options */
961
DRIZZLE_DECLARE_PLUGIN_END;