This repository was archived by the owner on Feb 23, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathworker.go
More file actions
185 lines (153 loc) · 4.81 KB
/
Copy pathworker.go
File metadata and controls
185 lines (153 loc) · 4.81 KB
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
package main
import (
"github.com/btcsuite/btcd/rpcclient"
"fmt"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"log"
"os"
"strings"
"time"
)
// A Worker contains all the components necessary to make RPC calls to bitcoind, and
// to place data into PostgreSQL.
type Worker struct {
client *rpcclient.Client
// Fields specifically for PostgreSQL
pgClient *pg.DB
pgBatch dataBatch
workFile *os.File
}
// Assumes enviroment variables: DB, DB_USERNAME, DB_PASSWORD, BITCOIND_HOST, BITCOIND_USERNAME, BITCOIND_PASSWORD, are all set.
// PostgreSQL and bitcoind should already be started.
func setupWorker(startTime string, id int) Worker {
workFileName := fmt.Sprintf("%v/worker-%v-%v", WORKER_PROGRESS_DIR, startTime, id)
// Create file to record progress in.
workFile, err := os.Create(workFileName)
if err != nil {
fatal("Error setting up workfile: ", err)
}
BITCOIND_HOST, ok := os.LookupEnv("BITCOIND_HOST")
if !ok {
BITCOIND_HOST = "localhost:8332"
}
// Connect to local bitcoin core RPC server using HTTP POST mode.
connCfg := &rpcclient.ConnConfig{
Host: BITCOIND_HOST,
User: os.Getenv("BITCOIND_USERNAME"),
Pass: os.Getenv("BITCOIND_PASSWORD"),
HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode
DisableTLS: true, // Bitcoin core does not provide TLS by default
}
// Notice the notification parameter is nil since notifications are
// not supported in HTTP POST mode.
client, err := rpcclient.New(connCfg, nil)
if err != nil {
fatal("Error connecting to bitcoin rpcclient", err)
}
DB_ADDR, ok := os.LookupEnv("DB_ADDR")
if !ok {
DB_ADDR = "localhost:5432"
}
db := pg.Connect(&pg.Options{
Addr: DB_ADDR,
User: os.Getenv("DB_USERNAME"),
Password: os.Getenv("DB_PASSWORD"),
Database: os.Getenv("DB"),
})
model := interface{}((*DashboardDataV2)(nil))
err = db.CreateTable(model, &orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
})
if err != nil {
fatal("Error creating Postgres table: ", err)
}
// Prints out the queries created by go-pg.
if SHOW_QUERIES {
db.OnQueryProcessed(func(event *pg.QueryProcessedEvent) {
query, err := event.FormattedQuery()
if err != nil {
fatal("Error formatting processed query: ", err)
}
log.Printf("%s %s", time.Since(event.StartTime), query)
})
}
worker := Worker{
client: client,
pgClient: db,
pgBatch: dataBatch{
versions: make([]int64, 0),
dashboardDataRows: make([]DashboardDataV2, 0),
},
workFile: workFile,
}
return worker
}
func (worker *Worker) shutdown() {
worker.client.Shutdown()
worker.pgClient.Close()
// Worker finished successfully so its progress record is unneeded.
err := os.Remove(worker.workFile.Name())
if err != nil {
log.Printf("Error removing %v: %v\n", worker.workFile, err)
}
}
// inserts a data from a single getblockstats call into the worker's DB
func (worker *Worker) insert(stats BlockStats) bool {
data := Data{
Version: CURRENT_VERSION_NUMBER,
DashboardDataRow: stats.transformToDashboardData(),
}
return worker.insertData(data)
}
func (worker *Worker) insertData(data Data) bool {
err := worker.pgClient.Insert(&data.DashboardDataRow)
if err != nil {
// Skip duplicate values.
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
log.Println("Skipping duplicate key at height: ", data.DashboardDataRow.Height)
return true
}
fatal("PG database insert failed! ", err)
}
log.Printf("\n\n STORED INTO POSTGRESQL \n\n")
if BACKUP_JSON {
storeDataAsFile(data)
}
return true
}
// setup the insertion of many BlockStats (stored internally)
// uses batch insertion / bulk insertion capabilities of DB_USED whenever possible
func (worker *Worker) batchInsert(stats BlockStats) {
worker.pgBatch.versions = append(worker.pgBatch.versions, CURRENT_VERSION_NUMBER)
worker.pgBatch.dashboardDataRows = append(worker.pgBatch.dashboardDataRows, stats.transformToDashboardData())
}
// actually do the write of batch created
func (worker *Worker) commitBatchInsert() bool {
err := worker.pgClient.Insert(&worker.pgBatch.dashboardDataRows)
if err != nil {
// Skip duplicate values.
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
log.Println("Skipping duplicate key in batch")
for _, row := range worker.pgBatch.dashboardDataRows {
worker.insertData(Data{CURRENT_VERSION_NUMBER, row})
}
return true
}
fatal("PG Commit Batch insert failed! ", err)
}
log.Printf("\n\n STORED INTO POSTGRESQL \n\n")
if BACKUP_JSON {
for i, dashDataRow := range worker.pgBatch.dashboardDataRows {
storeDataAsFile(Data{
Version: worker.pgBatch.versions[i],
DashboardDataRow: dashDataRow,
})
}
}
// Reset batch.
worker.pgBatch.versions = make([]int64, 0)
worker.pgBatch.dashboardDataRows = make([]DashboardDataV2, 0)
return true
}