Skip to content

Commit

Permalink
Add login command, refactor authorization.
Browse files Browse the repository at this point in the history
  • Loading branch information
glogiotatidis committed Apr 27, 2017
1 parent 3066583 commit 2011bd7
Show file tree
Hide file tree
Showing 7 changed files with 279 additions and 134 deletions.
145 changes: 117 additions & 28 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ NewRelic Synthetics (unofficial) CLI (NeReS)

|image0| |image1| |image2|

NeReS is a cli tool to manage `NewRelic
Synthetics <https://synthetics.newrelic.com/>`__ monitors with a
Synthetics Lite account. The tool emulates the actions of a user in the
browser and doesn't use the Synthetics API since that's only available
to the Pro accounts.
NeReS is a cli tool to manage `NewRelic Synthetics
<https://synthetics.newrelic.com/>`__ monitors with a Synthetics Lite account
(Pro should work too). The tool emulates the actions of a user in the browser
and doesn't use the Synthetics API since that's only available to the Pro
accounts.

Use the tools you can:

Expand All @@ -16,43 +16,133 @@ Use the tools you can:
- Create, update and delete monitors
- List available locations for monitor installation

Everything you can do in the Web is supported and provided to your shell
prompt.
Everything you can do using the Web console is supported and provided to your
shell prompt.

Configuration
-------------

1. You will need a newrelic account
2. Setup in your environment the following variables:
2. Start by using the `login` command
3. Read the docs or run `--help`

- ``NERES_ACCOUNT``: Get the number from the URL after you login to NR.
- ``NERES_EMAIL``: The email you use to login.
- ``NERES_PASSWORD``: The password you use to login.

or directly provide them when you run the tool.
Use
---

Commands
--------
Login to NewRelic
~~~~~~~~~~~~~~~~~~

- ``add-monitor``: Creates a monitor
- ``delete-monitor``: Delete a monitor
- ``get-monitor``: Get details on a monitor
- ``list-locations``: Lists available locations to install monitors to
- ``list-monitors``: Lists all monitors
- ``open``: The monitor webpage in the browser
- ``update-monitor``: Updates a monitor
Login to NewRelic with the `login` command:

Examples
--------
.. code:: shell
$ neres login
If you have multiple NewRelic accounts you can have different environments:

.. code:: shell
$ neres --environment work login
.. note::

Default environment is named `newrelic`. Remember to always pass `--environment`
to all neres commands to execute them in the correct environment. Alternatively
you can add `NERES_ENVIRONMENT` to your environment variables list.


List Accounts
~~~~~~~~~~~~~

You can list all the accounts connected to the email you used to connect using:

.. code:: shell
$ neres list-accounts
By default neres will act on the first account listed. This command will help
you select a different account by using the `ID` of the account in combination
with the `--account` option or by setting `NERES_ACCOUNT` in your environment.

List Locations
~~~~~~~~~~~~~~

Lists available monitor locations:

.. code:: shell
$ neres list-locations
List Monitors
~~~~~~~~~~~~~

Lists available monitors:

.. code:: shell
$ neres list-monitors
You can only list IDs of the monitors:

.. code:: shell
$ neres list-monitors --ids-only
Or get the raw JSON output from NewRelic:

.. code:: shell
$ neres list-monitors --raw
Add Monitor
~~~~~~~~~~~

Adds a Synthetics monitor:

.. code:: shell
$ neres add-monitor monitorName http://example.com
Use `--help` to get a full list of supported options for the command. All
options are optional.


Get Monitor
~~~~~~~~~~~

Get details on a monitor

.. code:: shell
$ NERES_ACCOUNT=11111 NERES_EMAIL=foo@example.com NERES_PASSWORD=123123 neres list-monitors
$ neres get-monitor de310b69-3195-435e-b1ef-3a0af67499de
TODOS
-----
- Configuration wizard
.. note::

You can use `list-monitors` to get a list of available monitors.

Update Monitor
~~~~~~~~~~~~~~

Update an existing monitor

.. code:: shell
$ neres update-monitor de310b69-3195-435e-b1ef-3a0af67499de --name "Foobar"
Use `--help` to get a full list of supported options for the command. All
options are optional.


Open Monitor
~~~~~~~~~~~~

Open monitor in the browser

.. code:: shell
$ neres open de310b69-3195-435e-b1ef-3a0af67499de
Credits
-------
Expand All @@ -65,4 +155,3 @@ project template.
.. |image0| image:: https://img.shields.io/pypi/v/neres.svg
.. |image1| image:: https://travis-ci.org/glogiotatidis/neres.svg?branch=master
.. |image2| image:: https://pyup.io/repos/github/glogiotatidis/neres/shield.svg

130 changes: 100 additions & 30 deletions neres/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,18 @@
@click.option('--redirect-is-failure', default=False, is_flag=True)
@click.option('--sla-threshold', default=7)
@click.option('--raw', default=False, is_flag=True)
def add_monitor(name, uri, location, frequency, email, validation_string,
@click.pass_context
def add_monitor(ctx, name, uri, location, frequency, email, validation_string,
bypass_head_request, verify_ssl, redirect_is_failure, sla_threshold, raw):
if validation_string:
# We must bypass head request we're to validate string.
bypass_head_request = True

with Spinner('Creating monitor: ', remove_message=raw):
status, message, monitor = newrelic.create_monitor(name, uri, frequency, location, email,
validation_string, bypass_head_request,
verify_ssl, redirect_is_failure,
sla_threshold)
status, message, monitor = newrelic.create_monitor(
ctx.obj['ACCOUNT'], name, uri, frequency, location, email,
validation_string, bypass_head_request, verify_ssl, redirect_is_failure,
sla_threshold)

if raw:
print(monitor)
Expand Down Expand Up @@ -69,7 +70,8 @@ def add_monitor(name, uri, location, frequency, email, validation_string,
@click.option('--verify-ssl/--no-verify-ssl', default=None, is_flag=True)
@click.option('--redirect-is-failure/--no-redirect-is-failure', default=None, is_flag=True)
@click.option('--raw', default=False, is_flag=True)
def update_monitor(monitor, **kwargs):
@click.pass_context
def update_monitor(ctx, monitor, **kwargs):
if kwargs['no_validation_string']:
if kwargs['validation_string']:
raise click.ClickException(
Expand All @@ -87,7 +89,7 @@ def update_monitor(monitor, **kwargs):
'with --add-location.')

with Spinner('Updating monitor: ', remove_message=kwargs['raw']):
status, message, monitor = newrelic.update_monitor(monitor, **kwargs)
status, message, monitor = newrelic.update_monitor(ctx.obj['ACCOUNT'], monitor, **kwargs)

if kwargs['raw']:
print(monitor)
Expand All @@ -104,9 +106,10 @@ def update_monitor(monitor, **kwargs):
@click.command()
@click.argument('monitor')
@click.option('--raw', default=False, is_flag=True)
def get_monitor(monitor, raw):
@click.pass_context
def get_monitor(ctx, monitor, raw):
with Spinner('Fetching monitor: '):
monitor = newrelic.get_monitor(monitor)
monitor = newrelic.get_monitor(ctx.obj['ACCOUNT'], monitor)

if raw:
print(monitor)
Expand Down Expand Up @@ -141,11 +144,12 @@ def get_monitor(monitor, raw):
@click.command()
@click.argument('monitor')
@click.option('--confirm', default=None)
def delete_monitor(monitor, confirm):
@click.pass_context
def delete_monitor(ctx, monitor, confirm):
if not confirm:
confirm = click.prompt('''
! WARNING: Destructive Action
! This command will destroy the monitor:\n\t{monitor}
! This command will destroy the monitor: {monitor}
! To proceed, type "{monitor}" or
re-run this command with --confirm={monitor}
Expand All @@ -155,15 +159,16 @@ def delete_monitor(monitor, confirm):
sys.exit(1)

with Spinner('Deleting monitor {}: '.format(monitor), remove_message=False):
newrelic.delete_monitor(monitor)
newrelic.delete_monitor(ctx.obj['ACCOUNT'], monitor)
print(click.style(u'OK', fg='green', bold=True))


@click.command()
@click.option('--raw', default=False, is_flag=True)
def list_locations(raw):
@click.pass_context
def list_locations(ctx, raw):
with Spinner('Fetching locations: '):
locations = newrelic.get_locations()
locations = newrelic.get_locations(ctx.obj['ACCOUNT'])

if raw:
print(locations)
Expand Down Expand Up @@ -206,9 +211,10 @@ def list_locations(raw):
@click.command()
@click.option('--ids-only', default=False, is_flag=True)
@click.option('--raw', default=False, is_flag=True)
def list_monitors(ids_only, raw):
@click.pass_context
def list_monitors(ctx, ids_only, raw):
with Spinner('Fetching monitors: '):
monitors = newrelic.get_monitors()
monitors = newrelic.get_monitors(ctx.obj['ACCOUNT'])

if raw:
print(monitors)
Expand Down Expand Up @@ -284,8 +290,9 @@ def list_monitors(ids_only, raw):

@click.command()
@click.argument('monitor')
def open_monitor(monitor):
url = urls.MONITOR.format(monitor)
@click.pass_context
def open_monitor(ctx, monitor):
url = urls.MONITOR.format(account=ctx.obj['ACCOUNT'], monitor=monitor)
if platform.system() == 'Windows':
os.startfile(url)
elif platform.system() == 'Darwin':
Expand All @@ -294,20 +301,83 @@ def open_monitor(monitor):
subprocess.Popen(['xdg-open', url])


@click.group()
def main():
newrelic.initialize_cookiejar()
@click.command()
@click.option('--raw', is_flag=True, default=False)
def list_accounts(raw):
with Spinner('Fetching accounts: '):
accounts = newrelic.get_accounts()

if raw:
for account in accounts:
print(account[0])

data = [[
'ID',
'Name'
]]
for account in accounts:
data.append([account['id'], account['name']])

table = SingleTable(data)
table.title = click.style('Accounts', fg='black')
print(table.table)


@click.command()
@click.pass_context
def login(ctx):
email = ctx.obj['EMAIL']
if not email:
email = click.prompt('Email')

password = ctx.obj['PASSWORD']
if not password:
password = click.prompt('Password', hide_input=True)

with Spinner('Logging in: ', remove_message=False):
newrelic.login(email, password)
print(click.style(u'OK', fg='green', bold=True))

main.add_command(list_monitors, name='list-monitors')
main.add_command(list_locations, name='list-locations')
main.add_command(delete_monitor, name='delete-monitor')
main.add_command(get_monitor, name='get-monitor')
main.add_command(add_monitor, name='add-monitor')
main.add_command(update_monitor, name='update-monitor')
main.add_command(open_monitor, name='open')

@click.group()
@click.option('--email')
@click.option('--password')
@click.option('--account')
@click.option('--environment', default='newrelic')
@click.pass_context
def cli(ctx, email, password, account, environment):
cookiejar = os.path.expanduser('~/.config/neres/{}.cookies'.format(environment))
if not os.path.exists(os.path.dirname(cookiejar)):
os.makedirs(os.path.dirname(cookiejar), 0o700)
newrelic.initialize_cookiejar(cookiejar)

if ctx.invoked_subcommand != 'login':
with Spinner('Authorizing: '):
if not newrelic.check_if_logged_in():
if not all([email, password]):
raise click.ClickException('Login first')
else:
newrelic.login(email, password)

if not account and ctx.invoked_subcommand != 'list-accounts':
account = newrelic.get_accounts()[0]['id']

ctx.obj = {}
ctx.obj['ACCOUNT'] = account
ctx.obj['EMAIL'] = email
ctx.obj['PASSWORD'] = email


cli.add_command(list_monitors, name='list-monitors')
cli.add_command(list_locations, name='list-locations')
cli.add_command(delete_monitor, name='delete-monitor')
cli.add_command(get_monitor, name='get-monitor')
cli.add_command(add_monitor, name='add-monitor')
cli.add_command(update_monitor, name='update-monitor')
cli.add_command(list_accounts, name='list-accounts')
cli.add_command(open_monitor, name='open')
cli.add_command(login, name='login')


if __name__ == "__main__":
# Does nothing if not on Windows.
main()
cli(auto_envvar_prefix='NERES')
Loading

0 comments on commit 2011bd7

Please sign in to comment.