IBM Cloud Docs
Python クライアントを使用したダッシュボードの管理

Python クライアントを使用したダッシュボードの管理

Python クライアントを使用すると、プログラムでダッシュボードを管理できます。

Python クライアントの使用方法については、Python クライアントの使用を参照してください。

特定のチームのリソースを処理するには、Monitoring (sysdig) トークンを使用する必要があります。

以下の表に、ダッシュボードの管理に使用できる Python 関数のいくつかをリストします。

ダッシュボードPython機能
アクション 関数
ダッシュボードの作成 sdclient.create_dashboard(dashboard_name)
ファイルからのダッシュボードの作成 sdclient.create_dashboard_from_file('dashboard_name', 'dashboard_name.json', scope_filter, shared=False, public=True)
ダッシュボードのコピー sdclient.create_dashboard_from_dashboard(dashboard_name, existing_dashboard_name, scope_filter, shared=False, public=True)
ダッシュボードのダウンロード sdclient.get_dashboards()
ダッシュボードの更新 sdclient.update_dashboard(dashboard_name)
ダッシュボードの削除 sdclient.delete_dashboard(dashboard_name)
ダッシュボードの検索 sdclient.find_dashboard_by(dashboard_name)
時系列の追加 sdclient.add_dashboard_panel(dashboard_name, panel_name, panel_type, metrics, scope=scope)
ダッシュボード・パネルの追加 sdclient.add_dashboard_panel(dashboard_name, panel_name, panel_type, metrics, sort_direction=sort_direction, limit=limit, layout=layout)
パネルの削除 sdclient.remove_dashboard_panel(dashboard_name, 'CPU Over Time')
ファイルへのダッシュボードの保存 sdclient.save_dashboard_to_file('dashboard_name', 'dashboard_name.json')

チームごとのダッシュボードのリスト

Python を使用して、チームで使用可能なダッシュボードをリストできます。

デフォルト・チームで使用可能なダッシュボードのリスト

以下のコードは、デフォルト・チームで使用可能なダッシュボードをリストするための Python スクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
 def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

# Show the list of dashboards
ok, res = sdclient.get_dashboards()

if not ok:
    print(res)
    sys.exit(1)

for db in res['dashboards']:
    print("%s [Team ID: %s] Name: %s, # Charts: %d" % ( db['id'], db['teamId'], db['name'], len(db['widgets'] if 'widgets' in db else [])))

チームで使用可能なダッシュボードのリスト

以下のコードは、特定のチームで使用可能なダッシュボードをリストするための Python スクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))

from sdcclient import SdMonitorClient

# Parse arguments.
def usage():
   print('usage: %s <endpoint-url> <sysdig_token>' % sys.argv[0])
   print('endpoint-url: The endpoint URL that should point to IBM Cloud')
   print('sysdig_token: Sysdig token for the team')
   sys.exit(1)

if len(sys.argv) != 3:
   usage()

URL = sys.argv[1]

# Set to the Sysdig token of the team
SYSDIG_TOKEN = sys.argv[2]

sdclient = SdMonitorClient(token=SYSDIG_TOKEN,sdc_url=URL)

# Show the list of dashboards
ok, res = sdclient.get_dashboards()

if not ok:
    print(res)
    sys.exit(1)

for db in res['dashboards']:
    print("%s [Team ID: %s] Name: %s, # Charts: %d" % ( db['id'], db['teamId'], db['name'], len(db['widgets'] if 'widgets' in db else [])))

ダッシュボードの作成

Python を使用してダッシュボードを作成できます。

デフォルト・チームでのダッシュボードの作成

以下のコードは、デフォルト・チーム用の新しいダッシュボードを作成するための Python スクリプトの構造を示しています。

以下のコードは、Python スクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
 def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

DASHBOARD_NAME = 'My New Dashboard from Python'
PANEL_NAME = 'CPU Over Time'

# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

# Create an empty dashboard
ok, res = sdclient.create_dashboard(DASHBOARD_NAME)

# Check the result
dashboard_name = None
if ok:
    print('Dashboard %d created successfully' % res['dashboard']['id'])
    dashboard_name = res['dashboard']
else:
    print(res)
    sys.exit(1)

# Add a time series panel
panel_type = 'timeSeries'
metrics = [
    {'id': 'proc.name'},
    {'id': 'cpu.used.percent', 'aggregations': {'time': 'avg', 'group': 'avg'}}
]
ok, res = sdclient.add_dashboard_panel(
    dashboard_name, PANEL_NAME, panel_type, metrics)

# Check the result
if ok:
    print('Panel added successfully')
    dashboard_name = res['dashboard']
else:
    print(res)
    sys.exit(1)

チームでダッシュボードを作成する

次のコードは、特定のチームのダッシュボードを作成するPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))

from sdcclient import SdMonitorClient

# Parse arguments.
def usage():
   print('usage: %s <endpoint-url> <sysdig_token>' % sys.argv[0])
   print('endpoint-url: The endpoint URL that should point to IBM Cloud')
   print('sysdig_token: Sysdig token for the team')
   sys.exit(1)

if len(sys.argv) != 3:
   usage()

URL = sys.argv[1]

# Set to the Sysdig token of the team
SYSDIG_TOKEN = sys.argv[2]

DASHBOARD_NAME = 'My New Dashboard from Python'
PANEL_NAME = 'CPU Over Time'

sdclient = SdMonitorClient(token=SYSDIG_TOKEN,sdc_url=URL)

# Create an empty dashboard
ok, res = sdclient.create_dashboard(DASHBOARD_NAME)

# Check the result
dashboard_name = None
if ok:
    print('Dashboard %d created successfully' % res['dashboard']['id'])
    dashboard_name = res['dashboard']
else:
    print(res)
    sys.exit(1)

# Add a time series panel
panel_type = 'timeSeries'
metrics = [
    {'id': 'proc.name'},
    {'id': 'cpu.used.percent', 'aggregations': {'time': 'avg', 'group': 'avg'}}
]
ok, res = sdclient.add_dashboard_panel(
    dashboard_name, PANEL_NAME, panel_type, metrics)

# Check the result
if ok:
    print('Panel added successfully')
    dashboard_name = res['dashboard']
else:
    print(res)
    sys.exit(1)

ダッシュボードのコピー

Pythonてダッシュボードをコピーすることができます。

カスタムダッシュボードをデフォルトチームにコピーする

以下のコードは、カスタムダッシュボードをデフォルトチームにコピーするPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
 def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

# Name for the dashboard to create
dashboard_name = "My new CPU dashboard"
# Existing dashboard to copy
existing_dashboard_name = "My Existing Dashboard"
# New filter to apply
scope_filter = 'host.hostName = "virtualserver02"'

# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

# Copy a dashboard
ok, res = sdclient.create_dashboard_from_dashboard(dashboard_name, existing_dashboard_name, scope_filter, shared=False, public=True)

# Check the result
#
if ok:
    print('Dashboard created successfully')
else:
    print(res)
    sys.exit(1)

デフォルトチーム内の定義済みダッシュボードをコピーする

以下のコードは、定義済みのダッシュボードをデフォルトチームにコピーするPythonスクリプトの構造を示している。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
 def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

# Name for the dashboard to create
dashboard_name = "My Overview by Process"
# Existing dashboard to copy
default_dashboard_name = "Overview by Process"
# New filter to apply
scope_filter = 'host.hostName = "virtualserver02"'

# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

# Copy a dashboard
ok, res = sdclient.create_dashboard_from_view(dashboard_name, default_dashboard_name, scope_filter, shared=False, public=True)

# Check the result
#
if ok:
    print('Dashboard created successfully')
else:
    print(res)
    sys.exit(1)

チーム内のダッシュボードをコピーする

次のコードは、ダッシュボードをチームにコピーするPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))

from sdcclient import SdMonitorClient

# Parse arguments.
def usage():
   print('usage: %s <endpoint-url> <sysdig_token>' % sys.argv[0])
   print('endpoint-url: The endpoint URL that should point to IBM Cloud')
   print('sysdig_token: Sysdig token for the team')
   sys.exit(1)

if len(sys.argv) != 3:
   usage()

URL = sys.argv[1]

# Set to the Sysdig token of the team
SYSDIG_TOKEN = sys.argv[2]

# Name for the dashboard to create
dashboard_name = "My new CPU dashboard"
# Existing dashboard to copy
existing_dashboard_name = "My Existing Dashboard"
# New filter to apply
scope_filter = 'host.hostName = "virtualserver02"'

sdclient = SdMonitorClient(token=SYSDIG_TOKEN,sdc_url=URL)


# Copy a dashboard
ok, res = sdclient.create_dashboard_from_dashboard(dashboard_name, existing_dashboard_name, scope_filter, shared=False, public=True)

# Check the result
#
if ok:
    print('Dashboard created successfully')
else:
    print(res)
    sys.exit(1)

ダッシュボードの削除

使用できますPythonダッシュボードを削除します。

ダッシュボードを削除するには、ダッシュボードの ID を知っている必要があります。

デフォルトチームからダッシュボードを削除する

以下のコードは、デフォルトチームからダッシュボードを削除するPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

# Name of the dashboard that you want to delete
DASHBOARD_NAME = "Nginx production"


# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

# Show the list of dashboards
ok, res = sdclient.get_dashboards()

# Loop through all fetched dashboards
for dashboard in res[1]['dashboards']:
    # Delete dashboard if it matches the pattern (one or many)
    if DASHBOARD_NAME in dashboard['name']:
        print("Deleting " + dashboard['name'])
        res = sdclient.delete_dashboard(dashboard)

チームからダッシュボードを削除する

次のコードは、特定のチームからダッシュボードを削除するPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))

from sdcclient import SdMonitorClient

# Parse arguments.
def usage():
   print('usage: %s <endpoint-url> <sysdig_token>' % sys.argv[0])
   print('endpoint-url: The endpoint URL that should point to IBM Cloud')
   print('sysdig_token: Sysdig token for the team')
   sys.exit(1)

if len(sys.argv) != 3:
   usage()

URL = sys.argv[1]

# Set to the Sysdig token of the team
SYSDIG_TOKEN = sys.argv[2]

sdclient = SdMonitorClient(token=SYSDIG_TOKEN,sdc_url=URL)

# Show the list of dashboards
ok, res = sdclient.get_dashboards()

# Loop through all fetched dashboards
for dashboard in res[1]['dashboards']:
    # Delete dashboard if it matches the pattern (one or many)
    if DASHBOARD_NAME in dashboard['name']:
        print("Deleting " + dashboard['name'])
        res = sdclient.delete_dashboard(dashboard)

カスタムダッシュボードをダウンロード

Pythonてカスタムダッシュボードをダウンロードできる。

ダッシュボードをダウンロードするときには、カスタム・ダッシュボードのみをダウンロードします。

デフォルトチームでカスタムダッシュボードをダウンロードする

以下のコードは、デフォルトチームからカスタムダッシュボードをダウンロードするPythonスクリプトの構造を示しています。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import IbmAuthHelper, SdMonitorClient

# Parse arguments.
 def usage():
    print('usage: %s <endpoint-url> <apikey> <instance-guid>' % sys.argv[0])
    print('endpoint-url: The endpoint URL that should point to IBM Cloud')
    print('apikey: IBM Cloud IAM apikey that will be used to retrieve an access token')
    print('instance-guid: GUID of an IBM Cloud Monitoring with monitoring instance')
    sys.exit(1)

if len(sys.argv) != 4:
   usage()


def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))


def cleanup_dir(path):
    if os.path.exists(path) == False:
        return
    if os.path.isdir(path) == False:
        print('Provided path is not a directory')
        sys.exit(-1)

    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
            else:
                print('Cannot clean the provided directory due to delete failure on %s' % file_path)
        except Exception as e:
            print(e)
    os.rmdir(path)

sysdig_dashboard_dir = 'sysdig-dashboard-dir'

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]

# Instantiate the client
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)

ok, res = sdclient.get_dashboards()

if not ok:
    print(res)
    sys.exit(1)

# Creating sysdig dashboard directory to store dashboards
if not os.path.exists(sysdig_dashboard_dir):
    os.makedirs(sysdig_dashboard_dir)

for db in res['dashboards']:
    sdclient.save_dashboard_to_file(db, os.path.join(sysdig_dashboard_dir, str(db['id'])))

    print("Name: %s, # Charts: %d" % (db['name'], len(db['widgets'])))

チームでカスタムダッシュボードをダウンロードする

次のコードは、Python特定のチームからカスタムダッシュボードをダウンロードするスクリプト。

#!/usr/bin/env python3

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))

from sdcclient import SdMonitorClient

# Parse arguments.
def usage():
   print('usage: %s <endpoint-url> <sysdig_token>' % sys.argv[0])
   print('endpoint-url: The endpoint URL that should point to IBM Cloud')
   print('sysdig_token: Sysdig token for the team')
   sys.exit(1)

if len(sys.argv) != 3:
   usage()

URL = sys.argv[1]

# Set to the Sysdig token of the team
SYSDIG_TOKEN = sys.argv[2]

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))


def cleanup_dir(path):
    if os.path.exists(path) == False:
        return
    if os.path.isdir(path) == False:
        print('Provided path is not a directory')
        sys.exit(-1)

    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
            else:
                print('Cannot clean the provided directory due to delete failure on %s' % file_path)
        except Exception as e:
            print(e)
    os.rmdir(path)

sysdig_dashboard_dir = 'sysdig-dashboard-dir'

sdclient = SdMonitorClient(token=SYSDIG_TOKEN,sdc_url=URL)

ok, res = sdclient.get_dashboards()

if not ok:
    print(res)
    sys.exit(1)

# Creating sysdig dashboard directory to store dashboards
if not os.path.exists(sysdig_dashboard_dir):
    os.makedirs(sysdig_dashboard_dir)

for db in res['dashboards']:
    sdclient.save_dashboard_to_file(db, os.path.join(sysdig_dashboard_dir, str(db['id'])))

    print("Name: %s, # Charts: %d" % (db['name'], len(db['widgets'])))