SlideShare a Scribd company logo
Advanced REST API Scripting
Todd Radel
Senior Manager, Enablement and Adoption
About Me
Todd Radel
SENIOR MANAGER
ENABLEMENT & ADOPTION, US EAST
• More than 20 years experience in the
software industry
• Java, .NET, Python, Perl
• Author of the Python SDK for
AppDynamics REST API
• Author of six AppDynamics Extensions:
F5, Tibco EMS, Redis, Keynote, SQL,
URL Monitor
Copyright © 2014 AppDynamics. All rights reserved. 2
tradel@appdynamics.com
+1 (484) 857-2335
tradel
todd.radel
linkedin.com/in/tradel
Today’s Agenda
Copyright © 2014 AppDynamics. All rights reserved. 3
1
2 Installing and using the Python SDK
3 Reporting on license usage
Hello World (in 3 languages!)
BUILDING ON THE FIRST REST API WEBINAR, WE WILL SHOW
YOU HOW TO SCRIPT AND AUTOMATE COMMON TASKS
4 DevOps integration – disabling health rules
during code deployment
Hello World
Hello World
OBJECTIVE
• Retrieve a list of business applications from the controller
• Print to stdout
FLAVORS
• Bash/cURL
• PowerShell
• Python – The Hard Way
• Python – The Easy Way
Copyright © 2014 AppDynamics. All rights reserved. 5
Bash and cURL
#! /bin/bash
# Print the list of tiers for an application
curl -X GET -u user1@customer1:welcome
"http://localhost:8080/controller/rest/applications?output=jso
n"
Copyright © 2014 AppDynamics. All rights reserved. 6
Windows PowerShell
# Print the list of tiers for an application
$usr="user1@customer1"
$pwd="welcome"
$headers = @{
Authorization = "Basic " +
[System.Convert]::ToBase64String(
[System.Text.Encoding]::ASCII.GetBytes(
"$($usr):$($pwd)"))
}
$url="http://localhost:8080/controller/rest/applications?outpu
t=json"
$response = Invoke-RestMethod $url -Headers $Headers
$response | ForEach-Object { [string]$_.id + " " + $_.name }
Python – The Hard Way
#! /usr/bin/env python
# Print the list of tiers for an application
import requests
usr = "user1@customer1"
pwd = "welcome"
url =
"http://localhost:8080/controller/rest/applications?output=jso
n"
response = requests.get(url, auth=(usr, pwd))
json = response.json()
for app in json:
print app['id'], app['name']
Copyright © 2014 AppDynamics. All rights reserved. 8
Python – The Easy Way
#! /usr/bin/env python
# Print the list of tiers for an application
from appd.request import AppDynamicsClient
c = AppDynamicsClient("http://localhost:8080",
"user1", "welcome")
for app in c.get_applications():
print app.id, app.name
# Wasn’t that easy?
Copyright © 2014 AppDynamics. All rights reserved. 9
Getting Started With The Python SDK
BREAKING NEWS:
AppDynamicsREST is now in the
Python Package Index!
Copyright © 2014 AppDynamics. All rights reserved. 11
Downloading and Installing
1. Install Python 2.7 from https://www.python.org/downloads/
2. Install PIP (if earlier than Python 2.7.9)
curl https://bootstrap.pypa.io/get-pip.py > get-pip.py
python get-pip.py
3. Install AppDynamicsREST
pip install AppDynamicsREST
4. Get coding!
Copyright © 2014 AppDynamics. All rights reserved. 12
Hello World – Your First Script
#! /usr/bin/env python
# Print the list of tiers for an application
from appd.request import AppDynamicsClient
c = AppDynamicsClient("http://localhost:8080",
"user1", "welcome")
for app in c.get_applications():
print app.id, app.name
Copyright © 2014 AppDynamics. All rights reserved. 13
Retrieving Metric Data
#! /usr/bin/env python
# Export key business metrics from AppDynamics
from appd.request import AppDynamicsClient
c = AppDynamicsClient("http://localhost:8080", "user1", "welcome")
metrics = c.get_metrics(metric_path='Business Transaction
Performance|Business Transactions|ECommerce
Server|ViewCart.addToCart|Average Response Time (ms)',
app_id='ACME Book Store Application',
time_range_type='BEFORE_NOW',
duration_in_mins=60,
rollup=False)
for point in metrics[0].values:
print point.start_time, 'Average Response Time: ',
point.value
Copyright © 2014 AppDynamics. All rights reserved. 14
License Usage Report
Hello World
OBJECTIVE
• Get count of licenses used per product (Java, .NET, etc.)
in the past 15 days
• Make a beautiful chart
TOOLS
• Python
• AppDynamicsREST
• PyGal
Copyright © 2014 AppDynamics. All rights reserved. 16
Source Code, Page 1
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from collections import OrderedDict, defaultdict
import pygal
import tzlocal
from appd.request import AppDynamicsClient
import creds.demo2 as creds
# Set up API client
c = AppDynamicsClient(creds.url, creds.user, creds.password, creds.account)
# Get my tenant account info
my_acct = c.get_my_account()
# Calculate start and end dates - we will start at midnight and go back 15 days
days = 15
mytz = tzlocal.get_localzone()
end_dt = datetime.now(mytz).replace(hour=0, minute=0, second=0, microsecond=0)
start_dt = end_dt - timedelta(days)
# Get license usage for my account
usage = c.get_license_usage(my_acct.id, None, start_dt, end_dt)
Copyright © 2014 AppDynamics. All rights reserved. 17
Source Code, Page 2
def daterange(start_dt, end_dt):
for n in range(int((end_dt - start_dt).days)):
yield start_dt + timedelta(days=n)
# Get the list of all licensed products:
products = set(x.license_module for x in usage.usages)
products = [x for x in products if 'eum' not in x and 'analytics' not in x]
usage_by_product = defaultdict(OrderedDict)
for product in products:
for day in daterange(start_dt, end_dt):
units = [x.max_units_used for x in usage.usages if
x.created_on.date() == day.date() and x.license_module == product]
usage_by_product[product][day] = max(units)
# Make a simple graph and display it
chart = pygal.StackedBar(x_label_rotation=45, width=1000)
chart.title = 'License Usage By Product - ' + c.base_url
chart.x_labels = [str(x.date()) for x in daterange(start_dt, end_dt)]
for product in products:
chart.add(product, usage_by_product[product].values())
chart.render_to_file('all_usage.svg')
Copyright © 2014 AppDynamics. All rights reserved. 18
Output
Copyright © 2014 AppDynamics. All rights reserved. 19
Enable & Disable Health Rules
Hello World
OBJECTIVES
• Programmatically enable and disable health rules
• Perform code deployments without triggering false alerts
TOOLS
• Python
• AppDynamicsREST v2
Copyright © 2014 AppDynamics. All rights reserved. 21
Wait … What is v2?
• Version 2 of AppDynamicsREST is being developed
• Supports original AppDynamics REST API and v2.0
• Supports XML or JSON output
• Fully RESTful object model
Old: c.get_nodes(app_id=10, tier_id=12)
New: c.application(10).tier(12).nodes
Best: c.application(‘ACME Book Store’)
.tier(‘E-Commerce’)
.nodes
Copyright © 2014 AppDynamics. All rights reserved. 22
New Features in v2
• Accounts
• Users
• Policies
• Health rules
• License usage
• License status
• App Agent Operations
• Collect log files
• Collect debug logs
• Take thread dumps
• Configuration import/export
Copyright © 2014 AppDynamics. All rights reserved. 23
Disabling Health Rules
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from appd.http.service import AppDynamicsService
c = AppDynamicsService('user1', 'welcome',
base_url='http://localhost:8080')
app = c.my_account.application('ACME Book Store')
for hr in app.health_rules:
hr.disable()
Copyright © 2014 AppDynamics. All rights reserved. 24
Output
Copyright © 2014 AppDynamics. All rights reserved. 25
Enabling Health Rules
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from appd.http.service import AppDynamicsService
c = AppDynamicsService('user1', 'welcome',
base_url='http://localhost:8080')
app = c.my_account.application('ACME Book Store')
for hr in app.health_rules:
hr.enable()
Copyright © 2014 AppDynamics. All rights reserved. 26
Output
Copyright © 2014 AppDynamics. All rights reserved. 27
Office Hours/Q&A
Further Reading
• Product Documentation
https://docs.appdynamics.com/display/PRO41/Use+the+AppDynami
cs+REST+API
• REST API SDK On Python Package Index
https://pypi.python.org/pypi/AppDynamicsREST
Thank You!

More Related Content

PDF
Appdynamics Training Session
PPTX
Monitoring_with_Prometheus_Grafana_Tutorial
PDF
Grafana introduction
PPTX
Dynatrace
PDF
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
PPTX
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
PPTX
Grafana
PPTX
Cloud Custodian
Appdynamics Training Session
Monitoring_with_Prometheus_Grafana_Tutorial
Grafana introduction
Dynatrace
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
Grafana
Cloud Custodian

What's hot (20)

PDF
Velero search & practice 20210609
PPTX
Apache doris (incubating) introduction
PPTX
Observability
PPTX
Google cloud
PPTX
MySQL Monitoring using Prometheus & Grafana
PDF
Google Cloud Networking Deep Dive
PPTX
Azure Container Apps
PPTX
Comment l’architecture événementielle révolutionne la communication dans le S...
PDF
[네전따] 네트워크 엔지니어에게 쿠버네티스는 어떤 의미일까요
PDF
AWS
PPTX
Application Performance Monitoring (APM)
PPTX
Introduction to kubernetes
PPTX
Azure vs Aws vs Google Cloud Providers
PDF
Business Transactions with AppDynamics
PDF
Application & Account Monitoring in AWS
PPTX
Airflow Clustering and High Availability
PPTX
Microsoft Azure Technical Overview
PPT
Cloud stack vs openstack vs eucalyptus
PDF
Introduction to kubernetes
PDF
Microservices for Application Modernisation
Velero search & practice 20210609
Apache doris (incubating) introduction
Observability
Google cloud
MySQL Monitoring using Prometheus & Grafana
Google Cloud Networking Deep Dive
Azure Container Apps
Comment l’architecture événementielle révolutionne la communication dans le S...
[네전따] 네트워크 엔지니어에게 쿠버네티스는 어떤 의미일까요
AWS
Application Performance Monitoring (APM)
Introduction to kubernetes
Azure vs Aws vs Google Cloud Providers
Business Transactions with AppDynamics
Application & Account Monitoring in AWS
Airflow Clustering and High Availability
Microsoft Azure Technical Overview
Cloud stack vs openstack vs eucalyptus
Introduction to kubernetes
Microservices for Application Modernisation
Ad

Viewers also liked (20)

PPTX
Webinar - Building Custom Extensions With AppDynamics
PDF
End User Monitoring with AppDynamics - AppSphere16
PPTX
AppDynamics Advanced BT Configuration
PPT
Building a CRM on top of ElasticSearch
PDF
Enterprise Sales
PPTX
Rapid Deployment of BMC Remedy Solutions 2006
PPTX
BMC Control-M for SAP, BPI, and AFT - VPMA - Secret Weapons for a Successful...
PPTX
How The Container Store uses AppDynamics in their development lifecycle
PPTX
Cerner APM Journey with AppDynamics
PDF
AppDynamics- A sneak peak into the product that is disrupting the Application...
PPTX
What's New in the BMC Remedy Suite
PPTX
Introduction to appDynamics
PDF
AppSphere 15 - Toys vs Tools: AppDynamics, a Swiss Army Knife for IT Professi...
PPTX
Sales Onboarding - Accelerating New Hire Productivity
PDF
Cloud & DevOps = A Match made in IT Heaven: Clyde Logue, BMC Software
PDF
How AppDynamics leveraged sales enablement to grow from one to 350 reps
PDF
Velocity Presentation - Unified Monitoring with AppDynamics
PPTX
BMC Engage - ITAM 2015-2020: The Evolving Role of the IT Asset Manager
PPTX
BMC Engage 2015: IT Asset Management - An essential pillar for the digital en...
PDF
Under the Hood: Monitoring Azure and .NET - AppSphere16
Webinar - Building Custom Extensions With AppDynamics
End User Monitoring with AppDynamics - AppSphere16
AppDynamics Advanced BT Configuration
Building a CRM on top of ElasticSearch
Enterprise Sales
Rapid Deployment of BMC Remedy Solutions 2006
BMC Control-M for SAP, BPI, and AFT - VPMA - Secret Weapons for a Successful...
How The Container Store uses AppDynamics in their development lifecycle
Cerner APM Journey with AppDynamics
AppDynamics- A sneak peak into the product that is disrupting the Application...
What's New in the BMC Remedy Suite
Introduction to appDynamics
AppSphere 15 - Toys vs Tools: AppDynamics, a Swiss Army Knife for IT Professi...
Sales Onboarding - Accelerating New Hire Productivity
Cloud & DevOps = A Match made in IT Heaven: Clyde Logue, BMC Software
How AppDynamics leveraged sales enablement to grow from one to 350 reps
Velocity Presentation - Unified Monitoring with AppDynamics
BMC Engage - ITAM 2015-2020: The Evolving Role of the IT Asset Manager
BMC Engage 2015: IT Asset Management - An essential pillar for the digital en...
Under the Hood: Monitoring Azure and .NET - AppSphere16
Ad

Similar to Advanced REST API Scripting With AppDynamics (20)

PDF
15minutesintroductiontoappdynamics1.pdf
PDF
Use AppDynamics SDK to Integrate with your Applications - AppSphere16
PDF
AppSphere 15 - Expedia Lessons from the Trenches: Managing AppDynamics at Scale
PPTX
AppSphere 2016 - Automate performance testing with AppDynamics using continuo...
PDF
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
PDF
Completing the Microservices Puzzle: Kubernetes, Prometheus and FreshTracks.io
PDF
Mastering the Administration of your AppDynamics Deployment - AppSphere16
PPTX
What's New in the Winter '16 Release (4.2)
PDF
AppSphere 15 - Deep Dive into AppDynamics Application Analytics
PDF
AppSphere 15 - PHP, Node.js and Python Deep Dive
PPTX
Design Reviews for Operations - Velocity Europe 2014
PDF
Enterprise-Ready FastAPI: Beyond the Basics
PDF
Thousands of JVMs, Hundreds of Applications, and Two People: How Cerner Learn...
PPTX
Top 5 Java Performance Metrics, Tips & Tricks
PDF
Cloud-Native Insights: How Platform & App Visibility Drive Business Outcomes
PDF
Fast 5 Things You Can Do Now to Get Ready for the Cloud
PDF
Advanced APM .NET Hands-On Lab - AppSphere16
PDF
12 Factor, or Cloud Native Apps - What EXACTLY Does that Mean for Spring Deve...
PDF
Full Stack Serverless 1st Edition Nader Dabit
PDF
Getting Additional Value from Logs and APM Data with AppDynamics Unified Anal...
15minutesintroductiontoappdynamics1.pdf
Use AppDynamics SDK to Integrate with your Applications - AppSphere16
AppSphere 15 - Expedia Lessons from the Trenches: Managing AppDynamics at Scale
AppSphere 2016 - Automate performance testing with AppDynamics using continuo...
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Completing the Microservices Puzzle: Kubernetes, Prometheus and FreshTracks.io
Mastering the Administration of your AppDynamics Deployment - AppSphere16
What's New in the Winter '16 Release (4.2)
AppSphere 15 - Deep Dive into AppDynamics Application Analytics
AppSphere 15 - PHP, Node.js and Python Deep Dive
Design Reviews for Operations - Velocity Europe 2014
Enterprise-Ready FastAPI: Beyond the Basics
Thousands of JVMs, Hundreds of Applications, and Two People: How Cerner Learn...
Top 5 Java Performance Metrics, Tips & Tricks
Cloud-Native Insights: How Platform & App Visibility Drive Business Outcomes
Fast 5 Things You Can Do Now to Get Ready for the Cloud
Advanced APM .NET Hands-On Lab - AppSphere16
12 Factor, or Cloud Native Apps - What EXACTLY Does that Mean for Spring Deve...
Full Stack Serverless 1st Edition Nader Dabit
Getting Additional Value from Logs and APM Data with AppDynamics Unified Anal...

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Presentation of Computer CLASS 2 .pptx
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
medical staffing services at VALiNTRY
PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PPT
Introduction Database Management System for Course Database
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Materi-Enum-and-Record-Data-Type (1).pptx
PPTX
L1 - Introduction to python Backend.pptx
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
AI in Product Development-omnex systems
PDF
How Creative Agencies Leverage Project Management Software.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Presentation of Computer CLASS 2 .pptx
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
medical staffing services at VALiNTRY
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
Upgrade and Innovation Strategies for SAP ERP Customers
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Introduction Database Management System for Course Database
Softaken Excel to vCard Converter Software.pdf
Materi-Enum-and-Record-Data-Type (1).pptx
L1 - Introduction to python Backend.pptx
PTS Company Brochure 2025 (1).pdf.......
Understanding Forklifts - TECH EHS Solution
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
Which alternative to Crystal Reports is best for small or large businesses.pdf
Materi_Pemrograman_Komputer-Looping.pptx
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
AI in Product Development-omnex systems
How Creative Agencies Leverage Project Management Software.pdf

Advanced REST API Scripting With AppDynamics

  • 1. Advanced REST API Scripting Todd Radel Senior Manager, Enablement and Adoption
  • 2. About Me Todd Radel SENIOR MANAGER ENABLEMENT & ADOPTION, US EAST • More than 20 years experience in the software industry • Java, .NET, Python, Perl • Author of the Python SDK for AppDynamics REST API • Author of six AppDynamics Extensions: F5, Tibco EMS, Redis, Keynote, SQL, URL Monitor Copyright © 2014 AppDynamics. All rights reserved. 2 [email protected] +1 (484) 857-2335 tradel todd.radel linkedin.com/in/tradel
  • 3. Today’s Agenda Copyright © 2014 AppDynamics. All rights reserved. 3 1 2 Installing and using the Python SDK 3 Reporting on license usage Hello World (in 3 languages!) BUILDING ON THE FIRST REST API WEBINAR, WE WILL SHOW YOU HOW TO SCRIPT AND AUTOMATE COMMON TASKS 4 DevOps integration – disabling health rules during code deployment
  • 5. Hello World OBJECTIVE • Retrieve a list of business applications from the controller • Print to stdout FLAVORS • Bash/cURL • PowerShell • Python – The Hard Way • Python – The Easy Way Copyright © 2014 AppDynamics. All rights reserved. 5
  • 6. Bash and cURL #! /bin/bash # Print the list of tiers for an application curl -X GET -u user1@customer1:welcome "http://localhost:8080/controller/rest/applications?output=jso n" Copyright © 2014 AppDynamics. All rights reserved. 6
  • 7. Windows PowerShell # Print the list of tiers for an application $usr="user1@customer1" $pwd="welcome" $headers = @{ Authorization = "Basic " + [System.Convert]::ToBase64String( [System.Text.Encoding]::ASCII.GetBytes( "$($usr):$($pwd)")) } $url="http://localhost:8080/controller/rest/applications?outpu t=json" $response = Invoke-RestMethod $url -Headers $Headers $response | ForEach-Object { [string]$_.id + " " + $_.name }
  • 8. Python – The Hard Way #! /usr/bin/env python # Print the list of tiers for an application import requests usr = "user1@customer1" pwd = "welcome" url = "http://localhost:8080/controller/rest/applications?output=jso n" response = requests.get(url, auth=(usr, pwd)) json = response.json() for app in json: print app['id'], app['name'] Copyright © 2014 AppDynamics. All rights reserved. 8
  • 9. Python – The Easy Way #! /usr/bin/env python # Print the list of tiers for an application from appd.request import AppDynamicsClient c = AppDynamicsClient("http://localhost:8080", "user1", "welcome") for app in c.get_applications(): print app.id, app.name # Wasn’t that easy? Copyright © 2014 AppDynamics. All rights reserved. 9
  • 10. Getting Started With The Python SDK
  • 11. BREAKING NEWS: AppDynamicsREST is now in the Python Package Index! Copyright © 2014 AppDynamics. All rights reserved. 11
  • 12. Downloading and Installing 1. Install Python 2.7 from https://www.python.org/downloads/ 2. Install PIP (if earlier than Python 2.7.9) curl https://bootstrap.pypa.io/get-pip.py > get-pip.py python get-pip.py 3. Install AppDynamicsREST pip install AppDynamicsREST 4. Get coding! Copyright © 2014 AppDynamics. All rights reserved. 12
  • 13. Hello World – Your First Script #! /usr/bin/env python # Print the list of tiers for an application from appd.request import AppDynamicsClient c = AppDynamicsClient("http://localhost:8080", "user1", "welcome") for app in c.get_applications(): print app.id, app.name Copyright © 2014 AppDynamics. All rights reserved. 13
  • 14. Retrieving Metric Data #! /usr/bin/env python # Export key business metrics from AppDynamics from appd.request import AppDynamicsClient c = AppDynamicsClient("http://localhost:8080", "user1", "welcome") metrics = c.get_metrics(metric_path='Business Transaction Performance|Business Transactions|ECommerce Server|ViewCart.addToCart|Average Response Time (ms)', app_id='ACME Book Store Application', time_range_type='BEFORE_NOW', duration_in_mins=60, rollup=False) for point in metrics[0].values: print point.start_time, 'Average Response Time: ', point.value Copyright © 2014 AppDynamics. All rights reserved. 14
  • 16. Hello World OBJECTIVE • Get count of licenses used per product (Java, .NET, etc.) in the past 15 days • Make a beautiful chart TOOLS • Python • AppDynamicsREST • PyGal Copyright © 2014 AppDynamics. All rights reserved. 16
  • 17. Source Code, Page 1 #! /usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta from collections import OrderedDict, defaultdict import pygal import tzlocal from appd.request import AppDynamicsClient import creds.demo2 as creds # Set up API client c = AppDynamicsClient(creds.url, creds.user, creds.password, creds.account) # Get my tenant account info my_acct = c.get_my_account() # Calculate start and end dates - we will start at midnight and go back 15 days days = 15 mytz = tzlocal.get_localzone() end_dt = datetime.now(mytz).replace(hour=0, minute=0, second=0, microsecond=0) start_dt = end_dt - timedelta(days) # Get license usage for my account usage = c.get_license_usage(my_acct.id, None, start_dt, end_dt) Copyright © 2014 AppDynamics. All rights reserved. 17
  • 18. Source Code, Page 2 def daterange(start_dt, end_dt): for n in range(int((end_dt - start_dt).days)): yield start_dt + timedelta(days=n) # Get the list of all licensed products: products = set(x.license_module for x in usage.usages) products = [x for x in products if 'eum' not in x and 'analytics' not in x] usage_by_product = defaultdict(OrderedDict) for product in products: for day in daterange(start_dt, end_dt): units = [x.max_units_used for x in usage.usages if x.created_on.date() == day.date() and x.license_module == product] usage_by_product[product][day] = max(units) # Make a simple graph and display it chart = pygal.StackedBar(x_label_rotation=45, width=1000) chart.title = 'License Usage By Product - ' + c.base_url chart.x_labels = [str(x.date()) for x in daterange(start_dt, end_dt)] for product in products: chart.add(product, usage_by_product[product].values()) chart.render_to_file('all_usage.svg') Copyright © 2014 AppDynamics. All rights reserved. 18
  • 19. Output Copyright © 2014 AppDynamics. All rights reserved. 19
  • 20. Enable & Disable Health Rules
  • 21. Hello World OBJECTIVES • Programmatically enable and disable health rules • Perform code deployments without triggering false alerts TOOLS • Python • AppDynamicsREST v2 Copyright © 2014 AppDynamics. All rights reserved. 21
  • 22. Wait … What is v2? • Version 2 of AppDynamicsREST is being developed • Supports original AppDynamics REST API and v2.0 • Supports XML or JSON output • Fully RESTful object model Old: c.get_nodes(app_id=10, tier_id=12) New: c.application(10).tier(12).nodes Best: c.application(‘ACME Book Store’) .tier(‘E-Commerce’) .nodes Copyright © 2014 AppDynamics. All rights reserved. 22
  • 23. New Features in v2 • Accounts • Users • Policies • Health rules • License usage • License status • App Agent Operations • Collect log files • Collect debug logs • Take thread dumps • Configuration import/export Copyright © 2014 AppDynamics. All rights reserved. 23
  • 24. Disabling Health Rules #! /usr/bin/env python # -*- coding: utf-8 -*- from appd.http.service import AppDynamicsService c = AppDynamicsService('user1', 'welcome', base_url='http://localhost:8080') app = c.my_account.application('ACME Book Store') for hr in app.health_rules: hr.disable() Copyright © 2014 AppDynamics. All rights reserved. 24
  • 25. Output Copyright © 2014 AppDynamics. All rights reserved. 25
  • 26. Enabling Health Rules #! /usr/bin/env python # -*- coding: utf-8 -*- from appd.http.service import AppDynamicsService c = AppDynamicsService('user1', 'welcome', base_url='http://localhost:8080') app = c.my_account.application('ACME Book Store') for hr in app.health_rules: hr.enable() Copyright © 2014 AppDynamics. All rights reserved. 26
  • 27. Output Copyright © 2014 AppDynamics. All rights reserved. 27
  • 29. Further Reading • Product Documentation https://docs.appdynamics.com/display/PRO41/Use+the+AppDynami cs+REST+API • REST API SDK On Python Package Index https://pypi.python.org/pypi/AppDynamicsREST

Editor's Notes

  • #12: With documentation and hints for syntax completion Over 1000 downloads per month!
  • #13: If you already have Python installed, skip step 1. If you already have pip (or easy_install), skip step 2.
  • #15: Live demo - using metric browser, right-click and “Copy Full Path”, paste into script (bt_performance.py) Enhance to display all BT’s (bt_performance_2.py)
  • #16: file:///Users/tradel/Code/REST-API-Webinar/all_usage.svg
  • #21: http://localhost:8080/controller/#/location=ALERT_RESPOND_HEALTH_RULES&timeRange=last_15_minutes.BEFORE_NOW.-1.-1.15&application=10 Switch to appdynamics-dexml project