BLOB & mnesia

40 views
Skip to first unread message

ufm

unread,
Aug 30, 2009, 5:32:46 AM8/30/09
to Erlang в России
Я все со своими дикого размера данными.

И так, у меня есть записи с большими данными внутри. Теперь пришло
время сложить эти записи в базу.

Так как скорость мне в данном случае менее принципиальна чем память -
таблицу делаю disc_only_copies. Начинаю заполнять
mnesia:transaction(fun() -> mnesia:write(R) end)
посматривая на размер файла с таблицей в каталоге и ответами мнезии. В
какой-то момент (рядом с "магическими" 2Г) база расти перестаёт (что
не удивительно, ограничения в DETS никто не отменял), но при этом
мнезия на каждую транзакцию продолжает радостно отвечать {atomic,ok}.
Чешу репу. Стопаю мнезию mnesia:stop(). Стартую mnesia:start() и
получаю, что DAT файл у меня неправильно закрыт, его надо
восстанавливать. Дальше долгое тарахтение винтом и...

Crash dump was written to: erl_crash.dump
binary_alloc: Cannot allocate 369098772 bytes of memory (of type
"binary").

Вобщем база умерла безвозвратно, ибо отрепейрить оно этот файл так и
не смогло.

Решаю попробовать фрагментированные таблицы. Убиваю схему, создаю
заново, создаю таблицу, начинаю заполнять
mnesia:activity(transaction,(fun() -> mnesia:write(R)
end),mnesia_frag)
опять посматривая на ответы и размеры файлов. В какой-то момент один
из фрагментов опять перестаёт расти. В остальные - данные добавляются
(а из этого, кстати, выборка уже не работает). Останавливаю мнезию.
стартую. Ну дальше не интересно - тоже самое с точностью до
невозможности восстановить базу.

Собственно вопрос, может это я тупой? Может на самом деле принято на
транзакцию возвращать ok при этом ничего не делая? Да бог с ней, с
транзакцией. Базу-то зачем гробить?

P.S. на самом деле жалко - мне очень хотелось переложить на плечи
мнезии всю котовасию с синхронизацией баз между нодами и прочими
радостями. А устраивать "закат солнца вручную" с бекэндом в виде
мускуля так не хочется... :((

Ryukzak Neskazov

unread,
Aug 30, 2009, 6:27:41 AM8/30/09
to erlang-...@googlegroups.com
mnesia в нутри себя, если не ошибаюсь, использует dets. У него ограничение в 2 гигабайта фаил. Так что с этим можно смириться. 

А вообще не стоит использовать mnesia для заранения больших файлов. Так говорится в книгу Erlang Programing. Надеюсь цитата такая адекватна:

When to Use Mnesia
Mnesia was originally built for integration in distributed, massively concurrent, soft real-time systems with high availability requirements (i.e., telecoms). You want to use Mnesia if your system requires the following:
• •
Fast key-value lookups of potentially complex data
Distributed and replicated data across a cluster of nodes with support for location transparency
Data persistency with support for fast data access
Runtime reconfiguration of the table location and table features • Support for transactions, possibly across a distributed cluster of nodes • Data indexing • The same level of fault tolerance as for a typical Erlang system • Tight coupling of your data model to Erlang data types and to Erlang itself • Relational queries that don’t have soft real-time deadlines
You do not want to use Mnesia if your system requires the following:
Simple key-value lookup • A storage medium for large binaries such as pictures or audio files • A persistent log • A database that has to store gigabytes of data • A large data archive that will never stop growing
For simple key-value lookups, you can use ETS tables or the dict library module. For large binaries, you are probably better off with individual files for each item; for dealing with audit and trace logs, the disk_log library module should be your first point of call.
If you are looking to store your user data for the next Web 2.0 social networking killer application that has to scale to hundreds of millions of users overnight, Mnesia might not be the right choice. For massive numbers of entries that you want to be able to access readily, you might be better off using CouchDB, MySQL, PostgreSQL, or Ber- keley DB, all of which have open source Erlang drivers and APIs available. The upper limit of a Dets table is 2 GB. This means the upper limit of a Mnesia table is 2 GB if the storage type is disc-only copies. For other storage types the upper limit depends on the system architecture. In 32-bit systems the upper limit is 4 GB (4 * 109 bytes), and in 64-bit systems it is 16 exabytes (16 * 1018 bytes). If you need to store larger quantities of data, you will have to fragment your tables and possibly distribute them across many nodes. Mnesia has built-in support for fragmented tables.
While Mnesia might not be the first choice for all of your Web 2.0 user data, it is the perfect choice for caching all of the user session data. Once users have logged on, it can be read from a persistent storage medium and duplicated across a cluster of computers for redundancy reasons. The login might take a little longer while you retrieve the user data, but once it’s done, all of the session activities would be extremely fast. When the user logs out or the session expires, you would delete the entry and update the user profile in the persistent database.
That being said, Mnesia has been known to handle live data for tens of millions of users. It is extremely fast and reliable, so using it in the right setting will provide great benefits from a maintenance and operational point of view. Just picture your application’s da- tabase, the glue and logic alongside the formatting and parsing of data from externa APIs, all running in the same memory space and controlled uniformly by an Erlang system. Your application becomes not only efficient but also easy to maintain.

ufm

unread,
Aug 30, 2009, 6:34:40 AM8/30/09
to Erlang в России
Я в курсе про ограничения. И я осознанно пытался использовать мнезию
зная об этих ограничениях (не даром я стал пользоваться
фрагментированными таблицами). Меня смущает неадекватное поведение
мнезии. Т.е. её, получается, нельзя использовать _вобще_, ибо СУБД
гробящая собственные таблицы и возвращающая ok на явно ошибочную
ситуацию - декорация.

ufm

unread,
Aug 30, 2009, 10:04:21 AM8/30/09
to Erlang в России
что интересно - mnesia:dirty_write(R) базу не портит и честно говорит
что "оппачки, место кончилось".

On 30 авг, 13:34, ufm <ufm...@gmail.com> wrote:
> Я в курсе про ограничения. И я осознанно пытался использовать мнезию
> зная об этих ограничениях (не даром я стал пользоваться
> фрагментированными таблицами). Меня смущает неадекватное поведение
> мнезии. Т.е. её, получается, нельзя использовать _вобще_, ибо СУБД
> гробящая собственные таблицы и возвращающая ok на явно ошибочную
> ситуацию - декорация.
>
> On 30 авг, 13:27, Ryukzak Neskazov <ryuk...@gmail.com> wrote:
>
> > mnesia в нутри себя, если не ошибаюсь,
> > использует dets. У него ограничение в 2
> > гигабайта фаил. Так что с этим можно
> > смириться.
>
> > А вообще не стоит использовать mnesia для
> > заранения больших файлов. Так
> > говорится в книгу Erlang Programing. Надеюсь
> > цитата такая адекватна:
>
> > When to Use Mnesia
> > Mnesia was originally built for integration in distributed, massively
> > concurrent, soft real-time systems with high availability requirements
> > (i.e., telecoms). You want to use Mnesia if your system requires the
> > following:

> > * *
> > *


> > Fast key-value lookups of potentially complex data
> > Distributed and replicated data across a cluster of nodes with support
> > for location transparency
> > Data persistency with support for fast data access

> > * Runtime reconfiguration of the table location and table features
> > * Support for transactions, possibly across a distributed cluster of
> > nodes * Data indexing * The same level of fault tolerance as for a
> > typical Erlang system * Tight coupling of your data model to Erlang
> > data types and to Erlang itself * Relational queries that don't

> > have soft real-time deadlines
> > You do not want to use Mnesia if your system requires the following:

> > * Simple key-value lookup * A storage medium for large binaries
> > such as pictures or audio files * A persistent log * A database
> > that has to store gigabytes of data * A large data archive that will

Maxim Treskin

unread,
Aug 30, 2009, 1:24:26 PM8/30/09
to erlang-...@googlegroups.com
Можно попробовать написать в рассылку erlang-questions, может быть они чем помогут.

2009/8/30 ufm <ufm...@gmail.com>



--
Maxim Treskin
Reply all
Reply to author
Forward
0 new messages