This repository has been archived by the owner on Dec 26, 2017. It is now read-only.
forked from omniscale/imposm3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
210 lines (178 loc) · 4.6 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package state
import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/omniscale/imposm3/logging"
"github.com/omniscale/imposm3/parser/pbf"
)
var log = logging.NewLogger("diff")
type DiffState struct {
Time time.Time
Sequence int32
Url string
}
func (d DiffState) String() string {
return fmt.Sprintf("Diff #%d from %s", d.Sequence, d.Time.Local())
}
func (d DiffState) WriteToFile(file string) error {
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
writer := bufio.NewWriter(f)
lines := []string{}
lines = append(lines, "timestamp="+d.Time.Format(timestampFormat))
if d.Sequence != 0 {
lines = append(lines, "sequenceNumber="+fmt.Sprintf("%d", d.Sequence))
}
lines = append(lines, "replicationUrl="+d.Url)
for _, line := range lines {
_, err = writer.WriteString(line + "\n")
if err != nil {
return err
}
}
return writer.Flush()
}
func WriteLastState(cacheDir string, state *DiffState) error {
stateFile := path.Join(cacheDir, "last.state.txt")
return state.WriteToFile(stateFile)
}
func ParseFromOsc(oscFile string) (*DiffState, error) {
var stateFile string
if !strings.HasSuffix(oscFile, ".osc.gz") {
log.Warn("cannot read state file for non .osc.gz files")
return nil, nil
}
stateFile = oscFile[:len(oscFile)-len(".osc.gz")] + ".state.txt"
if _, err := os.Stat(stateFile); os.IsNotExist(err) {
log.Warn("cannot find state file ", stateFile)
return nil, nil
}
f, err := os.Open(stateFile)
if err != nil {
return nil, err
}
defer f.Close()
return ParseFile(stateFile)
}
func FromPbf(pbfFile *pbf.Pbf, before time.Duration) *DiffState {
var timestamp time.Time
if pbfFile.Header.Time.Unix() != 0 {
timestamp = pbfFile.Header.Time
} else {
fstat, err := os.Stat(pbfFile.Filename)
if err != nil {
log.Warn("unable to stat pbffile: ", err)
return nil
}
timestamp = fstat.ModTime()
}
replicationUrl := "http://planet.openstreetmap.org/replication/minute/"
seq := estimateSequence(replicationUrl, timestamp)
if seq == 0 {
return nil
}
// start earlier
seq -= int32(before.Minutes())
return &DiffState{Time: timestamp, Url: replicationUrl, Sequence: seq}
}
func ParseFile(stateFile string) (*DiffState, error) {
f, err := os.Open(stateFile)
if err != nil {
return nil, err
}
defer f.Close()
return Parse(f)
}
func Parse(f io.Reader) (*DiffState, error) {
values, err := parseSimpleIni(f)
if err != nil {
return nil, err
}
timestamp, err := parseTimeStamp(values["timestamp"])
if err != nil {
return nil, err
}
sequence, err := parseSequence(values["sequenceNumber"])
if err != nil {
return nil, err
}
url := values["replicationUrl"]
return &DiffState{timestamp, sequence, url}, nil
}
func ParseLastState(cacheDir string) (*DiffState, error) {
stateFile := path.Join(cacheDir, "last.state.txt")
if _, err := os.Stat(stateFile); os.IsNotExist(err) {
return nil, err
}
return ParseFile(stateFile)
}
func parseSimpleIni(f io.Reader) (map[string]string, error) {
result := make(map[string]string)
reader := bufio.NewScanner(f)
for reader.Scan() {
line := reader.Text()
if line != "" && line[0] == '#' {
continue
}
if strings.Contains(line, "=") {
keyVal := strings.SplitN(line, "=", 2)
result[strings.TrimSpace(keyVal[0])] = strings.TrimSpace(keyVal[1])
}
}
if err := reader.Err(); err != nil {
return nil, err
}
return result, nil
}
const timestampFormat = "2006-01-02T15\\:04\\:05Z"
func parseTimeStamp(value string) (time.Time, error) {
if value == "" {
return time.Time{}, errors.New("missing timestamp in state")
}
return time.Parse(timestampFormat, value)
}
func parseSequence(value string) (int32, error) {
if value == "" {
log.Warn("missing sequenceNumber in state file")
return 0, nil
}
val, err := strconv.ParseInt(value, 10, 32)
return int32(val), err
}
func currentState(url string) (*DiffState, error) {
resp, err := http.Get(url + "state.txt")
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(fmt.Sprintf("invalid repsonse: %v", resp))
}
defer resp.Body.Close()
return Parse(resp.Body)
}
func estimateSequence(url string, timestamp time.Time) int32 {
state, err := currentState(url)
if err != nil {
// try a second time befor failing
log.Warn("unable to fetch current state from ", url, ":", err, ", retry in 30s")
time.Sleep(time.Second * 30)
state, err = currentState(url)
if err != nil {
log.Warn("unable to fetch current state from ", url, ":", err, ", giving up")
return 0
}
}
behind := state.Time.Sub(timestamp)
return state.Sequence - int32(behind.Minutes())
}