!pip show qumulo_api

import qumulo
import os
import io
import glob
import re
import time
from datetime import datetime
import dateutil.parser as date_parser
from qumulo.rest_client import RestClient

%%javascript
// this will prevent the large output window below from being boxed in.
IPython.OutputArea.auto_scroll_threshold = 9999;

# set your environment variables or fill in the variables below
API_HOSTNAME = os.environ['API_HOSTNAME'] if 'API_HOSTNAME' in os.environ else 'product.eng.qumulo.com'
API_USER =     os.environ['API_USER']     if 'API_USER'     in os.environ else 'admin'
API_PASSWORD = os.environ['API_PASSWORD'] if 'API_PASSWORD' in os.environ else ''

"""
Explanation: Deep dive into the Qumulo API python bindings
<span style="background-color: #FFBBAA; padding: 5px;">This data is current as of Qumulo Version 3.3.1</span>
This notebook helps a user explore the Qumulo API python bindings. First, it will list out all of the supported Qunmulo API python modules and functions. Don't forget to run <code>pip install qumulo_api</code> first.
After listing all of the defined python functions, it demonstrates one (ore more) functions inside each of python modules. All code examples below are will only read data and configuration from your Qumulo cluster.
End of explanation
"""


qumulo_lib_path = os.path.dirname(qumulo.__file__) + '/rest'

total_matches = 0
for f in glob.glob(qumulo_lib_path + '/*.py'):
    file_name = os.path.basename(f)
    if file_name == '__init__.py':
        continue
    print("")
    print("-"*80)
    print("Area: %s" % (file_name, ))
    c = open(f, 'r').read()
    rx_str = '@request.request[ \r\n]+def ([^(]+)\([ \r\n]*conninfo,[ \r\n]*credentials([^\)]*)(.*?)(return|yield)'
    ms = re.findall(rx_str, c, re.S|re.M)
    for m in ms:
        total_matches += 1
        func_name = m[0]
        
        # get arguments
        args = []
        arg_ms = m[1].split(',')
        for arg_m in arg_ms:
            if arg_m.strip() != "":
                args.append(re.sub('=.*', '', arg_m.strip()))

        # method
        method = "GET"
        method_m = re.search('method[ ]*=[ ]*"([A-Z]+)', m[2])
        if method_m is not None:
            method = method_m.group(1)

        # uri, currently more work for fs methods
        uri = "/"
        uri_m = re.search('uri[ ]*=.*?"([^"]+)', m[2])
        if uri_m is not None:
            uri = uri_m.group(1)
        uri_m = re.search('uri[ ]*=.*?\'([^\']+)', m[2])
        if uri_m is not None:
            uri = uri_m.group(1)

        print("   rc.%s.%s(%s)" % (file_name.replace('.py', ''), 
                                   func_name, 
                                   ', '.join(args[:4]) + (' ...' if len(args)>4 else '')))


"""
Explanation: Inspect all of the Qumulo python bindings and show methods
End of explanation
"""


# Create a new reset client and login.
rc = RestClient(API_HOSTNAME, 8000)
rc.login(API_USER, API_PASSWORD)

"""
Explanation: Create a new python REST client instance and login.
End of explanation
"""


# if qumulo_api is installed via pip, this will return its version.
cmd_output = !pip show qumulo_api

# parse out results if "pip show"
pip_version = '! Unknown !'
for line in cmd_output:
    parts = line.split(':')
    if parts[0] == 'Version':
        pip_version = parts[1]

print("Qumulo API python library version: %s" % (pip_version.strip(),))

# get the Qumulo cluster software version via the API
cluster_version = rc.version.version()
print("Qumulo Cluster software version: %s" % (cluster_version['revision_id'].replace('Qumulo Core ', ''),))

# How old is the current build on the Qumulo cluster?
build_time = int(date_parser.parse(cluster_version['build_date']).strftime('%s'))
cur_time = time.time()
print("Qumulo Cluster software version is: %d days old." % ((cur_time - build_time)/(60*60*24),))

"""
Explanation: Show Qumulo API python client library version and Qumulo cluster software version
End of explanation
"""


# Show the current status of the Cluster's AD relationship
rc.ad.list_ad()

"""
Explanation: Active Directory (ad) - list AD status
End of explanation
"""


# Get the latest minute's metrics from the timeseries data endpoint.
# This data is used on the Qumulo web application's dashboard home page.
# Show the average value for the last minute for each series.
data = rc.analytics.time_series_get(begin_time=int(time.time() - 60))
for series in data:
    # skip totals since they are duplicated by the other metrics
    if 'total' in series['id']:
        continue
    print("%22s - %11s" % (series['id'],
                       round(sum(series['values']) / len(series['values']), 1)))

"""
Explanation: analytics - timeseries data
End of explanation
"""


for a in rc.auth.local_username_to_all_related_identities('tommy'):
    print("%(id_type)s - %(id_value)s" % a)

"""
Explanation: Authentication and Authorization (auth) - get related identities
End of explanation
"""


for n in rc.cluster.list_nodes():
    print("%(node_name)s/%(id)s - %(model_number)s" % n)

"""
Explanation: cluster - list nodes
End of explanation
"""


for d in rc.dns.resolve_ips_to_names(['127.0.0.1', '10.20.217.62', '192.168.0.1', '192.168.1.1', 
                               '192.168.154.1', '172.16.1.1', '10.120.246.43', '10.10.1.1']):
    print("%(ip_address)15s - %(result)10s - %(hostname)s" % d)

"""
Explanation: dns - resolve names from ip addresses
End of explanation
"""


path = '/test/'
dir_ent = rc.fs.read_directory(path=path)
for d in dir_ent['files']:
    if d['type'] == 'FS_FILE_TYPE_FILE':
        fw = io.BytesIO()
        print("Read file %(name)s which is %(size)s bytes, and print first 80 bytes" % d)
        rc.fs.read_file(fw, path = path + d['name'])
        print(fw.getvalue()[:80])
        break


"""
Explanation: File System (fs) - list files and read a file
End of explanation
"""


for g in rc.groups.list_groups():
    print("%(gid)6s %(id)6s %(name)16s %(sid)50s" % g)

"""
Explanation: groups - list all groups in Qumulo
End of explanation
"""


for c in rc.network.connections():
    print("Node %2s connection count: %4s  ----  First %s: %s" % (
            c['id'], 
            len(c['connections']),
            min(len(c['connections']), 10), 
            ', '.join([d['network_address'] + '/' + d['type'].replace('CONNECTION_TYPE_', '') 
                       for d in c['connections']])))

"""
Explanation: network - show current connection counts to all nodes
End of explanation
"""


for share in rc.nfs.nfs_list_exports():
    print("%(export_path)s -> %(fs_path)s - %(description)s" % share)

"""
Explanation: nfs - list shares
End of explanation
"""


print(rc.node_state.get_node_state())
# (only prints the state of the node the rest client is currently connected to)

"""
Explanation: node_state - get current node state
End of explanation
"""


quota_count = 0
for qd in rc.quota.get_all_quotas_with_status():
    for q in qd['quotas']:
        quota_count += 1
        if quota_count > 20:
            break
        print("%(path)s - id: %(id)s - %(capacity_usage)s bytes used of %(limit)s" % q)

"""
Explanation: quota - list first 20 quotas and capacity used for each
End of explanation
"""


for share in rc.smb.smb_list_shares():
    print("%(share_name)s -> %(fs_path)s - %(description)s" % share)

"""
Explanation: smb - list shares
End of explanation
"""


for snap in rc.snapshot.list_snapshots()['entries'][:10]:
    print("%(name)s - %(source_file_id)s - %(directory_name)s - %(timestamp)s" % snap)

"""
Explanation: snapshots - list directory-level snapshots
End of explanation
"""


rc.support.get_config()

"""
Explanation: support - check support/monitoring status
End of explanation
"""


rc.time_config.get_time_status()

"""
Explanation: time_config - get current time status
End of explanation
"""


for user in rc.users.list_users():
    print("%(name)10s - %(uid)5s - %(id)5s - %(primary_group)4s - %(sid)s" % user)

"""
Explanation: users - list users
End of explanation
"""


