/
d3.jl
364 lines (348 loc) · 13.3 KB
/
d3.jl
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
using Mux, Sockets
import HTTP
import HTTP: WebSockets
using MemPool, Distributed
struct LinePlot
core_key::Symbol
data_key::Symbol
xlabel::String
ylabel::String
end
StructTypes.StructType(::Type{LinePlot}) = StructTypes.CustomStruct()
StructTypes.lower(lp::LinePlot) = "linePlot(svg_container, \"$(lp.core_key)\", \"$(lp.data_key)\", \"$(lp.xlabel)\", \"$(lp.ylabel)\")"
const GanttPlotFieldSpec = Tuple{Union{Symbol,Nothing},Symbol,Float64,Bool}
struct GanttPlot
core_key::Symbol
id_key::Symbol
esat_key::Symbol
psat_key::Symbol
title::String
x_label::String
x_key::Union{Symbol,Nothing}
to_color::Vector{GanttPlotFieldSpec}
end
GanttPlot(core_key, id_key, esat_key, psat_key; title="Overview", x_label="Time", x_key=nothing, to_color=GanttPlotFieldSpec[]) =
GanttPlot(core_key, id_key, esat_key, psat_key,
title, x_label, x_key, to_color)
StructTypes.StructType(::Type{GanttPlot}) = StructTypes.CustomStruct()
StructTypes.lower(lp::GanttPlot) = "ganttPlot(svg_container, \"$(lp.core_key)\", \"$(lp.id_key)\", \"$(lp.esat_key)\", \"$(lp.psat_key)\", \"$(lp.title)\", \"$(lp.x_label)\", \"$(lp.x_key)\", $(JSON3.write(sanitize(lp.to_color))))"
struct GraphPlot
core_key::Symbol
id_key::Symbol
timeline_key::Symbol
profile_key::Symbol
title::String
end
StructTypes.StructType(::Type{GraphPlot}) = StructTypes.CustomStruct()
StructTypes.lower(lp::GraphPlot) = "graphPlot(svg_container, \"$(lp.core_key)\", \"$(lp.id_key)\", \"$(lp.timeline_key)\", \"$(lp.profile_key)\", \"$(lp.title)\")"
struct ProfileViewer
core_key::Symbol
profile_key::Symbol
title::String
end
StructTypes.StructType(::Type{ProfileViewer}) = StructTypes.CustomStruct()
StructTypes.lower(lp::ProfileViewer) = "profileViewer(svg_container, \"$(lp.core_key)\", \"$(lp.profile_key)\", \"$(lp.title)\")"
## Core globals
const D3R_RUNNING = Dict{Int,Bool}()
const D3R_LOGS = Dict{Int,Dict{Symbol,Any}}()
const D3R_ACTUAL_PORT = Dict{Int,Int}()
## Client/forwarding globals
# Port -> Worker -> Sockets
# TODO: Concrete socket types
const D3R_CLIENT_SOCKETS = Dict{Int,Dict{Int,Vector{Any}}}()
const D3R_WORKER_HOST_MAP = Dict{Int,Union{IPAddr,String}}()
const D3R_WORKER_PORT_MAP = Dict{Int,Int}()
struct D3Renderer
port::Int
port_range::UnitRange{Int}
config::Vector{Any}
config_updated::Ref{Bool}
update_cond::Threads.Condition
seek_store
end
"""
D3Renderer(port::Int, port_range::UnitRange; seek_store=nothing) -> D3Renderer
Constructs a `D3Renderer`, which is a TimespanLogging aggregator which renders
the logs over HTTP using the d3.js library. `port` is the port that will be
serving the HTTP website. `port_range` specifies a range of ports that will be
used to listen for connections from other Dagger workers. `seek_store`, if
specified, is a Tables.jl-compatible object that logs will be written to and
read from. This table can be written to disk and then re-read later for offline
log analysis.
"""
D3Renderer(port::Int, port_range=50000:59999; seek_store=nothing) =
D3Renderer(port,
port_range,
Vector{Any}(),
Ref{Bool}(false),
Threads.Condition(),
seek_store)
TimespanLogging.init_similar(d3r::D3Renderer) =
D3Renderer(d3r.port,
d3r.port_range,
d3r.config,
Ref{Bool}(false),
Threads.Condition(),
d3r.seek_store)
function (d3r::D3Renderer)(logs)
D3R_LOGS[d3r.port] = logs
d3r_init(d3r.port, d3r.port_range, d3r.config_updated, d3r.config, d3r.seek_store)
lock(d3r.update_cond) do
notify(d3r.update_cond)
end
end
function Base.push!(d3r::D3Renderer, x)
push!(d3r.config, x)
d3r.config_updated[] = true
end
function d3r_init(port::Int, port_range::UnitRange, config_updated::Ref{Bool}, config, seek_store)
get(D3R_RUNNING, port, false) && return
# Ensure some variables are setup
get!(()->Dict{Symbol,Any}(), D3R_LOGS, port)
get!(()->[], get!(()->Dict{Int,Vector{Any}}(), D3R_CLIENT_SOCKETS, port), myid())
# Server configuration
d3_app = (
Mux.prod_defaults,
page("/", req->Dict(
:status=>301,
:headers=>Dict(:Location=>"/index.html"),
:body=>"Moved permanently"
)),
page("/index.html", req->begin
html = String(read(joinpath(@__DIR__, "index.html")))
hdrs = Dict(
Symbol("Content-Type")=>"text/html",
# For interactive development
Symbol("Cache-Control")=>"no-store",
)
Dict(
:body=>html,
:headers=>hdrs,
)
end),
page("/fs/:path", req->begin
path = req[:params][:path]
path = "/tmp/" * path
if ispath(path)
Dict(:body=>String(read(path)))
else
Dict(:status=>404)
end
end),
page("/assets/:path", req->begin
path = req[:params][:path]
occursin("..", path) && return Dict(:status=>404)
assets_path = normpath(joinpath(@__DIR__, "..", "assets"))
path = normpath(joinpath(assets_path, path))
if ispath(path) && normpath(dirname(path)) == assets_path
Dict(:body=>String(read(path)))
else
Dict(:status=>404)
end
end),
page("/worker_id", respond("$(myid())")),
page("/worker/:id/:location", req->begin
id = parse(Int, req[:params][:id])
location = req[:params][:location]
worker_host, worker_port = worker_host_port(id, port, port_range)
res = HTTP.get("http://$worker_host:$worker_port/$location")
return Dict(
:status=>res.status,
:body=>String(res.body),
)
end),
Mux.notfound()
)
d3_wapp = (
Mux.wdefaults,
route("/data_feed", req->begin
sock = req[:socket]
client_handler(sock, myid(), port, port_range, config_updated, config, seek_store)
end),
route("/worker/:id/data_feed", req->begin
sock = req[:socket]
id = parse(Int, req[:params][:id])
client_handler(sock, id, port, port_range, config_updated, config, seek_store)
end),
Mux.wclose,
Mux.notfound()
)
actual_port = get_actual_port(port, port_range)
# Start D3R server
Mux.serve(Mux.App(mux(d3_app...)),
Mux.App(mux(d3_wapp...)),
actual_port)
@debug "D3R initialized for port $port at actual port $actual_port"
D3R_ACTUAL_PORT[port] = actual_port
D3R_RUNNING[port] = true
end
function client_handler(sock, id, port, port_range, config_updated, config, seek_store)
fsock = nothing
if id != myid()
fsock_ready = Base.Event()
worker_host, worker_port = worker_host_port(id, port, port_range)
WebSockets.open("ws://$worker_host:$worker_port/data_feed") do _fsock
fsock = _fsock
@debug "D3R forwarder for $id ready"
notify(fsock_ready)
while true
try
bytes = WebSockets.receive(fsock)
if length(bytes) == 0
sleep(0.1)
continue
end
data = String(bytes)
#@info "D3R forwarder for $id received data"
WebSockets.send(sock, data)
catch err
if err isa WebSockets.WebSocketError && err.message isa WebSockets.CloseFrameBody
# Force-close client and forwarder
@async close(sock)
@async close(fsock)
break
end
@error "D3R forwarder for $id error!" exception=(err,catch_backtrace())
rethrow(err)
end
end
@debug "D3R forwarder for $id closed"
end
wait(fsock_ready)
end
if id == myid()
@debug "D3R client for $id sending initial config"
WebSockets.send(sock, JSON3.write((;cmd="data", payload=sanitize(D3R_LOGS[port]))))
_workers = workers()
if !(myid() in _workers)
# FIXME: Get this from the Context
_workers = vcat(myid(), _workers)
end
WebSockets.send(sock, JSON3.write((;cmd="config", payload=sanitize((;myid=myid(),workers=_workers,ctxs=config)))))
end
push!(get!(()->[], D3R_CLIENT_SOCKETS[port], id), sock)
@debug "D3R client for $id ready"
while true
try
data = String(WebSockets.receive(sock))
@debug "D3R client for $id received: $data"
if id == myid()
#= FIXME
if config_updated[]
config_updated[] = false
WebSockets.send(sock, JSON3.write((;cmd="config", payload=sanitize(config))))
end
=#
if seek_store !== nothing
if data == "fulldata"
raw_logs = seek_store[0:typemax(UInt64)]
logs = Dict{Symbol,Vector{Any}}()
for (idx,key) in enumerate(Tables.columnnames(raw_logs))
logs[key] = Tables.columns(raw_logs)[idx]
end
WebSockets.send(sock, JSON3.write((;cmd="data", payload=sanitize(logs))))
continue
end
m = match(r"seek\(([0-9]*),([0-9]*)\)", data)
if m !== nothing
ts_start, ts_stop = parse.(Ref(UInt64), m.captures)
raw_logs = seek_store[ts_start:ts_stop]
logs = Dict{Symbol,Vector{Any}}()
for (idx,key) in enumerate(Tables.columnnames(raw_logs))
logs[key] = Tables.columns(raw_logs)[idx]
end
WebSockets.send(sock, JSON3.write((;cmd="data", payload=sanitize(logs))))
continue
end
end
if data == "data"
WebSockets.send(sock, JSON3.write((;cmd="data", payload=sanitize(D3R_LOGS[port]))))
end
else
@debug "D3R client sending to forwarder: $data"
WebSockets.send(fsock, data)
end
catch err
if err isa WebSockets.WebSocketError && err.message isa WebSockets.CloseFrameBody
idx = findfirst(x->x==sock, D3R_CLIENT_SOCKETS[port][id])
if idx !== nothing
deleteat!(D3R_CLIENT_SOCKETS[port][id], idx)
end
# Force-close client and forwarder
@async close(sock)
@async close(fsock)
break
end
@error "D3R client for $id error!" exception=(err,catch_backtrace())
rethrow(err)
end
end
@debug "D3R client for $id closed"
end
function TimespanLogging.Events.creation_hook(d3r::D3Renderer, log)
for sock in get!(()->[], get!(()->Dict{Int,Vector{Any}}(), D3R_CLIENT_SOCKETS, d3r.port), myid())
try
WebSockets.send(sock, JSON3.write((;cmd="add", payload=sanitize(log))))
catch err
if err isa WebSockets.WebSocketError && err.message isa WebSockets.CloseFrameBody
continue
end
rethrow(err)
end
end
end
function TimespanLogging.Events.deletion_hook(d3r::D3Renderer, idx)
for sock in get!(()->[], get!(()->Dict{Int,Vector{Any}}(), D3R_CLIENT_SOCKETS, d3r.port), myid())
try
WebSockets.send(sock, JSON3.write((;cmd="delete", payload=idx)))
catch err
if err isa WebSockets.WebSocketError && err.message isa WebSockets.CloseFrameBody
continue
end
rethrow(err)
end
end
end
function worker_host_port(id::Int, port::Int, port_range::UnitRange)
worker_host = get!(D3R_WORKER_HOST_MAP, port) do
worker_host, worker_port = remotecall_fetch(id, port) do port
host = gethostname()
if isempty(host)
host = getipaddr()
end
(host, get_actual_port(port, port_range))
end
D3R_WORKER_PORT_MAP[port] = worker_port
worker_host
end
worker_port = D3R_WORKER_PORT_MAP[port]
return worker_host, worker_port
end
function get_actual_port(port::Int, port_range::UnitRange)
get!(D3R_ACTUAL_PORT, port) do
# Check if the requested port is available
# If not, pick another port in the provided range
actual_port = port
while true
port_available = try
close(listen(actual_port))
true
catch err
err isa Base.IOError || rethrow(err)
if err.code == -98
false
else
rethrow(err)
end
end
if port_available
if port != actual_port && myid() == 1
@warn "Port $port not available, serving on $actual_port"
end
break
end
actual_port = rand(port_range)
end
actual_port
end
end