Skip to content

Commit

Permalink
Add cli commands 'save', 'show', and 'fix'
Browse files Browse the repository at this point in the history
'save' will save the log data to disk

'show' will dump data to std output and can filter by stream

'fix' intention is to check and fix a log with issues
  that prevent it from being served by the server. Currently it will
  check the index and metadata and regenerate them if necessary.
  This is useful when streaming from a "live" data source
  that may not send metadata.

TODO:
 - save should store in same format data was sent.
 - testing for all commands
 - docs for all commands
  • Loading branch information
twojtasz committed May 18, 2020
1 parent a4ca3f7 commit c6633ff
Show file tree
Hide file tree
Showing 8 changed files with 475 additions and 0 deletions.
39 changes: 39 additions & 0 deletions modules/cli/src/cmds/fix.js
@@ -0,0 +1,39 @@
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint no-console: ["error", { allow: ["log"] }] */
/* eslint-env node, browser */

import {FixXVIZ} from '../fix';

export function fixArgs(inArgs) {
return inArgs.command(
'fix [source]',
'Fix XVIZ will regenerate the index file and minimal metadata if not present',
args => {},
args => {
command(args);
}
);
}

/**
* Validate the content and order of XVIZ messages
*/
export default function command(args) {
const fix = new FixXVIZ(args);

// Only works with files, not webSocket
fix.fix();
}
49 changes: 49 additions & 0 deletions modules/cli/src/cmds/save.js
@@ -0,0 +1,49 @@
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint no-console: ["error", { allow: ["log"] }] */
/* eslint-env node, browser */

import {addDataArgs} from '../commonargs';
import {SaveXVIZ} from '../save';
import {openSource} from '../connect';

export function saveArgs(inArgs) {
return inArgs.command(
'save <host> [log]',
'Save XVIZ data to disk',
args => {
addDataArgs(args);
args.options('output', {
alias: 'o',
describe: 'Directory to save the messages'
});
},
args => {
command(args);
}
);
}

/**
* Validate the content and order of XVIZ messages
*/
export default function command(args) {
// The middleware stack handle all messages
const save = new SaveXVIZ({output: args.output});
const stack = [save];

// Everything async from here...
openSource(args, stack);
}
58 changes: 58 additions & 0 deletions modules/cli/src/cmds/show.js
@@ -0,0 +1,58 @@
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint no-console: ["error", { allow: ["log"] }] */
/* eslint-env node, browser */

import {addDataArgs, addMetadataArg, addCondensedArg, addStreamArg} from '../commonargs';
import {ShowXVIZ, ShowMode} from '../show';
import {openSource} from '../connect';

export function showArgs(inArgs) {
return inArgs.command(
'show <host> [log]',
'Print XVIZ data to stdout',
args => {
addDataArgs(args);
addMetadataArg(args, 'Just fetch metadata and exit');
addCondensedArg(args, 'Display summary information');
addStreamArg(args, 'Specify specific streams to show');
},
args => {
command(args);
}
);
}

/**
* Validate the content and order of XVIZ messages
*/
export default function command(args) {
// Determine how verbose the user wants their output
const showMode = (() => {
if (args.oneline) {
return ShowMode.ONELINE;
} else if (args.condensed) {
return ShowMode.CONDENSED;
}
return ShowMode.ALL;
})();

// The middleware stack handle all messages
const show = new ShowXVIZ({mode: showMode, stream: args.stream});
const stack = [show];

// Everything async from here...
openSource(args, stack);
}
6 changes: 6 additions & 0 deletions modules/cli/src/commonargs.js
Expand Up @@ -44,3 +44,9 @@ export function addCondensedArg(args, help) {
describe: help
});
}

export function addStreamArg(args, help) {
args.options('stream', {
describe: help
});
}
129 changes: 129 additions & 0 deletions modules/cli/src/fix.js
@@ -0,0 +1,129 @@
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint-env node, browser */
/* eslint-disable camelcase */
import {isPath} from './connect';

import {FileSource, FileSink} from '@xviz/io/node';
// TODO: replace this with XVIZReaderFactory
import {XVIZJSONReader, XVIZBinaryReader, XVIZProtobufReader, XVIZData} from '@xviz/io';

/**
* XVIZ command that correct issues with an XVIZ log
* - create index file
* - if no metadata file, create one
* - minimal
* - populate streams
*/
export class FixXVIZ {
constructor(options = {}) {
// eslint-disable-next-line no-console
this.log = options.log || console.log;
this.source = options.source;
}

_fixIndex(reader) {
this.log('Reconstructing index file...');
const sink = new FileSink(this.source);
let n = 0;
const timing = [];

while (reader.checkMessage(n)) {
const msg = reader.readMessage(n);
const idx = n;
n++;

const data = new XVIZData(msg);
// TODO(twojtasz): fix protobuf data.type determination
if (data.type === 'state_update') {
const message = data.message().data;
const length = message.updates.length;
timing.push([
message.updates[0].timestamp,
message.updates[length - 1].timestamp,
idx,
`${idx + 2}-frame`
]);
}
}

if (timing.length > 0) {
const index = {
startTime: timing[0][0],
endTime: timing[timing.length - 1][0],
timing
};

sink.writeSync('0-frame.json', JSON.stringify(index));
this.log('Index file written');
} else {
this.log('Index timing information not found');
}
}

_fixMetadata(reader) {
this.log('Writing minimal metadata');

const minimalMetadata = {
type: 'xviz/metadata',
data: {
version: '2.0.0'
}
};

const timeRange = reader.timeRange();

if (!timeRange.startTime || !timeRange.endTime) {
throw new Error(
'Failed to fix metadata due to missing index with startTime and endTime entries'
);
}
minimalMetadata.data.log_info = {
start_time: timeRange.startTime,
end_time: timeRange.endTime
};

const sink = new FileSink(this.source);
sink.writeSync('1-frame.json', JSON.stringify(minimalMetadata));
}

fix() {
// this.log(`${header} ${data}`);
if (isPath(this.source)) {
const source = new FileSource(this.source);

const pb_reader = new XVIZProtobufReader(source);
const json_reader = new XVIZJSONReader(source);
const glb_reader = new XVIZBinaryReader(source);
const reader = [pb_reader, json_reader, glb_reader].find(rdr => rdr.checkMessage(0));

if (!reader) {
this.log(`The path ${this.source} is not valid for current supported XVIZ Readers.`);
} else {
// Check for messageCount, and if undefined write out index.
if (reader.messageCount() === undefined) {
this._fixIndex(reader);
}

if (reader.readMetadata() === undefined) {
this._fixMetadata(reader);
}
reader.close();
}
} else {
this.log(`The fix cmd only works with paths and ${this.source} is not a valid path.`);
}
}
}
6 changes: 6 additions & 0 deletions modules/cli/src/index.js
Expand Up @@ -22,6 +22,9 @@ import {WebSocketInterface} from './websocket';
// Pull in sub commands
import {validateArgs} from './cmds/validate';
import {dumpArgs} from './cmds/dump';
import {showArgs} from './cmds/show';
import {saveArgs} from './cmds/save';
import {fixArgs} from './cmds/fix';

/**
* Main function for entire tool
Expand All @@ -31,6 +34,9 @@ function main() {

args = dumpArgs(args);
args = validateArgs(args);
args = showArgs(args);
args = saveArgs(args);
args = fixArgs(args);

return args.argv;
}
Expand Down
62 changes: 62 additions & 0 deletions modules/cli/src/save.js
@@ -0,0 +1,62 @@
// Copyright (c) 2019 Uber Technologies, Inc. //
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint-env node, browser */
/* eslint-disable no-console */
import fs from 'fs';
import {XVIZ_FORMAT, XVIZFormatWriter} from '@xviz/io';
import {XVIZData} from '@xviz/io';
import {FileSink} from '@xviz/io/node';

/**
* XVIZ middleware that echos all messages, with configurable level of
* details.
*/
export class SaveXVIZ {
constructor(options = {}) {
// eslint-disable-next-line no-console
this.log = options.log || console.log;
this.output = options.output;

if (!fs.existsSync(this.output)) {
fs.mkdirSync(this.output);
}

this.format = XVIZ_FORMAT.BINARY_PBE;
this.sink = new FileSink(this.output);
this.writer = new XVIZFormatWriter(this.sink, {format: this.format});
this.count = 0;

process.on('SIGINT', () => {
console.log('Aborting, writing index file.');
this.writer.close();
});
}

onMetadata(msg) {
const data = new XVIZData(msg);
this.writer.writeMetadata(data);
this.log('[METADATA]');
}

onStateUpdate(msg) {
const data = new XVIZData(msg);
this.writer.writeMessage(this.count, data);
this.log('[Msg]', this.count);
this.count++;
}

onClose() {
this.writer.close();
}
}

0 comments on commit c6633ff

Please sign in to comment.