设为首页 收藏本站
查看: 1071|回复: 0

[经验分享] 运维自动化之Cisco Dell 采用Python 方式实现自定义Raid 级别

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-3-11 08:40:57 | 显示全部楼层 |阅读模式
#!/usr/bin/env python
#-*-coding:UTF-8-*-
"""
@Item   :  V1.0
@Author :  ShengWangQiang
@Group  :  System ITEM
@Date   :  2015-01-28
@E-mail :  swq.499809608@hotmail.com
@Funtion:

"RAID Level : Primary-1, Secondary-0, RAID Level Qualifier-0") echo "Raid Level :Raid 1";;
"RAID Level : Primary-0, Secondary-0, RAID Level Qualifier-0") echo "Raid Level :Raid 0";;
"RAID Level : Primary-5, Secondary-0, RAID Level Qualifier-3") echo "Raid Level :Raid 5";;
"RAID Level : Primary-1, Secondary-3, RAID Level Qualifier-0") echo "Raid Level :Raid 10";;

"""

import os,sys,time,socket,commands,traceback,re,fcntl,json
import struct



class DellRaid(object):
    def __init__(self):
        version = 1.0

    # Log file and save log info
    def log(self,info):
        if not os.path.exists('/var/log/autostack/'):
            os.makedirs('/var/log/autostack/')
        files = open('/var/log/autostack/autostack.log','a')
        try:
            files.write('[%s]: %s \n' %(time.ctime(),info))
        except IOError:
            files.close()
        files.close()


    # Call system commands
    def execute(self,*cmd):
        """
        execute the cmd, and return the outpurt of cmd
        simple way to get cmd output.
        """
        cmd = list(cmd)
        cmd = map(str, cmd)
        cmd_line = ' '.join(cmd)

        code, output = commands.getstatusoutput(cmd_line)
         
        if code == 0:
            self.log(output)
            self.log(cmd_line)
            return output
        else:
            self.log(traceback.format_exc())
        self.log(cmd_line)

    # Megacli create Raid 0
    def raid_0(self,raid_type,enclosure,slot):
        try:
            raid_type = raid_type.split('_')[-1]
            sinfo = ','.join(['%s:' %enclosure + str(i) for i in slot])
            self.execute( """/usr/bin/megacli -CfgLdAdd -r%s [%s] WB Direct -a0"""  \
                        %(raid_type,sinfo))
            self.log("Raid Group %s create is oK" %raid_type)

        except:
            self.log('raid_0 Error %s ' %traceback.format_exc())

    # Megacli create Raid 1  
    def raid_1(self,raid_type,enclosure,slot):
        try:
            raid_type = raid_type.split('_')[-1]
            sinfo = ','.join(['%s:' %enclosure + str(i) for i in slot])
            self.execute( """/usr/bin/megacli -CfgLdAdd -r%s [%s] WB Direct -a0"""  \
                        %(raid_type,sinfo))
            self.log("Raid Group %s create is oK" %raid_type)
        except:
            self.log('raid_1 Error %s ' %traceback.format_exc())

    # Megacli create Raid 5
    def raid_5(self,raid_type,enclosure,slot):
        try:
            raid_type = raid_type.split('_')[-1]
            sinfo = ','.join(['%s:' %enclosure + str(i) for i in slot])
            self.execute( """/usr/bin/megacli -CfgLdAdd -r%s [%s] WB Direct -a0"""  \
                        %(raid_type,sinfo))
            self.log("Raid Group %s create is oK" %raid_type)
        except:
            self.log('raid_5 Error %s ' %traceback.format_exc())

    # Megacli create Raid 10
    def raid_10(self,raid_type,enclosure,slot):
        try:
            raid_type = raid_type.split('_')[-1]
            arry_slot =  self._arry_slot(enclosure,slot)
            self.execute("""/usr/bin/megacli -CfgSpanAdd -r%s %s WB Direct -a0 """ \
                        %(raid_type,arry_slot))
            print 'yes'
            self.log("Raid Group %s create is oK" %raid_type)
        except:
            print traceback.format_exc()
            self.log('raid_10 Error %s ' %traceback.format_exc())
  
    # Array split Raid
    def _arry_slot(self,enclosure,slot):
        bnext = iter(slot)
        count = 0
        ret = []
        try:
            for i in bnext:
                i = int(i.encode() )
                ret.append('-Array%i[%s:%s,%s:%s]'%(count, enclosure,i,enclosure, bnext.next()))
                count += 1
            self.log('Array str %s '%' '.join(ret))
            return ' '.join(ret)
        except:
            self.log(traceback.format_exc())
            return ''

    # Split enclosure str
    def _enclosure(self,disks):
        enclosure = dict()
        try:
            for d in disks:
                rest =d['enclosure']
            if not rest:
                rest = self._esc()
            enclosure['enclosure'] = rest
        except:
            self.log(traceback.format_exc())
         
        return enclosure

    def _esc(self):
        try:
            ecs =  self.execute(""" /usr/bin/megacli   -cfgdsply -aALL |grep 'Enclosure Device ID' """)
            ecs =int(ecs.split(":")[-1].strip())
            return ecs
        except:
            self.log(traceback.format_exc())
    # Split slot str info
    def _slot(self,disks):
        slot = list()
        try:
            for d in disks:
                slot.append(d['slot'])
        except:
            self.log(traceback.format_exc())

        return slot

    # Delete Raid Group ,defautl values is ID
    def delete_raid_group(self):
        try:
            ids = self.execute("""/usr/bin/megacli  -cfgdsply -aALL | \
                                grep "Number of DISK GROUPS"  """)
            for i in range(int(ids.split(':')[-1])):
                self.execute(""" /usr/bin/megacli  -CfgLdDel -L%s -a0""" %i)
                self.log("Raid Group %s delete is oK" %i)
        except:
            self.log(traceback.format_exc())

    def set_ipmit_boot(self):
        try:
            self.execute(""" /usr/bin/ipmitool chassis bootdev pxe """)
            self.log("Set Service boot pxe is ok")
        except:
            self.log(traceback.format_exc())
    def work(self,data):
        # Get Raid Group  info for Create raid live
        raid_info = dict()
        for info in range(len(data)):
            raid_info[data[info]['raid_group']] = dict()
            raid_info[data[info]['raid_group']]['raid_group'] = data[info]['raid_group']
            raid_info[data[info]['raid_group']]['raid_type'] = data[info]['raid_type']
            raid_info[data[info]['raid_group']]['os_flag'] = data[info]['os_flag']
            raid_info[data[info]['raid_group']]['enclosure'] = self._enclosure(data[info]['disks'])['enclosure']
            raid_info[data[info]['raid_group']]['slot'] = self._slot(data[info]['disks'])

        # Delete old raid group
        self.delete_raid_group()
         
        # Set Service boot is PXE
        self.set_ipmit_boot()

        # Create Raid Group ...
        for m in  raid_info:
            # The os Raid is create
            if  raid_info[m]['os_flag']:
                if raid_info[m]['raid_type']  == 'raid_0':
                    self.raid_0(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_1':
                    self.raid_1(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_5':
                    self.raid_5(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_10':
                    self.raid_10(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
         
        for m in  raid_info:
            # The not is os Raid
            if not raid_info[m]['os_flag']:
                if raid_info[m]['raid_type']  == 'raid_0':
                    self.raid_0(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_1':
                    self.raid_1(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_5':
                    self.raid_5(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])
                elif raid_info[m]['raid_type']  == 'raid_10':
                    self.raid_10(raid_info[m]['raid_type'],
                                raid_info[m]['enclosure'],
                                raid_info[m]['slot'])

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-45483-1-1.html 上篇帖子: python glob模块的应用 下篇帖子: 日志切割|程序数据库备份 Cisco
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表