This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bysession.go
240 lines (203 loc) · 6.48 KB
/
bysession.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
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
package main
// Utility that takes in a dataexport dump file and emits a directory containing events grouped by session (invdid, sessionId) and sorted by time.
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/buger/jsonparser"
"github.com/coreos/pkg/multierror"
"github.com/golang/glog"
pkgerrors "github.com/pkg/errors"
)
var (
outDir = flag.String("out", ".", "The dir we will ensure exists, and emit the session-grouped events to")
)
func runBysession(ctx context.Context, args []string) error {
if len(args) < 1 {
errorstr := fmt.Sprintf("Bysession tool requires at least 1 argument (name of the folder containing exports)\n%s",
"Usage: ./fs-explore bysession <exports folder>")
return errors.New(errorstr)
}
inDir := args[0]
builtinArgs := make([]string, 1)
builtinArgs[0] = "-stderrthreshold=INFO" // Making logging verbose by default
flag.CommandLine.Parse(builtinArgs)
orgName := filepath.Base(inDir)
orgDir := path.Join(*outDir, orgName+"-bysession")
glog.Infof("Creating output dir [%s]", orgDir)
defer glog.Flush()
if _, err := os.Stat(orgDir); !os.IsNotExist(err) {
glog.Errorf("Aborting. Output dir [%s] already exists (and export is non-idempotent)", orgDir)
return nil
}
if err := os.MkdirAll(orgDir, 0750); err != nil {
return pkgerrors.Wrapf(err, "Failed to create data directory "+orgDir)
}
glog.Infof("processing data export files in [%s]...", inDir)
startTime := time.Now()
defer glog.Infof("processing data export files in [%s] finished in %s", inDir, time.Since(startTime))
// Process each dump file in parallel up to NumCPU workers.
numWorkers := runtime.NumCPU()
processFileCh := make(chan string, numWorkers)
processor := newExportProcesser(orgDir)
var wg sync.WaitGroup
// Close the channel after walking the files. Block until all workers are done.
defer func() {
close(processFileCh)
wg.Wait()
}()
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
processor.processFiles(ctx, processFileCh)
}()
}
// Walk the dump dir to collect and process export files.
return filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return pkgerrors.Wrap(err, "walk called with error")
} else if info.IsDir() {
return nil
}
glog.Infof("Processing [%s]", path)
if strings.HasSuffix(path, ".json") {
processFileCh <- path
}
return nil
})
}
type exportProcessor struct {
// Where we output session events to.
orgDir string
// When writing a session to disk, we need to make sure that concurrent file processors linearize around specific sessions for sessions spanning export files.
writeLocks *TransientLockMap
}
func newExportProcesser(orgDir string) *exportProcessor {
return &exportProcessor{
orgDir: orgDir,
writeLocks: NewTransientLockMap(),
}
}
// Processes a dump file. Builds an in-memory table of all events swimlaned by indvId:sessionId.
// Emits a file per session with each session containing the events sorted by EventStart.
func (p *exportProcessor) processFiles(ctx context.Context, processFileCh chan string) {
defer glog.Flush()
for path := range processFileCh {
sessions := map[string]sessionEvents{}
jsonBytes, err := ioutil.ReadFile(path)
if err != nil {
glog.Errorf("Couldn't read file [%s]: %s", path, pkgerrors.Wrap(err, ""))
continue
}
var errs multierror.Error
eachEvent := func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
// Iterate each event.
if err != nil {
errs = append(errs, err)
return
}
indvId, err := jsonparser.GetInt(value, "IndvId")
if err != nil {
glog.Errorf("%s", pkgerrors.Wrap(err, "couldn't get json int value for IndyId"))
return
}
sessionId, err := jsonparser.GetInt(value, "SessionId")
if err != nil {
glog.Errorf("%s", pkgerrors.Wrap(err, "couldn't get json int value for SessionId"))
return
}
sessionKey := fmt.Sprintf("%d:%d", indvId, sessionId)
session := sessions[sessionKey]
sessions[sessionKey] = append(session, value)
}
if _, err := jsonparser.ArrayEach(jsonBytes, eachEvent); err != nil {
glog.Errorf("%s", pkgerrors.Wrap(err, "couldn't parse json bytes as array"))
continue
}
doInLock := func(sessionKey string, f func()) {
acquired := p.writeLocks.Lock(ctx, sessionKey)
defer p.writeLocks.Unlock(sessionKey)
if acquired {
f()
} else {
glog.Errorf("failed to acquire lock for [%s]", sessionKey)
}
}
// Write the session files to disk.
for sessionKey, sessionEvents := range sessions {
glog.Infof("Saving session: [%s]", sessionKey)
sessionFileName := filepath.Join(p.orgDir, sessionKey) + ".json"
doInLock(sessionKey, func() {
_, err := os.Stat(sessionFileName)
if err == nil {
// Exists. Let's chain to it.
// Read existing file. Merge it and resort with ours.
existingSession, err := ioutil.ReadFile(sessionFileName)
if err != nil {
glog.Errorf("%s", err)
return
}
jsonparser.ArrayEach(existingSession, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
sessionEvents = append(sessionEvents, value)
})
sort.Sort(sessionEvents)
if err := ioutil.WriteFile(sessionFileName, sessionEvents.AsJson(), 0750); err != nil {
glog.Errorf("%s", err)
}
} else if os.IsNotExist(err) {
// Create it.
sort.Sort(sessionEvents)
if err := ioutil.WriteFile(sessionFileName, sessionEvents.AsJson(), 0750); err != nil {
glog.Errorf("%s", err)
}
} else {
// Some other error.
glog.Errorf("%s", err)
}
})
}
if len(errs) > 0 {
glog.Errorf("%s", errs.AsError())
}
}
}
// Events in a single session. Where each event is a []byte corresponding to it's JSON encoding.
type sessionEvents [][]byte
func (s sessionEvents) AsJson() []byte {
buf := &bytes.Buffer{}
buf.WriteString("[")
for i, e := range s {
if i > 0 {
buf.WriteString(",")
}
buf.Write(e)
}
buf.WriteString("]")
return buf.Bytes()
}
func (s sessionEvents) Len() int { return len(s) }
func (s sessionEvents) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sessionEvents) Less(i, j int) bool {
si, err := jsonparser.GetString(s[i], "EventStart")
if err != nil {
panic(err)
}
sj, err := jsonparser.GetString(s[j], "EventStart")
if err != nil {
panic(err)
}
// Lexicographic string comparison ought to work.
return strings.TrimSuffix(si, "Z") < strings.TrimSuffix(sj, "Z")
}