devops之Python编程-类的基础架构
阅读原文时间:2023年08月22日阅读:1

Python中,可以通过关键字class来定义一个类。类是一种自定义数据类型,它可以包含属性(变量)和方法(函数)。下面是一个示例:

class MyClass:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hello, " + self.name + "!")

在上面的示例中,我们定义了一个名为MyClass的类。该类有一个构造方法__init__,它会在创建类的实例时被调用。构造方法接受一个参数name,并将其保存在实例变量self.name中。

另外,该类还有一个方法say_hello,用于打印出问候消息。在方法定义中,我们使用self来引用当前实例对象。

要使用这个类,可以创建一个类的实例,并调用其方法:

obj = MyClass("Alice")
obj.say_hello()  # 输出:Hello, Alice!

通过类的实例,我们可以访问实例变量和调用方法。这是面向对象编程的基本概念。

(注:以上内容摘录自互联网人工智能大数据,因为其理论定义更官方哈哈!以下内容则为本人原创,欢迎大家指教!)

实战示例:

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Filename: get_gluster_data.py
# CreateDate: 20230417
# Description: 获取glusterfs分布式存储集群性能数据
# ------------------------------------------------------------
# Version 1.2
# ------------------------------------------------------------
"""
用法:
python get_gluster_data.py
"""

import time
import os
import re
import commands
import getopt
import logging
import logging.handlers
import sys
reload(sys)
sys.setdefaultencoding('utf8')

LOG_FILE = "/tmp/get_gluster_data.log"
handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024*1024, backupCount = 5)
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
logger = logging.getLogger('get_gluster_data')
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

#file_path = "/var/lib/sdsom/var/log/diamond/ops.data"
class storageCluster:    #定义一个存储集群类

  def __init__(self, data_file):    #定义一个构造方法,声明类属性:集群的性能数据文件
    self.data_file = data_file

  def get_performance_data(self):    #获取性能数据的方法
    gather_cmd = "/var/lib/sdsom/venv/bin/whisper-fetch.py --from=$(date +%s -d \"-5 min\") /var/lib/sdsom/var/lib/graphite/whisper/gluster/cluster/"
    cmd = gather_cmd + self.data_file + ".wsp | grep -v None | tail -1 | awk '{print $2}'"
    value = commands.getoutput(cmd)    ##执行shell
    key = self.data_file
    print key + ":" + value
    if re.search("ops", key):    #不同的性能数据进行单位换算
      zabbix_value = float('%.2f' % float(value))
      print zabbix_value
      return zabbix_value
    elif re.search("mbps", key):
      value = float(value)/1024/1024
      zabbix_value = float('%.2f' % value)
      print zabbix_value
      return zabbix_value
    elif re.search("latency", key):
      value = float(value)/1000
      zabbix_value = float('%.2f' % value)
      print zabbix_value
      return zabbix_value

  def send_zabbix(self, key, value):    #数据发送到zabbix服务端的方法

    cmd = "/opt/aspire/product/zabbix/bin/zabbix_sender -c /opt/aspire/product/zabbix/conf/zabbix_agentd.conf -k %s -o %s "%(key,value)

    logger.debug(cmd)    #记录日志
    status,value = commands.getstatusoutput(cmd)   #执行shell

    print ("Program Execution_code: ") + str(status) + ",",("result: ") + str(value)
    logger.debug("%s,%s"%(str(status),value))
    if status==0:
      print "%s,send to zabbix successfully!"%(cmd)
      print (" ")
      print ("------------------------------------------------------------")
      logger.debug("%s,True"%(cmd))
      return True
    else:
      print "%s,send to zabbix failed!"%(cmd)
      print (" ")
      print ("------------------------------------------------------------")
      logger.debug("%s,False"%(cmd))
      return False

  def get_performance_log(self):    #记录本地性能数据日志的方法
    date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())    #格式化时间
    logdir = "/var/log/ops/"
    #判断/var/log/ops/目录是否存在,如果不存在则创建
    if os.path.exists(logdir) is False:
    os.mkdir(logdir)
    performance_log = logdir + self.data_file + ".log"
    with open(performance_log, 'a+') as f:
    value = self.get_performance_data()
    log = date + '\t' + str(value) + '\n'
    print(log)
    f.write(log)
    f.close()

if __name__ == '__main__':

  startTime = time.time()    #脚本执行开始时间

  data_list = [ops, read_ops, write_ops, write_mbps, read_mbps, write_latency, read_latency]     #创建性能数据文件列表

  for i in data_list:

    storcluster = storageCluster(i).send_zabbix(key=self.data_file, value=self.get_performance_data())    #实例化类并获取性能数据并发送到zabbix服务端

    storcluster = storageCluster(i).get_performance_log()

  #storcluster = storageCluster("ops").get_performance_data()    #获取性能数据

  #storcluster = storageCluster("read_ops").get_performance_log()    #记录本地性能数据日志

  endTime = time.time()    #脚本执行结束时间

  runtime = startTime - endTime

  print(runtime)

  print("performance_data send completed !")

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器