diff --git a/.gitignore b/.gitignore index 303335e..82cee7b 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ logs results npm-debug.log + +.dogapirc diff --git a/README.md b/README.md index 26d7293..86ac385 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,6 @@ Keys can be found at: https://app.datadoghq.com/account/settings#api The keys can be provided either as constructor parameters when creating an instance of `dogapi` as `api_key` and `app_key` or as the environment variables `DD_API_KEY` and `DD_APP_KEY`. -**Constructor parameters:** ```javascript var dogapi = require('dogapi'); @@ -37,134 +36,18 @@ var options = { app_key: 'YOUR_KEY_HERE', }; -var app = new dogapi(options); +dogapi.initialize(options); ``` -**Environment Variables:** -```bash -DD_API_KEY=YOUR_KEY_HERE DD_APP_KEY=YOUR_KEY_HERE node app.js -``` - -## API - -`dogapi` implements all available functions in the official datadog api, http://docs.datadoghq.com/api/. - -* `dogapi.constants.STATUSES` - * `OK`, `WARNING`, `CRITICAL`, `UNKNOWN` -* `dogapi.stream(start, end, [[filter], callback])` - * function used to retrieve all events that have occured between -* `dogapi.polling_stream(interval, [[filter], callback])` - * function used to continuously call `stream` for new events -* `dogapi.get_event(event_id, callback)` - * method used to retrieve a single event's data -* `dogapi.add_event(event, callback)` - * method used to add a new event to datadog -* `dogapi.add_comment(comment, [callback])` - * method used to add a new comment to datadog -* `dogapi.update_comment(comment_id, comment, callback)` - * method used to update a comment that already exists in datadog -* `dogapi.delete_comment(comment_id, callback)` - * method used to remove a comment from datadog -* `dogapi.add_alert(alert, [callback])` - * add a new alert to datadog -* `dogapi.update_alert(alert_id, alert, [callback])` - * update an existing alert -* `dogapi.get_alert(alert_id, [callback])` - * get the details of an alert from the given id -* `dogapi.delete_alert(alert_id, [callback])` - * delete the given alert from datadog -* `dogapi.get_all_alerts([callback])` - * get the details of all alerts in datadog -* `dogapi.mute_alerts([callback])` - * mute all alerts -* `dogapi.unmute_alerts([callback])` - * unmute all alerts -* `dogapi.get_dashboard(dash_id, [callback])` - * method to get a single dashboard information -* `dogapi.get_all_dashboards([callback])` - * method to retrieve all dashboards in datadog -* `dogapi.create_dashboard(dashboard, [callback])` - * method used to create a new dashboard in datadog -* `dogapi.update_dashboard(dash_id, dashboard, [callback])` - * method used to update the dashboard with the provided `dash_id` -* `dogapi.delete_dashboard(dash_id, [callback])` - * method to remove a dashboard from datadog -* `dogapi.get_screenboard(screen_id, [callback])` - * method to get a single screenboard information -* `dogapi.get_all_screenboards([callback])` - * method to retrieve all screenboards in datadog -* `dogapi.create_screenboard(screenboard, [callback])` - * method used to create a new screenboard in datadog -* `dogapi.update_screenboard(screen_id, screenboard, [callback])` - * method used to update the screenboard with the provided `screen_id` -* `dogapi.delete_screenboard(screen_id, [callback])` - * method to remove a screenboard from datadog -* `dogapi.search(query, [callback])` - * method used to query the api for `metrics` or `hosts` -* `dogapi.add_metric(metric, [callback])` - * method used to add a single metric to datadog -* `dogapi.add_metrics(metrics, [callback])` - * method used to add multiple metrics to datadog -* `dogapi.all_tags([[source], callback])` - * method to get all the tags in datadog -* `dogapi.host_tags(host, [[source], callback])` - * method to get the tags associated with a given `host` -* `dogapi.host_tags_by_source(host, [[source], callback])` - * method to return the tags associated with a host, arranged by source -* `dogapi.add_tags(host, tags, [[source], callback])` - * add new tags to given `host` -* `dogapi.update_tags(host, tags, [[source], callback])` - * update the tags associated with the given `host` -* `dogapi.detach_tags(host, [[source], callback])` - * method to remove tags for a given `host` -* `dogapi.add_snapshot(snapshot, [callback])` - * method used to take a snapshot of a datadog graph -* `dogapi.add_snapshot_from_def(snapshot, [callback])` - * method used to take a snapshot of a datadog graph -* `dogapi.snapshot_status(snapshot_url, [callback])` - * method used to check the status of a datadog snapshot -* `dogapi.service_check(status, check, host, [[extra], [callback]])` - * method used to post a new service check (see `dogapi.constants.STATUSES`) -* `dogapi.schedule_downtime(scope, [options], [callback])` - * method to schedule a new downtime -* `dogapi.update_downtime(downtime_id, [options], [callback])` - * method to update an existing downtime -* `dogapi.cancel_downtime(downtime_id, [callback])` - * method to cancel an existing downtime -* `dogapi.get_downtime(downtime_id, [callback])` - * method to get an existing downtime -* `dogapi.get_all_downtimes([current_only], [callback])` - * method to get all downtimes - -## Sample Usage: - -**Example:** get all events since this time yesterday: -```javascript -var dogapi = require('dogapi'); +## API Documentation -var options = { - api_key: 'YOUR_KEY_HERE', - app_key: 'YOUR KEY_HERE', -}; - -var api = new dogapi(options); +https://brettlangdon.github.io/node-dogapi -var end = parseInt(new Date().getTime() / 1000); -var start = end - 86400; -api.stream(start, end, function(error, result, status_code){ - if(error){ - console.log('Error: ', error); - console.log('Status Code: ', status_code); - return; - } - - result['events'].forEach(function(event){ - console.log(event['id'] + ': ' + event['title']); - }); -}); -``` +## TODO +- [ ] Add tests +- [ ] Add parameter validation (especially for dashboards) ## License diff --git a/bin/dogapi b/bin/dogapi new file mode 100755 index 0000000..ad28513 --- /dev/null +++ b/bin/dogapi @@ -0,0 +1,79 @@ +#!/usr/bin/env node +var dogapi = require("../"); +var minimist = require("minimist"); +var rc = require("rc"); + +var config = rc("dogapi", { + api_key: null, + app_key: null +}); +dogapi.initialize(config); + +var usage = [ + "Usage:", + " dogapi --help", + " dogapi --help", + " dogapi --version", + " dogapi now", + " dogapi past ", + " dogapi future " +]; +var help = []; +for(var key in dogapi){ + if(!dogapi.hasOwnProperty(key)){ + continue; + } else if(!dogapi[key].hasOwnProperty("getUsage") || typeof dogapi[key].getUsage !== "function"){ + continue; + } else if(!dogapi[key].hasOwnProperty("handleCli") || typeof dogapi[key].handleCli !== "function"){ + continue; + } + usage = usage.concat(dogapi[key].getUsage()); + + if(dogapi[key].hasOwnProperty("getHelp") && typeof dogapi[key].getHelp === "function"){ + help = help.concat([""], dogapi[key].getHelp()); + } +} + +usage = usage.concat(help); +usage = usage.join("\r\n"); +var args = minimist(process.argv); + +var command = args._[2]; +var subcommand = args._[3]; + +// this is the one unusual case +if(command === "servicecheck"){ + command = "serviceCheck"; +} + +if(command === "now"){ + console.log(dogapi.now()); +} else if(command === "past" && args._.length > 3){ + console.log(dogapi.now() - parseInt(args._[args._.length - 1])); +} else if(command === "future" && args._.length > 3){ + console.log(dogapi.now() + parseInt(args._[args._.length - 1])); +} else if(dogapi.hasOwnProperty(command)){ + if(subcommand){ + dogapi[command].handleCli(subcommand, args, function(err, res){ + if(err){ + console.error(JSON.stringify(err, null, ' ')); + process.exit(1); + } else { + if(res === ""){ + res = "success"; + } + console.log(JSON.stringify(res, null, ' ')); + } + }); + } else { + var commandUsage = ["Usage:"].concat(dogapi[command].getUsage()); + if(dogapi[command].hasOwnProperty("getHelp") && typeof dogapi[command].getHelp === "function"){ + commandUsage = commandUsage.concat(["\r\n"], dogapi[command].getHelp()); + } + console.log(commandUsage.join("\r\n").replace(/\$\{command\}/g, " dogapi")); + } +} else if(args.version){ + console.log(require("../package.json").version); +} else { + console.log(usage); +} diff --git a/docs/create.js b/docs/create.js new file mode 100644 index 0000000..e633180 --- /dev/null +++ b/docs/create.js @@ -0,0 +1,140 @@ +var path = require("path"); + +var docast = require("docast"); +var glob = require("glob"); +var marked = require("marked"); +var yaml = require("js-yaml"); + +marked.setOptions({ + gfm: true, + sanitize: true, + pedantic: false +}); + +var above = path.resolve(__dirname, "../lib/"); +var match = above + "/**/*.js"; + +var docs = {}; +glob(match, function(er, files){ + files.forEach(function(file){ + var comments = docast.parse(file); + for(var i = 0; i < comments.length; ++i){ + var comment = comments[i]; + try{ + comment.doc = yaml.safeLoad(comment.doc); + if(!comment.doc.hasOwnProperty("section")){ + continue; + } + if(!docs[comment.doc.section]){ + docs[comment.doc.section] = {}; + } + + for(var key in comment.doc.params){ + if(comment.doc.params.hasOwnProperty(key)){ + comment.doc.params[key] = comment.doc.params[key].replace(/optional/g, "_optional_"); + comment.doc.params[key] = marked(comment.doc.params[key]); + } + } + if(comment.doc.hasOwnProperty("example")){ + comment.doc.example = marked(comment.doc.example); + } else { + comment.doc.example = ""; + } + + if(comment.doc.hasOwnProperty("comment")){ + comment.doc.comment = marked(comment.doc.comment); + } else { + comment.doc.comment = ""; + } + + docs[comment.doc.section][comment.name] = comment.doc; + } catch(e){} + } + }); + + var output = "\n\n\n"; + output += "\n"; + output += "\n\n"; + output += "\n"; + output += "\n"; + output += "\n\n"; + output += "Jump To Top\n"; + output += "
\n"; + output += "
\n"; + output += "
\n"; + output += "

Node Dogapi

\n"; + output += "
    \n"; + for(var section in docs){ + if(!docs.hasOwnProperty(section)){ + continue; + } + output += "
  • " + section + "\n"; + output += "
  • \n"; + } + output += "
\n
\n
\n"; + + for(var section in docs){ + if(!docs.hasOwnProperty(section)){ + continue; + } + methods = docs[section]; + + output += "
\n"; + output += "
\n

" + section + "

\n"; + + output += "
    \n"; + for(var name in methods){ + if(!methods.hasOwnProperty(name)){ + continue; + } + output += "
  • " + name + "
  • \n"; + } + + output += "
\n"; + + for(var name in methods){ + if(!methods.hasOwnProperty(name)){ + continue; + } + doc = methods[name]; + + var className = section + "-" + name; + output += "
\n"; + + var definition = name + "("; + if(doc.params && typeof doc.params === "object"){ + definition += Object.keys(doc.params).join(", "); + } + definition += ")"; + + output += "

" + definition + "

\n"; + output += "
\n"; + output += doc.comment; + if(doc.params){ + output += "

Parameters:

\n"; + output += "
\n"; + for(var param in doc.params){ + if(!doc.params.hasOwnProperty(param)){ + continue; + } + var comment = doc.params[param]; + output += "
" + param + "
\n"; + output += "
" + comment + "
\n"; + } + output += "
\n"; + } + output += "
\n"; + + output += "
\n"; + output += doc.example; + output += "
\n"; + + output += "
\n"; + } + output += "
\n"; + } + output += "
\n"; + output += "\"Fork"; + output += ""; + console.log(output); +}); diff --git a/index.html b/index.html new file mode 100644 index 0000000..1846c11 --- /dev/null +++ b/index.html @@ -0,0 +1,1805 @@ + + + + + + + + + + +Jump To Top +
+
+
+

Node Dogapi

+ +
+
+
+
+

comment

+ +
+

create(message, properties, callback)

+
+

create a new comment

+

Parameters:

+
+
message
+

the message of the comment

+
+
properties
+

optional, an object containing any of the following

+
    +
  • handle: the handle to associate the comment with (e.g. "user@domain.com")
  • +
  • related_event_id: the event to associate the comment with
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.comment.create("a comment message", function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

update(commentId, message, handle, callback)

+
+

update an existing comment

+

Parameters:

+
+
commentId
+

the id of the comment to update

+
+
message
+

the message of the comment

+
+
handle
+

optional, the handle to associate the comment with (e.g. "user@domain.com")

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.comment.update(1234, "new message", function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

remove(commentId, callback)

+
+

remove a comment

+

Parameters:

+
+
commentId
+

the id of the comment to remove

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.comment.remove(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

downtime

+ +
+

create(scope, properties, callback)

+
+

schedule a new downtime

+

Parameters:

+
+
scope
+

string scope that the downtime should apply to (e.g. "env:staging")

+
+
properties
+

optional, an object containing any of the following

+
    +
  • start: POSIX timestamp for when the downtime should start
  • +
  • end: POSIX timestamp for when the downtime should end
  • +
  • message: a string message to accompany the downtime
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.downtime.create("env:staging", function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

update(downtimeId, properties, callback)

+
+

update an existing downtime

+

Parameters:

+
+
downtimeId
+

the id the downtie to update

+
+
properties
+

optional, an object containing any of the following

+
    +
  • scope: the scope the downtime should be changed to (e.g. "env:staging")
  • +
  • start: POSIX timestamp for when the downtime should start
  • +
  • end: POSIX timestamp for when the downtime should end
  • +
  • message: a string message to accompany the downtime
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var properties = {
+  scope: "env:staging"
+};
+dogapi.downtime.update(1234, properties, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

remove(downtimeId, callback)

+
+

delete a scheduled downtime

+

Parameters:

+
+
downtimeId
+

the id of the downtime

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.downtime.remove(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

get(downtimeId, callback)

+
+

get a scheduled downtimes details

+

Parameters:

+
+
downtimeId
+

the id of the downtime

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.downtime.get(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

getAll(callback)

+
+

get all downtimes details

+

Parameters:

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.downtime.getAll(function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

event

+ +
+

create(title, text, properties, callback)

+
+

create a new event

+

Parameters:

+
+
title
+

the title of the event

+
+
text
+

the body of the event

+
+
properties
+

an optional object continaing any of the following additional optional properties

+
    +
  • date_happened: POSIX timestamp of when it happened
  • +
  • priority: "normal" or "low" [defualt: "normal"]
  • +
  • host: the host name to associate with the event
  • +
  • tags: array of "tag:value"'s to associate with the event
  • +
  • alert_type: "error", "warning", "info" or "success" [defualt: "info"]
  • +
  • aggregation_key: an arbitrary string used to aggregate like events
  • +
  • source_type_name: options: "nagios", "hudson", "jenkins", "user", "my apps", "feed", "chef", "puppet", "git", "bitbucket", "fabric", "capistrano"
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
 var dogapi = require("dogapi");
+ var options = {
+   api_key: "api_key",
+   app_key: "app_key"
+ };
+ dogapi.initialize(options);
+ var title = "some new event";
+ var text = "IT HAPPENED!";
+ dogapi.event.create(title, text, function(err, res){
+   console.dir(res);
+ });
+ title = "another event";
+ text = "IT HAPPENED AGAIN!";
+ var properties = {
+   tags: ["some:tag"],
+   alert_type: "error"
+ };
+ dogapi.event.create(title, text, properties, function(err, res){
+   console.dir(res);
+ });
+
+
+
+
+

get(eventId, callback)

+
+

get event details from the provided event id

+

Parameters:

+
+
eventId
+

the id of the event to fetch

+
+
callback
+

function(err, res)

+
+
+
+
+
 var dogapi = require("dogapi");
+ var options = {
+   api_key: "api_key",
+   app_key: "app_key"
+ };
+ dogapi.initialize(options);
+ dogapi.event.get(10005, function(err, res){
+   console.dir(res);
+ });
+
+
+
+
+

query(start, end, parameters, callback)

+
+

query the event stream

+

Parameters:

+
+
start
+

POSIX timestamp for start of query

+
+
end
+

POSIX timestamp for end of query

+
+
parameters
+

optional parameters to use for the query

+
    +
  • priority: "low" or "normal"
  • +
  • sources: comma separated list of sources (e.g. "jenkins,user")
  • +
  • tags: comma separated list of tags (e.g. "tag:value1,tag:value2")
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
 var dogapi = require("dogapi");
+ var options = {
+   api_key: "api_key",
+   app_key: "app_key"
+ };
+ dogapi.initialize(options);
+ var now = parseInt(new Date().getTime() / 1000);
+ var then = now - 3600; // an hour ago
+ var parameters = {
+   tags: "some:tag",
+   sources: "jenkins"
+ };
+ dogapi.event.query(then, now, parameters, function(err, res){
+   console.dir(res);
+ });
+
+
+
+
+
+
+

graph

+ +
+

snapshot(query, from, to, eventQuery, callback)

+
+

take a snapshot of a metric query

+

Parameters:

+
+
query
+

the metric query to use for the snapshot

+
+
from
+

POSIX timestamp for the beginning of the query

+
+
to
+

POSIX timestamp for the end of the query

+
+
eventQuery
+

optional, an event query to overlay event bands on the snapshot

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var query = "system.cpu.idle{*}";
+var to = dogapi.now();
+var from = from - 3600;  // an hour ago
+dogapi.graph.snapshot(query, from, to, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

host

+ +
+

mute(hostname, options, callback)

+
+

mute the given host, if it is not already muted

+

Parameters:

+
+
hostname
+

the hostname of the host to mute

+
+
options
+

optional, an object containing any of the following

+
    +
  • end: POSIX timestamp for when the mute should end
  • +
  • override: whether or not to override the end for an existing mute
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.host.mute("my.host.name", function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

unmute(hostname, callback)

+
+

unmute the given host, if it is not already unmuted

+

Parameters:

+
+
hostname
+

the hostname of the host to unmute

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.host.unmute("my.host.name", function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

infrastructure

+ + +
+
+
+

metric

+ +
+

send(metric, points, extra, callback)

+
+

submit a new metric

+

Parameters:

+
+
metric
+

the metric name

+
+
points
+

single datapoint or array of [timestamp, datapoint], if a single point +is given "now" is used as the timestamp

+
+
extra
+

optional, object which can contain the following keys

+
    +
  • host: the host source of the metric
  • +
  • tags: array of "tag:value"'s to use for the metric
  • +
  • metric_type: which metric type to use ("gauge" or "counter") [default: gauge]
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.metric.send("my.metric", 1000, function(err, results){
+  console.dir(results);
+});
+var now = parseInt(new Date().getTime() / 1000);
+dogapi.metric.send("my.metric", [now, 1000], function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

send_all(metrics, callback)

+
+

send a list of metrics

+

Parameters:

+
+
metrics
+

an array of metrics where each element is an object with the following keys

+
    +
  • metric: the name of the metric
  • +
  • points: a single datapoint or an array of [timestamp, datapoint] (same as dogapi.metric.send)
  • +
  • tags: an array of "tag:value"'s
  • +
  • host: the source hostname to use for the metrics
  • +
  • metric_type: the type of metric to use ("gauge" or "counter") [default: gauge]
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var now = parseInt(new Date().getTime() / 1000);
+var metrics = [
+  {
+    metric: "my.metric",
+    points: [now, 1000],
+    tags: ["tag:value"]
+  },
+  {
+    metric: "another.metric",
+    points: 1000
+  }
+];
+dogapi.metric.send_all(metrics, function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

query(from, to, query, callback)

+
+

make a metric query

+

Parameters:

+
+
from
+

POSIX timestamp for start of query

+
+
to
+

POSIX timestamp for end of query

+
+
query
+

the string query to perform (e.g. "system.cpu.idle{*}by{host}")

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var now = parseInt(new Date().getTime() / 1000);
+var then = now - 3600; // one hour ago
+var query = "system.cpu.idle{*}by{host}";
+dogapi.metric.query(then, now, query, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

monitor

+ +
+

create(type, query, properties, callback)

+
+

create a new monitor

+

Parameters:

+
+
type
+

one of "metric alert" or "service check"

+
+
query
+

the monitor query to use, you probably want to read datadog's monitor create docs

+
+
properties
+

optional, an object containing any of the following

+
    +
  • name: the name of the monitor
  • +
  • message: the message for the monitor
  • +
  • options: an object, to see available options please see the monitor create docs
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var metricType = "metric alert";
+var query = "avg(last_1h):sum:system.net.bytes_rcvd{host:host0} > 100";
+dogapi.monitor.create(metricType, query, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

get(monitorId, groupStates, callback)

+
+

get an existing monitor's details

+

Parameters:

+
+
monitorId
+

the id of the monitor

+
+
groupStates
+

an array containing any of the following "all", "alert", "warn", or "no data"

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.get(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

getAll(options, callback)

+
+

get all monitors

+

Parameters:

+
+
options
+

optional, an object containing any of the following

+
    +
  • group_states: an array containing any of the following "all", "alert", "warn", or "no data"
  • +
  • tags: an array of "tag:value"'s to filter on
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.getAll(function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

update(monitorId, query, properties, callback)

+
+

update a monitor's details

+

Parameters:

+
+
monitorId
+

the id of the monitor to edit

+
+
query
+

the query that the monitor should have, see the monitor create docs for more info

+
+
properties
+

optional, an object containing any of the following

+
    +
  • name: the name of the monitor
  • +
  • message: the message for the monitor
  • +
  • options: an object, to see available options please see the monitor create docs
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var query = "avg(last_1h):sum:system.net.bytes_rcvd{host:host0} > 100";
+dogapi.monitor.update(1234, query, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

remove(monitorId, callback)

+
+

delete an existing monitor

+

Parameters:

+
+
monitorId
+

the id of the monitor to remove

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.remove(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

mute(monitorId, options, callback)

+
+

mute an existing monitor

+

Parameters:

+
+
monitorId
+

the id of the monitor to mute

+
+
options
+

optional, an object containing any of the following

+
    +
  • scope: the scope to mute (e.g. "role:db")
  • +
  • end: POSIX timestamp indicating when the mute should end
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.mute(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

muteAll(callback)

+
+

mute all monitors

+

Parameters:

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.muteAll(function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

unmute(monitorId, scope, callback)

+
+

unmute an existing monitor

+

Parameters:

+
+
monitorId
+

the id of the monitor to unmute

+
+
scope
+

optional, a scope to apply the unmute to (e.g. "role:db")

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.unmute(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

unmuteAll(callback)

+
+

unmute all monitors

+

Parameters:

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.monitor.unmuteAll(function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

screenboard

+ +
+

create(title, description, graphs, options, callback)

+
+

create a new screenboard

+

Parameters:

+
+
title
+

the name of the screenboard

+
+
description
+

description of the screenboard

+
+
graphs
+

an array of objects which required the following keys

+ +
+
options
+

optional, a object which can contain any of the following keys

+
    +
  • templateVariables: | +an array of objects with the following keys
      +
    • name: the name of the variable
    • +
    • prefix: optional, the tag prefix for this variable
    • +
    • default: optional, the default value for this tag
    • +
    +
  • +
  • width: the width of the screenboard in pixels
  • +
  • height: the height of the screenboard in pixels
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var title = "my screenboard";
+var description = "it is super awesome";
+var graphs = [
+  {
+    type: "image",
+    height: 20,
+    width: 32,
+    y: 7,
+    x: 32,
+    url: "https://path/to/image.jpg"
+  }
+];
+var options = {
+  templateVariables: [
+    {
+      name: "host1",
+      prefix: "host",
+      "default": "host:my-host"
+    }
+  ]
+};
+dogapi.screenboard.create(
+  title, description, graphs, options,
+  function(err, res){
+    console.dir(res);
+  }
+);
+
+
+
+
+

remove(boardId, callback)

+
+

delete an existing screenboard

+

Parameters:

+
+
boardId
+

the id of the screenboard to delete

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.screenboard.remove(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

get(boardId, callback)

+
+

get the info of a single existing screenboard

+

Parameters:

+
+
boardId
+

the id of the screenboard to fetch

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.screenboard.get(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

getAll(callback)

+
+

get all existing screenboards

+

Parameters:

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.screenboard.getAll(function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

share(boardId, callback)

+
+

share an existing screenboard

+

Parameters:

+
+
boardId
+

the id of the screenboard to share

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.screenboard.share(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

serviceCheck

+ +
+

check(check, hostName, status, parameters, callback)

+
+

post an update to a service check

+

Parameters:

+
+
check
+

the check name (e.g. "app.ok")

+
+
hostName
+

the name of the host submitting the check

+
+
status
+

one of dogapi.OK, dogapi.WARNING, dogapi.CRITICAL or dogapi.UNKNOWN

+
+
parameters
+

optional, an object containing any of the following

+
    +
  • timestamp: POSIX timestamp for when the check happened
  • +
  • message: string message to accompany the check
  • +
  • tags: an array of "tag:value"'s associated with the check
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
 var dogapi = require("dogapi");
+ var options = {
+   api_key: "api_key",
+   app_key: "app_key"
+ };
+ dogapi.initialize(options);
+ var check = "app.ok";
+ var hostName = "some.machine";
+ dogapi.serviceCheck.check(
+   check, hostName, dogapi.WARNING, function(err, res){
+     console.dir(res);
+ });
+
+
+
+
+
+
+

tag

+ +
+

getAll(source, callback)

+
+

get all host tags

+

Parameters:

+
+
source
+

optional, only show tags for a particular source [default: null]

+
+
callback
+

function callback(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.tag.getAll(function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

get(hostname, options, callback)

+
+

get the host tags for a provided host name or host id

+

Parameters:

+
+
hostname
+

the hostname or host id

+
+
options
+

optional, an object of options for the query allowing the following

+
    +
  • source: the source of the tags (e.g. chef, puppet, users, etc) [default: null]
  • +
  • by_source: whether or not to group the results by source [default: false]
  • +
+
+
callback
+

function callback(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.tag.get("host.name", function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

create(hostname, tags, source, callback)

+
+

assign new host tags to the provided host name or host id

+

Parameters:

+
+
hostname
+

the hostname or host id

+
+
tags
+

list of <tag>:<value> tags to assign to the server

+
+
source
+

optional, the source of the tags (e.g. chef, puppet, etc) [default: users]

+
+
callback
+

function callback(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.tag.create("host.name", ["role:webserver"], function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

update(hostname, tags, source, callback)

+
+

update the host tags for the provided host name or host id

+

Parameters:

+
+
hostname
+

the hostname or host id

+
+
tags
+

list of <tag>:<value> tags to assign to the server

+
+
source
+

optional, the source of the tags (e.g. chef, puppet, etc) [default: users]

+
+
callback
+

function callback(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.tag.update("host.name", function(err, results){
+  console.dir(results);
+});
+
+
+
+
+

remove(hostname, source, callback)

+
+

delete the host tags for the provided host name or host id

+

Parameters:

+
+
hostname
+

the hostname or host id

+
+
source
+

optional, the source of the tags (e.g. chef, puppet, etc) [default: users]

+
+
callback
+

function callback(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.tag.remove("host.name", function(err, results){
+  console.dir(results);
+});
+
+
+
+
+
+
+

timeboard

+ +
+

create(title, description, graphs, templateVariables, callback)

+
+

add a new timeboard

+

Parameters:

+
+
title
+

the title of the timeboard

+
+
description
+

the description of the timeboard

+
+
graphs
+

an array of objects with the following keys

+
    +
  • title: the name of the graph
  • +
  • definition: an object containing the graph definition, e.g. {"requests": [{"q": "system.cpu.idle{*} by {host}"}
  • +
+
+
templateVariables
+

optional, an array of objects with the following keys

+
    +
  • name: the name of the variable
  • +
  • prefix: optional, the tag prefix for this variable
  • +
  • default: optional, the default value for this tag
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var title = "Time Keeps on Slipping";
+var description = "Into the Future";
+var graphs = [
+  {
+    definition: {
+      events: [],
+      requests: [
+        {q: "avg:system.mem.free{*}"}
+      ],
+      viz: "timeseries"
+    },
+    title: "Average Memory Free"
+  }
+];
+var templateVariables = [
+  {
+    name: "host1",
+    prefix: "host",
+    "default": "host:my-host"
+  }
+];
+dogapi.timeboard.create(
+  title, description, graphs, templateVariables,
+  function(err, res){
+    console.dir(res);
+  }
+);
+
+
+
+
+

update(dashId, title, description, graphs, templateVariables, callback)

+
+

update an existing timeboard

+

Parameters:

+
+
dashId
+

the id of the timeboard to update

+
+
title
+

the title of the timeboard

+
+
description
+

the description of the timeboard

+
+
graphs
+

an array of objects with the following keys

+
    +
  • title: the name of the graph
  • +
  • definition: an object containing the graph definition, e.g. {"requests": [{"q": "system.cpu.idle{*} by {host}"}
  • +
+
+
templateVariables
+

optional, an array of objects with the following keys

+
    +
  • name: the name of the variable
  • +
  • prefix: optional, the tag prefix for this variable
  • +
  • default: optional, the default value for this tag
  • +
+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var title = "Time Keeps on Slipping";
+var description = "Into the Future";
+var graphs = [
+  {
+    definition: {
+      events: [],
+      requests: [
+        {q: "avg:system.mem.free{*}"}
+      ],
+      viz: "timeseries"
+    },
+    title: "Average Memory Free"
+  }
+];
+var templateVariables = [
+  {
+    name: "host1",
+    prefix: "host",
+    default: "host:my-host"
+  }
+];
+dogapi.timeboard.update(
+  1234, title, description, graphs, templateVariables,
+  function(err, res){
+    console.dir(res);
+  }
+);
+
+
+
+
+

remove(dashId, callback)

+
+

remove an existing timeboard

+

Parameters:

+
+
dashId
+

the id of the timeboard to remove

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.timeboard.remove(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

getAll(callback)

+
+

get all existing timeboards

+

Parameters:

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.timeboard.getAll(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+

get(dashId, callback)

+
+

get an existing timeboard

+

Parameters:

+
+
dashId
+

the id of the timeboard to get

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.timeboard.get(1234, function(err, res){
+  console.dir(res);
+});
+
+
+
+
+
+
+

user

+ +
+

invite(emails, callback)

+
+

invite users via e-mail

+

Parameters:

+
+
emails
+

an array of email addresses to send invites to

+
+
callback
+

function(err, res)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+var emails = ["me@domain.com", "you@domain.com"];
+dogapi.user.invite(emails, fuction(err, res){
+  console.dir(res):
+});
+
+
+
+
+
+
+

client

+ +
+

client()

+
+

the constructor for client object

+
+ +
+
+

request(method, path, params, callback)

+
+

used to make a raw request to the datadog api

+

Parameters:

+
+
method
+

http method GET, POST, PUT, DELETE

+
+
path
+

the api url path e.g. /tags/hosts

+
+
params
+

an object which allows the keys query or body

+
+
callback
+

function to call on success/failure callback(err, result)

+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "api_key",
+  app_key: "app_key"
+};
+dogapi.initialize(options);
+dogapi.client.request("GET", "/url/path", {}, function(err, results){
+  console.dir(results);
+});
+
+
+
+
+
+
+

dogapi

+ +
+

initialize(options)

+
+

configure the dogapi client with your app/api keys

+

Parameters:

+
+
options
+

An object which allows you to override the default set parameters for interacting +with the datadog api. The available options are.

+
    +
  • api_key: your api key
  • +
  • app_key: your app key
  • +
  • api_version: the version of the api [default: v1]
  • +
  • api_host: the host to call [default: api.datadoghq.com]
  • +
+
+
+
+
+
var dogapi = require("dogapi");
+var options = {
+  api_key: "<API_KEY_HERE>",
+  app_key: "<APP_KEY_HERE>"
+};
+dogapi.initialize(options);
+dogapi.event.create(...);
+
+
+
+
+

now()

+
+

get the current POSIX timestamp

+
+
+
var dogapi = require("dogapi");
+dogapi.now();
+// this is the same as
+parseInt(new Date().getTime() / 1000);
+
+
+
+
+
+Fork me on GitHub diff --git a/lib/api/alert.js b/lib/api/alert.js deleted file mode 100644 index cc7bc9c..0000000 --- a/lib/api/alert.js +++ /dev/null @@ -1,123 +0,0 @@ -var util = require('util'); - - -var alert_api = function(){}; - -alert_api.prototype.add_alert = function(alert, callback){ - /* - * alert_api.add_alert(alert, [callback]) - * - * add a new alert to datadog - * - * `alert` is an object containing: - * query: *required*, the metric to query on - * name: name of the alert - * message: an optional message to include with the alert - * silenced: whether the alert should notify by email and in the stream - * - * `callback` an optional function to get called with the results of the api call - * callback(error, result, status_code) - */ - if(typeof alert != 'object'){ - throw new Error('`alert` parameter must be an object'); - } - - if(!alert['query']){ - throw new Error('`alert["query"]` is required'); - } - - this.request('POST', '/alert', {body: alert}, callback); -}; - -alert_api.prototype.update_alert = function(alert_id, alert, callback){ - /* - * alert_api.update_alert(alert_id, alert, [callback]) - * - * update an existing alert - * - * `alert_id` the id of alert to update - * `alert` is an object containing: - * query: *required*, the metric to query on - * name: name of the alert - * message: an optional message to include with the alert - * silenced: whether the alert should notify by email and in the stream - * - * `callback` an optional function to get called with the results of the api call - * callback(error, result, status_code) - */ - if(typeof alert != 'object'){ - throw new Error('`alert` parameter must be an object'); - } - - if(!alert['query']){ - throw new Error('`alert["query"]` is required'); - } - - this.request('PUT', util.format('/alert/%s', alert_id), {body: alert}, callback); -}; - -alert_api.prototype.get_alert = function(alert_id, callback){ - /* - * alert_api.get_alert(alert_id, [callback]) - * - * get the details of an alert from the given id - * - * `alert_id` the id for the alert to get - * - * `callback` an optional function to call with the results - * callback(error, result, status_code) - */ - this.request('GET', util.format('/alert/%s', alert_id), callback); -}; - -alert_api.prototype.delete_alert = function(alert_id, callback){ - /* - * alert_api.delete_alert(alert_id, [callback]) - * - * delete the given alert from datadog - * - * `alert_id` the id for the alert to get - * - * `callback` an optional function to call with the results - * callback(error, result, status_code) - */ - this.request('DELETE', util.format('/alert/%s', alert_id), callback); -}; - -alert_api.prototype.get_all_alerts = function(callback){ - /* - * alert_api.get_all_alerts([callback]) - * - * get the details of all alerts in datadog - * - * `callback` an optional function to call with the results - * callback(error, result, status_code) - */ - this.request('GET', '/alert', callback); -}; - -alert_api.prototype.mute_alerts = function(callback){ - /* - * alert_api.mute_alerts([callback]) - * - * mute all alerts - * - * `callback` an optional function to call with the results - * callback(error, result, status_code) - */ - this.request('POST', '/mute_alerts', callback); -}; - -alert_api.prototype.unmute_alerts = function(callback){ - /* - * alert_api.unmute_alerts([callback]) - * - * unmute all alerts - * - * `callback` an optional function to call with the results - * callback(error, result, status_code) - */ - this.request('POST', '/unmute_alerts', callback); -}; - -return module.exports = alert_api; diff --git a/lib/api/comment.js b/lib/api/comment.js new file mode 100644 index 0000000..309c857 --- /dev/null +++ b/lib/api/comment.js @@ -0,0 +1,157 @@ +var client = require("../client"); +var util = require("util"); + +/*section: comment + *comment: create a new comment + *params: + * message: the message of the comment + * properties: | + * optional, an object containing any of the following + * * handle: the handle to associate the comment with (e.g. "user@domain.com") + * * related_event_id: the event to associate the comment with + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.comment.create("a comment message", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function create(message, properties, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = properties; + properties = {}; + } + + var params = { + body: { + message: message + } + }; + + if(typeof properties === "object"){ + if(properties.handle){ + params.body.handle = properties.handle; + } + if(properties.related_event_id){ + params.body.related_event_id = properties.related_event_id; + } + } + + client.request("POST", "/comments", params, callback); +} + +/*section: comment + *comment: update an existing comment + *params: + * commentId: the id of the comment to update + * message: the message of the comment + * handle: optional, the handle to associate the comment with (e.g. "user@domain.com") + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.comment.update(1234, "new message", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function update(commentId, message, handle, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = handle; + handle = undefined; + } + + var params = { + body: { + message: message + } + }; + if(handle){ + params.body.handle = properties.handle; + } + + client.request("PUT", util.format("/comments/%s", commentId), params, callback); +} + +/*section: comment + *comment: remove a comment + *params: + * commentId: the id of the comment to remove + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.comment.remove(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function remove(commentId, callback){ + client.request("DELETE" ,util.format("/comments/%s", commentId), callback); +} + + +module.exports = { + create: create, + update: update, + remove: remove, + getUsage: function(){ + return [ + " dogapi comment create [--handle ] [--event ]", + " dogapi comment update [--handle ]", + " dogapi comment remove " + ]; + }, + getHelp: function(){ + return [ + "Comment:", + " Subcommands:", + " create add a new comment", + " update update an existing comment", + " remove delete a comment", + "", + " Options:", + " --handle the handle to associate with the comment (e.g. \"user@domain.com\")", + " --event related event id to associate the comment with" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "create"){ + var message = args._[4]; + var properties = {}; + if(args["handle"]){ + properties.handle = args["handle"]; + } + if(args["event"]){ + properties.related_event_id = parseInt(args["event"]); + } + create(message, properties, callback); + } else if(subcommand === "update"){ + var commentId = args._[4]; + var message = args._[5]; + update(commentId, message, args["handle"], callback); + } else if(subcommand === "remove"){ + var commentId = args._[4]; + remove(commentId, callback); + } else { + callback("unknown subcommand or arguments try `dogapi comment --help` for help", false); + } + } +}; diff --git a/lib/api/dash.js b/lib/api/dash.js deleted file mode 100644 index fc53a9a..0000000 --- a/lib/api/dash.js +++ /dev/null @@ -1,103 +0,0 @@ -var util = require('util'); - -var validate_dashboard = function(dashboard){ - if(typeof dashboard != 'object'){ - throw new Error('`dashboard` parameter must be an object'); - } - - if(typeof dashboard['title'] != 'string'){ - throw new Error('`dashboard["title"]` must be a string'); - } - - if(typeof dashboard['description'] != 'string'){ - throw new Error('`dashboard["description"]` must be a string'); - } - - if(typeof dashboard['graphs'] != 'object'){ - throw new Error('`dashboard["graphs"]` must be an array'); - } - - for(var i in dashboard['graphs']){ - if(!dashboard['graphs'][i]['title']){ - throw new Error(util.format('`dashboard["graphs"][%s]["title"]` is missing', i)); - } - if(!dashboard['graphs'][i]['definition']){ - throw new Error(util.format('`dashboard["graphs"][%s]["definition"]` is missing', i)); - } - } -}; - -var dash_api = function(){}; - -dash_api.prototype.get_dashboard = function(dash_id, callback){ - /* - * dash_api.get_dashboard(dash_id, [callback]) - * - * method to get a single dashboard information - * - * `dash_id` is the id of the dashboard to get information for - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - this.request('GET', util.format('/dash/%s', dash_id), callback); -}; - -dash_api.prototype.get_all_dashboards = function(callback){ - /* - * dash_api.get_all_dashboards([callback]) - * - * method to retrieve all dashboards in datadog - * - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - this.request('GET', '/dash', callback); -}; - -dash_api.prototype.create_dashboard = function(dashboard, callback){ - /* - * dash_api.create_dashboard(dashboard, [callback]) - * - * method used to create a new dashboard in datadog - * - * `dashboard` is the definition for the dashboard - * please see (http://docs.datadoghq.com/api/) for more information - * - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - validate_dashboard(dashboard); - this.request('POST', '/dash', {body: dashboard}, callback); -}; - -dash_api.prototype.update_dashboard = function(dash_id, dashboard, callback){ - /* - * dash_api.update_dashboard(dash_id, dashboard, [callback]) - * - * method used to update the dashboard with the provided `dash_id` - * - * `dash_id` the id of the dashboard to update - * `dashboard` is a definition for the datadog dashboard - * please see (http://docs.datadoghq.com/api/) for more information - * - * `callback` an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - validate_dashboard(dashboard); - this.request('PUT', util.format('/dash/%s', dash_id), {body: dashbboard}, callback); -}; - -dash_api.prototype.delete_dashboard = function(dash_id, callback){ - /* - * dash_api.delete_dashboard(dash_id, [callback]) - * - * method to remove a dashboard from datadog - * - * `dash_id` the id for the dashboard to remove - * `callback` an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - this.request('DELETE', util.format('/dash/%s', dash_id), callback); -}; - -return module.exports = dash_api; diff --git a/lib/api/downtime.js b/lib/api/downtime.js index 98dcf66..5f35a96 100644 --- a/lib/api/downtime.js +++ b/lib/api/downtime.js @@ -1,102 +1,242 @@ -var util = require('util'); - -var downtime_api = function(){}; - -downtime_api.prototype.schedule_downtime = function(scope, options, callback){ - /* - * downtime_api.schedule_downtime(scope, [options], [callback]) - * - * method to schedule a new downtime - * - * `scope` the scope to schedule downtime for - * `options` optional `start` `end` and `message` paramaters - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - if(typeof scope !== 'string'){ - throw new Error('scope parameter must be a string'); +var client = require("../client"); +var util = require("util"); + +/*section: downtime + *comment: schedule a new downtime + *params: + * scope: string scope that the downtime should apply to (e.g. "env:staging") + * properties: | + * optional, an object containing any of the following + * * start: POSIX timestamp for when the downtime should start + * * end: POSIX timestamp for when the downtime should end + * * message: a string message to accompany the downtime + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.downtime.create("env:staging", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function create(scope, properties, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = properties; + properties = {}; } - if(typeof options === 'function'){ - callback = options; - options = {}; + var params = { + body: { + scope: scope + } + }; + if(typeof properties === "object"){ + if(properties.start){ + params.body.start = parseInt(properties.start); + } + if(properties.end){ + params.body.end = parseInt(properties.end); + } + if(properties.message){ + params.body.message = properties.message; + } } - options.scope = scope; - - this.request('POST', '/downtime', {body: options}, callback); -}; - -downtime_api.prototype.update_downtime = function(downtime_id, options, callback){ - /* - * downtime_api.update_downtime(downtime_id, [options], [callback]) - * - * method to update an existing downtime - * - * `downtime_id` the id of the downtime - * `options` optional `scope` `start` `end` and `message` paramaters - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - - if(typeof options === 'function'){ - callback = options; - options = {}; + client.request("POST", "/downtime", params, callback); +} + +/*section: downtime + *comment: update an existing downtime + *params: + * downtimeId: the id the downtie to update + * properties: | + * optional, an object containing any of the following + * * scope: the scope the downtime should be changed to (e.g. "env:staging") + * * start: POSIX timestamp for when the downtime should start + * * end: POSIX timestamp for when the downtime should end + * * message: a string message to accompany the downtime + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var properties = { + * scope: "env:staging" + * }; + * dogapi.downtime.update(1234, properties, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function update(downtimeId, properties, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = properties; + properties = {}; } - - this.request('PUT', util.format('/downtime/%s', downtime_id), {body: options}, callback); -}; - -downtime_api.prototype.get_downtime = function(downtime_id, callback){ - /* - * downtime_api.get_downtime(downtime_id, [callback]) - * - * method to get an existing downtime - * - * `downtime_id` the id of the downtime - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - - this.request('GET', util.format('/downtime/%s', downtime_id), callback); -}; - -downtime_api.prototype.cancel_downtime = function(downtime_id, callback){ - /* - * downtime_api.cancel_downtime(downtime_id, [callback]) - * - * method to cancel an existing downtime - * - * `downtime_id` the id of the downtime - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - - this.request('DELETE', util.format('/downtime/%s', downtime_id), callback); -}; - -downtime_api.prototype.get_all_downtimes = function(current_only, callback){ - /* - * downtime_api.get_all_downtimes(downtime_id, [current_only], [callback]) - * - * method to get all downtimes - * - * `downtime_id` the id of the downtime - * `current_only` whether or not to get the current downtime only - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - - if(typeof current_only === 'function'){ - callback = current_only; - current_only = false; + var params = { + body: {} + }; + if(typeof properties === "object"){ + if(properties.scope){ + params.body.scope = properties.scope; + } + if(properties.start){ + params.body.start = parseInt(properties.start); + } + if(properties.end){ + params.body.end = parseInt(properties.end); + } + if(properties.message){ + params.body.message = properties.message; + } } - - query = {}; - if(current_only){ - query.current_only = true; + client.request("PUT", util.format("/downtime/%s", downtimeId), params, callback); +} + +/*section: downtime + *comment: delete a scheduled downtime + *params: + * downtimeId: the id of the downtime + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.downtime.remove(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function remove(downtimeId, callback){ + client.request("DELETE", util.format("/downtime/%s", downtimeId), callback); +} + +/*section: downtime + *comment: get a scheduled downtimes details + *params: + * downtimeId: the id of the downtime + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.downtime.get(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function get(downtimeId, callback){ + client.request("GET", util.format("/downtime/%s", downtimeId), callback); +} + +/*section: downtime + *comment: get all downtimes details + *params: + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.downtime.getAll(function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function getAll(callback){ + client.request("GET", "/downtime", callback); +} + + +module.exports = { + create: create, + update: update, + remove: remove, + get: get, + getAll: getAll, + getUsage: function(){ + return [ + " dogapi downtime create [--start ] [--end ] [--message ]", + " dogapi downtime update [--scope ] [--start ] [--end ] [--message ]", + " dogapi downtime remove ", + " dogapi downtime get ", + " dogapi downtime getall", + ]; + }, + getHelp: function(){ + return [ + "Downtime:", + " Subcommands:", + " create create a new downtime with the provided scope (e.g. \"env:staging\")", + " update update an existing downtime with the provided id", + " remove remove the downtime with the provided id", + " get get the details of the downtime with the provided id", + " getall get the details of all downtimes", + "", + " Options:", + " --start POSIX timestamp for when the downtime should start", + " --end POSIX timestamp for when the downtime should end", + " --message a string message to accompany the downtime", + " --scope the scope of the downtime (e.g. \"env:staging\")" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "get"){ + get(args._[4], callback); + } else if(subcommand === "getall"){ + getAll(callback); + } else if(subcommand === "remove"){ + remove(args._[4], callback); + } else if(subcommand === "create"){ + var scope = args._[4]; + var properties = {}; + if(args["start"]){ + properties.start = parseInt(args["start"]); + } + if(args["end"]){ + properties.end = parseInt(args["end"]); + } + if(args["message"]){ + properties.message = args["message"]; + } + create(scope, properties, callback); + } else if(subcommand === "update"){ + var downtimeId = args._[4]; + var properties = {}; + if(args["scope"]){ + properties.scope = args["scope"]; + } + if(args["start"]){ + properties.start = parseInt(args["start"]); + } + if(args["end"]){ + properties.end = parseInt(args["end"]); + } + if(args["message"]){ + properties.message = args["message"]; + } + update(downtimeId, properties, callback); + } else { + callback("unknown subcommand or arguments try `dogapi downtime --help` for help", false); + } } - - this.request('GET', '/downtime', {query: query}, callback); }; - -return module.exports = downtime_api; diff --git a/lib/api/event.js b/lib/api/event.js index d2a9cb5..4c1be38 100644 --- a/lib/api/event.js +++ b/lib/api/event.js @@ -1,216 +1,209 @@ -var extend = require('extend'); -var util = require('util'); - - -var event_api = function(){}; - -event_api.prototype.stream = function(start, end, filter, callback){ - /* - * event_api.stream( start, end, [[filter], callback] ) - * - * function used to retrieve all events that have occured between - * `start` and `end` (POSIX timestamps) - * - * optionally filter the query with `filter`: - * { - * 'priority': ("low" or "normal"), - * 'sources': ["sources", "as", "a", "list"], - * 'tags': ["tags", "as", "a", "list"], - * } - * - * optionally provide a `callback` function to get the result - * of this api call: - * callback(error, result, status_code) - */ - if(arguments.length < 2){ - throw new Error('parameters `start` and `end` are required'); - } - query = { - start: parseInt(start), - end: parseInt(end), +var client = require("../client"); +var util = require("util"); + +/*section: event + *comment: | + * create a new event + *params: + * title: the title of the event + * text: the body of the event + * properties: | + * an optional object continaing any of the following additional optional properties + * * date_happened: POSIX timestamp of when it happened + * * priority: "normal" or "low" [defualt: "normal"] + * * host: the host name to associate with the event + * * tags: array of "tag:value"'s to associate with the event + * * alert_type: "error", "warning", "info" or "success" [defualt: "info"] + * * aggregation_key: an arbitrary string used to aggregate like events + * * source_type_name: options: "nagios", "hudson", "jenkins", "user", "my apps", "feed", "chef", "puppet", "git", "bitbucket", "fabric", "capistrano" + * callback: | + * function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var title = "some new event"; + * var text = "IT HAPPENED!"; + * dogapi.event.create(title, text, function(err, res){ + * console.dir(res); + * }); + * title = "another event"; + * text = "IT HAPPENED AGAIN!"; + * var properties = { + * tags: ["some:tag"], + * alert_type: "error" + * }; + * dogapi.event.create(title, text, properties, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function create(title, text, properties, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = properties; + properties = {}; + } + if(typeof properties !== "object"){ + properties = {}; + } + + properties.title = title; + properties.text = text; + + var params = { + body: properties }; - - // this is the only case we have to check - // if we have `event_api(1234, 5678, callback)` then - // we want to push callback back - if(arguments.length == 3 && typeof arguments[2] == 'function'){ - callback = arguments[2]; - filter = {}; - } - - // validate the filters we were given and append to `query` - // if they exist and meet their requirements - if(filter['priority'] && ['low', 'normal'].indexOf(filter['priority'].toLowerCase()) >= 0){ - query['priority'] = filter['priority'].toLowerCase(); - } - if(filter['sources'] && typeof filter['sources'] == 'object'){ - query['sources'] = filter['sources'].join(); - } - if(filter['tags'] && typeof filter['tags'] == 'object'){ - query['tags'] = filter['tags'].join(); - } - - params = { - query: query, + client.request("POST", "/events", params, callback); +} + +/*section: event + *comment: | + * get event details from the provided event id + *params: + * eventId: | + * the id of the event to fetch + * callback: | + * function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.event.get(10005, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function get(eventId, callback){ + client.request("GET", util.format("/events/%s", eventId), callback); +} + +/*section: event + *comment: | + * query the event stream + *params: + * start: POSIX timestamp for start of query + * end: POSIX timestamp for end of query + * parameters: | + * optional parameters to use for the query + * * priority: "low" or "normal" + * * sources: comma separated list of sources (e.g. "jenkins,user") + * * tags: comma separated list of tags (e.g. "tag:value1,tag:value2") + * callback: | + * function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var now = parseInt(new Date().getTime() / 1000); + * var then = now - 3600; // an hour ago + * var parameters = { + * tags: "some:tag", + * sources: "jenkins" + * }; + * dogapi.event.query(then, now, parameters, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function query(start, end, parameters, callback){ + if(arguments.length < 4 && typeof argument[2] === "function"){ + callback = parameters; + parameters = {}; + } + + if(typeof parameters !== "object"){ + parameters = {} + } + parameters.start = start; + parameters.end = end; + + var params = { + query: parameters }; - this.request('GET', '/events', params, callback); -}; - -event_api.prototype.polling_stream = function(interval, filter, callback){ - /* - * event_api.polling_stream(interval, [[filter], callback] ) - * - * function used to continuously call `stream` for new events - * - * `interval` seconds between each call - * `filter` is an object to limit the results by - * `callback` is an optional function called with the results of the api call - * callback(error, result, status_code) - */ - if(arguments.length < 3 && typeof arguments[1] == 'function'){ - callback = arguments[1]; - filter = {}; - } - if(typeof filter != 'object'){ - throw new Error('`filter` parameter must be an object'); - } - - var last_run = new Date().getTime() / 1000; - var self = this; - setInterval(function(){ - var start = last_run; - last_run = new Date().getTime() / 1000; - self.stream(start, last_run, filter, callback); - }, interval * 1000); - -}; - -event_api.prototype.get_event = function(event_id, callback){ - /* - * event_api.get_event(event_id, callback) - * - * method used to retrieve a single event's data - * - * `event_id` the id of the event to get the information for - * `callback` an optional function called with the results - * callback(error, result, status_code) - */ - if(!event_id){ - throw new Error('`event_id` parameter is required'); - } - - this.request('GET', util.format('/events/%s', event_id), callback); -}; - -event_api.prototype.add_event = function(event, callback){ - /* - * event_api.add_event(event, callback) - * - * method used to add a new event to datadog - * - * `event` is an object containing any of the following: - * title: *required*, string, title for the new event - * text: *required*, string, event message - * date_happened: int, when the event occurred. if unset defaults to the current time. (POSIX timestamp) - * handle: string, user to post the event as. defaults to owner of the application key used to submit. - * priority: string, priority to post the event as. ("normal" or "low", defaults to "normal") - * related_event_id: post event as a child of the given event - * tags: array, tags to post the event with - * host: string, host to post the event with - * device_name: string, device_name to post the event with - * aggregation_ket: string, key to aggregate this event on - * - * `callback` is an optional function for the result - * callback(error, result, status_code) - */ - if(typeof event != 'object'){ - throw new Error('`event` parameter must be an object'); - } - if(!event['title']){ - throw new Error('`title` property of `event` parameter is required'); - } - - if(!event['text']){ - throw new Error('`text` property of `event` parameter is required'); - } - - if(!event['date_happened']){ - event['date_happened'] = Math.round((new Date()).getTime() / 1000); - } - - if(event['priority']){ - if(['normal', 'low'].indexOf(event['priority'].toLowerCase()) == -1){ - event['priority'] = undefined; + client.request("GET", "/events", params, callback); +} + +module.exports = { + create: create, + get: get, + query: query, + getUsage: function(){ + return [ + " dogapi event get ", + " dogapi event query [--priority ] [--sources ] [--tags ]", + " dogapi event create <text> [--time <timestamp>] [--priority <priority>] [--host <host>] [--tags <tags>] [--type <type>] [--agg-key <agg-key>] [--source <source>]" + ]; + }, + getHelp: function(){ + return [ + "Event:", + " Subcommands:", + " get <event-id> get the event with the provided <event-id>", + " query <from> <to> query the event stream between <from> and <to> POSIX timestamps", + " create <title> <text> create a new event with <title> and <text>", + " Options:", + " --priority <priority> the priority of the event \"normal\" or \"low\"", + " --sources <sources> a comma separated list of sources (e.g. \"users,jenkins,chef\")", + " --tags <tags> a comma separated list of \"tag:value\"'s", + " --time <time> a POSIX timestamp for when the event happened", + " --host <host> the host to associate the event to", + " --type <type> the event type \"error\", \"warning\", \"info\" or \"success\"", + " --agg-key <agg-key> an aggregation key to use to associate like events", + " --source <source> the source to associate with this event (e.g. \"users\", \"jenkins\", etc)" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "get" && args._.length > 4){ + get(parseInt(args._[4]), callback); + } else if(subcommand === "query" && args._.length > 5){ + var from = parseInt(args._[4]); + var to = parseInt(args._[5]); + var parameters = {}; + if(args["sources"]){ + parameters.sources = args["sources"]; + } + if(args["tags"]){ + parameters.tags = args["tags"]; + } + query(from, to, parameters, callback); + } else if(subcommand === "create" && args._.length > 5){ + var title = args._[4]; + var text = args._[5]; + var properties = {}; + if(args["priority"]){ + properties.priority = args["priority"]; + } + if(args["host"]){ + properties.host = args["host"]; + } + if(args["time"]){ + properties.date_happened = parseInt(args["time"]); + } + if(args["tags"]){ + properties.tags = args["tags"].split(","); + } + if(args["agg-key"]){ + properties.aggregation_key = args["agg-key"]; + } + if(args["source"]){ + properties.source_type_name = args["source"]; + } + create(title, text, properties, callback); + } else { + callback("unknown subcommand or arguments try `dogapi event --help` for help", false); } } - - if(event['tags']){ - event['tags'] = event['tags'].join(); - } - - this.request('POST', '/events', {body: event}, callback); }; - -event_api.prototype.add_comment = function(comment, callback){ - /* - * event_api.add_comment(comment, [callback]) - * - * method used to add a new comment to datadog - * - * `comment` is a object representation of the new comment: - * message: *require*, string, comment text body - * handle: string, optional handle name to use instead of owner of the app key - * related_event_id: string, optional event id to attach this comment to - * - * `callback` is an optional function for the result of the call - * callback(error, result, status_code) - */ - if(typeof comment != 'object'){ - throw new Error('`comment` parameter must be an object'); - } - - if(!comment['message']){ - throw new Error('`message` property of `comment` paramter is required'); - } - - this.request('POST', '/comments', {body: comment}, callback); -}; - -event_api.prototype.update_comment = function(comment_id, comment, callback){ - /* - * event_api.update_comment(comment_id, comment, callback) - * - * method used to update a comment that already exists in datadog - * - * `comment_id` is the id of the comment to update - * `comment` an object representation of the comment changes to make - * message: string, the new message text for the comment - * handle: string, the new owner of the comment - * - * `callback` an optional callback to call with the result - * callback(error, result, status_code) - */ - if(typeof comment != 'object'){ - throw new Error('`comment` parameter must be an object'); - } - - this.request('PUT', util.format('/comments/%s', comment_id), {body: comment}, callback); -}; - -event_api.prototype.delete_comment = function(comment_id, callback){ - /* - * event_api.delete_comment(comment_id, callback) - * - * method used to remove a comment from datadog - * - * `comment_id` the comment id for the comment to remove - * `callback` an optional function to handle the result - * callback(error, result, status_code) - * - */ - this.request('DELETE', util.format('/comments/%s', comment_id), callback); -}; - - -return module.exports = event_api; diff --git a/lib/api/graph.js b/lib/api/graph.js new file mode 100644 index 0000000..84fdbff --- /dev/null +++ b/lib/api/graph.js @@ -0,0 +1,73 @@ +var client = require("../client"); + +/*section: graph + *comment: take a snapshot of a metric query + *params: + * query: the metric query to use for the snapshot + * from: POSIX timestamp for the beginning of the query + * to: POSIX timestamp for the end of the query + * eventQuery: optional, an event query to overlay event bands on the snapshot + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var query = "system.cpu.idle{*}"; + * var to = dogapi.now(); + * var from = from - 3600; // an hour ago + * dogapi.graph.snapshot(query, from, to, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function snapshot(query, from, to, eventQuery, callback){ + if(arguments.length < 5 && typeof arguments[3] === "function"){ + callback = eventQuery; + eventQuery = undefined; + } + var params = { + query: { + metric_query: query, + start: parseInt(from), + end: parseInt(to) + } + }; + if(eventQuery){ + params.query.event_query = eventQuery; + } + + client.request("GET", "/graph/snapshot", params, callback); +} + +module.exports = { + snapshot: snapshot, + getUsage: function(){ + return [ + " dogapi graph snapshot <query> <from> <to> [--events <event-query>]" + ]; + }, + getHelp: function(){ + return [ + "Graph:", + " Subcommands:", + " snapshot <query> <from> <to> take a snapshot of a graph", + " Options:", + " --events <event-query> a query for event bands to add to the snapshot" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(args._.length > 5){ + var query = args._[4]; + var from = parseInt(args._[5]); + var to = parseInt(args._[6]); + var eventQuery = args["events"]; + snapshot(query, from, to, eventQuery, callback); + } else { + callback("unknown subcommand or arguments try `dogapi graph --help` for help", false); + } + } +}; diff --git a/lib/api/host.js b/lib/api/host.js new file mode 100644 index 0000000..e2e2bb2 --- /dev/null +++ b/lib/api/host.js @@ -0,0 +1,112 @@ +var client = require("../client"); + +/*section: host + *comment: mute the given host, if it is not already muted + *params: + * hostname: the hostname of the host to mute + * options: | + * optional, an object containing any of the following + * * end: POSIX timestamp for when the mute should end + * * override: whether or not to override the end for an existing mute + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.host.mute("my.host.name", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function mute(hostname, options, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = options; + options = {}; + } + var params = { + body: { + hostname: hostname + } + }; + if(typeof options === "object"){ + if(options.end){ + params.body.end = parseInt(options.end); + } + if(options.override){ + params.body.override = options.override; + } + } + client.request("POST", "/host", params, callback); +} + +/*section: host + *comment: unmute the given host, if it is not already unmuted + *params: + * hostname: the hostname of the host to unmute + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.host.unmute("my.host.name", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function unmute(hostname, callback){ + var params = { + body: { + hostname: hostname + } + }; + client.request("POST", "/host", params, callback); +} + +module.exports = { + mute: mute, + unmute: unmute, + getUsage: function(){ + return [ + " dogapi host mute <host> [--end <end>] [--override]", + " dogapi host unmute <host>" + ]; + }, + getHelp: function(){ + return [ + "Host:", + " Subcommands:", + " mute <host> mute the host with the provided hostname", + " unmute <host> unmute the host with the provided hostname", + "", + " Options:", + " --end <end> POSIX timestamp for when the mute should end", + " --override override an existing \"end\" for a mute on a host" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "mute"){ + var hostname = args._[4]; + var options = {}; + if(args["end"]){ + options.end = parseInt(args["end"]); + } + if(args["override"]){ + options.override = args["override"]; + } + mute(hostname, options, callback); + } else if(subcommand === "unmute"){ + var hostname = args._[4]; + unmute(hostname, callback); + } else { + callback("unknown subcommand or arguments try `dogapi host --help` for help", false); + } + } +}; diff --git a/lib/api/index.js b/lib/api/index.js new file mode 100644 index 0000000..21bb552 --- /dev/null +++ b/lib/api/index.js @@ -0,0 +1,21 @@ +var api = { + comment: require("./comment"), + downtime: require("./downtime"), + event: require("./event"), + graph: require("./graph"), + host: require("./host"), + infrastructure: require("./infrastructure"), + metric: require("./metric"), + monitor: require("./monitor"), + screenboard: require("./screenboard"), + serviceCheck: require("./serviceCheck"), + tag: require("./tag"), + timeboard: require("./timeboard"), + user: require("./user"), +}; + +module.exports = function(obj){ + for(key in api){ + obj[key] = api[key]; + } +}; diff --git a/lib/api/infrastructure.js b/lib/api/infrastructure.js new file mode 100644 index 0000000..b96f245 --- /dev/null +++ b/lib/api/infrastructure.js @@ -0,0 +1,52 @@ +var client = require("../client"); + +/*section: infrastructure + *comment: | + * search for metrics or hosts + *params: + * query: | + * the query to use for search see [datadog docs](http://docs.datadoghq.com/api/#search) + * for examples of the query (e.g. "hosts:database", "metrics:system" or "test") + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.infrastructure.search("hosts:database", function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function search(query, callback){ + var params = { + query: { + q: query + } + }; + + client.request("GET", "/search", params, callback); +} + +module.exports = { + search: search, + getUsage: function(){ + return [ + " dogapi infrastructure search <query>" + ] + }, + getHelp: function(){ + return [ + "Infrastructure:", + " Subcommands:", + " search <query> query for hosts or metrics with <query> (see http://docs.datadoghq.com/api/#search)", + ]; + }, + handleCli: function(subcommand, args, callback){ + var query = args._[4]; + search(query, callback); + } +}; diff --git a/lib/api/metric.js b/lib/api/metric.js index 6cdba32..71c9ec3 100644 --- a/lib/api/metric.js +++ b/lib/api/metric.js @@ -1,59 +1,187 @@ -var metric_api = function(){}; +var client = require("../client"); -metric_api.prototype.add_metric = function(metric, callback){ - /* - * metric_api.add_metric(metric, [callback]) - * - * method used to add a single metric to datadog - * - * `metric` an object representation of the metric - * metric: *required*, the name of the metric - * points: *required*, an array of elements [ timestamp, value ] - * host: name of the host that produced the event - * tags: array of tags to associate with the event - * type: "guage" or "counter" - * - * `callback` an optional function to call with the results - * callback(metric, [callback]) - */ - var metrics = { - 'series': [metric] - }; - this.add_metrics(metrics, callback); -}; -metric_api.prototype.add_metrics = function(metrics, callback){ - /* - * metric_api.add_metrics(metrics, [callback]) - * - * method used to add multiple metrics to datadog - * - * `metrics` an object representation of the metric: - * series: an array of `metrics` to add - * - * `callback` an optional function to call with the results - * callback(metric, [callback]) - */ - if(typeof metrics != 'object'){ - throw new Error('`metrics` parameter must be an object'); +/*section: metric + *comment: | + * submit a new metric + *params: + * metric: the metric name + * points: | + * single datapoint or array of [timestamp, datapoint], if a single point + * is given "now" is used as the timestamp + * extra: | + * optional, object which can contain the following keys + * * host: the host source of the metric + * * tags: array of "tag:value"'s to use for the metric + * * metric_type: which metric type to use ("gauge" or "counter") [default: gauge] + * callback: | + * function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.metric.send("my.metric", 1000, function(err, results){ + * console.dir(results); + * }); + * var now = parseInt(new Date().getTime() / 1000); + * dogapi.metric.send("my.metric", [now, 1000], function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function send(metric, points, extra, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = tags; + extra = {}; } - if(!metrics['series'] || typeof metrics['series'] != 'object'){ - throw new Error('`metrics["series"]` parameter must be an array'); + extra = extra || {}; + var series = [ + { + metric: metric, + points: points, + host: extra.host, + tags: extra.tags, + metric_type: extra.metric_type + } + ]; + + send_all(series, callback); +} + +/*section: metric + *comment: | + * send a list of metrics + *params: + * metrics: | + * an array of metrics where each element is an object with the following keys + * * metric: the name of the metric + * * points: a single datapoint or an array of [timestamp, datapoint] (same as `dogapi.metric.send`) + * * tags: an array of "tag:value"'s + * * host: the source hostname to use for the metrics + * * metric_type: the type of metric to use ("gauge" or "counter") [default: gauge] + * callback: | + * function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var now = parseInt(new Date().getTime() / 1000); + * var metrics = [ + * { + * metric: "my.metric", + * points: [now, 1000], + * tags: ["tag:value"] + * }, + * { + * metric: "another.metric", + * points: 1000 + * } + * ]; + * dogapi.metric.send_all(metrics, function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function send_all(metrics, callback){ + var now = parseInt(new Date().getTime() / 1000); + for(var i = 0; i < metrics.length; ++i){ + if(!Array.isArray(metrics[i].points)){ + metrics[i].points = [now, metrics[i].points]; + } } + var params = { + body: metrics + }; + client.request("POST", "/series", params, callback); +} - for(var i in metrics['series']){ - var metric = metrics['series'][i]; - if(!metric['metric']){ - throw new Error('metric["metric"] is required'); +/*section: metric + *comment: | + * make a metric query + *params: + * from: POSIX timestamp for start of query + * to: POSIX timestamp for end of query + * query: the string query to perform (e.g. "system.cpu.idle{*}by{host}") + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var now = parseInt(new Date().getTime() / 1000); + * var then = now - 3600; // one hour ago + * var query = "system.cpu.idle{*}by{host}"; + * dogapi.metric.query(then, now, query, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function query(from, to, query, callback){ + var params = { + query: { + from: from, + to: to, + query: query } + }; + client.request("GET", "/query", params, callback); +} - if(!metric['points'] || typeof metric['points'] != 'object'){ - throw new Error('metric["points"] must be an array'); +module.exports = { + send: send, + send_all: send_all, + query: query, + getUsage: function(){ + return [ + " dogapi metric send <metric> <point> [--tags <tags>] [--host <host>] [--type <type>]", + " dogapi metric query <from> <to> <query>" + ] + }, + getHelp: function(){ + return [ + "Metric:", + " Subcommands:", + " send <metric> <point> add a new datapoint for <metric> for right now", + " query <from> <to> <query> query for <query> between <from> and <to> POSIX timestamps", + "", + " Options:", + " --tags <tags> a comma separated list of \"tag:value\"'s", + " --host <host> the hostname that should be associated with this metric", + " --type <type> the type of metric \"gauge\" or \"counter\"" + ] + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "send"){ + var extra = {}; + if(args["--tags"]){ + extra.tags = args["--tags"].split(","); + } + if(args["--host"]){ + extra.host = args["--host"]; + } + if(args["--type"]){ + extra.metric_type = args["--type"]; + } + send(args["<metric>"], args["<point>"], extra, callback); + } else if(subcommand === "query" && args._.length > 6){ + var from = parseInt(args._[4]); + var to = parseInt(args._[5]); + var q = args._[6]; + query(from, to, q, callback); + } else { + callback("unknown subcommand or arguments try `dogapi metric --help` for help", false); } } - - this.request('POST', '/series', {body: metrics}, callback); }; - -return module.exports = metric_api; diff --git a/lib/api/monitor.js b/lib/api/monitor.js new file mode 100644 index 0000000..ac03d5b --- /dev/null +++ b/lib/api/monitor.js @@ -0,0 +1,438 @@ +var client = require("../client"); +var util = require("util"); + +/*section: monitor + *comment: create a new monitor + *params: + * type: one of "metric alert" or "service check" + * query: the monitor query to use, you probably want to read datadog's [monitor create](http://docs.datadoghq.com/api/#monitor-create) docs + * properties: | + * optional, an object containing any of the following + * * name: the name of the monitor + * * message: the message for the monitor + * * options: an object, to see available options please see the [monitor create](http://docs.datadoghq.com/api/#monitor-create) docs + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var metricType = "metric alert"; + * var query = "avg(last_1h):sum:system.net.bytes_rcvd{host:host0} > 100"; + * dogapi.monitor.create(metricType, query, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function create(type, query, properties, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = properties; + properties = {}; + } + + var params = { + body: { + type: type, + query: query + } + }; + + if(typeof properties === "object"){ + if(properties.name){ + params.body.name = properties.name; + } + if(properties.messsage){ + params.body.message = properties.message; + } + if(typeof properties.options === "object"){ + params.body.options = properties.options; + } + } + client.request("POST", "/monitor", params, callback); +} + +/*section: monitor + *comment: get an existing monitor's details + *params: + * monitorId: the id of the monitor + * groupStates: an array containing any of the following "all", "alert", "warn", or "no data" + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.get(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function get(monitorId, groupStates, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = groupStates; + groupStates = undefined; + } + + var params = {}; + if(groupStates){ + params.query = { + group_states: groupStates.join(",") + }; + } + + client.request("GET", util.format("/monitor/%s", monitorId), params, callback); +} + +/*section: monitor + *comment: get all monitors + *params: + * options: | + * optional, an object containing any of the following + * * group_states: an array containing any of the following "all", "alert", "warn", or "no data" + * * tags: an array of "tag:value"'s to filter on + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.getAll(function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function getAll(options, callback){ + if(arguments.length < 2 && typeof arguments[0] === "function"){ + callback = options; + options = {}; + } + var params = {}; + if(typeof options === "object"){ + params.query = {}; + if(options.group_states){ + params.query.group_states = options.group_states.join(","); + } + if(options.tags){ + params.query.tags = options.tags.join(","); + } + } + client.request("GET", "/monitor", params, callback); +} + +/*section: monitor + *comment: update a monitor's details + *params: + * monitorId: the id of the monitor to edit + * query: the query that the monitor should have, see the [monitor create](http://docs.datadoghq.com/api/#monitor-create) docs for more info + * properties: | + * optional, an object containing any of the following + * * name: the name of the monitor + * * message: the message for the monitor + * * options: an object, to see available options please see the [monitor create](http://docs.datadoghq.com/api/#monitor-create) docs + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var query = "avg(last_1h):sum:system.net.bytes_rcvd{host:host0} > 100"; + * dogapi.monitor.update(1234, query, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function update(monitorId, query, properties, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = properties; + properties = {}; + } + + var params = { + body: { + query: query + } + }; + + if(typeof properties === "object"){ + if(properties.name){ + params.body.name = properties.name; + } + if(properties.messsage){ + params.body.message = properties.message; + } + if(typeof properties.options === "object"){ + params.body.options = properties.options; + } + } + client.request("PUT", util.format("/monitor/%s", monitorId), params, callback); +} + +/*section: monitor + *comment: delete an existing monitor + *params: + * monitorId: the id of the monitor to remove + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.remove(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function remove(monitorId, callback){ + client.request("DELETE", util.format("/monitor/%s", monitorId), callback); +} + +/*section: monitor + *comment: mute an existing monitor + *params: + * monitorId: the id of the monitor to mute + * options: | + * optional, an object containing any of the following + * * scope: the scope to mute (e.g. "role:db") + * * end: POSIX timestamp indicating when the mute should end + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.mute(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function mute(monitorId, options, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = options; + options = {}; + } + var params = {}; + if(typeof options === "object"){ + params.body = {}; + if(options.scope){ + params.body.scope = options.scope; + } + if(options.end){ + params.body.end = parseInt(options.end); + } + } + client.request("POST", util.format("/monitor/%s/mute"), params, callback); +} + +/*section: monitor + *comment: mute all monitors + *params: + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.muteAll(function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function muteAll(callback){ + client.request("POST", "/monitor/mute_all", callback); +} + +/*section: monitor + *comment: unmute an existing monitor + *params: + * monitorId: the id of the monitor to unmute + * scope: optional, a scope to apply the unmute to (e.g. "role:db") + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.unmute(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function unmute(monitorId, scope, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = scope; + scope = undefined; + } + var params = {}; + if(scope){ + params.body = { + scope: scope + }; + } + client.request("POST", util.format("/monitor/%s/unmute", monitorId), params, callback); +} + +/*section: monitor + *comment: unmute all monitors + *params: + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.monitor.unmuteAll(function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function unmuteAll(callback){ + client.request("POST", "/monitor/unmute_all", callback); +} + +module.exports = { + create: create, + get: get, + update: update, + remove: remove, + getAll: getAll, + mute: mute, + muteAll: muteAll, + unmute: unmute, + unmuteAll: unmuteAll, + getUsage: function(){ + return [ + " dogapi monitor create <type> <query> [--name <name>] [--message <message>]", + " dogapi monitor get <monitor-id> [--states <states>]", + " dogapi monitor getall [--states <states>] [--tags <tags>]", + " dogapi monitor mute <monitor-id> [--scope <scope>] [--end <end>]", + " dogapi monitor muteall", + " dogapi monitor remove <monitor-id>", + " dogapi monitor unmute <monitor-id> [--scope <scope>]", + " dogapi monitor unmuteall", + " dogapi monitor update <monitor-id> <query> [--name <name>] [--message <message>]" + ]; + }, + getHelp: function(){ + return [ + "Monitor:", + " Subcommands:", + " create <type> <query> create a new monitor", + " get <monitor-id> get a monitors details", + " getall get a list of all monitors", + " mute <monitor-id> mute the monitor with the id <monitor-id>", + " muteall mute all monitors", + " remove <monitor-id> delete the monitor with the id <monitor-id>", + " unmute <monitor-id> unmute the monitor with the id <monitor-id>", + " unmuteall unmute all monitors", + " update <monitor-id> <query> update an existing monitor", + "", + " Options:", + " --states <states> a comma separated list containing any of \"all\", \"alert\", \"warn\", or \"no data\"", + " --tags <tags> a comma separated list of \"tag:value\"'s", + " --scope <scope> the scope of the monitor to mute (e.g. \"role:db\")", + " --end <end> POSIX timestamp for when the mute should end", + " --name <name> the name for the monitor", + " --message <message> the message for the monitor" + ]; + }, + handleCli: function(subcommand, args, callback){ + var states = []; + if(args["states"]){ + states = args["states"].split(","); + } + + var tags = []; + if(args["tags"]){ + tags = args["tags"].split(","); + } + + var name = args["name"]; + var message = args["message"]; + + if(subcommand === "get"){ + var monitorId = args._[4]; + get(monitorId, states, callback); + } else if(subcommand === "getall"){ + var options = {}; + if(states.length){ + options.group_states = states; + } + if(tags.length){ + options.tags = tags; + } + getAll(options, callback); + } else if(subcommand === "mute"){ + var monitorId = args._[4]; + var options = {}; + if(args["scope"]){ + options.scope = args["scope"]; + } + if(args["end"]){ + options.end = args["end"]; + } + mute(monitorId, options, callback); + } else if(subcommand === "unmute"){ + var monitorId = args._[4]; + var scope = args["scope"]; + unmute(monitorId, scope, callback); + } else if(subcommand === "unmuteall"){ + unmuteAll(callback); + } else if(subcommand === "muteall"){ + muteAll(callback); + } else if(subcommand === "remove"){ + var monitorId = args._[4]; + remove(monitorId, callback); + } else if(subcommand === "create" && args._.length > 5){ + var type = args._[4]; + var query = args._[5]; + var properties = {}; + if(name){ + properties.name = name; + } + if(message){ + properties.message = message; + } + create(type, query, properties, callback); + } else if(subcommand === "update" && args._.length > 5){ + var monitorId = args._[4]; + var query = args._[5]; + var properties = {}; + if(name){ + properties.name = name; + } + if(message){ + properties.message = message; + } + update(monitorId, query, properties, callback); + } else { + callback("unknown subcommand or arguments try `dogapi monitor --help` for help", false); + } + } +}; diff --git a/lib/api/screen.js b/lib/api/screen.js deleted file mode 100644 index febfb8f..0000000 --- a/lib/api/screen.js +++ /dev/null @@ -1,116 +0,0 @@ -var util = require('util'); - -var validate_screenboard = function(screenboard){ - if(typeof screenboard != 'object'){ - throw new Error('`screenboard` parameter must be an object'); - } - - if(typeof screenboard['board_title'] != 'string'){ - throw new Error('`screenboard["board_title"]` must be a string'); - } - - if(screenboard['width'] != undefined && typeof screenboard['width'] != 'number'){ - throw new Error('`screenboard["width"]` must be a number'); - } - - if(screenboard['height'] != undefined && typeof screenboard['height'] != 'number'){ - throw new Error('`screenboard["height"]` must be a number'); - } - - if(typeof screenboard['widgets'] != 'object'){ - throw new Error('`screenboard["widgets"]` must be an array'); - } - - for(var i in screenboard['widgets']){ - if(!screenboard['widgets'][i]['type']){ - throw new Error(util.format('`screenboard["widgets"][%s]["type"]` is missing', i)); - } - if(!screenboard['widgets'][i]['width']){ - throw new Error(util.format('`screenboard["widgets"][%s]["width"]` is missing', i)); - } - if(!screenboard['widgets'][i]['height']){ - throw new Error(util.format('`screenboard["widgets"][%s]["height"]` is missing', i)); - } - if(!screenboard['widgets'][i]['x']){ - throw new Error(util.format('`screenboard["widgets"][%s]["x"]` is missing', i)); - } - if(!screenboard['widgets'][i]['y']){ - throw new Error(util.format('`screenboard["widgets"][%s]["y"]` is missing', i)); - } - } -}; - -var screen_api = function(){}; - -screen_api.prototype.get_screenboard = function(screen_id, callback){ - /* - * screen_api.get_screenboard(screen_id, [callback]) - * - * method to get a single screenboard information - * - * `screen_id` is the id of the screenboard to get information for - * `callback` is an optional function to call with the results of the api call - * callback(error, results, status_code) - */ - this.request('GET', util.format('/screen/%s', screen_id), callback); -}; - -screen_api.prototype.get_all_screenboards = function(callback){ - /* - * screen_api.get_all_screenboards([callback]) - * - * method to retrieve all screenboards in datadog - * - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - this.request('GET', '/screen', callback); -}; - -screen_api.prototype.create_screenboard = function(screenboard, callback){ - /* - * screen_api.create_screenboard(screenboard, [callback]) - * - * method used to create a new screenboard in datadog - * - * `screenboard` is the definition for the screenboard - * please see (http://docs.datadoghq.com/api/) for more information - * - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - validate_screenboard(screenboard); - this.request('POST', '/screen', {body: screenboard}, callback); -}; - -screen_api.prototype.update_screenboard = function(screen_id, screenboard, callback){ - /* - * screen_api.update_screenboard(screen_id, screenboard, [callback]) - * - * method used to update the screenboard with the provided `screen_id` - * - * `screen_id` the id of the screenboard to update - * `screenboard` is a definition for the datadog screenboard - * please see (http://docs.datadoghq.com/api/) for more information - * - * `callback` an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - validate_screenboard(screenboard); - this.request('PUT', util.format('/screen/%s', screen_id), {body: screenboard}, callback); -}; - -screen_api.prototype.delete_screenboard = function(screen_id, callback){ - /* - * screen_api.delete_screenboard(screen_id, [callback]) - * - * method to remove a screenboard from datadog - * - * `screen_id` the id for the screenboard to remove - * `callback` an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - this.request('DELETE', util.format('/screen/%s', screen_id), callback); -}; - -return module.exports = screen_api; diff --git a/lib/api/screenboard.js b/lib/api/screenboard.js new file mode 100644 index 0000000..86797d7 --- /dev/null +++ b/lib/api/screenboard.js @@ -0,0 +1,239 @@ +var client = require("../client"); +var util = require("util"); + + +/*section: screenboard + *comment: create a new screenboard + *params: + * title: the name of the screenboard + * description: description of the screenboard + * graphs: | + * an array of objects which required the following keys + * * title: the name of the graph + * * widgets: an array of widgets, see http://docs.datadoghq.com/api/screenboards/ for more info + * options: | + * optional, a object which can contain any of the following keys + * * templateVariables: | + * an array of objects with the following keys + * * name: the name of the variable + * * prefix: optional, the tag prefix for this variable + * * default: optional, the default value for this tag + * * width: the width of the screenboard in pixels + * * height: the height of the screenboard in pixels + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var title = "my screenboard"; + * var description = "it is super awesome"; + * var graphs = [ + * { + * type: "image", + * height: 20, + * width: 32, + * y: 7, + * x: 32, + * url: "https://path/to/image.jpg" + * } + * ]; + * var options = { + * templateVariables: [ + * { + * name: "host1", + * prefix: "host", + * "default": "host:my-host" + * } + * ] + * }; + * dogapi.screenboard.create( + * title, description, graphs, options, + * function(err, res){ + * console.dir(res); + * } + * ); + * ``` + */ +function create(title, description, graphs, options, callback){ + if(arguments.length < 5 && typeof arguments[3] === "function"){ + callback = options; + options = {}; + } + if(typeof options !== "object"){ + options = {}; + } + + var params = { + body: { + title: title, + description: description, + graphs: graphs + } + }; + + if(options.templateVariables){ + params.body.template_variables = options.templateVariables; + } + if(options.width){ + params.body.width = options.width; + } + if(options.height){ + params.body.height = options.height; + } + + client.request("POST", "/screen", params, callback); +} + +/*section: screenboard + *comment: delete an existing screenboard + *params: + * boardId: the id of the screenboard to delete + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.screenboard.remove(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function remove(boardId, callback){ + client.request("DELETE", util.format("/screen/%s", boardId), callback); +} + +/*section: screenboard + *comment: get the info of a single existing screenboard + *params: + * boardId: the id of the screenboard to fetch + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.screenboard.get(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function get(boardId, callback){ + client.request("GET", util.format("/screen/%s", boardId), callback); +} + +/*section: screenboard + *comment: get all existing screenboards + *params: + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.screenboard.getAll(function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function getAll(callback){ + client.request("GET", "/screen", callback); +} + +/*section: screenboard + *comment: share an existing screenboard + *params: + * boardId: the id of the screenboard to share + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.screenboard.share(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function share(boardId, callback){ + client.request("GET", util.format("/screen/share/%s", boardId), callback); +} + + +module.exports = { + create: create, + remove: remove, + get: get, + getAll: getAll, + share: share, + getUsage: function(){ + return [ + "dogapi screenboard create <title> <description> <graphs> [--tmpvars <templateVariables>] [--width <width>] [--height <height>]", + "dogapi screenboard remove <boardId>", + "dogapi screenboard get <boardId>", + "dogapi screenboard getall", + "dogapi screenboard share <boardId>" + ]; + }, + getHelp: function(){ + return [ + "Screenboard:", + " Subcommands:", + " create <title> <description> <graphs> create a new screenboard, <graphs> is a json of the graph definition", + " remove <boardId> remove an existing screenboard", + " get <boardId> get an existing screenboard", + " getall get all screenboards", + " share <boardId> get share info for an existing screenboard", + " Options:", + " --tmpvars <templateVariables> json representation of the template variable definition", + " --width <width> width of the screenboard in pixels", + " --height <height> height of the screenboard in pixels", + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "get"){ + get(args._[4], callback); + } else if(subcommand === "getall"){ + getAll(callback); + } else if(subcommand === "remove"){ + remove(args._[4], callback); + } else if(subcommand === "share"){ + share(args._[4], callback); + } else if(subcommand === "create"){ + var title = args._[4]; + var description = args._[5]; + var graphs = JSON.parse(args._[6]); + + var options = {}; + if(args["tmpvars"]){ + options.templateVariables = JSON.parse(args["tmpvars"]); + } + if(args["width"]){ + options.width = parseInt(args["width"]); + } + if(args["height"]){ + options.height = parseInt(args["height"]); + } + + create(title, description, graphs, options, callback); + } else { + callback("unknown subcommand or arguments try `dogapi screenboard --help` for help", false); + } + } +}; diff --git a/lib/api/search.js b/lib/api/search.js deleted file mode 100644 index 416110c..0000000 --- a/lib/api/search.js +++ /dev/null @@ -1,16 +0,0 @@ -var search_api = function(){}; -search_api.prototype.search = function(query, callback){ - /* - * search_api.search(query, [callback]) - * - * method used to query the api for `metrics` or `hosts` - * - * `query` the query to use to search the datadog service - * - * `callback` an optional function called with the results of the search - * callback(error, result, status_code) - */ - this.request('GET', '/search', {query: {'q': query}}, callback); -}; - -return module.exports = search_api; diff --git a/lib/api/serviceCheck.js b/lib/api/serviceCheck.js new file mode 100644 index 0000000..6a6e7fe --- /dev/null +++ b/lib/api/serviceCheck.js @@ -0,0 +1,89 @@ +var client = require("../client"); + +/*section: serviceCheck + *comment: | + * post an update to a service check + *params: + * check: the check name (e.g. "app.ok") + * hostName: the name of the host submitting the check + * status: one of `dogapi.OK`, `dogapi.WARNING`, `dogapi.CRITICAL` or `dogapi.UNKNOWN` + * parameters: | + * optional, an object containing any of the following + * * timestamp: POSIX timestamp for when the check happened + * * message: string message to accompany the check + * * tags: an array of "tag:value"'s associated with the check + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var check = "app.ok"; + * var hostName = "some.machine"; + * dogapi.serviceCheck.check( + * check, hostName, dogapi.WARNING, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function check(check, hostName, status, parameters, callback){ + if(arguments.length < 5 && typeof arguments[3] === "function"){ + callback = parameters; + parameters = {}; + } + + if(typeof parameters !== "object"){ + parameters = {}; + } + + parameters.check = check; + parameters.host_name = hostName, + parameters.status = status; + + var params = { + body: parameters + }; + client.request("POST", "/check_run", params, callback); +}; + + +module.exports = { + check: check, + getUsage: function(){ + return [ + " dogapi servicecheck check <check> <host> <status> [--time <timestamp>] [--message <message>] [--tags <tags>]" + ]; + }, + getHelp: function(){ + return [ + "Service Check:", + " Subcommands:", + " check <check> <host> <status> add a new service check for <check> and <host> at level <status> (0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN)", + "", + " Options:", + " --time <timestamp> the POSIX timestamp to use for the check", + " --message <message> an optional message to accompany the check", + " --tags <tags> a comma separated list of \"tag:value\"'s for the check" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(args._.length > 6){ + var parameters = {}; + if(args["time"]){ + parameters.time = parseInt(args["time"]); + } + if(args["message"]){ + paramaters.message = args["message"]; + } + if(args["tags"]){ + parameters.tags = args["tags"].split(","); + } + check(args._[4], args._[5], parseInt(args._[6]), parameters, callback); + } else { + callback("not enough arguments try `dogapi servicecheck --help` for help", false); + } + } +}; diff --git a/lib/api/service_check.js b/lib/api/service_check.js deleted file mode 100644 index c762981..0000000 --- a/lib/api/service_check.js +++ /dev/null @@ -1,47 +0,0 @@ -var util = require('util'); - -var constants = require('../constants'); - -var service_check_api = function(){}; - - -service_check_api.prototype.service_check = function(status, check, host, extra, callback){ - /* - * service_check_api.service_check(options, callback]) - * - * used to post a service check - * - * `status` the `dogapi.constant.STATUSES` status code for the check - * `check` the name of the check - * `host` the host associated with the check - * `extra` an object of optional arguments `timestamp`, `message` or `tags` - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(typeof extra === 'function'){ - callback = extra; - extra = {}; - } - - if(constants.ALL_STATUSES.indexOf(status) < 0){ - throw new Error(util.format('Unknown service_check status %s', status)); - } - - var body = { - check: check, - status: status, - host_name: host, - timestamp: parseInt(extra['timestamp'] || (new Date().getTime() / 1000)), - }; - - if(extra['message']){ - body['message'] = extra['message']; - } - if(extra['tags']){ - body['tags'] = extra['tags']; - } - - this.request('POST', '/check_run', {body: body}, callback); -}; - -return module.exports = service_check_api; diff --git a/lib/api/snapshot.js b/lib/api/snapshot.js deleted file mode 100644 index 2ce482a..0000000 --- a/lib/api/snapshot.js +++ /dev/null @@ -1,101 +0,0 @@ -var extend = require('extend'); -var util = require('util'); - -var snapshot_api = function(){}; - -snapshot_api.prototype.add_snapshot = function(snapshot, callback){ - /* - * snapshot_api.add_snapshot(snapshot, [callback]) - * - * method used to add a new snapshot to datadog - * - * `snapshot` is an object containing any of the following: - * metric_query: *required*, The metric query. - * start: *required*, int, Start of the query.(POSIX timestamp) - * end: *required*, int, End of the query.(POSIX timestamp) - * event_query: A query that will add event bands to the graph. - * - * `callback` is an optional function for the result - * callback(error, result, status_code) - */ - if(typeof snapshot != 'object'){ - throw new Error('`snapshot` parameter must be an object'); - } - - if(!snapshot['metric_query']){ - throw new Error('`metric_query` property of `snapshot` parameter is required'); - } - - if(!snapshot['start']){ - throw new Error('`start` property of `snapshot` parameter is required'); - } - - if(!snapshot['end']){ - throw new Error('`end` property of `snapshot` parameter is required'); - } - - this.request('GET', '/graph/snapshot', {query: snapshot}, callback); -}; - -snapshot_api.prototype.add_snapshot_from_def = function(snapshot, callback){ - /* - * snapshot_api.add_snapshot_from_def(snapshot, [callback]) - * - * method used to add a new snapshot to datadog based on a graph definition - * https://github.com/DataDog/dogapi/commit/583f13d7bd8de5a86daa2ff53f2d7cf6570e7ab2 - * feature is not currently documented (at time of writing), but very useful. - * - * `snapshot` is an object containing any of the following: - * graph_def: *required*, JSON string dump of an existing graph definition - * start: *required*, int, Start of the query.(POSIX timestamp) - * end: *required*, int, End of the query.(POSIX timestamp) - * - * `callback` is an optional function for the result - * callback(error, result, status_code) - */ - if(typeof snapshot != 'object'){ - throw new Error('`snapshot` parameter must be an object'); - } - - if(!snapshot['graph_def']){ - throw new Error('`graph_def` property of `snapshot` parameter is required'); - } - - if(!snapshot['start']){ - throw new Error('`start` property of `snapshot` parameter is required'); - } - - if(!snapshot['end']){ - throw new Error('`end` property of `snapshot` parameter is required'); - } - - this.request('GET', '/graph/snapshot', {query: snapshot}, callback); -}; - -snapshot_api.prototype.snapshot_status = function(snapshot_url, callback){ - /* - * snapshot_api.add_snapshot(snapshot_url, [callback]) - * - * method used to check the status of a datadog snapshot. - * https://github.com/DataDog/dogapi/blob/master/src/dogapi/http/snapshot.py#L64 - * Snapshot URLs are returned right away, but may be empty if the query or graph is complicated. - * Result will be a json payload, with 403 for incomplete, or 200 for complete. - * Examples: - * * {"status_code":403} - incomplete (still processing, image is empty) - * * {"status_code":200} - image is rendered and ready - * - * `snapshot_url` is a string containing URL returned from a call to add_snapshot or add_snapshot_from_def - * - * `callback` is an optional function for the result - * callback(error, result, status_code) - */ - if(typeof snapshot_url != 'string'){ - throw new Error('`snapshot_url` parameter must be a string'); - } - - url = snapshot_url.split('/snapshot/view/')[1].split('.png')[0] - - this.request('GET', '/graph/snapshot_status/'+url, {}, callback); -}; - -return module.exports = snapshot_api; diff --git a/lib/api/tag.js b/lib/api/tag.js index f155430..3094a36 100644 --- a/lib/api/tag.js +++ b/lib/api/tag.js @@ -1,169 +1,264 @@ +var client = require("../client"); var util = require('util'); -var tag_api = function(){}; - - -tag_api.prototype.all_tags = function(source, callback){ - /* - * tag_api.all_tags([[source], callback]) - * - * method to get all the tags in datadog - * - * `source` a source to limit to - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(arguments.length < 2 && typeof arguments[0] == 'function'){ - callback = arguments[0]; + +/*section: tag + *comment: | + * get all host tags + *params: + * source: | + * optional, only show tags for a particular source [default: null] + * callback: | + * function callback(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.tag.getAll(function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function getAll(source, callback){ + if(arguments.length < 2 && typeof arguments[0] === "function"){ + callback = source; source = undefined; } - params = { + var params = { query: { source: source } }; - this.request('GET', '/tags/hosts', params, callback); -}; + client.request("GET", "/tags/hosts", params, callback); +} -tag_api.prototype.host_tags = function(host, source, callback){ - /* - * tag_api.host_tags(host, [[source], callback]) - * - * method to get the tags associated with a given `host` - * - * `host` the hostname or id to get tags for - * `source` a source to limit the results to - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(arguments.length < 3 && typeof arguments[1] == 'function'){ - callback = arguments[1]; - source = undefined; +/*section: tag + *comment: | + * get the host tags for a provided host name or host id + *params: + * hostname: | + * the hostname or host id + * options: + * | + * optional, an object of options for the query allowing the following + * * source: the source of the tags (e.g. chef, puppet, users, etc) [default: null] + * * by_source: whether or not to group the results by source [default: false] + * callback: | + * function callback(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.tag.get("host.name", function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function get(hostname, options, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = options; + options = {}; } + options = options || {}; - params = { + var params = { query: { - source: source, } }; - this.request('GET', util.format('/tags/hosts/%s', host), params, callback); -}; - -tag_api.prototype.host_tags_by_source = function(host, source, callback){ - /* - * tag_api.host_tags_by_source(host, [[source], callback]) - * - * method to return the tags associated with a host, arranged by source - * - * `host` the hostname of id to get tags for - * `source` a source to limit the lookup for - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(arguments.length < 3 && typeof arguments[1] == 'function'){ - callback = arguments[1]; - source = undefined; + if(options.source){ + params.query.source = options.source; } - - params = { - query: { - source: source, - by_source: true, - } - }; - this.request('GET', util.format('/tags/hosts/%s', host), params, callback); + if(options.by_source){ + params.query.by_source = options.by_source; + } + client.request("GET", "/tags/hosts/" + hostname, params, callback); }; -tag_api.prototype.add_tags = function(host, tags, source, callback){ - /* - * tag_api.add_tags(host, tags, [[source], callback]) - * - * add new tags to given `host` - * - * `host` the hostname or id of the machine to add tags for - * `tags` an array of tags to add to the `host` - * `source` the source to associate the tags with, default: user - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(typeof tags != 'object'){ - throw new Error('`tags` parameter must be an array'); - } - if(arguments.length < 4 && typeof arguments[2] == 'function'){ - callback = arguments[2]; +/*section: tag + *comment: | + * assign new host tags to the provided host name or host id + *params: + * hostname: | + * the hostname or host id + * tags: | + * list of `<tag>:<value>` tags to assign to the server + * source: | + * optional, the source of the tags (e.g. chef, puppet, etc) [default: users] + * callback: | + * function callback(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.tag.create("host.name", ["role:webserver"], function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function create(hostname, tags, source, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = source; source = undefined; } - params = { - query: { - source: source, - }, + var params = { body: { tags: tags, - } + source: source + }, }; - this.request('POST', util.format('/tags/hosts/%s', host), params, callback); + client.request("POST", "/tags/hosts/" + hostname, params, callback); }; -tag_api.prototype.update_tags = function(host, tags, source, callback){ - /* - * tag_api.update_tags(host, tags, [[source], callback]) - * - * update the tags associated with the given `host` - * - * `host` is the hostname or id of the machine to update tags for - * `tags` an array of tags to associate with the `host` - * `source` the source to associate the tags with, default: user - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(typeof tags != 'object'){ - throw new Error('`tags` parameter must be an array'); - } - if(arguments.length < 4 && typeof arguments[2] == 'function'){ - callback = arguments[2]; +/*section: tag + *comment: | + * update the host tags for the provided host name or host id + *params: + * hostname: | + * the hostname or host id + * tags: | + * list of `<tag>:<value>` tags to assign to the server + * source: | + * optional, the source of the tags (e.g. chef, puppet, etc) [default: users] + * callback: | + * function callback(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.tag.update("host.name", function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function update(hostname, tags, source, callback){ + if(arguments.length < 4 && typeof arguments[2] === "function"){ + callback = source; source = undefined; } - params = { - query: { - source: source, - }, + var params = { body: { tags: tags, - } + source: source + }, }; - - this.request('PUT', util.format('/tags/hosts/%s', host), params, callback); + client.request("PUT", "/tags/hosts/" + hostname, params, callback); }; -tag_api.prototype.detach_tags = function(host, source, callback){ - /* - * tag_api.detach_tags(host, [[source], callback]) - * - * method to remove tags for a given `host` - * - * `host` the hostname or id of the machine to remove the tags for - * `source` the source of the tags - * `callback` is an optional function to call with the results of the api call - * callback(error, result, status_code) - */ - if(arguments.length < 3 && typeof arguments[1] == 'function'){ - callback = arguments[1]; +/*section: tag + *comment: | + * delete the host tags for the provided host name or host id + *params: + * hostname: | + * the hostname or host id + * source: | + * optional, the source of the tags (e.g. chef, puppet, etc) [default: users] + * callback: | + * function callback(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.tag.remove("host.name", function(err, results){ + * console.dir(results); + * }); + * ``` + */ +function remove(hostname, source, callback){ + if(arguments.length < 3 && typeof arguments[1] === "function"){ + callback = source; source = undefined; } - params = { + var params = { query: { - source: source, - }, + source: source + } }; - - this.request('DELETE', util.format('/tags/hosts/%s', host), params, callback); + client.request("DELETE", "/tags/hosts/" + hostname, params, callback); }; -return module.exports = tag_api; +module.exports = { + _client: client, + getAll: getAll, + get: get, + create: create, + update: update, + remove: remove, + getUsage: function(){ + return [ + " dogapi tag getall [--source <source>]", + " dogapi tag get <host> [--source <source>] [--by-source]", + " dogapi tag remove <host> [--source <source>]", + " dogapi tag create <host> <tags> [--source <source>]", + " dogapi tag update <host> <tags> [--source <source>]" + ]; + }, + getHelp: function(){ + return [ + "Tag:", + " Subcommands:", + " getall get all tags", + " get <host> get all tags for a given host", + " remove <host> delete tags for a given host", + " create <host> <tags> add the comma separates \"tag:value\"'s from <tag> to <host>", + " update <host> <tags> update the comma separates \"tag:value\"'s from <tag> to <host>", + "", + " Options:", + " --source <source> the source of the tags (e.g. \"chef\", \"user\", \"jenkins\", etc)", + " --by-source whether the results should be grouped by source" + ]; + }, + handleCli: function(subcommand, args, callback){ + var source = args["source"]; + var host = args._[4]; + + if(subcommand === "getall"){ + getAll(source, callback); + } else if(subcommand === "get"){ + var options = {}; + if(source){ + options.source = source; + } + if(args["by-source"]){ + options.by_source = true; + } + get(host, options, callback); + } else if(subcommand === "create"){ + var tags = args._[5].split(","); + create(host, tags, source, callback); + } else if(subcommand === "update"){ + var tags = args._[5].split(","); + update(host, tags, source, callback); + } else if(subcommand === "delete"){ + remove(host, source, callback); + } else { + callback("unknown subcommand or arguments try `dogapi tag --help` for help", false); + } + } +} diff --git a/lib/api/timeboard.js b/lib/api/timeboard.js new file mode 100644 index 0000000..c2c4e18 --- /dev/null +++ b/lib/api/timeboard.js @@ -0,0 +1,274 @@ +var client = require("../client"); +var util = require("util"); + +/*section: timeboard + *comment: add a new timeboard + *params: + * title: the title of the timeboard + * description: the description of the timeboard + * graphs: | + * an array of objects with the following keys + * * title: the name of the graph + * * definition: an object containing the graph definition, e.g. `{"requests": [{"q": "system.cpu.idle{*} by {host}"}` + * templateVariables: | + * optional, an array of objects with the following keys + * * name: the name of the variable + * * prefix: optional, the tag prefix for this variable + * * default: optional, the default value for this tag + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var title = "Time Keeps on Slipping"; + * var description = "Into the Future"; + * var graphs = [ + * { + * definition: { + * events: [], + * requests: [ + * {q: "avg:system.mem.free{*}"} + * ], + * viz: "timeseries" + * }, + * title: "Average Memory Free" + * } + * ]; + * var templateVariables = [ + * { + * name: "host1", + * prefix: "host", + * "default": "host:my-host" + * } + * ]; + * dogapi.timeboard.create( + * title, description, graphs, templateVariables, + * function(err, res){ + * console.dir(res); + * } + * ); + * ``` + */ +function create(title, description, graphs, templateVariables, callback){ + if(arguments.length < 5 && typeof arguments[3] === "function"){ + callback = templateVariables; + templateVariables = []; + } + + var params = { + body: { + title: title, + description: description, + graphs: graphs + } + }; + if(Array.isArray(templateVariables) && templateVariables.length){ + params.body.template_variables = templateVariables; + } + + client.request("POST", "/dash", params, callback); +} + +/*section: timeboard + *comment: update an existing timeboard + *params: + * dashId: the id of the timeboard to update + * title: the title of the timeboard + * description: the description of the timeboard + * graphs: | + * an array of objects with the following keys + * * title: the name of the graph + * * definition: an object containing the graph definition, e.g. `{"requests": [{"q": "system.cpu.idle{*} by {host}"}` + * templateVariables: | + * optional, an array of objects with the following keys + * * name: the name of the variable + * * prefix: optional, the tag prefix for this variable + * * default: optional, the default value for this tag + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var title = "Time Keeps on Slipping"; + * var description = "Into the Future"; + * var graphs = [ + * { + * definition: { + * events: [], + * requests: [ + * {q: "avg:system.mem.free{*}"} + * ], + * viz: "timeseries" + * }, + * title: "Average Memory Free" + * } + * ]; + * var templateVariables = [ + * { + * name: "host1", + * prefix: "host", + * default: "host:my-host" + * } + * ]; + * dogapi.timeboard.update( + * 1234, title, description, graphs, templateVariables, + * function(err, res){ + * console.dir(res); + * } + * ); + * ``` + */ +function update(dashId, title, description, graphs, templateVariables, callback){ + if(arguments.length < 6 && typeof arguments[4] === "function"){ + callback = templateVariables; + templateVariables = []; + } + + var params = { + body: { + title: title, + description: description, + graphs: graphs + } + }; + if(Array.isArray(templateVariables) && templateVariables.length){ + params.body.template_variables = templateVariables; + } + + client.request("POST", util.format("/dash/%s", dashId), params, callback); +} + +/*section: timeboard + *comment: remove an existing timeboard + *params: + * dashId: the id of the timeboard to remove + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.timeboard.remove(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function remove(dashId, callback){ + client.request("DELETE", util.format("/dash/%s", dashId), params, callback); +} + +/*section: timeboard + *comment: get all existing timeboards + *params: + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.timeboard.getAll(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function getAll(callback){ + client.request("GET", "/dash", params, callback); +} + +/*section: timeboard + *comment: get an existing timeboard + *params: + * dashId: the id of the timeboard to get + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.timeboard.get(1234, function(err, res){ + * console.dir(res); + * }); + * ``` + */ +function get(dashId, callback){ + client.request("GET", util.format("/dash/%s", dashId), params, callback); +} + +module.exports = { + create: create, + update: update, + remove: remove, + getAll: getAll, + get: get, + getUsage: function(){ + return [ + " dogapi timeboard get <dash-id>", + " dogapi timeboard getall", + " dogapi timeboard remove <dash-id>", + " dogapi timeboard create <title> <description> <graphs> [--tmpvars <templateVariables>]", + " dogapi timeboard update <dash-id> <title> <description> <graphs> [--tmpvars <templateVariables>]", + ]; + }, + getHelp: function(){ + return [ + "Timeboard:", + " Subcommands:", + " get <dash-id> get an existing timeboard", + " getall get all existing timeboards", + " remove <dash-id> remove an existing timeboard", + " create <title> <description> <graphs> create a new timeboard, <graphs> is a json of the graphs definition", + " update <dash-id> <title> <description> <graphs> update an existing timeboard, <graphs> is a json of the graphs definition", + " Options:", + " --tmpvars <templateVariables> a json representation of the template variables definition" + ]; + }, + handleCli: function(subcommand, args, callback){ + if(subcommand === "get"){ + get(args._[4], callback); + } else if(subcommand === "getall"){ + getAll(callback); + } else if(subcommand === "remove"){ + remove(args._[4], callback); + } else if(subcommand === "create"){ + var title = args._[4]; + var description = args._[5]; + var graphs = JSON.parse(args._[6]); + var templateVariables = []; + if(args["tmpvars"]){ + templateVariables = JSON.parse(args["tmpvars"]); + } + + create(title, description, graphs, templateVariables, callback); + } else if(subcommand === "update"){ + var dashId = parseInt(args._[4]); + var title = args._[5]; + var description = args._[6]; + var graphs = JSON.parse(args._[7]); + var templateVariables = []; + if(args["tmpvars"]){ + templateVariables = JSON.parse(args["tmpvars"]); + } + + update(dashId, title, description, graphs, templateVariables, callback); + } else { + callback("unknown subcommand or arguments try `dogapi timeboard --help` for help", false); + } + } +}; diff --git a/lib/api/user.js b/lib/api/user.js new file mode 100644 index 0000000..e0f21f3 --- /dev/null +++ b/lib/api/user.js @@ -0,0 +1,48 @@ +var client = require("../client"); + +/*section: user + *comment: invite users via e-mail + *params: + * emails: an array of email addresses to send invites to + * callback: function(err, res) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * var emails = ["me@domain.com", "you@domain.com"]; + * dogapi.user.invite(emails, fuction(err, res){ + * console.dir(res): + * }); + * ``` + */ +function invite(emails, callback){ + var params = { + body: { + emails: emails + } + }; + client.request("POST", "/invite_users", params, callback); +}; + +module.exports = { + invite: invite, + getUsage: function(){ + return [ + " dogapi user invite <address>..." + ]; + }, + getHelp: function(){ + return [ + "User:", + " Subcommands:", + " invite <address>... invite the given list of e-mail addresses to your datadog org" + ]; + }, + handleCli: function(subcommand, args, callback){ + invite(args._.slice(4), callback) + } +}; diff --git a/lib/client.js b/lib/client.js new file mode 100644 index 0000000..3e91e40 --- /dev/null +++ b/lib/client.js @@ -0,0 +1,122 @@ +var extend = require("extend"); +var https = require("https"); +var url = require("url"); +var util = require("util"); + + +/*section: client + *comment: | + * the constructor for _client_ object + *params: + *example: | + * See [client.request](#client-request) + */ +var client = function(){ + this.api_key = null; + this.app_key = null; + this.api_version = "v1"; + this.api_host = "app.datadoghq.com"; +}; + +/*section: client + *comment: | + * used to make a raw request to the datadog api + *params: + * method: | + * http method GET, POST, PUT, DELETE + * path: | + * the api url path e.g. /tags/hosts + * params: | + * an object which allows the keys `query` or `body` + * callback: | + * function to call on success/failure callback(err, result) + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "api_key", + * app_key: "app_key" + * }; + * dogapi.initialize(options); + * dogapi.client.request("GET", "/url/path", {}, function(err, results){ + * console.dir(results); + * }); + * ``` + */ +client.prototype.request = function(method, path, params, callback){ + if(arguments.length === 3 && typeof arguments[2] === "function"){ + callback = arguments[2]; + params = {}; + } + + params = params || {}; + var body = (typeof params["body"] === "object")? JSON.stringify(params["body"]) : params["body"]; + var query = { + "api_key": this.api_key, + "application_key": this.app_key, + }; + + if(typeof params["query"] === "object"){ + extend(query, params["query"]); + } + + path = url.format({ + "pathname": util.format("/api/%s%s", this.api_version, path), + "query": query, + }); + + var http_options = { + hostname: this.api_host, + port: 443, + method: method.toUpperCase(), + path: path, + }; + + if(["POST", "PUT"].indexOf(http_options["method"]) >= 0){ + http_options["headers"] = { + "Content-Type": "application/json", + "Content-Length": body.length, + }; + } + + var req = https.request(http_options, function(res){ + res.on("error", function(err){ + if(typeof callback == "function"){ + callback(err, null, res.statusCode); + } + }); + + var data = ""; + res.on("data", function(chunk){ + data += chunk; + }); + + res.on("end", function(){ + var error = null; + try{ data = JSON.parse(data); }catch(e){} + if(data["errors"]){ + error = data["errors"]; + data = null; + } + + if(typeof callback === "function"){ + callback(error, data, res.statusCode); + } + }); + }); + + // This should only occur for errors such as a socket hang up prior to any + // data being received, or SSL-related issues. + req.on("error", function(err){ + if(typeof callback === "function"){ + callback(err, null, 0); + } + }); + + if(["POST", "PUT"].indexOf(http_options["method"]) >= 0){ + req.write(body); + } + req.end() +}; + +module.exports = new client(); diff --git a/lib/http_client.js b/lib/http_client.js deleted file mode 100644 index bfcb8fc..0000000 --- a/lib/http_client.js +++ /dev/null @@ -1,145 +0,0 @@ -var extend = require('extend'); -var https = require('https'); -var url = require('url'); -var util = require('util'); - - -var client = function(options){ - /* - * new http_client([options]) - * - * http client used to make requests to datadog api service - * - * `options` is an optional object of parameters to set: - * { - * 'api_key': 'datadog api key', - * 'app_key': 'datadog app key', - * 'api_version': 'default is v1', - * 'api_host': 'default is app.datadoghq.com', - * } - * - * this client also allows you to provide these options as - * environment variables instead: - * - * api_key: DD_API_KEY - * app_key: DD_APP_KEY - * api_version: DD_API_VERSION - * api_host: DD_API_HOST - */ - options = (options)? options : {}; - - this.api_key = (options['api_key'])? options['api_key'] : process.env['DD_API_KEY']; - if(!this.api_key){ - throw new Error('`api_key` is not present, either provide `api_key` in `options` or use environment variable `DD_API_KEY`'); - } - - this.app_key = (options['app_key'])? options['app_key'] : process.env['DD_APP_KEY']; - if(!this.api_key){ - throw new Error('`app_key` is not present, either provide `app_key` in `options` or use environment variable `DD_APP_KEY`'); - } - - this.api_version = (options['api_version'])? options['api_version'] : process.env['DD_API_VERSION']; - if(!this.api_version){ - this.api_version = 'v1'; - } - - this.api_host = (options['api_host'])? options['api_host'] : process.env['DD_API_HOST']; - if(!this.api_host){ - this.api_host = 'app.datadoghq.com'; - } - - -}; - -client.prototype.request = function(method, path, params, callback){ - /* - * http_client.request(method, path, [[params], callback]) - * - * method used to send an http request to the datadog api service - * - * `method` is the http method to use ('POST', 'GET', 'DELETE', etc) - * `path` the api url to call, e.g '/events', '/series', '/dash', etc - * `params` an optional object of additional options: - * { - * 'query': { 'key': 'value' }, - * 'body': { 'json/object': 'body' } or 'string body', - * } - * `callback` an optional function to obtain the results of the api call - * callback(error, result) - */ - if(arguments.length == 3 && typeof arguments[2] == 'function'){ - callback = arguments[2]; - params = {}; - } - - params = params || {}; - var body = (typeof params['body'] == 'object')? JSON.stringify(params['body']) : params['body']; - var query = { - 'api_key': this.api_key, - 'application_key': this.app_key, - }; - - if(typeof params['query'] == 'object'){ - extend(query, params['query']); - } - - path = url.format({ - 'pathname': util.format('/api/%s%s', this.api_version, path), - 'query': query, - }); - - var http_options = { - hostname: this.api_host, - port: 443, - method: method.toUpperCase(), - path: path, - }; - - if(['POST', 'PUT'].indexOf(http_options['method']) >= 0){ - http_options['headers'] = { - 'Content-Type': 'application/json', - 'Content-Length': body.length, - }; - } - - var req = https.request(http_options, function(res){ - res.on('error', function(err){ - if(typeof callback == 'function'){ - callback(err, null, res.statusCode); - } - }); - - var data = ''; - res.on('data', function(chunk){ - data += chunk; - }); - - res.on('end', function(){ - var error = null; - try{ data = JSON.parse(data); }catch(e){} - if(data['errors']){ - error = data['errors']; - data = null; - } - - if(typeof callback == 'function'){ - callback(error, data, res.statusCode); - } - }); - }); - - // This should only occur for errors such as a socket hang up prior to any - // data being received, or SSL-related issues. - req.on('error', function(err) { - if(typeof callback == 'function'){ - callback(err, null, 0); - } - }); - - if(['POST', 'PUT'].indexOf(http_options['method']) >= 0){ - req.write(body); - } - req.end() -}; - -return module.exports = client; diff --git a/lib/index.js b/lib/index.js index 7cfc672..08f06fa 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,36 +1,55 @@ -var extend = require('extend'); +require("./api")(module.exports); -var http_client = require('./http_client.js'); -var constants = require('./constants.js'); -var alert_api = require('./api/alert.js'); -var dash_api = require('./api/dash.js'); -var screen_api = require('./api/screen.js'); -var event_api = require('./api/event.js'); -var tag_api = require('./api/tag.js'); -var metric_api = require('./api/metric.js'); -var search_api = require('./api/search.js'); -var service_check_api = require('./api/service_check.js'); -var snapshot_api = require('./api/snapshot.js'); -var downtime_api = require('./api/downtime.js'); - - -var dogapi = function(options){ - http_client.call(this, options); +/*section: dogapi + *comment: configure the dogapi client with your app/api keys + *params: + * options: + * | + * An object which allows you to override the default set parameters for interacting + * with the datadog api. The available options are. + * * api_key: your api key + * * app_key: your app key + * * api_version: the version of the api [default: `v1`] + * * api_host: the host to call [default: `api.datadoghq.com`] + *example: + * | + * ```javascript + * var dogapi = require("dogapi"); + * var options = { + * api_key: "<API_KEY_HERE>", + * app_key: "<APP_KEY_HERE>" + * }; + * dogapi.initialize(options); + * dogapi.event.create(...); + * ``` + */ +function initialize(options){ + options = options || {}; + for(var key in options){ + if(module.exports.client.hasOwnProperty(key)){ + module.exports.client[key] = options[key]; + } + } }; -extend(dogapi.prototype, - http_client.prototype, - alert_api.prototype, - dash_api.prototype, - screen_api.prototype, - event_api.prototype, - tag_api.prototype, - metric_api.prototype, - search_api.prototype, - service_check_api.prototype, - snapshot_api.prototype, - downtime_api.prototype); - -dogapi.constants = constants; +/*section: dogapi + *comment: get the current POSIX timestamp + *example: | + * ```javascript + * var dogapi = require("dogapi"); + * dogapi.now(); + * // this is the same as + * parseInt(new Date().getTime() / 1000); + * ``` + */ +function now(){ + return parseInt(new Date().getTime() / 1000); +}; -return module.exports = dogapi; +module.exports.client = require("./client"), +module.exports.initialize = initialize; +module.exports.now = now; +module.exports.OK = 0; +module.exports.WARNING = 1; +module.exports.CRITICAL = 2; +module.exports.UNKNOWN = 3; diff --git a/package.json b/package.json index 57c3e91..7edfdd9 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,11 @@ "description": "Datadog API Node.JS Client", "main": "lib/index.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "docs": "node ./docs/create.js > index.html" + }, + "bin": { + "dogapi": "bin/dogapi" }, "repository": { "type": "git", @@ -19,7 +23,7 @@ "dog api" ], "author": "Brett Langdon <brett@blangdon.com> (http://brett.is)", - "contributors":[ + "contributors": [ "colinjonesx (http://www.thetestpeople.com)", "dalehamel (http://blog.srvthe.net)" ], @@ -27,6 +31,14 @@ "readmeFilename": "README.md", "gitHead": "f388635a5ab4f4da25702dc0999385d437bdf2bc", "dependencies": { - "extend": "^2.0.0" + "extend": "^2.0.0", + "minimist": "^1.1.1", + "rc": "^1.0.0" + }, + "devDependencies": { + "docast": "^0.1.1", + "glob": "^5.0.3", + "js-yaml": "^3.2.7", + "marked": "^0.3.3" } }