-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
dashboard.tsx
646 lines (585 loc) · 15.9 KB
/
dashboard.tsx
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
import { IFrame, MainAreaWidget, ToolbarButton } from '@jupyterlab/apputils';
import { PageConfig, URLExt } from '@jupyterlab/coreutils';
import { ServerConnection } from '@jupyterlab/services';
import { searchIcon } from '@jupyterlab/ui-components';
import { JSONExt, JSONObject } from '@lumino/coreutils';
import { Poll } from '@lumino/polling';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget, PanelLayout } from '@lumino/widgets';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
/**
* Info for a a given dashboard URL.
*/
export type DashboardURLInfo = {
/**
* The user provided url in the search box.
*/
url: string;
/**
* Whether there is a live dashboard at the URL.
*/
isActive: boolean;
/**
* A new URL to use after redirects or proxies.
*/
effectiveUrl?: string;
/**
* A mapping from individual dashboard plot names to their sub-path.
*/
plots: { [name: string]: string };
};
/**
* A class for hosting a Dask dashboard in an iframe.
*/
export class DaskDashboard extends MainAreaWidget<IFrame> {
/**
* Construct a new dashboard widget.
*/
constructor() {
super({
// Disable allow some iframe extensions to let server requests
// and scripts to execute in the bokeh server context.
// This is unsafe, but we presumably trust the code in the bokeh server.
content: new IFrame({ sandbox: ['allow-scripts', 'allow-same-origin'] })
});
this._inactivePanel = Private.createInactivePanel();
this.content.node.appendChild(this._inactivePanel);
this.update();
}
/**
* The current dashboard item for the widget.
*/
get item(): IDashboardItem | null {
return this._item;
}
set item(value: IDashboardItem | null) {
if (JSONExt.deepEqual(value, this._item)) {
return;
}
this._item = value;
this.update();
}
/**
* The current dashboard URL for the widget.
*/
get dashboardUrl(): string {
return this._dashboardUrl;
}
set dashboardUrl(value: string) {
if (value === this._dashboardUrl) {
return;
}
this._dashboardUrl = Private.normalizeDashboardUrl(value);
this.update();
}
/**
* Whether the dashboard is active. When inactive,
* it will show a placeholder panel.
*/
get active(): boolean {
return this._active;
}
set active(value: boolean) {
if (value === this._active) {
return;
}
this._active = value;
this.update();
}
/**
* Handle an update request to the dashboard panel.
*/
protected onUpdateRequest(): void {
// If there is nothing to show, empty the iframe URL and
// show the inactive panel.
if (!this.item || !this.dashboardUrl || !this.active) {
this.content.url = '';
this._inactivePanel.style.display = '';
return;
}
// Make sure the inactive panel is hidden
this._inactivePanel.style.display = 'none';
this.content.url = URLExt.join(this.dashboardUrl, this.item.route);
}
private _item: IDashboardItem | null = null;
private _dashboardUrl: string = '';
private _active: boolean = false;
private _inactivePanel: HTMLElement;
}
/**
* A widget for hosting Dask dashboard launchers.
*/
export class DaskDashboardLauncher extends Widget {
/**
* Create a new Dask sidebar.
*/
constructor(options: DaskDashboardLauncher.IOptions) {
super();
let layout = (this.layout = new PanelLayout());
this._dashboard = new Widget();
this._serverSettings = ServerConnection.makeSettings();
this._input = new URLInput(this._serverSettings, options.linkFinder);
layout.addWidget(this._input);
layout.addWidget(this._dashboard);
this.addClass('dask-DaskDashboardLauncher');
this._items = options.items || [];
this._launchItem = options.launchItem;
this._input.urlInfoChanged.connect(this._updateLinks, this);
}
private _updateLinks(_: URLInput, change: URLInput.IChangedArgs): void {
if (!change.newValue.isActive) {
this.update();
return;
}
const result = Private.getDashboardPlots(change.newValue);
this._items = result;
this.update();
}
/**
* The list of dashboard items which can be launched.
*/
get items(): IDashboardItem[] {
return this._items;
}
/**
* Get the URL input widget.
*/
get input(): URLInput {
return this._input;
}
/**
* Handle an update request.
*/
protected onUpdateRequest(): void {
// Don't bother if the sidebar is not visible
if (!this.isVisible) {
return;
}
ReactDOM.render(
<DashboardListing
launchItem={this._launchItem}
isEnabled={this.input.urlInfo.isActive}
items={this._items}
/>,
this._dashboard.node
);
}
/**
* Rerender after showing.
*/
protected onAfterShow(): void {
this.update();
}
private _dashboard: Widget;
private _input: URLInput;
private _launchItem: (item: IDashboardItem) => void;
private _items: IDashboardItem[];
private _serverSettings: ServerConnection.ISettings;
}
/**
* A widget for hosting a url input element.
*/
export class URLInput extends Widget {
/**
* Construct a new input element.
*/
constructor(
serverSettings: ServerConnection.ISettings,
linkFinder?: () => Promise<string>
) {
super();
this.addClass('dask-URLInput');
const layout = (this.layout = new PanelLayout());
const wrapper = new Widget();
wrapper.addClass('dask-URLInput-wrapper');
this._input = document.createElement('input');
this._input.placeholder = 'DASK DASHBOARD URL';
wrapper.node.appendChild(this._input);
layout.addWidget(wrapper);
this._serverSettings = serverSettings;
if (linkFinder) {
const findButton = new ToolbarButton({
icon: searchIcon,
onClick: async () => {
let link = await linkFinder();
if (link) {
this.url = link;
}
},
tooltip: 'Auto-detect dashboard URL'
});
layout.addWidget(findButton);
}
this._startUrlCheckTimer();
}
/**
* The underlying input value.
*/
get input(): HTMLInputElement {
return this._input;
}
/**
* The base url for the dask webserver.
*
* #### Notes
* Setting this value will result in a urlChanged
* signal being emitted, but it will happen asynchronously,
* as it first checks to see whether the url is pointing
* at a valid dask dashboard server.
*/
set url(newValue: string) {
this._input.value = newValue;
const oldValue = this._urlInfo;
if (newValue === oldValue.url) {
return;
}
void Private.testDaskDashboard(newValue, this._serverSettings).then(
result => {
this._urlInfo = result;
this._urlChanged.emit({ oldValue, newValue: result });
this._input.blur();
this.update();
if (!result) {
console.warn(
`${newValue} does not appear to host a valid Dask dashboard`
);
}
}
);
}
/**
* The URL information for the dashboard. This should be set via the url setter,
* but read through this getter, as it brings in some extra information.
*/
get urlInfo(): DashboardURLInfo {
return this._urlInfo;
}
/**
* A signal emitted when the url changes.
*/
get urlInfoChanged(): ISignal<this, URLInput.IChangedArgs> {
return this._urlChanged;
}
/**
* Dispose of the resources held by the dashboard.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._poll.dispose();
super.dispose();
}
/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the widget.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the main area widget's node. It should
* not be called directly by user code.
*/
handleEvent(event: KeyboardEvent): void {
switch (event.type) {
case 'keydown':
switch (event.keyCode) {
case 13: // Enter
event.stopPropagation();
event.preventDefault();
this.url = this._input.value;
break;
default:
break;
}
break;
default:
break;
}
}
/**
* Handle `after-attach` messages for the widget.
*/
protected onAfterAttach(): void {
this._input.addEventListener('keydown', this, true);
}
/**
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(): void {
this._input.removeEventListener('keydown', this, true);
}
/**
* Periodically poll for valid url.
*/
private _startUrlCheckTimer(): void {
this._poll = new Poll({
factory: async () => {
const urlInfo = this._urlInfo;
// Don't bother checking if there is no url.
if (!urlInfo.url) {
return;
}
const result = await Private.testDaskDashboard(
urlInfo.url,
this._serverSettings
);
if (!result.isActive && urlInfo.isActive) {
console.warn(
`The connection to dask dashboard ${urlInfo.url} has been lost`
);
}
if (!JSONExt.deepEqual(result, urlInfo)) {
this._urlInfo = result;
this._urlChanged.emit({
oldValue: urlInfo,
newValue: result
});
}
// Throw an error if the connection died. If we don't raise/reject here,
// then the poll won't back off.
if (!result.isActive) {
throw Error(`No connection to ${urlInfo.url}`);
}
},
frequency: { interval: 4 * 1000, backoff: true, max: 120 * 1000 },
standby: 'when-hidden'
});
// When the URL changes, refresh the poll and backoff.
this._urlChanged.connect(() => this._poll.refresh(), this);
}
private _urlChanged = new Signal<this, URLInput.IChangedArgs>(this);
private _urlInfo: DashboardURLInfo = { isActive: false, url: '', plots: {} };
private _input: HTMLInputElement;
private _poll: Poll;
private _serverSettings: ServerConnection.ISettings;
}
/**
* A namespace for URLInput statics.
*/
export namespace URLInput {
/**
* Changed args for the url.
*/
export interface IChangedArgs {
/**
* The old url info.
*/
oldValue: DashboardURLInfo;
/**
* The new url info.
*/
newValue: DashboardURLInfo;
}
}
/**
* A namespace for DaskDashboardLauncher statics.
*/
export namespace DaskDashboardLauncher {
/**
* Options for the constructor.
*/
export interface IOptions {
/**
* A function that attempts to find a link to
* a dask bokeh server in the current application
* context.
*/
linkFinder?: () => Promise<string>;
/**
* A callback to launch a dashboard item.
*/
launchItem: (item: IDashboardItem) => void;
/**
* A list of items for the launcher.
*/
items?: IDashboardItem[];
}
}
/**
* A React component for a launcher button listing.
*/
function DashboardListing(props: IDashboardListingProps) {
if (!props.isEnabled) {
return (
<div className="dask-DashboardListing-inactive">
<span className="dask-DashboardListing-inactive-title">
Dashboard not connected
</span>
<span className="dask-DashboardListing-inactive-detail">
To connect, paste a dashboard URL in the box above, or create a new
Dask cluster with the cluster manager below. If you are still unable
to connect, check your network setup.
</span>
</div>
);
}
const items = [...props.items].sort((e1, e2) =>
e1.label <= e2.label ? -1 : 1
);
const listing = items.map(item => {
return (
<li className="dask-DashboardListing-item" key={item.route}>
<button
className="jp-mod-styled jp-mod-accept"
value={item.label}
disabled={!props.isEnabled}
onClick={() => props.launchItem(item)}
>
{item.label}
</button>
</li>
);
});
// Return the JSX component.
return (
<div>
<ul className="dask-DashboardListing-list">{listing}</ul>
</div>
);
}
/**
* Props for the dashboard listing component.
*/
export interface IDashboardListingProps {
/**
* A list of dashboard items to render.
*/
items: IDashboardItem[];
/**
* A callback to launch a dashboard item.
*/
launchItem: (item: IDashboardItem) => void;
/**
* Whether the items should be enabled.
*/
isEnabled: boolean;
}
/**
* An interface dashboard launcher item.
*/
export interface IDashboardItem extends JSONObject {
/**
* The route to add the the base url.
*/
route: string;
/**
* The display label for the item.
*/
label: string;
}
/**
* A namespace for private functionality.
*/
namespace Private {
/**
* Optionally remove a `status` route from a dashboard url.
*/
export function normalizeDashboardUrl(url: string, baseUrl = ''): string {
if (isLocal(url)) {
if (!baseUrl) {
baseUrl = PageConfig.getBaseUrl();
}
// If the path-portion of the baseUrl has been included,
// strip that off.
const tmp = new URL(baseUrl);
if (url.startsWith(tmp.pathname)) {
url = url.slice(tmp.pathname.length);
}
// Fully qualify the local URL to remove any relative-path confusion.
url = baseUrl + url;
}
// If 'status' has been included at the end, strip it.
if (url.endsWith('status')) {
url = url.slice(0, -'status'.length);
} else if (url.endsWith('status/')) {
url = url.slice(0, -'status/'.length);
}
return url;
}
/**
* Return the json result of /individual-plots.json
*/
export function getDashboardPlots(info: DashboardURLInfo): IDashboardItem[] {
const plots: IDashboardItem[] = [];
for (let key in info.plots) {
const label = key.replace('Individual ', '');
const route = String(info.plots[key]);
const plot = { route: route, label: label, key: label };
plots.push(plot);
}
return plots;
}
/**
* Test whether a given URL hosts a dask dashboard.
*/
export async function testDaskDashboard(
url: string,
settings: ServerConnection.ISettings
): Promise<DashboardURLInfo> {
url = normalizeDashboardUrl(url, settings.baseUrl);
// If this is a url that we are proxying under the notebook server,
// check for the individual charts directly.
if (url.indexOf(settings.baseUrl) === 0) {
return ServerConnection.makeRequest(
URLExt.join(url, 'individual-plots.json'),
{},
settings
)
.then(async response => {
if (response.status === 200) {
const plots = (await response.json()) as { [plot: string]: string };
return {
url,
isActive: true,
plots
};
} else {
return {
url,
isActive: false,
plots: {}
};
}
})
.catch(() => {
return {
url,
isActive: false,
plots: {}
};
});
}
const response = await ServerConnection.makeRequest(
URLExt.join(
settings.baseUrl,
'dask',
'dashboard-check',
encodeURIComponent(url)
),
{},
settings
);
const info = (await response.json()) as DashboardURLInfo;
return info;
}
export function createInactivePanel(): HTMLElement {
const panel = document.createElement('div');
panel.className = 'dask-DaskDashboard-inactive';
return panel;
}
/**
* Test whether the url is a local url.
*
* #### Notes
* This function returns `false` for any fully qualified url, including
* `data:`, `file:`, and `//` protocol URLs.
*/
export function isLocal(url: string): boolean {
const { protocol } = URLExt.parse(url);
return (
url.toLowerCase().indexOf(protocol!) !== 0 && url.indexOf('//') !== 0
);
}
}