This repository was archived by the owner on Jun 15, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdb.go
More file actions
178 lines (156 loc) · 3.7 KB
/
Copy pathdb.go
File metadata and controls
178 lines (156 loc) · 3.7 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
package kvs
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"sync"
"time"
)
// Kvs keeps the essential variables.
type Kvs struct {
// name is database name.
name string
// dir is directory of the data files.
dir string
// dbFile is a File object that handles File operations.
dbFile *os.File
// kv means key-value. It keeps the data in map.
kv map[string]string
// mu is mutex for avoiding conflicts.
mu sync.Mutex
// Addr is the server address.
Addr string
// duration stands for the time interval to save data into file periodically.
duration time.Duration
}
const (
baseDir = "/tmp/kvs/"
fileExtension = ".kvs"
)
// open creates data file for newly creating database. If the database file is
// already exists, it returns error without creating anything. name indicates
// database name.
func open(name string, addr string, duration time.Duration) (*Kvs, error) {
fullPath := baseDir + name + fileExtension
// Check database's base directory
if _, err := os.Stat(baseDir); os.IsNotExist(err) {
err := os.Mkdir(baseDir, 0777)
if err != nil {
return nil, fmt.Errorf("database directory couldn't created: %s", err.Error())
}
}
// Check database file's directory
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
dbFile, err := os.OpenFile(fullPath, os.O_CREATE, 0777)
if err != nil {
return nil, fmt.Errorf("database couldn't created: %s", err.Error())
}
m := make(map[string]string)
k := &Kvs{
name: name + fileExtension,
dir: baseDir + name + fileExtension,
dbFile: dbFile,
kv: m,
mu: sync.Mutex{},
Addr: addr,
duration: duration,
}
ticker := time.NewTicker(duration)
go func() {
for {
select {
case t := <-ticker.C:
err := k.write()
if err != nil {
log.Println("Writing file failed at", t.Local())
} else {
log.Println("Data saved on the file at", t.Local())
}
}
}
}()
return k, nil
}
k, err := openAndLoad(name, addr, duration)
if err != nil {
return nil, err
}
ticker := time.NewTicker(duration)
go func() {
for {
select {
case t := <-ticker.C:
err := k.write()
if err != nil {
log.Println("Writing file failed at", t.Local())
} else {
log.Println("Data saved on the file at", t.Local())
}
}
}
}()
return k, nil
}
// openAndLoad opens the named database file for file operations. Also, loads
// the database file into map to in-memory operations.
func openAndLoad(dbName string, addr string, duration time.Duration) (*Kvs, error) {
mu := sync.Mutex{}
mu.Lock()
defer mu.Unlock()
fullPath := baseDir + dbName + fileExtension
dbFile, err := os.OpenFile(fullPath, os.O_RDONLY, 0777)
if err != nil {
return nil, err
}
k := &Kvs{
name: dbName,
dir: fullPath,
dbFile: dbFile,
mu: sync.Mutex{},
Addr: addr,
duration: duration,
}
err = k.load()
if err != nil {
return nil, err
}
return k, nil
}
// Close closes the file.
func (k *Kvs) Close() error {
return k.write()
}
// load reads and loads the data from the file into map.
func (k *Kvs) load() error {
k.mu.Lock()
defer k.mu.Unlock()
m := make(map[string]string)
buf, err := os.ReadFile(k.dir)
if err != nil {
return err
}
fileData := string(buf[:])
if fileData == "" {
k.kv = m
return nil
}
dataArr := strings.Split(fileData, "\n")
for i := 0; i < len(dataArr)-1; i++ {
data := strings.Split(dataArr[i], "=")
k, v := data[0], data[1]
m[k] = v
}
k.kv = m
return nil
}
// write saves data into file. It writes the data in map to the file.
func (k *Kvs) write() error {
defer k.dbFile.Close()
d := ""
for key, val := range k.kv {
d += fmt.Sprintf("%s=%s\n", key, val)
}
return ioutil.WriteFile(k.dir, []byte(d), 0666)
}