Example #1
0
 def __init__(self, configname):
     zfscredfilename = os.path.join(scriptpath(), 'netappcredentials.cfg')
     if not os.path.isfile(zfscredfilename):
         raise Exception(
             self._exceptionbase,
             "Configuration file %s not found" % zfscredfilename)
     # Authentication information
     zfscredconfig = SafeConfigParser()
     zfscredconfig.read(zfscredfilename)
     zfsauth = (zfscredconfig.get('netappcredentials', 'user'),
                zfscredconfig.get('netappcredentials', 'password'))
     #
     self._filer = Configuration.get('filer', 'netapp')
     self._srv = NaServer(self._filer, 1, 1)
     # Check if CA certificate validation is needed
     try:
         self._cacert = os.path.join(scriptpath(), 'certs',
                                     Configuration.get('cacert', 'netapp'))
     except NoOptionError:
         self._cacert = None
     if self._cacert:
         self._srv.set_ca_certs(self._cacert)
         self._srv.set_server_cert_verification(True)
         self._srv.set_hostname_verification(False)
     #
     self._srv.set_admin_user(
         zfscredconfig.get('netappcredentials', 'user'),
         zfscredconfig.get('netappcredentials', 'password'))
     self._volprefix = Configuration.get('volumeprefix', 'netapp')
     self._volname = "%s%s" % (self._volprefix, configname)
     super(Netapp, self).__init__(configname)
Example #2
0
def main() :
    s = NaServer(filer, 1, 3)

    out = s.set_transport_type('HTTP')
    if (out and out.results_errno() != 0) :
        r = out.results_reason()
        print ("Connection to filer failed: " + r + "\n")
        sys.exit(2)

    out = s.set_style('LOGIN')
    
    if (out and out.results_errno() != 0) :
        r = out.results_reason()
        print ("Connection to filer failed: " + r + "\n")
        sys.exit(2)

    out = s.set_admin_user(user, pw)

    if(command == "object-list"):
        get_object_list(s)

    elif(command == "instance-list"):
        get_instance_list(s)

    elif(command == "counter-list"):
        get_counter_list(s)

    elif(command == "get-counter-values"):
        get_counter_values(s)

    else:
        print ("Invalid operation\n")
        print_usage()
Example #3
0
def main():
    s = NaServer (filer, 1, 3)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    resp = s.set_style('LOGIN')
    
    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Failed to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)

    if(command == "file-get-snaplock-retention-time"):
        file_get_retention(s)

    elif(command == "file-set-snaplock-retention-time"):
        file_set_retention(s)

    elif(command == "file-snaplock-retention-time-list-info"):
        file_get_retention_list(s)

    elif(command == "file-get-snaplock-retention-time-list-info-max"):
        file_get_retention_list_info_max(s)

    else:
        print ("Invalid operation\n")
        print_usage()
Example #4
0
def main():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')
    
    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)
        
    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set HTTP transport" + r + "\n")
        sys.exit (2)

    if(command == "getStatus"):
        get_status(s)

    elif(command == "getVolStatus"):
        get_vol_status(s)

    elif(command == "off"):
        snapmirror_off(s)

    elif(command == "on"):
        snapmirror_on(s)

    else:
        print ("Invalid operation\n")
        print_usage()
Example #5
0
def main():
    s = NaServer(filer, 1, 3)
    resp = s.set_style('LOGIN')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Failed to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    if((command == "raw-capacity") or (command == "formatted-capacity")	or (command == "spare-capacity")) :
        calc_raw_fmt_spare_capacity(s)

    elif((command == "raid-overhead") or (command == "wafl-overhead")) :
        calc_raid_wafl_overhead(s)

    elif(command == "allocated-capacity") :
        calc_allocated_capacity(s)

    elif(command == "avail-user-data-capacity") :
        calc_avail_user_data_capacity(s)

    elif(command == "provisioning-capacity") :
        calc_provisioning_capacity(s)

    else :
        print ("Invalid operation\n")
Example #6
0
def main():
    s = NaServer (filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set HTTP transport" + r + "\n")
        sys.exit (2)

    if(command == "lun"):
        process_LUN(s)

    elif(command == "igroup"):
        process_igroup(s)

    elif(command == "fcp"):
        process_fcp(s)

    elif(command == "iscsi"):
        process_iscsi(s)

    else:
        print ("Invalid operation\n")
        print_usage()
def main():
    s = NaServer(filer, 1, 3)

    out = s.set_transport_type('HTTP')
    if (out and out.results_errno() != 0):
        r = out.results_reason()
        print("Connection to filer failed: " + r + "\n")
        sys.exit(2)

    out = s.set_style('LOGIN')

    if (out and out.results_errno() != 0):
        r = out.results_reason()
        print("Connection to filer failed: " + r + "\n")
        sys.exit(2)

    out = s.set_admin_user(user, pw)

    if (command == "object-list"):
        get_object_list(s)

    elif (command == "instance-list"):
        get_instance_list(s)

    elif (command == "counter-list"):
        get_counter_list(s)

    elif (command == "get-counter-values"):
        get_counter_values(s)

    else:
        print("Invalid operation\n")
        print_usage()
Example #8
0
File: snmp.py Project: raykuan/docs
def main():
    s = NaServer (filer, 1, 3)
    response = s.set_style('LOGIN')
    
    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)
        
    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set HTTP transport" + r + "\n")
        sys.exit (2)

    if(command == "get"):
        snmp_get(s)

    elif(command == "status"):
        snmp_status(s)

    elif(command == "addCommunity"):
        add_community(s)

    elif(command == "deleteCommunity"):
        delete_community(s)

    else:
        print ("Invalid operation\n")
        print_usage()
 def __sevenm_metrics(self, kind, instances, metrics):
     values = {}
     times = {}
     cmd = NaServer.NaElement("perf-object-get-instances-iter-start")
     cmd.child_add_string("objectname", kind)
     counters = NaServer.NaElement("counters")
     for metric in metrics:
         counters.child_add_string("counter", metric)
     cmd.child_add(counters)
     insts = NaServer.NaElement("instances")
     for inst in instances:
         insts.child_add_string("instance", inst)
     cmd.child_add(insts)
     res = self.server.invoke_elem(cmd)
     if res.results_errno():
         reason = res.results_reason()
         msg = ("perf-object-get-instances-iter-start"
                " cannot collect '%s': %s")
         raise ValueError(msg % (kind, reason))
     next_tag = res.child_get_string("tag")
     instance_time = float(res.child_get_string("timestamp"))
     counter = self.perf_max_records
     while counter == self.perf_max_records:
         cmd = NaServer.NaElement("perf-object-get-instances-iter-next")
         cmd.child_add_string("tag", next_tag)
         cmd.child_add_string("maximum", self.perf_max_records)
         res = self.server.invoke_elem(cmd)
         if res.results_errno():
             reason = res.results_reason()
             msg = ("perf-object-get-instances-iter-next"
                    " cannot collect '%s': %s")
             raise ValueError(msg % (kind, reason))
         counter = res.child_get_string("records")
         partial_values, partial_times, partial_inst_t \
             = self.__collect_instances(res)
         # Mix them with the previous records of the same instance
         # WARNING, BUG with same instance and time!!!!!!!!!
         for instance, values in values.iteritems():
             if instance in partial_values:
                 values.update(partial_values[instance])
                 del partial_values[instance]
         values.update(partial_values)
         times.update(partial_times)
     cmd = NaServer.NaElement("perf-object-instance-list-info-iter-end")
     cmd.child_add_string("tag", next_tag)
     res = self.server.invoke_elem(cmd)
     if res.results_errno():
         reason = res.results_reason()
         msg = ("perf-object-instance-list-info-iter-end"
                " cannot collect '%s': %s")
         raise ValueError(msg % (kind, reason))
     return values, times, instance_time
    def __init__(self, hostname, user, passwd):
        self.api = NaServer(hostname, 1, 3)
        response = self.api.set_style('LOGIN')

        if (response and response.results_errno() != 0):
            r = response.results_reason()
            print("Unable to set authentication style " + r + "\n")
            sys.exit(2)

        self.api.set_admin_user(user, passwd)
        self.api.set_transport_type('HTTPS')

        self.name = hostname
def main() :
    SevenMode = Get7ModeSystems()

    for toaster in SevenMode:
        drives_mapped = defaultdict(list)
        filer = toaster[0]
        user = toaster[1]
        pw = toaster[2]

        s = NaServer(filer, 1, 3)
        out = s.set_transport_type('HTTPS')

        if (out and out.results_errno() != 0) :
            r = out.results_reason()
            print ("Connection to filer failed: " + r + "\n")
            sys.exit(2)

        out = s.set_style('LOGIN')
    
        if (out and out.results_errno() != 0) :
            r = out.results_reason()
            print ("Connection to filer failed: " + r + "\n")
            sys.exit(2)

        out = s.set_admin_user(user, pw)

        if(command == "object-list"):
            get_object_list(s)

        elif(command == "instance-list"):
            get_instance_list(s)

        elif(command == "counter-list"):
           get_counter_list(s)

        elif(command == "get-counter-values"):
            message_lines = []
            #turn the filer FQDN into something more Graphite Friendly
            filername = filer.split(".")[0]
            message_lines = get_counter_values(filername, s)
            message = '\n'.join(message_lines) + '\n' 
            #print message
            SendToGraphite(message)


        else:
            print ("Invalid operation\n")
            print_usage()
 def __clusterm_instances(self, kind, filter=''):
     counter = self.perf_max_records
     next_tag = ''
     instances_list = []
     while counter == self.perf_max_records:
         cmd = NaServer.NaElement("perf-object-instance-list-info-iter")
         cmd.child_add_string("objectname", kind)
         if filter:
             cmd.child_add_string("filter-data", filter)
         if next_tag:
             cmd.child_add_string("tag", next_tag)
         cmd.child_add_string("max-records", self.perf_max_records)
         res = self.server.invoke_elem(cmd)
         if res.results_errno():
             reason = res.results_reason()
             msg = ("perf-object-instance-list-info-iter"
                    " cannot collect '%s': %s")
             raise ValueError(msg % (kind, reason))
         next_tag = res.child_get_string("next-tag")
         counter = res.child_get_string("num-records")
         attr_list = res.child_get("attributes-list")
         if attr_list:
             for inst in attr_list.children_get():
                 name = inst.child_get_string("uuid")
                 instances_list.append(name)
     return instances_list
    def Connect(self):
        """
        connect to the netapp via the API
        """

        #self.s = NaServer(self.filer, 1, 3)
        self.s = NaServer(self.filer, 1, 9)
        self.out = self.s.set_transport_type('HTTPS')
        _log.debug("attempting to connect to filer via HTTPS")

        if (self.out and self.out.results_errno() != 0) :
            r = self.out.results_reason()
            _log.warn("Connection to filer failed: " + r + "\n")
            sys.exit(3)

        self.out = self.s.set_style('LOGIN')
        _log.debug("attempting to login to " + self.filer + "\n")
    
        if (self.out and self.out.results_errno() != 0) :
            r = self.out.results_reason()
            _log.warn("Connection to filer failed: " + r + "\n")
            sys.exit(3)

        self.out = self.s.set_admin_user(self.user, self.pw)
        _log.debug("set admin user to" + self.user + "\n")
 def _get_version(self):
     cmd = NaServer.NaElement('system-get-version')
     res = self.server.invoke_elem(cmd)
     if res.results_errno():
         raise ValueError("system-get-version error: %s" %
                          res.results_reason())
     else:
         self.clustered = False
         clustered = res.child_get_string("is-clustered")
         if clustered == "true":
             self.clustered = True
         version_tuple = res.child_get("version-tuple")
         if version_tuple:
             version_tuple = version_tuple.child_get("system-version-tuple")
             self.generation = version_tuple.child_get_string("generation")
             self.major = version_tuple.child_get_string("major")
             self.minor = version_tuple.child_get_string("minor")
         else:
             version = res.child_get_string("version")
             if version:
                 version_tuple = re.search(r'(\d+)\.(\d+)\.(\d+)', version)
                 self.generation = version_tuple.group(1)
                 self.major = version_tuple.group(2)
                 self.minor = version_tuple.group(3)
         return (self.generation, self.major, self.minor)
 def get_info(self, kind):
     cmd = NaServer.NaElement("perf-object-counter-list-info")
     cmd.child_add_string("objectname", kind)
     res = self.server.invoke_elem(cmd)
     counters = {}
     if res.results_errno():
         reason = res.results_reason()
         msg = "perf-object-counter-list-info cannot collect '%s': %s"
         raise ValueError(msg % (kind, reason))
     for counter in res.child_get("counters").children_get():
         name = counter.child_get_string("name")
         desc = counter.child_get_string("desc")
         unit = ''
         if counter.child_get_string("unit"):
             unit = counter.child_get_string("unit")
         properties = ''
         if counter.child_get_string("properties"):
             properties = counter.child_get_string("properties")
         base = ''
         if counter.child_get_string("base-counter"):
             base = counter.child_get_string("base-counter")
         priv = counter.child_get_string("privilege-level")
         labels = []
         if counter.child_get("labels"):
             clabels = counter.child_get("labels")
             if clabels.child_get_string("label-info"):
                 tlabels = clabels.child_get_string("label-info")
                 labels = [l.strip() for l in tlabels.split(',')]
         counters[name] = (unit, properties, base, priv, desc, labels)
     return counters
 def __clusterm_metrics(self, kind, instances, metrics):
     cmd = NaServer.NaElement("perf-object-get-instances")
     inst = NaServer.NaElement("instance-uuids")
     for instance in instances:
         inst.child_add_string("instance-uuid", instance)
     cmd.child_add(inst)
     cmd.child_add_string("objectname", kind)
     counters = NaServer.NaElement("counters")
     for metric in metrics:
         counters.child_add_string("counter", metric)
     cmd.child_add(counters)
     res = self.server.invoke_elem(cmd)
     if res.results_errno():
         reason = res.results_reason()
         msg = "perf-object-get-instances cannot collect '%s': %s"
         raise ValueError(msg % (kind, reason))
     return self.__collect_instances(res)
Example #17
0
def create_qtree_quota():
    
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set transport type " + r + "\n")
        sys.exit (2)

    if(args >  5):
        out = s.invoke("qtree-create", "qtree", qtree, "volume", volume, "mode", mode )

    else :
        out = s.invoke( "qtree-create", "qtree", qtree, "volume", volume)

    if (out.results_status() == "failed"):
        print(out.results_reason())
        print("\n")
        sys.exit (2)

    print ("Created new qtree\n")
Example #18
0
    def __init__(self, cluster_name, cluster_ip, username, password, sdk_ver, server_type="FILER", transport_type="HTTPS", port="443", style="LOGIN"):
	major, minor = string.split(sdk_ver, '.')
	self.CLUSTER_NAME = cluster_name
	self.MAX_VOLUMES  = 2000
	self.s = NaServer(cluster_ip, major, minor)
	self.s.set_server_type(server_type)
	self.s.set_transport_type(transport_type)
	self.s.set_port(port)
	self.s.set_style(style)
	self.s.set_admin_user(username, password)
Example #19
0
def main():

    if(not ((command == "create") or (command == "estimate") or (command == "split") or (command == "status"))):
        print(command + " is not a valid command\n")
        print_usage()

    if ((command == "create") and (parent_vol == None)):
        print(command + " operation requires <parent-volname>\n")
        print("Usage: flexclone.py <filer> <user> <password>" + command + " <clone-volname> <parent-volname>\n")
        sys.exit (2)

    s = NaServer(filer, 1, 3)
    resp = s.set_style('LOGIN')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Failed to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    if(command == "create"):
        create_flexclone(s)

    elif(command == "estimate") :
        estimate_flexclone_split(s)

    elif(command == "split") :
        start_flexclone_split(s)

    elif(command == "status"):
        flexclone_split_status(s)

    else :
        print ("Invalid operation\n")
        print_usage()
 def __init__(self, configname):
     zfscredfilename = os.path.join(scriptpath(), 'netappcredentials.cfg')
     if not os.path.isfile(zfscredfilename):
         raise Exception(
             self._exceptionbase,
             "Configuration file %s not found" % zfscredfilename)
     # Authentication information
     zfscredconfig = SafeConfigParser()
     zfscredconfig.read(zfscredfilename)
     zfsauth = (zfscredconfig.get('netappcredentials', 'user'),
                zfscredconfig.get('netappcredentials', 'password'))
     #
     self._filer = Configuration.get('filer', 'netapp')
     self._srv = NaServer(self._filer, 1, 1)
     self._srv.set_admin_user(
         zfscredconfig.get('netappcredentials', 'user'),
         zfscredconfig.get('netappcredentials', 'password'))
     self._volprefix = Configuration.get('volumeprefix', 'netapp')
     self._volname = "%s%s" % (self._volprefix, configname)
     super(Netapp, self).__init__(configname)
Example #21
0
def get_volume_info():


    args = len(sys.argv) - 1
    
    if(args < 3):
        print_usage()
 
    filer = sys.argv[1]
    user = sys.argv[2]
    pw = sys.argv[3]
   
    if(args == 4):
        volume = sys.argv[4]

    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')
    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')
    
    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    if(args == 3):
        out = s.invoke("volume-list-info")

    else:
        out = s.invoke("volume-list-info", "volume", volume)

    if(out.results_status() == "failed"):
        print (out.results_reason() + "\n")
        sys.exit (2)

    volume_info = out.child_get("volumes")
    result = volume_info.children_get()

    for vol in result:
        vol_name = vol.child_get_string("name")
        print ("Volume name :" + vol_name + "\n")
        size_total = vol.child_get_int("size-total")
        print ("Total size: " + str(size_total) + " bytes \n")
        size_used = vol.child_get_int("size-used")
        print ("Used Size : " + str(size_used) + " bytes\n")
        print ("-------------------------------------------\n")
def main():
    # check for valid number of parameters
    s = NaServer (filer, 1, 3)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set HTTP transport" + r + "\n")
        sys.exit (2)
        
    if(command == "cg-start"):
        cg_start(s)

    elif(command == "cg-commit"):
        cg_commit(s)

    else:
        print ("Invalid operation\n")
        print_usage()
Example #23
0
def main():
    s = NaServer(filer, 1, 3)
    resp = s.set_style('LOGIN')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Failed to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Unable to set HTTP transport " + r + "\n")
        sys.exit(2)

    if ((command == "raw-capacity") or (command == "formatted-capacity")
            or (command == "spare-capacity")):
        calc_raw_fmt_spare_capacity(s)

    elif ((command == "raid-overhead") or (command == "wafl-overhead")):
        calc_raid_wafl_overhead(s)

    elif (command == "allocated-capacity"):
        calc_allocated_capacity(s)

    elif (command == "avail-user-data-capacity"):
        calc_avail_user_data_capacity(s)

    elif (command == "provisioning-capacity"):
        calc_provisioning_capacity(s)

    else:
        print("Invalid operation\n")
Example #24
0
def main():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set HTTP transport" + r + "\n")
        sys.exit(2)

    if (command == "lun"):
        process_LUN(s)

    elif (command == "igroup"):
        process_igroup(s)

    elif (command == "fcp"):
        process_fcp(s)

    elif (command == "iscsi"):
        process_iscsi(s)

    else:
        print("Invalid operation\n")
        print_usage()
    def __sevenm_instances(self, kind, filter=''):
        instances_list = []
        cmd = NaServer.NaElement("perf-object-instance-list-info-iter-start")
        cmd.child_add_string("objectname", kind)
        res = self.server.invoke_elem(cmd)
        if res.results_errno():
            reason = res.results_reason()
            msg = ("perf-object-instance-list-info-iter-start"
                   " cannot collect '%s': %s")
            raise ValueError(msg % (kind, reason))
        next_tag = res.child_get_string("tag")
        counter = self.perf_max_records
        while counter == self.perf_max_records:
            cmd = NaServer.NaElement(
                "perf-object-instance-list-info-iter-next")
            cmd.child_add_string("tag", next_tag)
            cmd.child_add_string("maximum", self.perf_max_records)
            res = self.server.invoke_elem(cmd)
            if res.results_errno():
                reason = res.results_reason()
                msg = ("perf-object-instance-list-info-iter-next"
                       " cannot collect '%s': %s")
                raise ValueError(msg % (kind, reason))
            counter = res.child_get_string("records")
            instances = res.child_get("instances")
            if instances:
                for inst in instances.children_get():
                    name = inst.child_get_string("name")
                    instances_list.append(name)
        cmd = NaServer.NaElement("perf-object-instance-list-info-iter-end")
        cmd.child_add_string("tag", next_tag)
        res = self.server.invoke_elem(cmd)
        if res.results_errno():
            reason = res.results_reason()
            msg = ("perf-object-instance-list-info-iter-end"
                   " cannot collect '%s': %s")
            raise ValueError(msg % (kind, reason))

        # filter
        return instances_list
Example #26
0
def main():

    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set HTTP transport " + r + "\n")
        sys.exit(2)

    if (command == "scheduleList"):
        schedule_list(s)

    elif (command == "relationshipStatus"):
        relationship_status(s)

    else:
        print("Invalid operation \n")
        print_usage()
def main():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set HTTP transport" + r + "\n")
        sys.exit(2)

    if (command == "getStatus"):
        get_status(s)

    elif (command == "getVolStatus"):
        get_vol_status(s)

    elif (command == "off"):
        snapmirror_off(s)

    elif (command == "on"):
        snapmirror_on(s)

    else:
        print("Invalid operation\n")
        print_usage()
def main():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set HTTP transport" + r + "\n")
        sys.exit(2)

    if (command == "get"):
        snmp_get(s)

    elif (command == "status"):
        snmp_status(s)

    elif (command == "addCommunity"):
        add_community(s)

    elif (command == "deleteCommunity"):
        delete_community(s)

    else:
        print("Invalid operation\n")
        print_usage()
def main():
    
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    if(option == "get"):
        get_option_info(s)

    elif(option == "set"):
        set_option_info(s)

    elif(option == "optionsList"):
        options_list_info(s)

    else:
        print("Invalid Option \n")
        print_usage()
Example #30
0
def main():
    s = NaServer(filer, 1, 3)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Unable to set HTTP transport " + r + "\n")
        sys.exit(2)

    resp = s.set_style('LOGIN')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Failed to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)

    if (command == "file-get-snaplock-retention-time"):
        file_get_retention(s)

    elif (command == "file-set-snaplock-retention-time"):
        file_set_retention(s)

    elif (command == "file-snaplock-retention-time-list-info"):
        file_get_retention_list(s)

    elif (command == "file-get-snaplock-retention-time-list-info-max"):
        file_get_retention_list_info_max(s)

    else:
        print("Invalid operation\n")
        print_usage()
    def run(self):
        self.filer_metrics = {}
        metric = self.MetricName
        filer = self.FilerName
        s = NaServer(filerdict[filer]['ipaddr'], 1, 3)
        out = s.set_transport_type('HTTPS')
        if (out and out.results_errno() != 0) :
            r = out.results_reason()
            print ("Connection to filer failed: " + r + "\n")
            sys.exit(2)
            
        out = s.set_style('LOGIN')
        if (out and out.results_errno() != 0) :
            r = out.results_reason()
            print ("Connection to filer failed: " + r + "\n")
            sys.exit(2)
        out = s.set_admin_user(filerdict[filer]['user'], filerdict[filer]['password'])

        #Get the volume performance metrics
        self.volume_perf_metrics(s)
        self.volume_capacity_metrics(s)
        self.quota_metrics(s)
  def __init__(self, hostname, user, passwd):
      self.api = NaServer(hostname, 1, 3)
      response = self.api.set_style('LOGIN')

      if (response and response.results_errno() != 0):
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

      self.api.set_admin_user(user, passwd)
      self.api.set_transport_type('HTTPS')

      self.name = hostname
Example #33
0
    def __init__(self,
                 logger=None,
                 debug_level=None,
                 log_console=False,
                 log_file=False):
        """Initializes settings, logging, and creates connections to vservers.

        Arguments:
            debug_level (string): Level of debugging information to log.
            logger (instance): A previously instantiated HMDCLogger instance.
            log_console (boolean): Enable/disable logging to the console.
            log_file (string): Full path to log file; False if disabled.

        Attributes:
            config_name (string): Class name for referencing.
            hmdclog (instance): Instance of HMDCLogger for logging.
            options (dictionary): Settings imported from conf file.
            vservers (dictionary): Instances of NaServer (NetApp).
        """

        config_name = self.__class__.__name__
        self.vservers = {}

        # Import conf file settings.
        conf = ConfigParser.ConfigParser()
        conf.read(self.CONFIG_FILE)

        self.options = {
            'debug_level': conf.get(config_name, 'debug_level'),
            'cdot_password': conf.get(config_name, 'cdot_password'),
            'cdot_username': conf.get(config_name, 'cdot_username'),
        }

        # Configure HMDC logging instance.
        if logger is None:
            if debug_level is None:
                debug_level = self.options['debug_level']
            self.hmdclog = hmdclogger.HMDCLogger(config_name, debug_level)
            if log_console:
                self.hmdclog.log_to_console()
            if log_file:
                self.hmdclog.log_to_file(log_file)
        else:
            self.hmdclog = logger

        # Instantiate and authenticate NetApp connections.
        for vserver in self.VOLUMES.iterkeys():
            # API major release 1, minor 20.
            self.vservers[vserver] = NaServer(vserver, 1, 20)
            # Authenticate to the NetApp.
            self._netapp_auth(vserver)
Example #34
0
def main():

        module = AnsibleModule(
                argument_spec=dict(
                        storage=dict(default=None, required=True),
                        user=dict(default='admin', required=False),
                        password=dict(default='P@ssw0rd', required=False),
                        vserver_name=dict(default=None, required=True),
			root_volume=dict(default='svm_root', required=False),
			root_volume_aggregate=dict(default=None, required=True),
			root_volume_security_style=dict(default='unix', required=False),
                ),
        )

        storage        = module.params['storage']
        user           = module.params['user']
        password       = module.params['password']
        vserver_name   = module.params['vserver_name']
	root_volume    = module.params['root_volume']
	root_volume_aggregate      = module.params['root_volume_aggregate']
	root_volume_security_style = module.params['root_volume_security_style']

	s = NaServer(storage, 1, 20)
	s.set_admin_user(user, password)

	api = NaElement('vserver-create')
	api.child_add_string('language','C');
	ns_switch = NaElement('name-server-switch');
	api.child_add(ns_switch)

	ns_switch.child_add_string('nsswitch','file')
	api.child_add_string('root-volume', root_volume)
	api.child_add_string('root-volume-aggregate', root_volume_aggregate)
	api.child_add_string('root-volume-security-style', root_volume_security_style)
	api.child_add_string('vserver-name', vserver_name);

	output = s.invoke_elem(api)
	module.exit_json(changed=True)
 def get_objects(self):
     cmd = NaServer.NaElement('perf-object-list-info')
     res = self.server.invoke_elem(cmd)
     objects = {}
     if res.results_errno():
         raise ValueError("perf-object-list-info error: %s" %
                          res.results_reason())
     else:
         for inst in res.child_get("objects").children_get():
             inst_name = inst.child_get_string("name")
             inst_desc = inst.child_get_string("description")
             inst_priv = inst.child_get_string("privilege-level")
             objects[inst_name] = (inst_desc, inst_priv)
     return objects
    def run(self):
        self.filer_metrics = {}
        metric = self.MetricName
        filer = self.FilerName
        s = NaServer(filerdict[filer]['ipaddr'], 1, 3)
        out = s.set_transport_type('HTTPS')
        if (out and out.results_errno() != 0):
            r = out.results_reason()
            print("Connection to filer failed: " + r + "\n")
            sys.exit(2)

        out = s.set_style('LOGIN')
        if (out and out.results_errno() != 0):
            r = out.results_reason()
            print("Connection to filer failed: " + r + "\n")
            sys.exit(2)
        out = s.set_admin_user(filerdict[filer]['user'],
                               filerdict[filer]['password'])

        #Get the volume performance metrics
        self.volume_perf_metrics(s)
        self.volume_capacity_metrics(s)
        self.quota_metrics(s)
Example #37
0
    def _netapp_login(self):
        """ Login to our netapp filer
        """

        sys.path.append(self.config['netappsdkpath'])
        try:
            import NaServer
        except ImportError:
            self.log.error("Unable to load netapp SDK from %s" %
                           self.config['netappsdkpath'])

        self.server = NaServer.NaServer(self.ip, 1, 3)
        self.server.set_transport_type('HTTPS')
        self.server.set_style('LOGIN')
        self.server.set_admin_user(self.netapp_user, self.netapp_password)
Example #38
0
    def prepare(self, arglist):
        self.host = self.getHost("RESOURCE_HOST_0")
        self.iscsiHost = self.getHost("RESOURCE_HOST_1")
        self.scsiid = string.split(
            self.host.lookup("OPTION_CARBON_DISKS", None), "scsi-")[1]

        ip = self.host.lookup(["UCSISCSI", "TARGET_ADDRESS"], None)
        username = self.host.lookup(["UCSISCSI", "TARGET_USERNAME"], None)
        password = self.host.lookup(["UCSISCSI", "TARGET_PASSWORD"], None)
        self._server = NaServer.NaServer(ip, 1, 0)
        self._server.set_admin_user(username, password)

        xenrt.TEC().logverbose("Number of active paths to boot LUN = %d" %
                               self.countActivePaths())
        if self.countActivePaths() != 2:
            raise xenrt.XRTError("Host does not have 2 paths to boot LUN")
Example #39
0
def connect_filer(host,user,passwd):
   plog.print_debug("Host: %s, User: %s" %(host,user))
   s = NaServer(host, 1, 1)
   s.set_server_type("Filer")
   s.set_admin_user(user,passwd)
   response = s.set_transport_type('HTTP')

   if(response and response.results_errno() != 0 ):
      r = response.results_reason()
      plog.print_error("Unable to set HTTP transport " + r + "\n")
      sys.exit (1)

   response = s.set_style('LOGIN')
   if(response and response.results_errno() != 0 ):
      r = response.results_reason()
      plog.print_error("Unable to set authentication style " + r + "\n")
      sys.exit (1)

   return s
 def _connect(self,
              device,
              user,
              password,
              apiversion,
              timeout=None,
              method='HTTP'):
     try:
         self.apimajor = int(apiversion.split('.')[0])
         self.apiminor = int(apiversion.split('.')[1])
     except:
         raise ValueError("incorrect API version: '%s'" % apiversion)
     self.server = NaServer.NaServer(device, self.apimajor, self.apiminor)
     self.server.set_transport_type(method)
     self.server.set_style('LOGIN')
     self.server.set_admin_user(user, password)
     if timeout is not None:
         self.server.set_timeout(timeout)
     self.device = device
Example #41
0
    def __init__(self, cluster_name, cluster_ip, username, password, sdk_ver, server_type="FILER", transport_type="HTTPS", port="443", style="LOGIN"):
        major, minor = string.split(sdk_ver, '.')
        self.CLUSTER_NAME = cluster_name
        self.MAX_VOLUMES  = 20000
        self.s = NaServer(cluster_ip, major, minor)
        self.s.set_server_type(server_type)
        self.s.set_transport_type(transport_type)
        self.s.set_port(port)
        self.s.set_style(style)
        self.s.set_admin_user(username, password)
	self.sd = statsd.StatsClient('localhost',8125)
	self.fp = open("/var/tmp/tellme.log", "a")
	try:
	    self.debug = open("/var/tmp/debugenabled")
	    self.debug.close()
	    self.debug = True
	except IOError:
	    self.debug = False
	    pass
	self.targ_vol_counters = "avg_latency,cifs_other_latency,cifs_other_ops,cifs_read_data,cifs_read_latency,cifs_read_ops,cifs_write_data,cifs_write_latency,cifs_write_ops,fcp_other_latency,fcp_other_ops,fcp_read_data,fcp_read_latency,fcp_read_ops,fcp_write_data,fcp_write_latency,fcp_write_ops,flexcache_other_ops,flexcache_read_data,flexcache_read_ops,flexcache_receive_data,flexcache_send_data,flexcache_write_data,flexcache_write_ops,iscsi_other_latency,iscsi_other_ops,iscsi_read_data,iscsi_read_latency,iscsi_read_ops,iscsi_write_data,iscsi_write_latency,iscsi_write_ops,nfs_other_latency,nfs_other_ops,nfs_read_data,nfs_read_latency,nfs_read_ops,nfs_write_data,nfs_write_latency,nfs_write_ops,other_latency,other_ops,read_blocks,read_data,read_latency,read_ops,san_other_latency,san_other_ops,san_read_data,san_read_latency,san_read_ops,san_write_data,san_write_latency,san_write_ops,total_ops,write_blocks,write_data,write_latency,write_ops"
Example #42
0
def get_quota_info():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set transport type " + r + "\n")
        sys.exit(2)

    out = s.invoke("quota-list-entries")

    if (out.results_status() == "failed"):
        print(out.results_reason() + "\n")
        sys.exit(2)

    quota_info = out.child_get("quota-entries")
    result = quota_info.children_get()
    print("-----------------------------------------------------\n")

    for quota in result:
        if (quota.child_get_string("quota-target")):
            quota_target = quota.child_get_string("quota-target")
            print("Quota Target: " + quota_target + " \n")

        if (quota.child_get_string("volume")):
            volume = quota.child_get_string("volume")
            print("Volume: " + volume + "\n")

        if (quota.child_get_string("quota-type")):
            quota_type = quota.child_get_string("quota-type")
            print("Quota Type: " + quota_type + "\n")

        print("-----------------------------------------------------\n")
def get_volume_info():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0):
        r = response.results_reason()
        print("Unable to set HTTP transport" + r + "\n")
        sys.exit(2)

    for volume in volumes:
        out = s.invoke("volume-list-info", "volume", volume)

        if (out.results_status() == "failed"):
            print(out.results_reason() + "\n")
            sys.exit(2)

        volume_info = out.child_get("volumes")
        result = volume_info.children_get()

        global total_volume_size
        global used_volume_size
        global percent_space_avail

        for vol in result:
            total_volume_size = vol.child_get_int("size-total")
            used_volume_size = vol.child_get_int("size-used")
            space_avail = (total_volume_size - used_volume_size)
            percent_space_avail = (float(space_avail) /
                                   float(total_volume_size)) * 100

            if (percent_space_avail < threshold):
                send_mail(volume)
def main():

    if (not ((command == "create") or (command == "estimate") or
             (command == "split") or (command == "status"))):
        print(command + " is not a valid command\n")
        print_usage()

    if ((command == "create") and (parent_vol == None)):
        print(command + " operation requires <parent-volname>\n")
        print("Usage: flexclone.py <filer> <user> <password>" + command +
              " <clone-volname> <parent-volname>\n")
        sys.exit(2)

    s = NaServer(filer, 1, 3)
    resp = s.set_style('LOGIN')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Failed to set authentication style " + r + "\n")
        sys.exit(2)

    s.set_admin_user(user, pw)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0):
        r = resp.results_reason()
        print("Unable to set HTTP transport " + r + "\n")
        sys.exit(2)

    if (command == "create"):
        create_flexclone(s)

    elif (command == "estimate"):
        estimate_flexclone_split(s)

    elif (command == "split"):
        start_flexclone_split(s)

    elif (command == "status"):
        flexclone_split_status(s)

    else:
        print("Invalid operation\n")
        print_usage()
Example #45
0
def get_quota_info():
    s = NaServer(filer, 1, 3)
    response = s.set_style('LOGIN')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if(response and response.results_errno() != 0 ):
        r = response.results_reason()
        print ("Unable to set transport type " + r + "\n")
        sys.exit (2)

    out = s.invoke( "quota-list-entries" )

    if (out.results_status() == "failed"):
        print(out.results_reason() + "\n")
        sys.exit (2)

    quota_info = out.child_get("quota-entries")
    result = quota_info.children_get()
    print("-----------------------------------------------------\n")

    for quota in result :
        if(quota.child_get_string("quota-target")):
            quota_target = quota.child_get_string("quota-target")
            print  ("Quota Target: " + quota_target + " \n")
            
        if(quota.child_get_string("volume")):
            volume = quota.child_get_string("volume")
            print  ("Volume: " + volume + "\n")

        if(quota.child_get_string("quota-type")):
            quota_type = quota.child_get_string("quota-type")
            print  ("Quota Type: " + quota_type + "\n")

        print ("-----------------------------------------------------\n")
Example #46
0
def get_volume_info():
    s = NaServer (filer, 1, 3)
    response = s.set_style('LOGIN')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    response = s.set_transport_type('HTTP')

    if (response and response.results_errno() != 0) :
        r = response.results_reason()
        print ("Unable to set HTTP transport" + r + "\n")
        sys.exit (2)

    for volume in volumes:
        out = s.invoke( "volume-list-info","volume", volume )
        
        if (out.results_status() == "failed"):
            print(out.results_reason() + "\n")
            sys.exit (2)

        volume_info = out.child_get("volumes")
        result = volume_info.children_get()

        global total_volume_size
        global used_volume_size
        global percent_space_avail

        for vol in result:
            total_volume_size = vol.child_get_int("size-total")
            used_volume_size = vol.child_get_int("size-used")
            space_avail = (total_volume_size - used_volume_size)
            percent_space_avail = (float(space_avail)/float(total_volume_size))*100

            if (percent_space_avail < threshold):
                send_mail(volume)
Example #47
0
def main():
	
	module = AnsibleModule(
   		argument_spec=dict(
        		storage=dict(default=None, required=True),
			user=dict(default='admin', required=False),
			password=dict(default='P@ssw0rd', required=False),
			vserver_name=dict(default=None, required=True),
			volume_name=dict(default=None, required=True),
			security_style=dict(default='unix', required=False),
			guarantee=dict(default='volume', required=False),
			aggr_name=dict(default=None, required=True),
		),
	)
	
	storage        = module.params['storage']
	user           = module.params['user']
	password       = module.params['password']
	vserver_name   = module.params['vserver_name']
	volume_name    = module.params['volume_name']
	security_style = module.params['security_style']
	guarantee      = module.params['guarantee']
	aggr_name      = module.params['aggr_name']

	s = NaServer(storage, 1, 20)
	s.set_admin_user(user, password)
	s.set_vserver(vserver_name)

	api = NaElement('volume-create')
	api.child_add_string('volume', volume_name)
	api.child_add_string('space-reserve', guarantee)
	api.child_add_string('containing-aggr-name', aggr_name)

	output = s.invoke_elem(api)
	#print(output.results_status())
	#print(output.sprintf())

	module.exit_json(changed=True)
Example #48
0
# Alvin Chan
# [email protected]
##

import sys, getpass

sys.path.append("/home/alvinch/netapp-manageability-sdk-5.2/lib/python/NetApp")

from NaServer import *

help = "script filer_username filer volume"
args = len(sys.argv)
user_name = sys.argv[1]
password = getpass.getpass()
filer_name = sys.argv[2]
filer = NaServer(filer_name,1,6)
filer.set_admin_user(user_name, password)
tag = "tag"
while True:
        naelement=NaElement('vserver-get-iter')
        out=filer.invoke_elem(naelement)
        if tag:
           naelement.child_add_string('tag', tag)

        #out=filer.invoke_elem(naelement)

        tag=out.child_get_string('next-tag')

        vserver_list=out.child_get('attributes-list').children_get()

        for v in vserver_list:
Example #49
0
#!/usr/bin/python
import sys
sys.path.append("../lib/NetappSDK/")
from NaServer import *

filerIP = raw_input("filer IP: ")
myPass = raw_input("filer password: "******"dir path: ")

s = NaServer(filerIP, 1 , 15)
s.set_server_type("FILER")
s.set_transport_type("HTTPS")
s.set_port(443)
s.set_style("LOGIN")
s.set_admin_user("root", myPass)

# Obtain the Data ONTAP version.
api = NaElement("system-get-version")

xo = s.invoke_elem(api)
if (xo.results_status() == "failed") :
      print ("Error:\n")
      print (xo.sprintf())
      sys.exit (1)

print ("Received:\n")
print (xo.sprintf())
# Delete a directory.
print "Deleting....\n"
api = NaElement('file-delete-directory')
# Path of the directory to delete. The value is expected to begin with /vol/<volumename>. The directory must be empty in order for this API to succeed.
Example #50
0
# Alvin Chan
# [email protected]
##

import sys, getpass

sys.path.append("/home/alvinch/netapp-manageability-sdk-5.2/lib/python/NetApp")

from NaServer import *

help = "script filer_username filer volume"
args = len(sys.argv)
user_name = sys.argv[1]
password = getpass.getpass()
filer_name = sys.argv[2]
filer = NaServer(filer_name,1,6)
filer.set_admin_user(user_name, password)

def readable_size(size):
        for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']:
                if size < 1000.0 and size > -1000.0:
                        return "%3.2f %s" % (size, unit)
                size /= 1024.0
        return "%3.2f %s" % (size, 'PB')

#list_in = NaElement('volume-footprint-get-iter')
#cmd = filer.invoke_elem(list_in)
tag = "tag"

while True:
        list_in = NaElement('volume-footprint-get-iter')
class Toaster(nagiosplugin.Resource):
    """
    Determines the system Network interface stats
    The `probe` method returns the following for all interfaces
    'recv_packets'
    'recv_errors'
    'send_packets'
    'send_errors'
    'collisions'
    'recv_data'
    'send_data'
    'recv_mcasts'
    'send_mcasts'
    'recv_drop_packets
    """

    def __init__(self, filer, user, pw, interface=False):
        self.filer = filer
        self.user = user
        self.pw = pw
        self.specific_interface = interface
        self.perf_obj = "ifnet"
        self.counter_values = ["recv_packets",
                  "recv_errors",
                  "send_packets",
                  "send_errors",
                  "collisions",
                  "recv_data", 
                  "send_data",
                  "recv_mcasts", 
                  "send_mcasts",
                  "recv_drop_packets"
                 ]


    def Connect(self):
        """
        connect to the netapp via the API
        """

        #self.s = NaServer(self.filer, 1, 3)
        self.s = NaServer(self.filer, 1, 9)
        self.out = self.s.set_transport_type('HTTPS')
        _log.debug("attempting to connect to filer via HTTPS")

        if (self.out and self.out.results_errno() != 0) :
            r = self.out.results_reason()
            _log.warn("Connection to filer failed: " + r + "\n")
            sys.exit(3)

        self.out = self.s.set_style('LOGIN')
        _log.debug("attempting to login to " + self.filer + "\n")
    
        if (self.out and self.out.results_errno() != 0) :
            r = self.out.results_reason()
            _log.warn("Connection to filer failed: " + r + "\n")
            sys.exit(3)

        self.out = self.s.set_admin_user(self.user, self.pw)
        _log.debug("set admin user to" + self.user + "\n")


    def cpus(self):
        _log.info('counting cpus with "nproc"')
        cpus = int(subprocess.check_output(['nproc']))
        _log.debug('found %i cpus in total', cpus)
        return cpus



    def probe(self):
        """
        use the netapp API and connection object
        to extract the specified counters for the object
        and return in a dictionary of dictionaries
        in the self.data var e.g.
        print self.data[self.specific_interface]["send_data"]
        This is implicity used by the nagiosplugin class to generate the metrics
        if an interface is specified, it returns that, otherwise returns 
        all interfaces, skipping the 'filername' aggregate metric, which seems
        to be a 'since boot' set of counters

        """


        #turn the filer FQDN into something more Graphite Friendly
        self.filername = self.filer.split(".")[0]
        self.Connect()

        _log.info('attempting to grab all interface data')

        self.data = \
                get_counter_values(self.filername, 
                                   self.s, 
                                   self.perf_obj, 
                                   self.counter_values,
                                  )
        #import pprint
        #pp = pprint.PrettyPrinter(indent=4)
        #pp.pprint(self.data)

        if self.specific_interface:
            #print self.data[self.specific_interface]["send_data"]
            metricname = \
                    self.filer + "_" + self.specific_interface + "_" + "send_errors"
            testm = nagiosplugin.Metric( metricname,
                                self.data[self.specific_interface]["send_errors"],
                                'c', 
                                min=0, 
                                context='errors', # set this to errors
                               )
            #import pprint
            #pp = pprint.PrettyPrinter(indent=4)
            #pp.pprint(testm)
            yield testm

        else:
            for metric in ["send_errors", "recv_errors", "collisions",
                           "recv_drop_packets" ]:
                _log.debug('reporting on %s', metric)
                # a number of interfaces are provided by the API as totals since
                # boot, which isn't useful for point in time alerting, so ignore
                # them
                for instance in self.data:
                    _log.debug('reporting on if %s', instance)

                    #skip the api provided filenamed interface thats just totals
                    if self.filername in instance:

                        _log.debug('skipping totaled interface: %s',\
                                   str(instance))
                        continue 
                   #skip the interface groups, just look at individual if's
                   # pre OnTAP 8.1
                    if "ifgrp" in instance:
                        _log.debug('skipping ifgrp interface: %s',\
                                   str(instance))
                        continue
                   #skip the virtual interface (vif) groups, just look at individual if's
                   # pre OnTAP 8.1
                    if "vif" in instance:
                        _log.debug('skipping vif interface: %s',\
                                   str(instance))
                        continue
                    
                    #print "interface: " + str(instance) + " errors: " + \
                    #        str(self.data[instance][metric])
                    metricname = \
                        self.filer + "_" + instance + "_" + metric
                    yield nagiosplugin.Metric( \
                                            metricname,
                                            self.data[instance][metric],
                                            min=0,
                                            context='errors',
                                            )
Example #52
0
def main() :
    s = NaServer(filer, 1, 3)
    resp = s.set_style('LOGIN')
  
    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Failed to set authentication style " + r + "\n")
        sys.exit (2)

    s.set_admin_user(user, pw)
    resp = s.set_transport_type('HTTP')

    if (resp and resp.results_errno() != 0) :
        r = resp.results_reason()
        print ("Unable to set HTTP transport " + r + "\n")
        sys.exit (2)

    if(command == "create") :
        vfiler_create(s)
	
    elif(command == "list") :
        vfiler_list(s)

    if(args < 5 and (command == "start" or command == "stop" or  command == "status" or  command == "destroy")):
        print ("This operation requires <vfiler-name> \n\n")
        print_usage()

    if(command == "start") :
        out = s.invoke("vfiler-start", "vfiler", vfiler)

        if(out.results_status() == "failed") :
            print(out.results_reason() + "\n")
            sys.exit(2)
	
    elif(command == "status") :
        out = s.invoke("vfiler-get-status", "vfiler", vfiler)

        if(out.results_status() == "failed") :
            print(out.results_reason() + "\n")
            sys.exit(2)
		
        status = out.child_get_string("status")
        print("status:" + status + "\n")

	
    elif(command == "stop") :
        out = s.invoke("vfiler-stop", "vfiler", vfiler)

        if(out.results_status() == "failed") :
            print(out.results_reason() + "\n")
            sys.exit(2)

    elif(command == "destroy"):
        out = s.invoke("vfiler-destroy","vfiler",vfiler)

        if(out.results_status() == "failed") :
            print(out.results_reason() + "\n")
            sys.exit(2)

    else :
        print ("Invalid operation\n")
        print_usage()
Example #53
0
  print ("<password> -- Password\n")
  sys.exit (1)

args = len(sys.argv) - 1

if(args < 3):
  print_usage()

filer = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]

aggr_name = "cinder_aggr"
vol_name = "cinder"

s = NaServer(filer, 1, 1)
s.set_server_type("Filer")
s.set_admin_user(user, password)
s.set_transport_type("HTTP")

# Get the sysid of "this" controller
system = s.invoke("system-get-info")
sysinfo = system.child_get("system-info")
sysid = sysinfo.child_get_string("system-id")

# get the disks that this controller owns
output = s.invoke("disk-sanown-list-info")

if(output.results_errno() != 0):
   r = output.results_reason()
   print("Failed: \n" + str(r))
filer_list = ( "filer101",
	       "filer102",
	       "filer103",
	       "filer104",
	       "filer105",
	       "filer106",
	       "filer107",
	       "filer108",
	       "filer109",
	       "filer110",
	       "filer111")

for filer_name in filer_list:
	print "============ %s ============ " % filer_name
	filer = NaServer(filer_name,1,6)
	filer.set_admin_user('root', 'password')
	cmd = NaElement("snapmirror-get-status")
	ret = filer.invoke_elem(cmd)

	if(ret.results_status() == "failed"):
		print "%s failed." % filer_name
		print(ret.results_reason() + "\n")
		sys.exit(2)
	
	status = ret.child_get("snapmirror-status")

	if(not(status == None)):
		result = status.children_get()
	else:
		print "status_children_get was empty\n"
Example #55
0
    print("           -r <filer> <user> <pw> <vol> <oldsnapshotname> <newname> \n")
    print("           -d <filer> <user> <pw> <vol> <snapshotname>\n")
    sys.exit(1)


args = len(sys.argv) - 1

if(args < 5):
    print_usage()
    
opt = sys.argv[1]
filer = sys.argv[2]
user = sys.argv[3]
pw = sys.argv[4]
vol = sys.argv[5]
s = NaServer(filer, 1, 1)
s.set_admin_user(user, pw)

#
# snapshot-get-schedule
#
if (opt == "-g") :
    output = s.invoke("snapshot-get-schedule", "volume", vol)

    if (output.results_errno() != 0) :
        r = output.results_reason()
        print ("snapshot-get-schedule failed:" + r + "\n")

    minutes = output.child_get_int("minutes")
    hours =   output.child_get_int("hours")
    days =    output.child_get_int("days")
Example #56
0
    def collect(self, device, ip, user, password):
        """
        This function collects the metrics for one filer.
        """
        sys.path.append(self.config['netappsdkpath'])
        try:
            import NaServer
        except ImportError:
            self.log.error("Unable to load NetApp SDK from %s" %
                           (self.config['netappsdkpath']))
            return

        # Set up the parameters
        server = NaServer.NaServer(ip, 1, 3)
        server.set_transport_type('HTTPS')
        server.set_style('LOGIN')
        server.set_admin_user(user, password)

        # We're only able to query a single object at a time,
        # so we'll loop over the objects.
        for na_object in self.METRICS.keys():

            # For easy reference later, generate a new dict for this object
            LOCALMETRICS = {}
            for metric in self.METRICS[na_object]:
                metricname, prettyname, multiplier = metric
                LOCALMETRICS[metricname] = {}
                LOCALMETRICS[metricname]["prettyname"] = prettyname
                LOCALMETRICS[metricname]["multiplier"] = multiplier

            # Keep track of how long has passed since we checked last
            CollectTime = time.time()
            time_delta = None
            if na_object in self.LastCollectTime.keys():
                time_delta = CollectTime - self.LastCollectTime[na_object]
            self.LastCollectTime[na_object] = CollectTime

            self.log.debug("Collecting metric of object %s" % na_object)
            query = NaServer.NaElement("perf-object-get-instances-iter-start")
            query.child_add_string("objectname", na_object)
            counters = NaServer.NaElement("counters")
            for metric in LOCALMETRICS.keys():
                counters.child_add_string("counter", metric)
            query.child_add(counters)

            res = server.invoke_elem(query)
            if (res.results_status() == "failed"):
                self.log.error("Connection to filer %s failed; %s" %
                               (device, res.results_reason()))
                return

            iter_tag = res.child_get_string("tag")
            num_records = 1
            max_records = 100

            # For some metrics there are dependencies between metrics for
            # a single object, so we'll need to collect all, so we can do
            # calculations later.
            raw = {}

            while (num_records != 0):
                query = NaServer.NaElement(
                    "perf-object-get-instances-iter-next")
                query.child_add_string("tag", iter_tag)
                query.child_add_string("maximum", max_records)
                res = server.invoke_elem(query)

                if (res.results_status() == "failed"):
                    print "Connection to filer %s failed; %s" % (
                        device, res.results_reason())
                    return

                num_records = res.child_get_int("records")

                if (num_records > 0):
                    instances_list = res.child_get("instances")
                    instances = instances_list.children_get()

                    for instance in instances:
                        raw_name = unicodedata.normalize(
                            'NFKD', instance.child_get_string("name")).encode(
                                'ascii', 'ignore')
                        # Shorten the name for disks as they are very long and
                        # padded with zeroes, eg:
                        # 5000C500:3A236B0B:00000000:00000000:00000000:...
                        if na_object is "disk":
                            non_zero_blocks = [
                                block for block in raw_name.split(":")
                                if block != "00000000"
                            ]
                            raw_name = "".join(non_zero_blocks)
                        instance_name = re.sub(r'\W', '_', raw_name)
                        counters_list = instance.child_get("counters")
                        counters = counters_list.children_get()

                        for counter in counters:
                            metricname = unicodedata.normalize(
                                'NFKD',
                                counter.child_get_string("name")).encode(
                                    'ascii', 'ignore')
                            metricvalue = counter.child_get_string("value")
                            # We'll need a long complete pathname to not
                            # confuse self.derivative
                            pathname = ".".join([
                                self.config["path_prefix"], device, na_object,
                                instance_name, metricname
                            ])
                            raw[pathname] = int(metricvalue)

            # Do the math
            self.log.debug("Processing %i metrics for object %s" %
                           (len(raw), na_object))

            # Since the derivative function both returns the derivative
            # and saves a new point, we'll need to store all derivatives
            # for local reference.
            derivative = {}
            for key in raw.keys():
                derivative[key] = self.derivative(key, raw[key])

            for key in raw.keys():
                metricname = key.split(".")[-1]
                prettyname = LOCALMETRICS[metricname]["prettyname"]
                multiplier = LOCALMETRICS[metricname]["multiplier"]

                if metricname in self.DROPMETRICS:
                    continue
                elif metricname in self.DIVIDERS.keys():
                    self._gen_delta_depend(key, derivative, multiplier,
                                           prettyname, device)
                else:
                    self._gen_delta_per_sec(key, derivative[key], time_delta,
                                            multiplier, prettyname, device)
Example #57
0
import sys

sys.path.append("../lib/NetappSDK/")
from NaServer import *
import getpass

# default stuff
user = "******"

# Interactive stuff
filer = raw_input("Filername: ")
# password prompt (echo disabled)
pw = getpass.getpass(prompt="Filer password: "******"FILER")
s.set_transport_type("HTTPS")
s.set_port(443)
s.set_style("LOGIN")
s.set_admin_user(user, pw)

# Obtain the Data ONTAP version.
api_sys_ver = NaElement("system-get-version")

out = s.invoke_elem(api_sys_ver)
if out.results_status() == "failed":
    print ("Error:\n")
    print (out.sprintf())
    sys.exit(1)
print ("\nResults:\n")