-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
280 lines (237 loc) · 6.12 KB
/
main.go
File metadata and controls
280 lines (237 loc) · 6.12 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"strconv"
"syscall"
"time"
"bazil.org/fuse"
"bazil.org/fuse/fs"
_ "bazil.org/fuse/fs/fstestutil"
"bazil.org/fuse/fuseutil"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
"github.com/kelseyhightower/envconfig"
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s MOUNTPOINT\n", os.Args[0])
flag.PrintDefaults()
}
var svc *dynamodb.Client
type AppendHistoryMessage struct {
Content string
Timestamp int
}
var ch chan AppendHistoryMessage
var dynmodbTableName string = "bash-eternal-history"
var content *ContentRepository = nil
var existingDataLoaded bool = false
var data []byte = make([]byte, 0)
type Config struct {
ReadContentTimeout time.Duration `envconfig:"READ_CONTENT_TIMEOUT" default:"15s"`
}
var appConig Config = Config{}
func init() {
err := envconfig.Process("", &appConig)
if err != nil {
log.Fatal(err.Error())
}
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx, config.WithRetryer(func() aws.Retryer {
return aws.NopRetryer{}
}))
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
svc = dynamodb.NewFromConfig(cfg)
ch = make(chan AppendHistoryMessage, 100)
content = NewContentRepository(svc, dynmodbTableName)
go func() {
ctx := context.TODO()
for {
m := <-ch
for {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_, err := svc.PutItem(ctx, &dynamodb.PutItemInput{
TableName: &dynmodbTableName,
Item: map[string]types.AttributeValue{
"timestamp": &types.AttributeValueMemberN{Value: strconv.Itoa(m.Timestamp)},
"timestamp_2": &types.AttributeValueMemberN{Value: strconv.Itoa(m.Timestamp)},
"content": &types.AttributeValueMemberS{Value: m.Content},
},
})
if err == nil {
break
}
log.Printf("unable to write to dynamodb, trying again: %v", err)
time.Sleep(5 * time.Second)
}
}
}()
}
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
os.Exit(2)
}
mountpoint := flag.Arg(0)
// create table if it does not exist
_, err := svc.DescribeTable(context.TODO(), &dynamodb.DescribeTableInput{
TableName: &dynmodbTableName,
})
var notFoundException *types.ResourceNotFoundException
if errors.As(err, ¬FoundException) {
input := &dynamodb.CreateTableInput{
TableName: &dynmodbTableName,
AttributeDefinitions: []types.AttributeDefinition{
{
AttributeName: aws.String("timestamp"),
AttributeType: types.ScalarAttributeTypeN,
},
{
AttributeName: aws.String("timestamp_2"),
AttributeType: types.ScalarAttributeTypeN,
},
},
KeySchema: []types.KeySchemaElement{
{
AttributeName: aws.String("timestamp"),
KeyType: types.KeyTypeHash,
},
{
AttributeName: aws.String("timestamp_2"),
KeyType: types.KeyTypeRange,
},
},
BillingMode: types.BillingModePayPerRequest,
}
_, err := svc.CreateTable(context.TODO(), input)
if err != nil {
panic(err)
}
log.Println("error:", notFoundException)
} else if err != nil {
panic(err)
}
c, err := fuse.Mount(
mountpoint,
fuse.FSName("basheternalhistory"),
fuse.Subtype("basheternalhistoryfs"),
fuse.AllowNonEmptyMount(),
)
if err != nil {
log.Fatal(err)
}
defer c.Close()
err = fs.Serve(c, FS{})
if err != nil {
log.Fatal(err)
}
}
// FS implements the hello world file system.
type FS struct{}
func (FS) Root() (fs.Node, error) {
return Dir{}, nil
}
// Dir implements both Node and Handle for the root directory.
type Dir struct{}
func (Dir) Attr(ctx context.Context, a *fuse.Attr) error {
a.Inode = 1
a.Mode = os.ModeDir | 0o555
return nil
}
func (Dir) Lookup(ctx context.Context, name string) (fs.Node, error) {
if name == ".bash_eternal_history" {
return NewFile("bash-eternal-history"), nil
}
return nil, syscall.ENOENT
}
var dirDirs = []fuse.Dirent{
{Inode: 2, Name: ".bash_eternal_history", Type: fuse.DT_File},
}
func (Dir) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
return dirDirs, nil
}
// File implements both Node and Handle for the hello file.
type File struct {
DynamodbTableName string
ContentCache string
}
type ContentCache struct {
Content string
LastUpdated time.Time
}
func NewFile(tableName string) *File {
return &File{
DynamodbTableName: tableName,
}
}
func (f *File) Attr(ctx context.Context, a *fuse.Attr) error {
if !existingDataLoaded {
log.Printf("DEBUG: loading existing data")
c, err := content.Get(ctx)
if err != nil {
log.Printf("DEBUG: WARN: could not get content: %v", err)
} else {
existingDataLoaded = true
}
data = []byte(c)
}
a.Inode = 2
a.Mode = 0o444
a.Size = uint64(len(data))
// TODO: I don't know how to set this correctly
a.Uid = 1000
a.Gid = 1000
return nil
}
func (f *File) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
log.Printf("DEBUG: Read()")
if !existingDataLoaded {
log.Printf("DEBUG: loading existing data")
c, err := content.Get(ctx)
if err != nil {
log.Printf("DEBUG: WARN: could not get content: %v", err)
} else {
existingDataLoaded = true
}
data = []byte(c)
}
fuseutil.HandleRead(req, resp, data)
return nil
}
func HandleWrite(req *fuse.WriteRequest, resp *fuse.WriteResponse, data *[]byte) {
size := len(req.Data)
if int(req.Offset)+size > int(len(*data)) {
newData := make([]byte, int(req.Offset)+size)
copy(newData, *data)
*data = newData
}
n := copy((*data)[req.Offset:int(req.Offset)+size], req.Data)
resp.Size = n
}
func (f *File) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {
defer duration(track("Write()"))
ch <- AppendHistoryMessage{
Timestamp: int(time.Now().UnixNano()),
Content: string(req.Data),
}
HandleWrite(req, resp, &data)
return nil
}
func track(msg string) (string, time.Time) {
return msg, time.Now()
}
func duration(msg string, start time.Time) {
log.Printf("DEBUG: %v: %v\n", msg, time.Since(start))
}