Skip to content

Instantly share code, notes, and snippets.

@jimjh
Created November 27, 2012 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimjh/4152358 to your computer and use it in GitHub Desktop.
Save jimjh/4152358 to your computer and use it in GitHub Desktop.
Experiments with pagecache-centric logging and recovery in Go.
package main
// crash_recover.go experiments with recovering from a file that suddenly
// crashed (files are written without sync or close.)
import (
"encoding/binary"
"fmt"
"math/rand"
"os"
"runtime"
"time"
)
// Goal: append `recovery.log` with consecutive integers.
func main() {
runtime.GOMAXPROCS(4)
rand.Seed(time.Now().UnixNano())
file, err := os.OpenFile("recovery.log", os.O_RDWR|os.O_CREATE, 0666)
if nil != err {
panic(err)
}
n := read(file) // last number in file was n
write(file, n) // continue writing from n
}
// read reads from the given file and reports the last entry in the file.
func read(file *os.File) uint32 {
if _, err := file.Seek(-4, os.SEEK_END); nil != err {
fmt.Println("File was empty.")
return 0
}
var n uint32
if err := binary.Read(file, binary.LittleEndian, &n); nil != err {
panic(err)
}
fmt.Println("Last entry was \t\t\t\t", n)
return n
}
// write appends to the given file and exits with probability 0.0001.
func write(file *os.File, n uint32) {
file.Seek(0, os.SEEK_END)
for {
err := binary.Write(file, binary.LittleEndian, n)
if nil != err {
panic(err)
}
if rand.Float32() < 0.0001 {
fmt.Println("Last number written was \t\t", n)
os.Exit(0)
}
n++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment