我正在尝试调试在另一个事件发生几天后发生的事情,并且希望加快测试速度而不绕过日期延迟相关代码。有没有办法暂时更改 ddev 容器中的日期?
感谢这个问题的帮助和@rfay的支持。我使用 libfaketime
想出了这个解决方案我创建了
.ddev/web-build/Dockerfile
,内容如下:
ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apt-get update && apt-get install -y make build-essential
WORKDIR /
RUN git clone https://github.com/wolfcw/libfaketime.git
WORKDIR /libfaketime/src
RUN make install
我运行了
ddev start
以确保容器仍能构建。
然后在
.ddev/commands/host/faketime
添加了一个命令:
#!/bin/bash
## Description: Enable or disable faketime
## Usage: faketime on YYYY-mm-dd|off|status
## Example: "ddev faketime on 2020-05-04", "ddev faketime off", "ddev faketime status"
if [ $# -eq 0 ] ; then
echo "usage faketime YYYY-mm-dd or faketime off"
fi
case $1 in
on|true|enable)
echo $1
echo $2
echo "turning on"
if date -j -f "%Y-%m-%d" -j ${2} > /dev/null 2>&1
then
echo "time set to ${2} 11:00:00, restarting..."
ddev config --web-environment=LD_PRELOAD="/usr/local/lib/faketime/libfaketime.so.1",FAKETIME="${2} 11:00:00" && ddev start
else
echo "faketime on usage: ddev faketime on YYYY-MM-DD"
fi
;;
off|false|disable)
echo "turning faketime off"
ddev config --web-environment=LD_PRELOAD="" && ddev start
;;
status)
if grep -q 'FAKETIME' ${DDEV_APPROOT}/.ddev/config.yaml;
then
echo "faketime is on."
ddev exec date +%F
else
echo "faketime is off."
ddev exec date +%F
fi
;;
*)
echo "invalid argument"
;;
esac
在 Mac 上,这允许我运行
ddev faketime on 2020-05-4
将容器日期设置为 2020 年 5 月 4 日,并运行 ddev faketime off
将其关闭。在基于 UNIX 的系统上,脚本的日期验证部分需要不同。
if date -j -f "%Y-%m-%d" -j ${2} > /dev/null 2>&1;
需要像这样
if date "+%Y-%m-%d" -d ${2} 2>&1;
faketime off
和faketime on
都会导致容器重新启动,而faketime status
只会读取时间是否被伪造并报告当前容器日期。
就我而言,将时间设置为上午 11 点就可以了。我只关心日期本身。对于您的应用程序,您可能想要更改参数并指定时间。
如果 another 答案在
ddev restart
上给出错误,并且您在 ddev logs
中看到此内容:
libfaketime: In ft_shm_init(), sem_open failed and recreation attempts failed: No such file or directory
libfaketime: sem_name was /faketime_sem_136, created locally: false
尝试这个
.ddev/web-build/Dockerfile
(基于this SO答案,仅限amd64):
COPY --from=trajano/ubuntu-faketime /faketime.so /lib/faketime.so
ENV LD_PRELOAD=/lib/faketime.so DONT_FAKE_MONOTONIC=1
并使用
FAKETIME
与 DDEV 配置:
ddev config --web-environment-add 'FAKETIME=2020-01-01 01:00:00'