def delete_user(sdmonitor: SdMonitorClient, email: AnyStr):
    ok, res = sdmonitor.delete_user(user_email=email)
    if not ok:
        print("error deleting the user: ", res)
        return EXIT_CODES.ERR_DELETING_USER

    return EXIT_CODES.OK
def delete_dashboards(sdmonitor: SdMonitorClient, ids: List):
    for id in ids:
        ok, res = sdmonitor.delete_dashboard(dashboard={"id": id})
        if not ok:
            print(f"error deleting the dashboard {id}: {res}")
            return EXIT_CODES.ERR_DELETING_DASHBOARD
        print(f"Deleted dashboard {id}")
    return EXIT_CODES.OK
def create_dashboards_from_file(sdmonitor: SdMonitorClient, file: Any):
    contents = file.read()
    try:
        dashboards = json.loads(contents)
        for dboard in dashboards:
            dboard['timeMode'] = {'mode': 1}
            dboard['time'] = {
                'last': 2 * 60 * 60 * 1000000,
                'sampling': 2 * 60 * 60 * 1000000
            }
            ok, res = sdmonitor.create_dashboard_from_template(
                dboard["name"], dboard, shared=dboard["isShared"])
            if not ok:
                print(f"Error creating the dashboard {dboard['name']}: {res}")
                return EXIT_CODES.ERR_CREATING_DASHBOARD
            print(f"Created dashboard {dboard['name']}")
        return EXIT_CODES.OK
    except:
        pass

    try:
        dashboards = yaml.load(contents)
        for dboard in dashboards:
            dboard['timeMode'] = {'mode': 1}
            dboard['time'] = {
                'last': 2 * 60 * 60 * 1000000,
                'sampling': 2 * 60 * 60 * 1000000
            }
            ok, res = sdmonitor.create_dashboard_from_template(
                dboard["name"], dboard, shared=dboard["isShared"])
            if not ok:
                print(f"Error creating the dashboard {dboard['name']}: {res}")
                return EXIT_CODES.ERR_CREATING_DASHBOARD
            print(f"Created dashboard {dboard['name']}")
        return EXIT_CODES.OK
    except:
        pass
    return EXIT_CODES.ERR_CREATING_DASHBOARD
def create_user(sdmonitor: SdMonitorClient,
                email,
                first_name,
                last_name,
                system_role="ROLE_USER"):
    ok, res = sdmonitor.create_user_invite(user_email=email,
                                           first_name=first_name,
                                           last_name=last_name,
                                           system_role=system_role)
    if not ok:
        print("error creating the user: ", res)
        return EXIT_CODES.ERR_CREATING_USER

    return EXIT_CODES.OK
def get_dashboards(sdmonitor: SdMonitorClient, ids: List, format: AnyStr):
    ok, data = sdmonitor.get_dashboards()
    ids = set([str(id) for id in ids])
    if not ok:
        print(data)
        return EXIT_CODES.ERR_METHOD_NOT_FOUND

    dashboards = [
        dash for dash in data["dashboards"] if str(dash["id"]) in ids
    ]
    if len(dashboards) == 0:
        print("No dashboards found with these IDs")
        return EXIT_CODES.ERR_METHOD_NOT_FOUND

    if format == "yaml":
        print(yaml.dump(dashboards))
        return EXIT_CODES.OK

    print(json.dumps(dashboards, indent=2))
    usage()

pattern = "API Test"
for opt, arg in opts:
    if opt in ("-p", "--pattern"):
        pattern = arg

if len(args) != 1:
    usage()

sdc_token = args[0]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# List the dashboards
#
ok, res = sdclient.get_dashboards()
if not ok:
    print(res)
    sys.exit(1)

#
# Delete all the dashboards containing pattern
#
for dashboard in res['dashboards']:
    if pattern in dashboard['name']:
        print(("Deleting " + dashboard['name']))
def run(sysdig_token, pager_duty_id, pager_duty_token, link, unlink, dry_run):
    if not link and not unlink:
        # by default, you're going to link accounts
        link = True

    sysdig = SdMonitorClient(sysdig_token)
    pager_duty = PagerDutyAPI(pager_duty_token)
    actions_factory = ActionFactory(sysdig, pager_duty, pager_duty_id)

    #
    # Get list of Sysdig notification channels
    #
    ok, res = sysdig.list_notification_channels()
    if not ok:
        print('\nUnable to fetch Sysdig notification channels')
        print(res)
        sys.exit(1)

    #
    # Find PagerDuty notification channels
    #
    pager_duty_channels = [
        channel for channel in res['notificationChannels']
        if channel['type'] == 'PAGER_DUTY'
    ]
    print('Found {} PagerDuty notification {} configured in Sysdig'.format(
        len(pager_duty_channels), pluralize('channel',
                                            len(pager_duty_channels))))

    # print(json.dumps(pager_duty_channels, sort_keys=True, indent=4))

    # Build map of notification channel -> integration key
    def get_integration_map(acc, channel):
        acc[channel['options']['serviceKey']] = channel
        return acc

    integration_keys = reduce(get_integration_map, pager_duty_channels, {})

    #
    # Get list of PagerDuty escalation policies
    #
    escalation_policies = pager_duty.get(
        '/escalation_policies')['escalation_policies']
    print('Found {} PagerDuty escalation {}'.format(
        len(escalation_policies),
        pluralize('policy', len(escalation_policies), 'policies')))
    escalation_policies_map = {}
    for escalation_policy in escalation_policies:
        escalation_policies_map[escalation_policy['id']] = escalation_policy
    # print(json.dumps(escalation_policies, sort_keys=True, indent=4))

    #
    # Get list of PagerDuty services
    #
    services = pager_duty.get('/services',
                              {'include[]': ['integrations']})['services']
    print('Found {} PagerDuty {}'.format(len(services),
                                         pluralize('service', len(services))))
    # print(json.dumps(services, sort_keys=True, indent=4))

    #
    # Get Sysdig vendor configuration
    #
    sysdig_vendor = pager_duty.get('/vendors', {
        'query': 'sysdig',
        'limit': 1,
        'offset': 0,
        'total': 'false'
    })['vendors'][0]

    #
    # Get integration details
    #
    for service in services:
        for integration in service['integrations']:
            integration['details'] = pager_duty.get(
                '/services/{}/integrations/{}'.format(
                    service['id'], integration['id']))['integration']

    #
    # Find integrations with Sysdig
    #
    service_integration_keys = {}
    for service in services:
        service['sysdig_integrations'] = [
            integration for integration in service['integrations']
            if 'vendor' in integration and integration['vendor']
            and integration['vendor']['id'] == sysdig_vendor['id']
        ]

        for integration in service['sysdig_integrations']:
            service_integration_keys[integration['integration_key']] = {
                'service': service,
                'integration': integration
            }

    #
    # Get actions
    #
    actions = []

    if unlink:
        #
        # delete all PagerDuty notification channels in Sysdig
        #
        for channel in pager_duty_channels:
            actions.append({
                'info':
                'Sysdig: Delete channel "{}" ({})'.format(
                    channel['name'], channel['id']),
                'fn':
                actions_factory.delete_notification_channel(channel)
            })

        #
        # delete integration with Sysdig
        #
        for service in services:
            if service['sysdig_integrations']:
                if len(service['sysdig_integrations']) == len(
                        service['integrations']):
                    #
                    # service connected to Sysdig only: delete service
                    #
                    actions.append({
                        'info':
                        'PagerDuty: Delete service "{}" ({})'.format(
                            service['name'], service['id']),
                        'fn':
                        actions_factory.delete_service(service['id'])
                    })
                else:
                    #
                    # service with some integrations with Sysdig: delete individual integrations
                    #
                    for integration in service['sysdig_integrations']:
                        actions.append({
                            'info':
                            'PagerDuty: Delete integration "{}" ({}) in service "{}" ({})'
                            .format(integration['name'], integration['id'],
                                    service['name'], service['id']),
                            'fn':
                            actions_factory.delete_integration(
                                service['id'], integration['id'])
                        })

    if link:
        #
        # delete all PagerDuty notification channels in Sysdig that do NOT have an integration in PagerDuty
        #
        for channel in pager_duty_channels:
            if not channel['options']['serviceKey'] in service_integration_keys:
                actions.append({
                    'info':
                    'Remove notification channel "{}" not connected to any integration'
                    .format(channel['name']),
                    'fn':
                    actions_factory.delete_notification_channel(channel)
                })

        for policy in escalation_policies:
            service_name = '{} (Sysdig)'.format(policy['name'])

            policy_services = [
                service for service in services
                if service['escalation_policy']['id'] == policy['id']
            ]
            sysdig_services = [
                service for service in policy_services
                if service['sysdig_integrations']
            ]
            disconnected_services = []
            for service in sysdig_services:
                for integration in service['integrations']:
                    if integration['vendor'] and integration['vendor'][
                            'id'] == sysdig_vendor['id'] and integration[
                                'integration_key'] not in integration_keys:
                        disconnected_services.append({
                            'service': service,
                            'integration': integration
                        })

            if not sysdig_services:
                #
                # create service and integration in PagerDuty, and notification channel in Sysdig
                #
                actions.append({
                    'info':
                    'Create service, integration, and notification channel for policy "{}"'
                    .format(policy['name']),
                    'fn':
                    actions_factory.create_all(policy, sysdig_vendor)
                })
            elif disconnected_services:
                #
                # create notification channel to disconnected integration
                #
                actions.append({
                    'info':
                    'Restore notification channel for disconnected service "{}" for policy "{}"'
                    .format(disconnected_services[0]['service']['name'],
                            policy['name']),
                    'fn':
                    actions_factory.create_notification_channel(
                        policy, disconnected_services[0]['service'],
                        disconnected_services[0]['integration'])
                })
            else:
                for service in sysdig_services:
                    for integration in service['integrations']:
                        if integration['vendor'] and integration['vendor'][
                                'id'] == sysdig_vendor['id'] and integration[
                                    'integration_key'] in integration_keys:
                            channel = integration_keys[
                                integration['integration_key']]
                            if channel['name'] != policy['name']:
                                #
                                # rename channel to match new policy name
                                #
                                actions.append({
                                    'info':
                                    'Rename notification channel "{}" to policy name "{}"'
                                    .format(channel['name'], policy['name']),
                                    'fn':
                                    actions_factory.
                                    rename_notification_channel(
                                        channel, policy['name'], service_name)
                                })
                            elif channel['options'][
                                    'serviceName'] != service_name:
                                #
                                # rename channel service to service name
                                #
                                actions.append({
                                    'info':
                                    'Rename channel service "{}" to service name "{}"'
                                    .format(service['name'], service_name),
                                    'fn':
                                    actions_factory.
                                    rename_notification_channel(
                                        channel, policy['name'], service_name)
                                })

                            if len(service['integrations']
                                   ) == 1 and service['name'] != service_name:
                                #
                                # rename service to match new policy name
                                #
                                actions.append({
                                    'info':
                                    'Rename service "{}" to "{}"'.format(
                                        service['name'], service_name),
                                    'fn':
                                    actions_factory.rename_service(
                                        service, service_name)
                                })

    if actions:
        #
        # Run action, or just print the task in dry mode
        #
        print('')
        print('Action items:')
        for action in actions:
            if dry_run:
                print('\t* {}'.format(action['info']))
            else:
                print('\t* {}...'.format(action['info']))
                action['fn']()
                print('\t  Done!')

        if dry_run:
            print(
                '\nTo apply changes, execute the same command without "--dry-run" parameter:\npython {}'
                .format(' '.join(
                    [arg for arg in sys.argv if arg != '--dry-run'])))

    else:
        if unlink:
            print(
                'All escalation policies have been disconnected from Sysdig!')
        if link:
            print('All escalation policies are already connected to Sysdig!')
Exemple #8
0
        'usage: %s <sysdig-v1-url> <sysdig-v1-token> <sysdig-v2-url> <sysdig-v2-token>'
        % sys.argv[0]))
    print(
        'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    )
    sys.exit(1)

sdc_v1_url = sys.argv[1]
sdc_v1_token = sys.argv[2]
sdc_v2_url = sys.argv[3]
sdc_v2_token = sys.argv[4]

#
# Instantiate the SDC client
#
sdclient_v2 = SdMonitorClient(sdc_v2_token, sdc_url=sdc_v2_url)
sdclient_v1 = SdMonitorClientV1(sdc_v1_token, sdc_url=sdc_v1_url)

#
# Serialize the first user dashboard to disk
#
ok, res = sdclient_v1.get_dashboards()

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

for dashboard in res['dashboards']:
    file_name = '{}.json'.format(dashboard['id'])
    print(
        ('Saving v1 dashboard {} to file {}...'.format(dashboard['name'],
#
# Parse arguments
#
if len(sys.argv) != 2:
    print(('usage: %s <sysdig-token>' % sys.argv[0]))
    print(
        'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    )
    sys.exit(1)

sdc_token = sys.argv[1]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Serialize the first user dashboard to disk
#
ok, res = sdclient.get_dashboards()

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

if len(res['dashboards']) > 0:
    sdclient.save_dashboard_to_file(res['dashboards'][0], 'dashboard.json')
else:
    print('the user has no dashboards. Exiting.')
    sys.exit(0)
#
# Parse arguments
#
if len(sys.argv) != 2:
    print('usage: %s <sysdig-token>' % sys.argv[0])
    print(
        'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    )
    sys.exit(1)

sdc_token = sys.argv[1]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Create Dashboard.
#
ok, res = sdclient.create_dashboard("Sample dashboard - " + uuid.uuid4().hex)

#
# Check for successful creation
#
if not ok:
    print(res)
    sys.exit(1)

dashboard = res['dashboard']
Exemple #11
0

#
# Parse arguments
#
if len(sys.argv) != 2:
    print(('usage: %s <sysdig-token>' % sys.argv[0]))
    print('You can find your token at https://app.sysdigcloud.com/#/settings/user')
    sys.exit(1)

sdc_token = sys.argv[1]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Get the entire list of events
#
ok, res = sdclient.get_events()

if ok:
    print_events(res)
else:
    print(res)
    sys.exit(1)

#
# Get the events before other event
#
# Parse arguments
#
if len(sys.argv) != 3:
    print(('usage: %s <sysdig-token> <file-name>' % sys.argv[0]))
    print(
        'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    )
    sys.exit(1)

sdc_token = sys.argv[1]
dashboard_state_file = sys.argv[2]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

zipf = zipfile.ZipFile(dashboard_state_file, 'r')

for info in zipf.infolist():
    data = zipf.read(info.filename)
    try:
        j = json.loads(data)
    except ValueError:
        print(('Invalid JSON file found in ZIP file ' + info.filename +
               ': skipping'))
        continue

    #
    # Handle old files
    #
Exemple #13
0
)
parser.add_argument(
    'sysdig_token',
    help=
    'You can find your token at https://app.sysdigcloud.com/#/settings/user')
parser.add_argument('name')
args = parser.parse_args()

tags = None
if args.tags:
    tags = json.loads(args.tags)

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(args.sysdig_token)

#
# Post the event using post_event(self, name, description=None, severity=None, event_filter=None, tags=None)
#
ok, res = sdclient.post_event(args.name, args.description, args.severity,
                              args.scope, tags)

#
# Return the result
#
if ok:
    print('Event Posted Successfully')
else:
    print(res)
    sys.exit(1)
        'instance-guid: GUID of an IBM Cloud Monitoring with Sysdig instance')
    sys.exit(1)


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

URL = sys.argv[1]
APIKEY = sys.argv[2]
GUID = sys.argv[3]
DASHBOARD_NAME = 'IBM Cloud IAM with Python Client Example'
PANEL_NAME = 'CPU Over Time'

# Instantiate the client with an IBM Cloud auth object
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_configuration = None
if ok:
    print('Dashboard %d created successfully' % res['dashboard']['id'])
    dashboard_configuration = res['dashboard']
else:
    print(res)
    sys.exit(1)

# Add a time series panel
panel_type = 'timeSeries'
    usage()

event_name = "test_event_name"
for opt, arg in opts:
    if opt in ("-e", "--event"):
        event_name = arg

if len(args) != 1:
    usage()

sdc_token = args[0]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Get the events that match a name
#
ok, res = sdclient.get_events(name=event_name)

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

#
# Delete the first event among the returned ones
#
for event in res['events']:
    print(("Deleting event " + event['name']))
Exemple #16
0
#
# Parse arguments
#
if len(sys.argv) != 3:
    print(('usage: %s <sysdig-token> <file-name>' % sys.argv[0]))
    print('You can find your token at https://app.sysdigcloud.com/#/settings/user')
    sys.exit(1)

sdc_token = sys.argv[1]
dashboard_state_file = sys.argv[2]
sysdig_dashboard_dir = 'sysdig-dashboard-dir'

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Fire the request.
#
ok, res = sdclient.get_dashboards()

#
# Show the list of dashboards
#
if not ok:
    print(res)
    sys.exit(1)

# Clean up any state in the tmp directory
cleanup_dir(sysdig_dashboard_dir)
Exemple #17
0
    usage()

dashboard_name = "My Dashboard"
for opt, arg in opts:
    if opt in ("-d", "--dashboard"):
        dashboard_name = arg

if len(args) != 1:
    usage()

sdc_token = args[0]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Create an empty dashboard
#
dashboard_configuration = None
ok, res = sdclient.create_dashboard(dashboard_name)

# Check the result
if ok:
    print('Dashboard %d created successfully' % res['dashboard']['id'])
    dashboard_configuration = res['dashboard']
else:
    print(res)
    sys.exit(1)
Exemple #18
0
# Name for the dashboard to create
dashboardName = "IBM_MIGRATION_DASHBOARD"
for opt, arg in opts:
    if opt in ("-d", "--dashboard"):
        dashboardName = arg

if len(args) != 1:
    usage()

sdc_token = args[0]

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Create the new dashboard, applying to cassandra in production
#
# Name of the custom/new dashboard.
dashboardName = "CUSTOMHTTP"
# Name of the view to copy
viewName = "HTTP"
# Filter to apply to the new dashboard.
# Remember that you can use combinations of any segmentation criteria you find
# in Sysdig Cloud Explore page.
# You can also refer to AWS tags by using "cloudProvider.tag.*" metadata or
# agent tags by using "agent.tag.*" metadata
dashboardFilter = 'kubernetes.namespace.name = "air"'
print('Creating dashboard from view')
Exemple #19
0
sdc_token = sys.argv[1]
name = sys.argv[2]
description = sys.argv[3]

scope = 'host.hostName = "foo" and container.name = "bar"'
tags = {"tag1": "value1"}

severity = 6
if len(sys.argv) < 4:
    severity = int(sys.argv[4])

#
# Instantiate the SDC client
#
sdclient = SdMonitorClient(sdc_token)

#
# Post the event
#
ok, res = sdclient.post_event(name, description, severity, scope, tags)

#
# Return the result
#
if ok:
    print('Event Posted Successfully')
else:
    print(res)
    sys.exit(1)