Please check the redis logs for details about the rdb error

Here is the detail from the log: === REDIS BUG REPORT START: Cut & paste starting from here === [0/428] [9701] 18 Jul 02:21:30.542 # Redis 2.9.7 crashed by signal: 11 [9701] 18 Jul 02:21:30.542...

Here is the detail from the log:

=== REDIS BUG REPORT START: Cut & paste starting from here === [0/428]
[9701] 18 Jul 02:21:30.542 # Redis 2.9.7 crashed by signal: 11
[9701] 18 Jul 02:21:30.542 # Failed assertion: (:0)
[9701] 18 Jul 02:21:30.542 # — STACK TRACE
/usr/local/bin/redis-server(logStackTrace+0x52)[0x4390d2]
/usr/local/bin/redis-server(dictNext+0x68)[0x4128d8]
/lib/x86_64-linux-gnu/libpthread.so.0(+0xfcb0)[0x7fcdf3a84cb0]
/usr/local/bin/redis-server(dictNext+0x68)[0x4128d8]
/usr/local/bin/redis-server(rdbSave+0x228)[0x4255a8]
/usr/local/bin/redis-server(rdbSaveBackground+0x6f)[0x4257af]
/usr/local/bin/redis-server(serverCron+0x467)[0x414f77]
/usr/local/bin/redis-server(aeProcessEvents+0x1f3)[0x410dd3]
/usr/local/bin/redis-server(aeMain+0x2b)[0x410fbb]
/usr/local/bin/redis-server(main+0x2c4)[0x40fe34]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fcdf36d976d]
/usr/local/bin/redis-server[0x40ff9d]
[9701] 18 Jul 02:21:30.542 # — INFO OUTPUT
[9701] 18 Jul 02:21:30.542 # # Server
redis_version:2.9.7
redis_git_sha1:a2db8e48
redis_git_dirty:1
os:Linux 3.2.0-23-generic x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.6.3
process_id:9701
run_id:5f48a144472ae281c1de68f5b18c8574caf48e49
tcp_port:6379
uptime_in_seconds:231
uptime_in_days:0
lru_clock:37199

Clients

connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

Memory

used_memory:4908282496
used_memory_human:4.57G
used_memory_rss:5015216128
used_memory_peak:4908397808
used_memory_peak_human:4.57G
used_memory_lua:30720
mem_fragmentation_ratio:1.02
mem_allocator:jemalloc-3.0.0

Persistence

loading:0
rdb_changes_since_last_save:17534
rdb_bgsave_in_progress:0
rdb_last_save_time:1342549047
rdb_last_bgsave_status:err
rdb_last_bgsave_time_sec:13
rdb_current_bgsave_time_sec:-1
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1

Stats

total_connections_received:4
total_commands_processed:44173
instantaneous_ops_per_sec:0
rejected_connections:0
expired_keys:0
evicted_keys:0
keyspace_hits:9198
keyspace_misses:1520
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:50434

Replication

role:master
connected_slaves:0

CPU

used_cpu_sys:0.59
used_cpu_user:11.56
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

Commandstats

cmdstat_sadd:calls=6410,usec=14064,usec_per_call=2.19
cmdstat_zadd:calls=3957,usec=19042,usec_per_call=4.81
cmdstat_zscore:calls=364,usec=1363,usec_per_call=3.74
cmdstat_hset:calls=2410,usec=4998,usec_per_call=2.07
cmdstat_hget:calls=4355,usec=5004,usec_per_call=1.15
cmdstat_hmset:calls=6369,usec=50431,usec_per_call=7.92
cmdstat_hmget:calls=5999,usec=10266,usec_per_call=1.71
cmdstat_select:calls=5,usec=5,usec_per_call=1.00
cmdstat_keys:calls=1,usec=1219,usec_per_call=1219.00
cmdstat_multi:calls=4766,usec=1480,usec_per_call=0.31
cmdstat_exec:calls=4766,usec=16059,usec_per_call=3.37
cmdstat_info:calls=5,usec=504,usec_per_call=100.80
cmdstat_watch:calls=4766,usec=4115,usec_per_call=0.86

Cluster

cluster_enabled:0

Keyspace

db0:keys=7595100,expires=0
db1:keys=3412,expires=0
hash_init_value: 1342206335

[9701] 18 Jul 02:21:30.542 # — CLIENT LIST OUTPUT
[9701] 18 Jul 02:21:30.542 # addr=127.0.0.1:35864 fd=6 age=231 idle=40 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=info

[9701] 18 Jul 02:21:30.542 # — REGISTERS
[9701] 18 Jul 02:21:30.542 #
RAX:00007bcdd25eef40 RBX:00007fcdf2c5a080
RCX:ff4febb51ed00b65 RDX:000000000000002e
RDI:00007fccc6c09340 RSI:00007fcdbdf25600
RBP:0000000000000000 RSP:00007fff24cc7028
R8 :0000000001f34ce0 R9 :1ed00b74615f6574
R10:73616c09064febb5 R11:00007fcdbdf255f5
R12:0000000000000000 R13:00007fccc6c09340
R14:00007fcdbdf79db0 R15:00000138962c3e94
RIP:00000000004128d8 EFL:0000000000010202
CSGSFS:0000000000000033
[9701] 18 Jul 02:21:30.542 # (00007fff24cc70a0) -> 3037392d706d6574
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7098) -> 0000000000467775
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7090) -> 0000000000000000
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7088) -> 00007fcdbdf25618
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7080) -> 00000001f3000010
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7078) -> 00007fcdf3000198
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7070) -> 0000000000000000
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7068) -> 0000000001f34c00
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7060) -> ccec6b508c3dbb83
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7058) -> 0000000000441490
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7050) -> 0000000000441370
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7048) -> 0000000000441380
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7040) -> 00000000004413a0
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7038) -> 00007fcdf2c10040
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7030) -> 0000000001f34c00
[9701] 18 Jul 02:21:30.542 # (00007fff24cc7028) -> 00000000004255a8
[9701] 18 Jul 02:21:30.542 #
=== REDIS BUG REPORT END. Make sure to include from START to END. ===

Sometimes Redis will throw out error:

    MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.

Override Error in Redis Configuration

Using redis-cli, you can stop it trying to save the snapshot:

config set stop-writes-on-bgsave-error no

This is a quick workaround, but if you care about the data you are using it for, you should check to make sure why BGSAVE failed in first place.

This gives a temporary fix to the problem. However, it is a horrible way to over look this error, since what this option does is stop redis from notifying that writes have been stopped and to move on without writing the data in a snapshot. This is simply ignoring this error.

Save Redis on Low Memory

There might be errors during the bgsave process due to low memory.

This error occurs because of BGSAVE being failed. During BGSAVE,  Redis forks a child process to save the data on disk. Although exact reason for failure of BGSAVE can be checked from logs (usually at /var/log/redis/redis-server.log on linux machines) but a lot of the times BGSAVE fails because the fork can’t allocate memory. Many times the fork fails to allocate memory  (although the machine has enough RAM available) because of a conflicting optimization by the OS.

As can be read from Redis FAQ:

Background saving is failing with a fork() error under Linux even if I’ve a lot of free RAM!

Redis background saving schema relies on the copy-on-write semantic of fork in modern operating systems: Redis forks (creates a child process) that is an exact copy of the parent. The child process dumps the DB on disk and finally exits. In theory the child should use as much memory as the parent being a copy, but actually thanks to the copy-on-write semantic implemented by most modern operating systems the parent and child process will share the common memory pages. A page will be duplicated only when it changes in the child or in the parent. Since in theory all the pages may change while the child process is saving, Linux can’t tell in advance how much memory the child will take, so if the overcommit_memory setting is set to zero fork will fail unless there is as much free RAM as required to really duplicate all the parent memory pages, with the result that if you have a Redis dataset of 3 GB and just 2 GB of free memory it will fail.

Setting overcommit_memory to 1 tells Linux to relax and perform the fork in a more optimistic allocation fashion, and this is indeed what you want for Redis.

# echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
# sysctl vm.overcommit_memory=1

Redis doesn’t need as much memory as the OS thinks it does to write to disk, so may pre-emptively fail the fork.

Содержание

  1. Stop writes on bgsave error issues related to redis persistence
  2. stop-writes-on-bgsave-error not being read from .conf #1000
  3. Comments
  4. Глава 6. Перманентность
  5. Введение
  6. RDB манипуляции
  7. Подготовка.
  8. Как это сделать.
  9. Как это работает.
  10. Также ознакомьтесь.
  11. Дополнительно
  12. Изучение RDB
  13. Подготовка.
  14. Как это сделать.
  15. Как это работает.
  16. Также ознакомьтесь.

I was very sleepy in the afternoon, but I found that I was not sleepy after returning the bus.

Well, I’m going to store the Key in Redis, and then:

(error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.

(error) MISCONF Redis is configured to save RDB snapshots, but it cannot be persisted on disk at present. The command that can modify the dataset is disabled because if the RDB snapshot fails (stop writes on bgsave error option), this instance is configured to report errors during writing. For more information about RDB errors, please check the Redis log.

Just set stop writes on bgsave error to no( (yes in my configuration file)
What exactly does this field mean?

Let’s start with something else:
Redis can save database snapshots in a binary file named dump.rdb.
RDB persistence is called snapshot.
operation mode:

  • Redis calls forks to get the child process
  • The subprocess writes the data set to a temporary RDB file
  • When the child process finishes writing the new RDB file, Redis replaces the original file with the new RDB file and deletes the old RDB file

This way of working enables Redis to benefit from the copy on write mechanism( AOF rewriting also takes advantage of copy on write)

Copy on write is an optimization strategy in the field of computer programming. The core idea is that if multiple callers request the same resource at the same time, they will jointly obtain the same pointer to the same resource. Until a caller tries to modify the content of the resource, the system will really copy a special copy to the caller, while the original resources seen by other callers remain unchanged. This process is transparent to other callers. The main advantage of this method is that if the caller does not modify the resource, no copy will be created. Therefore, multiple callers can share the same resource only when reading.

In fact, stop writes on bgsave error is in the configuration file and in the snapshot section.

By default, if RDB snapshot (at least one savepoint) is enabled and the latest background save fails, Redis will stop accepting writes.
This will make users realize (in a difficult way) that the data is not saved correctly on disk, otherwise it is likely that no one will notice and some disasters will occur.
If the background saving process starts working again, Redis will automatically allow writing again.
However, if you have set up proper monitoring of Redis server and persistence, you may want to disable this function so that Redis can continue to work as usual, even if there are problems such as disk and permissions.

Therefore, simply setting this option to no may still not fundamentally solve the problem, but I will still back up even if an error occurs.
In fact, stopping work when persistence fails is also a protection mechanism and prompt.

Later, I set stop writes on bgsave error to yes, but when I added KEY again, no error was reported.

In theory, you should look at the log, but I can guess that it should be related to memory, because my server only has 4G memory. There are several programs at one time, and the memory space is not enough for fork subprocesses

Even if I have a lot of free RAM, saving in the background under Linux will fail due to fork() error!
Short answer: echo 1 > /proc/sys/vm/overcommit_memory:)

Redis background saving mode depends on the write time replication semantics of fork in modern operating system: Redis fork (create child process) is an accurate copy of the parent process. The child process dumps the database to disk and eventually exits. Theoretically, the child process should use as much memory as the parent process as a copy, but in fact, due to the write time replication semantics implemented by most modern operating systems, the parent process and child process will share common memory pages. The page is copied only when the child page or parent page changes. In theory, all pages may change when the sub process is saved. Linux cannot know in advance how much memory the sub process will occupy. Therefore, if overcommit_ If memory is set to zero, fork will fail unless there is enough available RAM to actually copy all parent memory pages. As a result, if you have a 3 GB redis dataset and only 2 GB of available memory, it will fail.

Set overcommit_ A memory of 1 tells Linux to relax and perform fork in a more optimistic way, which is really what Redis wants.

Posted by arsenelupin at Jul 27, 2021 — 10:44 AM Tag: Redis Database

Источник

stop-writes-on-bgsave-error not being read from .conf #1000

I’ve got a pretty basic setup (v2.6.11), config file is all defaults, except for using local socket instead of TCP, and ‘stop-writes-on-bgsave-error no’ set instead of yes.

I perform a large load, and get the following error repeatedly (from redis-cli —pipe connected to same):

It seems to work fine from the client though, so it’s just something in the config file processing:

(I can attach config/log files if necessary, but seems straightforward)

The text was updated successfully, but these errors were encountered:

That’s issue #1000! Better to address it ASAP and properly 🙂 Looking into it right now. Thanks.

There is a fix in the 2.6 branch after exactly 13 minutes. Hope you like the service! 😉

p.s. however I’m not closing the issue, because in the first place, why you are getting an error while transferring a large amount of data with redis-cli? Could you provide some log?

I’ve got a 4.9G text file in the protocol format (almost entirely SADDs), which I’m piping directly to redis-cli.
It’s all on the same m1.medium EC2 instance (not ideal, but the best I can do at the moment).

If I suspend (^Z) redis-cli, then the bgsave will complete. But then when I resume it’ll start error-ing again after a bit.

Hmm. Looks like redis-server just crashed on me (I think it ran out of memory, it was up to 90% last I saw).

The data file is only 300m compressed, would you like it instead? It’ll take me a bit to generate debug logs.

My best guess is that the following happens:

  1. You stress redis with a big write load.
  2. It starts to produce the RDB file, but because of «1» there is a lot of copy-on-write going on, and the Linux OOM killer kills the saving instance. (Maybe overcommit policy is wrong?)
  3. It starts reporting errors.

If you stop redis-cli there is less memory used because of copy-on-write and everything worked.

In the end the instance itself used too much memory and got killed by OOM itself.

verified vm.overcommit_memory=1, but yeah looks like the OOM is doing the killing, not a crash. my bad!
I need to go find some bigger hardware. =)

Thanks for the quick responses!

Thanks for reporting the config bug!

I know that this Issue is closed.. However, I figured I would update in case anyone else hits this. We have hit this problem while bulk loading into Redis. If you check the kernel logs, you can see OOM killer invoked. Checking the Redis logs shows that the background save was killed with a SIGKILL. For now, for this particular instance, we are able to work effectively by disabling background save and having the final operation of the bulk load be a background save. However, that may not be applicable for all work loads, as other people may require background saves and bulk loading intermixed. Perhaps a new Redis command that hints that a bulk load operation is commencing? Thus, perhaps applying an adjustment factor to the key change counts?

I would hesitate to add a command to disable background saves, because what happens if the client doing the writing takes a fault?

What if the hint command gives an estimate for the number of key writes expected, this could allow for padding the key change counters?

I would hesitate to add a command to disable background saves, because what happens if the client doing the writing takes a fault?

You can easily alter change-vs-time based background saves at runtime with CONFIG SET SAVE . (see the example at http://redis.io/commands/config-set), so an additional command isn’t strictly necessary. (If you need to save/restore the value, you could have a script read the save entry, write it to a key, remove the live value, then on reset, just place the old entry back live.)

The only real solution here is to not bulk load data with automatic BGSAVE enabled. Ideally you can find a way to avoid bulk loading against a live dataset (load on startup, then make the server live for other reads/writes).

There’s no clean way in Redis to bulk load data as fast as you can with background saves enabled that won’t cause the background thread’s memory to increase.

BGSAVE always has a window of potential data loss when used against rapidly changing datasets, but that’s where AOF really helps out. Maybe you should disable BGSAVE completely during your load, rely on AOF to save your data, then after the high speed bulk load, execute a clean AOF rewrite or re-enable your BGSAVEs?

Yes, you are correct, I could use CONFIG SET SAVE . , still, my concern was over the bulk loading client disconnecting due to network problems.. I suppose I could monitor these types of errors.

I agree that the best solution is to not bulk load with BGSAVE enabled.. We have gone with that solution by disabling automatic BGSAVE, and having the final operation in the bulk load be a SAVE.

Also, I haven’t experimented with AOF in this instance. Thanks for reminding me.

Источник

Глава 6. Перманентность

Содержание

В этой главе мы рассмотрим такие рецепты:

Сочетание RDB и AOF

Введение

В своей предыдущей главе мы изучили как настраивать Redis подчинённым для репликации данных с хозяина. С точки зрения избыточности данных для резервного копирования имеющихся данных могут применяться репликации данных Redis/

Для того чтобы сберегать свои данные в безопасности Redis также предоставляет механизм удержания (persist — перманентности) данных на диске. Существует два варианта удержания данных: RDB и AOF. RDB является снимком на некий момент времени данных Redis, что исключительно для резервного копирования и восстановления данных. AOF является неким журналом операций записи, которые будут повторно выполняться при запуске сервера.

В данной главе мы сделаем введение в то как разрешать и настраивать в Redis RDB и AOF. Мы также бросим взгляд на соответствующие форматы файлов RDB и AOF, а также на важные параметры настроек для их регулирования при установке перманентности Redis. К окончанию данной главы мы поговорим о сочетании в Redis RDB и AOF.

RDB манипуляции

Как мы уже описывали в своём предыдущем рецепте, для некоторого хранилища данных в оперативной памяти подобного Redis, включение свойств удержания является наилучшей защитой от утраты данных. Одним из очевидных способов реализации перманентности является создание время- от- времени моментальных снимков оперативной памяти, в которой хранятся наши данные. Именно таким способом в основном и работает в Redis RDB.

В данном рецепте мы взглянем на то как осуществлять такую функциональность удержания и настраивать её, а также изучим дополнительные подробности относительно производства моментальных снимков.

Подготовка.

Вам требуется завершить установку своего Cервера Redis, которое мы описывали в своём рецепте Загрузка и установка Redis в Главе 1, Приступая к Redis.

Для целей данной демонстрации вам следует сбросить все данные при помощи команды FLUSHALL , а затем мы наполним какими- то образцами данных свой экземпляр Redis применив инструментарий случайной генерации данных для Redis, введённый нами в рецепте Поиск неисправности репликации из Главы 5, Репликации:

Как это сделать.

Для манипуляций RDB основные шаги такие:

Чтобы включить удержание RDB для запущенного экземпляра Redis вызвите соответствующую команду CONFIG SET следующим образом:

Если же мы желаем разрешить RDB на постоянной основе, установите значение настройки save в соответствующем файле конфигурации Redis:

Для отключения свойства удержания RDB для некоторого запущенного экземпляра Redis добавьте пустую строку в соответствующую опцию save с помощью redis-cli :

Для отключения RDB на постоянной основе просто экранируйте комментарием или удалите имеющиеся опции save в своём файле настроек Redis:

Чтобы проверить включена ли функциональность RDB, запросите соответствующий файл настроек save из redis-cli . Если в соответствующей опции save имеется некая пустая строка, это указывает на то, что функция RDB отключена. В противном случае будет получена разрешённая политика RDB переключения взятия моментальных снимков:

Мы можем убедиться в том был ли сгенерирован соответствующий файл RDB в установленном каталоге данных Redis:

Для создания некоего моментального снимка RDB вручную вызовите команду SAVE в redis-cli . Данный redis-cli выполнит блокировку на какое- то время и затем выполнит возврат в командную строку таким образом:

В качестве альтернативы мы можем вызвать BGSAVE для осуществления дампа RDB без блокировки:

Проверьте состояние pid своего процесса выполнения дампа, воспользовавшись соответствующей командой ps -ef |grep redis :

Быстро выполните наполнение некими образцами данных при выполнении дампа RDB:

Проверьте соответствующий журнал своего Сервера Redis:

Для выборки необходимых замеров и состояния удержания вызовите из redis-cli INFO Persistence :

Как это работает.

RDB работает подобно фотоаппарату для имеющейся оперативной памяти Redis. Когда достигается необходимая политика включения, выполняется некая фотография имеющихся в Redis данных путём вывода дампа в некий файл на текущем локальном диске. Прежде чем перейти к подробному рассмотрению данного процесса, мы для начала поясним те значения опции save , которые определяют установленную политику включения RDB, которые упомянуты в нашем предыдущем разделе. Соответствующий шаблон устанавливаемых значений выглядит как x 1 , y 1 , x 2 , y 2 . . Что означает, что выполнение дампа имеющихся данных в Redis осуществляется после x секунд если были изменены по крайней мере по крайней мере y ключей и нет никакого иного процессы выполнения дампа.

Для нашего предыдущего примера, 900 1 означает, что если по крайней мере 1 ключ был изменён в пределах 900 секунд, будет выполнен некий моментальный снимок. Мжет иметься более одной политики в соответствующей опции save для управления тем насколько часто выполняется моментальный снимок RDB.

Redis не выполняет соответствующий дамп пока не завершится в фоновом режиме самый последний сброс. Вам никогда не следует применять SAVE в своей промышленной реализации, так как он блокирует ваш Сервер Redis. Вместо этого, применив BGSAVE , имеющийся основной поток Redis продолжит обработку входящих команд пока создаётся посредством fork() некий дочерний процесс, который затем сохранит необходимый файл данных дампа в каом- то временном файле с названием temp- .rdb . После того как этот процесс выполнения дампа завершится, данный временный файл будет переименован в то имя, которое определено настройкой dbfilename в том локальном каталоге, который задан настройкой dir для замены имеющегося старого дампа. Между прочим, эти две настройки можно изменять динамически из redis-cli .

Отслеживая свои процессы при помощи команды ps вы можете перехватить соответствующий процесс с установленным названием redis-rdb-bgsave , который ответвляется вашим Сервером Redis для выполнения BGSAVE . Этот дочерний процесс сохраняет все данные в то время, когда осуществляется соответствующая команда BGSAVE . Благодаря механизму COW ( Copy-On-Write , Копирования- записью) нет необходимости для запущенного дочернего процесса применять такой же объём памяти, который имеет сам Сервер Redis.

На протяжении выполнения дампа мы можем воспользоваться INFO Persistence для получения соответствующих измерений выполняемого удержания. В данном примере значением rdb_bgsave_in_progress является 1 , что указывает на тот факт, что выполняется процесс получения дампа. Значением rdb_current_bgsave_time_sec является то время, которое прошло при выполнении BGSAVE .

По завершению данным потомком замены имеющегося старого файла дампа, он выполняет в журнале регистрацию сообщения на основе того какой объём частных данных использовал этот потомок следующим образом:

В основном оно исчисляет какой объём изменений выполнил родительский процесс по сравнению с дочерним (в том числе буферы чтения, буферы записи, изменения данных и тому подобного). В нашем примере мы выполняли наполнение Redis некими образцами данных на протяжении осуществления дампа, поэтому та память, которая использовалась COW (в соответствующей команде INFO ) не является очень маленьким (для 2 ГБ данных в Redis, если ничего не записывается на протяжении дампа, как правило, COW использует 10- 20 МБ). Данное измерение также сохраняется в соответствующей метрике rdb_last_cow_size , получаемой в команде INFO .

По окончанию BGSAVE , соответствующее состояние самого последнего BGSAVE сохраняется в измерении rdb_last_bgsave_status , а временной штамп UNIX этого последнего успешного сохранения запоминается в rdb_last_save_time :

Также ознакомьтесь.

Вот некоторые относящиеся к удержанию RDBварианты настройки. Вам рекомендуется оставлять установленные по умолчанию значения, которыми является значение yes для всех перечисленных ниже опций:

stop-writes-on-bgsave-error yes : При отказе BGSAVE , в качестве некоего механизма защиты, ваш Сервер Redis остановит приём на запись когда данный параметр установлен в значение yes .

rdbcompression yes : Сжатие может впечатляющим образом уменьшить получаемый размер файла дампа за счёт большего использования ЦПУ для осуществления сжатия LZF.

rdbchecksum yes : Создаёт некую контрольную сумму CRC64 в самом конце получаемого файла моментального снимка. Значение стоимости производительности в оплату в процессе сохранения и загрузки такого файла моментального снимка около 10%. Для получения максимальной производительности установите no , но это уменьшит устойчивость к разрушению данных.

Тот дамп, который вырабатывается SAVE/BGSAVE можно применять в качестве некоего файла резервной копии данных. Вы можете применять crontab в своей операционной системе для периодического копирования получаемого файла RDB в какой- то локальный каталог или в удалённую распределённую файловую систему, например, Amazon S3/ HDFS для целей применения в дальнейшем:

Для восстановления некоего моментального снимка RDB вам придётся скопировать соответствующий файл в то местоположение, которое определено установкой параметра dir и установить необходимые полномочия чтения/ записи для данного файла тому пользователю, который запускает соответствующий экземпляр Redis. После этого от вас требуется остановить исполняемый экземпляр вызвав команду SHUTDOWN NOSAVE и переименовать свой новый файл дампа в то название, которое задаётся dbfilename . При перезапуске этот набор данных загружается в Redis из данного файла резервной копии.

Дополнительно

Дополнительное обсуждение деталей относительно перманентности RDB вы можете отыскать на https://redis.io/topics/persistence

Если вам интересно то как работает COW в некоторой операционной системе, вы можете изучить подробности в en.wikipedia.org < Прим. пер.: или ознакомиться с нашими переводами Мастерство FreeBSD: ZFS Майкла В. Лукаса и Аллана Джуда или отдельных глав Мастерство SQL Server 2016 с высокой доступностью Пауля Бертуччи и Раджу Шривастава >

Изучение RDB

Мы уже изучили что посредством перманентности Redis выполняет дамп своих хранимых в памяти данных в некий файл с названием dump.rdb по умолчанию. Для начинающих этого может быть достаточно для понимания тех моментов, которые упоминаются в нашем предыдущем рецепте. Для тех чокнутых, которые страстно желают узнать подробнее о том как соответствующий файл RDB работает в качестве двоичного представления данных Redis в оперативной памяти имеется великолепное преимущество изучить сам формат RDB. В данном рецепте мы окунёмся в тонкости формата имеющегося файла RDB чтобы понять что мы можем делать со знаниями об имеющемся формате RDB.

Подготовка.

Вам требуется завершить установку своего Cервера Redis, которое мы описывали в своём рецепте Загрузка и установка Redis в Главе 1, Приступая к Redis.

Для исследования двоичного формата некоего файла необходим какой- то редактор бинарных файлов. В Linux Ubuntu наиболее распространённым бинарным редактором является bvi . Установите его следующим образом:

Для MacOS вы можете выгрузить HexFiend.

Для своих целей демонстрации необходимо выполнить сброс всех данных при помощи команды FLUSHALL .

Так как мы будем изучать свой файл RDB в шестнадцатеричном виде, следует просматривать символ ASCII в какой- то таблице ASCII. Великую помощь в этом оказывает вебсайт RapidTables.

Как это сделать.

Для изучения RDB необходимые шаги таковы:

Установите некую пару строковых ключ- значение:

Установите пару списочных ключ- значение:

Настройте пару ключ- значение хэша:

Настройте пару ключ- значение множества:

Установите пару ключ- значение сортированного множества:

Для включения выполнения дампа RDB вызовите в redis-cli команду SAVE :

В редакторе bvi откройте только что созданный нами файл dump.rdb :

Полученное содержимое dump.rdb отображено на следующем снимке экрана:

Рисунок 6-1

Как это работает.

В нашем предыдущем примере в имеющемся экземпляре Redis были размещены некоторые образцы проверочных данных. После этого был создан некий дамп RDB посредством команды SAVE .

После этого мы ближе рассмотрим что имеется в RDB в не заземлённом виде при помощи двоичного редактора bvi в Linux. Всё содержимое нашего файла RDB было преобразовано bvi в шестнадцатеричный вид. Рассматривая самые первые пять чисел (52 45 44 49 53) одно за другим в таблице ASCII (RapidTables), мы можем заключить, что этими первыми символами являются REDIS :

Рисунок 6-2

Следующими четырьмя символами после нашей магической строки являются 30 30 30 38 , которые указывают на значение версии формата RDB 0008. REDIS0008 является магической строкой какого- то файла RDB.

После этой магической строки имеется восемь видов метаданных, сохранённых в нашем файле RDB:

redis-ver : Значение версии данного экземпляра Redis.

redis-bits : Значение архитектуры того хоста, на котором запущен данный экземпляр Redis. Для этих метаданных допустимыми являются значения 64 или 32.

ctime : Значение временного штампа Unix момента создания данного RDB.

used-mem : Значение размера используемой памяти на момент вывода дампа.

repl_stream_db : Значение индекса имеющейся базы данных в некоторой цепочке репликации, существует только когда установлена некая репликация.

aof-preamble : Следует ли помещать данный моментальный снимок RDB как некую преамбулу существующего файла AOF.

repl-id : Значение идентификатора репликации основного хозяина.

repl-offset : Значение смещения репликации основного хозяина.

Между прочим, FA в этом файле RDB является неким вспомогательным кодом операции. После такого вспомогательного кода всегда имеется некая пара ключ- значение.

После сохранения необходимых метаданных для каждой базы данных из определённого Сервера Redis текущий процесс вывода дампа сохраняет получаемый индекс базы данных (в данном примере FE 00 , указывающий значение индекса базы данных равным 00 ), код изменения размера хэша, а также код операции изменения размера базы данных, помимо срока истечения кода операции изменения размера. Затем стартует некая итерация для записи каждого элемента из Redis для записи в этот файл дампа. Соответствующий формат пары ключ- значение в Redis таков:

Рисунок 6-3

Ввиду ограничений в пространстве данной книги мы не будем вдаваться в подробности указанного вышк формата данных. Если вас это интересует, вы можете рассмотреть исходные коды файлов rdb.c и rdb.h .

Данный файл RDB завершается неким EOF и контрольной суммой CRC64.

Также ознакомьтесь.

Понимая формат RDB вы можете создавать свои собственные инструменты Redis для анализа памяти, экспорта/ импорта данных, а также слияния множества экземпляров Redis. Если вы выполните поиск в GitHub по ключевым словам Redis RDB вы изучите намного больше о существующем формате RDB.

Источник

TL;DR: My windows service wasn’t installed properly. Change the config file to point the DB to an accessible directory and reinstall the service.

When trying to build a perioduc Celery task, I got the following error with Redis on Windows (running as a windows service):

redis.exceptions.ResponseError: MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.

This is quite unfortunate because the error doesn’t show at the very beginning, but only after about 5 mins on my computer.

The error obviously occurs because Redis can’t save the database snapshot. This can be tested with the following steps:

  1. Restart the service

  2. Execute the info command with redis-cli

    redis-cli info |grep bg
    

    which will produce an initial result:

    rdb_bgsave_in_progress:0
    rdb_last_bgsave_status:ok
    rdb_last_bgsave_time_sec:1
    rdb_current_bgsave_time_sec:-1
    aof_last_bgrewrite_status:ok
    
  3. Trigger a save

    redis-cli bgsave
    # Background saving started
    
  4. Show the command again

    redis-cli info | grep bg
    rdb_bgsave_in_progress:0
    rdb_last_bgsave_status:err
    rdb_last_bgsave_time_sec:0
    rdb_current_bgsave_time_sec:-1
    aof_last_bgrewrite_status:ok
    

you can see the rdb_last_bgsave_status:err status, which means the DB could not have been saved

To fix this, go to your REDIS installation (mine is on C:ProgramDatachocolateylibredis-64 because I’ve installed it via chocolatey) and:

  1. Uninstall the windows service

    ./redis-server --service-uninstall
    
  2. Edit the database directory to somewhere accessible (in redis.windows-service.conf)

    # ...
    dir C:/Users/[myuser]/tmp
    # ...
    

    while replacing [myuser] with your relevant user and creating the C:/Users/[myuser]/tmp directory

  3. Install the service (again)

    ./redis-server --service-install redis.windows-service.conf --loglevel verbose
    
  4. Start the service

    ./redis-server --service-start
    

Now, the service should work. If not, then look in the Event Viewer, Applications and Services Logs > redis for more details.

HTH,

During writes to Redis ( SET foo bar ) I am getting the following error:

MISCONF Redis is configured to save RDB snapshots, but is currently
not able to persist on disk. Commands that may modify the data set are
disabled. Please check Redis logs for details about the error.

Basically I understand that the problem is that redis is not able to save data on the disk, but have no idea how to get rid of the problem.

Also the following question has the same problem, it is abandoned long time ago with no answers and most probably no attempts to solve the problem.

30 Answers

In case you encounter the error and some important data cannot be discarded on the running redis instance (problems with permissions for the rdb file or its directory incorrectly, or running out of disk space), you can always redirect the rdb file to be written somewhere else.

Using redis-cli, you can do something like this:

CONFIG SET dir /tmp/some/directory/other/than/var
CONFIG SET dbfilename temp.rdb

After this, you might want to execute a BGSAVE command to make sure that the data will be written to the rdb file. Make sure that when you execute INFO persistence, bgsave_in_progress is already 0 and rdb_last_bgsave_status is ok. After that, you can now start backing up the generated rdb file somewhere safe.

Using redis-cli, you can stop it trying to save the snapshot:

config set stop-writes-on-bgsave-error no

This is a quick workaround, but if you care about the data you are using it for, you should check to make sure why bgsave failed in first place.

Restart your redis server.

  • macOS (brew): brew services restart redis.
  • Linux: sudo service redis restart / sudo systemctl restart redis
  • Windows: Windows + R -> Type services.msc, Enter -> Search for Redis then click on restart.

I personally had this issue after upgrading redis with Brew (brew upgrade).
After rebooting the laptop, it immediately worked.

There might be errors during the bgsave process due to low memory. Try this (from redis background save FAQ)

echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
sysctl vm.overcommit_memory=1

This error occurs because of BGSAVE being failed. During BGSAVE, Redis forks a child process to save the data on disk. Although exact reason for failure of BGSAVE can be checked from logs (usually at /var/log/redis/redis-server.log on linux machines) but a lot of the times BGAVE fails because the fork can’t allocate memory. Many times the fork fails to allocate memory (although the machine has enough RAM available) because of a conflicting optimization by the OS.

As can be read from Redis FAQ:

Redis background saving schema relies on the copy-on-write semantic of fork in modern operating systems: Redis forks (creates a child process) that is an exact copy of the parent. The child process dumps the DB on disk and finally exits. In theory the child should use as much memory as the parent being a copy, but actually thanks to the copy-on-write semantic implemented by most modern operating systems the parent and child process will share the common memory pages. A page will be duplicated only when it changes in the child or in the parent. Since in theory all the pages may change while the child process is saving, Linux can’t tell in advance how much memory the child will take, so if the overcommit_memory setting is set to zero fork will fail unless there is as much free RAM as required to really duplicate all the parent memory pages, with the result that if you have a Redis dataset of 3 GB and just 2 GB of free memory it will fail.

Setting overcommit_memory to 1 says Linux to relax and perform the fork in a more optimistic allocation fashion, and this is indeed what you want for Redis.

Redis doesn’t need as much memory as the OS thinks it does to write to disk, so may pre-emptively fail the fork.

To Resolve this, you can:

Modify /etc/sysctl.conf and add:

vm.overcommit_memory=1

Then restart sysctl with:

On FreeBSD:

sudo /etc/rc.d/sysctl reload

On Linux:

sudo sysctl -p /etc/sysctl.conf

in case you are working on a linux machine, also recheck the file and folder permissions of the database.

The db and the path to it can be obtained via:

in redis-cli:

CONFIG GET dir

CONFIG GET dbfilename

and in the commandline ls -l. The permissions for the directory should be 755, and those for the file should be 644. Also, normally redis-server executes as the user redis, therefore its also nice to give the user redis the ownership of the folder by executing sudo chown -R redis:redis /path/to/rdb/folder. This has been elaborated in the answer here.

Thanks everyone for checking the problem, apparently the error was produced during bgsave.

For me, typing config set stop-writes-on-bgsave-error no in a shell and restarting Redis solved the problem.

Start Redis Server in a directory where Redis has write permissions

The answers above will definitely solve your problem, but here’s what’s actually going on:

The default location for storing the rdb.dump file is ./ (denoting current directory). You can verify this in your redis.conf file. Therefore, the directory from where you start the redis server is where a dump.rdb file will be created and updated.

It seems you have started running the redis server in a directory where redis does not have the correct permissions to create the dump.rdb file.

To make matters worse, redis will also probably not allow you to shut down the server either until it is able to create the rdb file to ensure the proper saving of data.

To solve this problem, you must go into the active redis client environment using redis-cli and update the dir key and set its value to your project folder or any folder where non-root has permissions to save. Then run BGSAVE to invoke the creation of the dump.rdb file.

CONFIG SET dir "/hardcoded/path/to/your/project/folder"
BGSAVE

(Now, if you need to save the dump.rdb file in the directory that you started the server in, then you will need to change permissions for the directory so that redis can write to it. You can search stackoverflow for how to do that).

You should now be able to shut down the redis server. Note that we hardcoded the path. Hardcoding is rarely a good practice and I highly recommend starting the redis server from your project directory and changing the dir key back to./`.

CONFIG SET dir "./"
BGSAVE

That way when you need redis for another project, the dump file will be created in your current project’s directory and not in the hardcoded path’s project directory.

If you’re running MacOS and have recently upgraded to Catalina, you may need to run brew services restart redis as suggested in this issue.

Had encountered this error and was able to figure out from log that the error is because of the disk space not being enough. All the data that was inserted in my case was not needed any longer. So I tried to FLUSHALL. Since redis-rdb-bgsave process was running, it was not allowing to FLUSH the data also. I followed below steps and was able to continue.

  1. Login to redis client
  2. Execute config set stop-writes-on-bgsave-error no
  3. Execute FLUSHALL (Data stored was not needed)
  4. Execute config set stop-writes-on-bgsave-error yes

The process redis-rdb-bgsave was no longer running after the above steps.

A more permanent fix might be to look in /etc/redis/redis.conf around lines 200-250 there are settings for the rdb features, that were not a part of redis back in the 2.x days.

notably

dir ./

can be changed to

dir /home/someuser/redislogfiledirectory

or you could comment out all the save lines, and not worry about persistence. (See the comments in /etc/redis/redis.conf)

Also, don’t forget

service redis-server stop
service redis-server start

I faced the similar issue, the main reason behind this was the memory(RAM) consumption by redis.
My EC2 machine had 8GB RAM(arounf 7.4 available for consumption)

When my program was running the RAM usage went upto 7.2 GB leaving hardly ~100MB in RAM , this generally triggers the MISCONF Redis error ...

You can determine the RAM consumption using the htop command. Look for the Mem attribute after running htop command. If it shows high consumtion (like in my case it was 7.2GB/7.4GB) It’s better to upgrade the instance’s with larger Memory.
In this scenario using config set stop-writes-on-bgsave-error no will be a disaster for the server and may result in disrupting other services running on the server(if any). So, it better to avoid the config command and UPGRADE YOUR REDIS MACHINE.

FYI: You may need to install htop to make this work : sudo apt-get install htop

One more solution to this can be some other RAM heavy service running on your system, check for other service running on your server/machine/instance and stop it if its not necessary. To check all the services running on your machine use service --status-all

And a suggestion for people directly pasting the config command , please do reasearch a bit and atleast warn the user before using such commands. And as @Rodrigo mentioned in his comment : «It does not look cool to ignore the errors.»

—UPDATE—

YOu can also configure maxmemory and maxmemory-policy to define the behavior of Redis when a specific limit of memory is reached.
For example, if I want to keep the memory limit of 6GB and delete the least recently used keys from the DB to make sure that redis mem usage do not exceed 6GB, then we can set these two parameters (in redis.conf or CONFIG SET command):

maxmemory 6gb
maxmemory-policy allkeys-lru

There are a lot of other values which you can set for these two parameters you can read about this from here: https://redis.io/topics/lru-cache

all of those answers do not explain the reason why the rdb save failed.


as my case, I checked the redis log and found:

14975:M 18 Jun 13:23:07.354 # Background saving terminated by signal 9

run the following command in terminal:

sudo egrep -i -r 'killed process' /var/log/

it display:

/var/log/kern.log.1:Jun 18 13:23:07 10-10-88-16 kernel: [28152358.208108] Killed process 28416 (redis-server) total-vm:7660204kB, anon-rss:2285492kB, file-rss:0kB

that is it! this process(redis save rdb) is killed by OOM killer

refers:

https://github.com/antirez/redis/issues/1886

Finding which process was killed by Linux OOM killer

Nowadays the Redis write-access problems that give this error message to the client re-emerged in the official redis docker containers.

Redis from the official redis image tries to write the .rdb file in the containers /data folder, which is rather unfortunate, as it is a root-owned folder and it is a non-persistent location too (data written there will disappear if your container/pod crashes).

So after an hour of inactivity, if you have run your redis container as a non-root user (e.g. docker run -u 1007 rather than default docker run -u 0), you will get a nicely detailed error msg in your server log (see docker logs redis):

1:M 29 Jun 2019 21:11:22.014 * 1 changes in 3600 seconds. Saving...
1:M 29 Jun 2019 21:11:22.015 * Background saving started by pid 499
499:C 29 Jun 2019 21:11:22.015 # Failed opening the RDB file dump.rdb (in server root dir /data) for saving: Permission denied
1:M 29 Jun 2019 21:11:22.115 # Background saving error

So what you need to do is to map container’s /data folder to an external location (where the non-root user, here: 1007, has write access, such as /tmp on the host machine), e.g:

docker run --rm -d --name redis -p 6379:6379 -u 1007 -v /tmp:/data redis

So it is a misconfiguration of the official docker image (which should write to /tmp not /data) that produces this «time bomb» that you will most likely encounter only in production… overnight over some particularly quiet holiday weekend :/

for me

config set stop-writes-on-bgsave-error no

and I reload my mac, it works

$ redis-cli

config set stop-writes-on-bgsave-error no

According to Redis documentation, this is recommended only if you don’t have RDB snapshots enabled or if you don’t care about data persistence in the snapshots.

«By default Redis will stop accepting writes if RDB snapshots are enabled (at least one save point) and the latest background save failed. This will make the user aware (in a hard way) that data is not persisting on disk properly, otherwise,strong text chances are that no one will notice and some disaster will happen.»

What u should be doing is :

redis-cli

127.0.0.1:6379> CONFIG SET dir /data/tmp
OK
127.0.0.1:6379> CONFIG SET dbfilename temp.rdb
OK
127.0.0.1:6379> BGSAVE
Background saving started
127.0.0.1:6379>
Please Make sure /data/tmp has enough disk space.

I too was facing the same issue. Both the answers (the most upvoted one and the accepted one) just give a temporary fix for the same.

Moreover, the config set stop-writes-on-bgsave-error no is a horrible way to over look this error, since what this option does is stop redis from notifying that writes have been stopped and to move on without writing the data in a snapshot. This is simply ignoring this error.
Refer this

As for setting dir in config in redis-cli, once you restart the redis service, this shall get cleared too and the same error shall pop up again. The default value of dir in redis.conf is ./ , and if you start redis as root user, then ./ is / to which write permissions aren’t granted, and hence the error.

The best way is to set the dir parameter in redis.conf file and set proper permissions to that directory. Most of the debian distributions shall have it in /etc/redis/redis.conf

After banging my head through so many SO questions finally —
for me @Axel Advento’ s answer worked but with few extra steps —
I was still facing the permission issues.
I had to switch user to redis, create a new dir in it’s home dir and then set it as redis’s dir.

sudo su - redis -s /bin/bash
mkdir redis_dir
redis-cli CONFIG SET dir $(realpath redis_dir)
exit # to logout from redis user (optional)

I know this thread is slightly older, but here’s what worked for me when I got this error earlier, knowing I was nowhere near memory limit- both answers were found above.

Hopefully this could help someone in the future if they need it.

  1. Checked CHMOD on dir folder… found somehow the symbolic notation was different. CHMOD dir folder to 755
  2. dbfilename permissions were good, no changes needed
  3. Restarted redis-server
  4. (Should’ve done this first, but ah well) Referenced the redis-server.log and found that the error was the result of access being denied.

Again- unsure how the permissions on the DIR folder got changed, but I’m assuming CHMOD back to 755 and restarting redis-server took care of it as I was able to ping redis server afterwards.

Also- to note, redis did have ownership of the dbfilename and DIR folder.

On redis.conf line ~235 let’s try to change config like this

- stop-writes-on-bgsave-error yes
+ stop-writes-on-bgsave-error no

I hit this problem while working on a server with AFS disk space because my authentication token had expired, which yielded Permission Denied responses when the redis-server tried to save. I solved this by refreshing my token:

kinit USERNAME_HERE -l 30d && aklog

In case you are using docker/docker-compose and want to prevent redis from writing to file, you can create a redis config and mount into a container

docker.compose.override.yml

  redis:¬
      volumes:¬
        - ./redis.conf:/usr/local/etc/redis/redis.conf¬
      ports:¬
        - 6379:6379¬

You can download the default config from here

in the redis.conf file make sure you comment out these 3 lines

save 900 1
save 300 10
save 60 10000

myou can view more solutions for removing the persistent data here

In my case it happened because I just installed redis using the quick way. So redis is not running as root.
I was able to solve this problem by following the instructions under the Installing Redis more properly section of their Quick Start Guide. After doing so, the problem was solved and redis is now running as root. Check it out.

Check your Redis log before taking any action. Some of the solutions in this thread may erase your Redis data, so be careful about what you are doing.

In my case, the machine was running out of RAM. This also can happen when there is no more free disk space on the host.

In my case it was related to disk free space. (you can check it with df -h bash command) when I free some space this error disappeared.

If you are running Redis locally on a windows machine, try to «run as administrator» and see if it works. With me, the problem was that Redis was located in the «Program Files» folder, which restricts permissions by default. As it should.

However, do not automatically run Redis as an administrator You don’t want to grant it more rights that it is supposed to have. You want to solve this by the book.

So, we have been able to quickly identify the problem by running it as an administrator, but this is not the cure. A likely scenario is that you have put Redis in a folder that doesn’t have write rights and as a consequence the DB file is stored in that same location.

You can solve this by opening the redis.windows.conf and to search for the following configuration:

    # The working directory.
    #
    # The DB will be written inside this directory, with the filename specified
    # above using the 'dbfilename' configuration directive.
    #
    # The Append Only File will also be created inside this directory.
    #
    # Note that you must specify a directory here, not a file name.
    dir ./

Change dir ./ to a path you have regular read/write permissions for

You could also just move the Redis folder in it’s entirety to a folder you know has the right permissions.

Please, be aware, that this error appears when your server is under attack. Just found that redis fails to write to ‘/etc/cron.d/web’ where after correcting of permissions, new file consisting of mining algorithm with some hiding options was added.

# on redis 6.0.4 
# if show error 'MISCONF Redis is configured to save RDB snapshots'
# Because redis doesn't have permissions to create dump.rdb file
sudo redis/bin/redis-server 
sudo redis/bin/redis-cli

check the permission in dir : var/lib/redis it should be redis:redis

Понравилась статья? Поделить с друзьями:
  • Play machine ошибка 105
  • Play error что означает
  • Play error тв приставка
  • Please check mei driver is installed ошибка
  • Play error на приставке тв