概述
我從事的產品,是面向行業的Android應用,同時硬件也是自己開發的。因為屬于工程產品以及一些因素,并沒有設計電池,因此這里就一個很大的問題,掉電可能會導致數據丟失、甚至文件系統的損壞。好在,大部分場合不容易出現掉電的情況。
但有一天,同事報告一個BUG:使用PC軟件配置好硬件后,拔掉電源重新上電后,硬件會自動恢復到配置之前的狀態,但是拔掉電源之前,硬件提示寫入配置成功。我親自測試了一下,確實如此。操作迅速的話,基本是100%重現的。
分析
如果提示寫入配置成功,那么說明調用文件讀寫API成功,數據已經在存儲器上,掉電是不會丟失的,可是卻出現了數據丟失的現象。通過 adb
查看文件,配置數據確實沒有寫入。
稍微思考一下,如果提示寫入配置成功,那么也就是調用文件API成功,review下源碼,是個很簡單:FileOutputStream
調用,也有調用 close
方法和做異常處理。
既然代碼沒什么問題,那么只能從系統層面去思考了,我們知道,UNIX/LINUX內核設有緩沖區高速緩存或頁面高速緩存,當寫入文件的時候,先寫入到高速緩存,等到適合的時機才寫入到存儲器上。也就是說,如果數據在緩存里面,這個時候掉電,數據就理所當然的丟失了。
解決
要驗證這個猜想比較簡單,通過API把數據從緩存刷到存儲器上,然后再提示給用戶。對于C語言
,linux提供了:sync/fsync/fdatasync
,來實現。對于Java,只能先看看FileOutputStream
有什么方法可以使用。一眼看過去,比較接近的方法就是:flush
了。但是,文檔上 OutputStream.html#flush 是這樣描述的:
Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
The flush method of OutputStream does nothing.
主要是后面兩段,也就是說如果是一個文件,flush并不保證把數據刷到物理設備上,通常flush不做任何操作。閱讀Android上的實現:FileOutputStream.java 也可以證實這點,FileOutputStream
并沒有重載flush。
但是,我們注意到了 FileOutputStream
有個方法:getFD()
,返回:FileDescriptor
,一看名字,如果熟悉C
,就知道這玩意就是文件描述符,有文件描述符,基本可以解決問題了,查看 FileDescriptor
對象,有個 sync
方法,描述:
Force all system buffers to synchronize with the underlying device.
把系統緩沖區同步到基礎設備,查看其源碼實現 FileDescriptor.java:
/**
* Ensures that data which is buffered within the underlying implementation
* is written out to the appropriate device before returning.
*/
public void sync() throws SyncFailedException {
try {
if (Libcore.os.isatty(this)) {
Libcore.os.tcdrain(this);
} else {
Libcore.os.fsync(this);
}
} catch (ErrnoException errnoException) {
SyncFailedException sfe = new SyncFailedException(errnoException.getMessage());
sfe.initCause(errnoException);
throw sfe;
}
}
源碼實現很簡單, 如果打開的文件是個TTY,那么調用tcdrain,否則調用fsync。
最后,在close之前,調用fsync,然后進行測試,BUG得到了修復。
題外話
高速緩存與mount
當使用mount
命令來掛在設備的使用,可以指定不使用或者使用緩存,該參數分別是:sync
和 async
。但是對于早期的嵌入式存儲設備,因為性能低,因此默認情況下都是開啟緩存的。
易掉電的產品
我們的產品沒有設計電池,因為用戶數據不是很關鍵,加上數據是存儲在云端的,就沒所謂了。實際上大家非常了解的Android電視盒子或者電視,通常沒有電池的(有內置RTC電池,保證斷電后,時鐘繼續走),拔掉電源就等于關機了。
對于Android這類頻繁IO的操作系統來說,直接拔掉電源風險不是一般的大,不過廠商也有不少的應對方案,即使是系統文件因為意外掉電而損壞,基本上也是能自動修復的。