Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1067479
  • 博文数量: 186
  • 博客积分: 4939
  • 博客等级: 上校
  • 技术积分: 2075
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 17:15
文章分类

全部博文(186)

文章存档

2018年(1)

2017年(3)

2016年(11)

2015年(42)

2014年(21)

2013年(9)

2012年(18)

2011年(46)

2010年(35)

分类: 系统运维

2015-09-07 14:17:18

    某些BT的情况下,需要多个agent端1小时内多次执行某个cron(还得随机时刻), 此时puppet的cron这个resource type满足不了我们的需求了。此时解决办法呢?

   写个class, 里面用define, 大致如下:

class cron(arg1,arg2) {
define random_cron( $command) {
   cron { $name:
   command => $command,
   minute => inline_template("<%= (0..59).to_a.sample(4) %>"),  #执行4次, inline_template要用fqdn_rand的话是不对的,它是Puppet的函数,而inline_template里面是Ruby代码,显然不对。这<%= (0..59).to_a.sample(4) %>也没办法被puppet识别,具体原因不清楚,得分析cron这个resource的ruby代码了。

   hour     => $hour,
   ensure => "present",
  }
}

看下这里:

 (0..59).to_a.sample(4)
=> [2, 38, 1, 56]
不知道是否有重复,看下这个:
Array.new(4) { |e| e = rand(0..60)}
=> [4,14,30,4]   #明显有重复了,虽然用了rand函数。

最好自定义一个function, 检测是否重复,在class的define里面
minute  => random_points()

当然也可以在class里面调用generate()来用bash完成,这样对ruby不熟悉也可以轻松完成。

与fqdn_rand不同的是,这里的cron的minute每次都会变化。

要用python的话,

#!/usr/bin/env python
# generate cron job at different points based on $hostname

import sys, socket

if len(sys.argv) != 2 :
        print "not enough arguments ,exit "
        print "#"*40
        print "usage: python %s \"YOUR_CMD\"" % sys.argv[0]
        print "#"*40

        sys.exit()
else :
        cmd = sys.argv[1]

host = socket.gethostname()

time_range =  ",".join( [str((hash(host)%15)+i*15) for i in xrange(4)]) + " *"*4
cron =  "%s %s" %(time_range,cmd)

print cron
'''
try:
    with open("/tmp/%s" %host ,"wb") as f :
        f.writelines(cron)
        f.writelines("\n")   #write/writeline/writelines有区别的。
        f.close()
except Exception,e :

    print "ERROR" ,str(e)
'''


阅读(1218) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~