Beispiel #1
0
def main():
    ymls = sys.argv[1:]
    if not ymls:
        raise SystemExit('usage: {0} file1.yml [file2.yml [file3.yml]]'.format(sys.argv[0]))

    conn = iaas.connect_to_zone(config.zone , config.key, config.secret)
    conn.stop_instances(instances=[config.instances],force=True)
    print "reset_instances:", conn.reset_instances(instances=[config.instances], login_mode="keypair", login_keypair=config.keypair)
    check_ret_code = lambda x : x.get("ret_code") == 0

    # 等待重置成功后启动主机
    print "start_instances:", retry(conn.start_instances,kw={'instances': [config.instances], 'force': True} , check=check_ret_code)
    # 等待开放22端口
    for vxnet in conn.describe_instances(instances=[config.instances])['instance_set'][0]['vxnets']:
        ip = vxnet["private_ip"]
        retry(detect_port, args=(ip ,22))

    for yml in ymls:
        if not os.path.isfile(yml):
            raise SystemError("ERROR: '{0}'is not a file".format(yml))
        os.system("ansible-playbook -i /etc/ansible/base-hosts " + yml)

    print "stop_instances:", conn.stop_instances(instances=[config.instances],force=True)
    print "capture_instance:", retry(conn.capture_instance, args=(config.instances,),
                                     kw={"image_name" : config.image_name}, check=check_ret_code)
Beispiel #2
0
 def real_start(self):
     conn = connect_to_zone(self.zone, self.api_id, self.api_key)
     ret = conn.run_instances(image_id=self.image,
                              instance_type=self.conf,
                              login_mode="keypair",
                              login_keypair=self.keypair,
                              vxnets=[self.vxnets])
     self.instance_id = ret["instances"]
     ret = self.wait_booting(conn)
     self.host = ret["vxnets"][0]["private_ip"]
     self.conn_puppet()
Beispiel #3
0
 def real_start(self):
     conn = connect_to_zone(self.zone, self.api_id, self.api_key)
     ret = conn.run_instances(image_id=self.image,
                              instance_type=self.conf,
                              login_mode="keypair",
                              login_keypair=self.keypair,
                              vxnets=[self.vxnets])
     self.instance_id = ret["instances"]
     ret = self.wait_booting(conn)
     self.host = ret["vxnets"][0]["private_ip"]
     self.conn_puppet()
Beispiel #4
0
def startClusters(cluster):
    # 连接zone
    conn = iaas.connect_to_zone(config.zone, config.key, config.secret)
    data = conn.describe_clusters(clusters=[cluster])
    # 如果集群不存在则
    if data["total_count"] != 1:
        sys.stderr.write("find cluster Error\n")
        return False

    # 酌情启动集群
    status = data["cluster_set"][0]["status"]
    nodes = data["cluster_set"][0]["nodes"]
    ips = [node["private_ip"] for node in nodes]
    if status == "stopped":
        conn.start_clusters(clusters=[cluster])
        for ip in ips:
            try:
                retry(detect_port, args=(ip, 6379))
            except SystemError as e:
                return False
    return ips
Beispiel #5
0
def main():
    check_ret_code = lambda x : x.get("ret_code") == 0

    if len(sys.argv) < 3:
        raise SyntaxError('至少2个参数')

    cluseter = sys.argv[1]
    ansibleArgv = sys.argv[2:]
    # cluseter = "cl-dvmpwi5x"
    cluseterHosts = "/tmp/{0}.host".format(cluseter )

    conn = iaas.connect_to_zone(config.zone, config.key, config.secret)
    conn.describe_clusters(clusters=[cluseter])
    data = conn.describe_clusters(clusters=[cluseter])
    with open(cluseterHosts,'w' ) as f:
        f.write("[{0}]\n".format(cluseter))
        f.write('\n'.join(node["private_ip"] for node in data['cluster_set'][0]['nodes']))
    cmds =  "ansible {0} -i {1} {2}".format(cluseter, cluseterHosts, " ".join(ansibleArgv))
    print cmds
    # os.system(cmds)
    cmds = ["ansible", cluseter, "-i", cluseterHosts] + ansibleArgv

    subprocess.call(cmds)
    os.remove(cluseterHosts)
STAND_BY_STATE = [
    "running",  # 主机准备好
    "available",  # ip准备好
]

response_resources_name = [
    "instance_set",  # 主机键值
    "eip_set",  # ip键值
]

CN_SERVER_NAME = 'server_cn'
CN_IP_NAME = 'ip_cn'

conn = connect_to_zone(
    'gd1',
    config.QC_GD1_KEY_ID,
    config.QC_GD1_ACCESS_KEY,
)


def show_all_image():
    rs = [(item['image_id'], item['image_name']) for item in
          conn.describe_images(zone='gd1', provider='system', limit=200)['image_set']]
    rs.sort()
    return rs


def ensure_keypair():
    """
    确保不会重新创建key
    :return: keypair_id
Beispiel #7
0
def main():
    check_ret_code = lambda x: x.get("ret_code") == 0

    parser = optparse.OptionParser(
        usage='{0} [--reset] file1.yml [file2.yml [file3.yml]]'.format(
            sys.argv[0]))
    parser.add_option('--append',
                      action='store_true',
                      dest='append',
                      default=False,
                      help=u'给镜像添加脚本, 不重置系统')
    parser.add_option('--instances',
                      action='store',
                      dest='instances',
                      help='主机instances,默认读取"config.py"',
                      default=config.instances,
                      metavar=config.instances)
    parser.add_option('--zone',
                      action='store',
                      dest='zone',
                      help='区id, 默认读取config.ini',
                      default=config.zone,
                      metavar=config.zone)
    option, args = parser.parse_args()

    if not args:
        parser.error("not file")

    conn = iaas.connect_to_zone(option.zone, config.key, config.secret)

    # 重置系统
    if not option.append:
        conn.stop_instances(instances=[option.instances], force=True)
        print "reset_instances:", conn.reset_instances(
            instances=[option.instances],
            login_mode="keypair",
            login_keypair=config.keypair)
    # 等待重置成功后启动主机
    print "start_instances:", retry(conn.start_instances,
                                    kw={
                                        'instances': [option.instances],
                                        'force': True
                                    },
                                    check=check_ret_code)

    # 等待开放22端口
    for vxnet in conn.describe_instances(
            instances=[option.instances])['instance_set'][0]['vxnets']:
        ip = vxnet["private_ip"]
        retry(detect_port, args=(ip, 22))

    for yml in args:
        if not os.path.isfile(yml):
            raise SystemError("ERROR: '{0}'is not a file".format(yml))
        os.system("ansible-playbook " + yml)

    print "stop_instances:", conn.stop_instances(instances=[option.instances],
                                                 force=True)
    print "capture_instance:", retry(conn.capture_instance,
                                     args=(option.instances, ),
                                     kw={"image_name": config.image_name},
                                     check=check_ret_code)
Beispiel #8
0
 def real_terminate(self):
     self.puppet.fire_worker()
     self.puppet.shutdown()
     conn = connect_to_zone(self.zone, self.api_id, self.api_key)
     conn.terminate_instances(self.instance_id)
Beispiel #9
0
 def real_terminate(self):
     self.puppet.fire_worker()
     self.puppet.shutdown()
     conn = connect_to_zone(self.zone, self.api_id, self.api_key)
     conn.terminate_instances(self.instance_id)
Beispiel #10
0
	def connect(self):
		con = iaas.connect_to_zone('gd1',
			self.qy_access_key_id,
			self.qy_secret_access_key)

		return con
Beispiel #11
0
 def __init__(self):
     self.clt = iaas.connect_to_zone(
         'pek1',
         settings.QINGCLOUD_ACCESSKEY,
         settings.QINGCLOUD_ACCESSSECRET,
     )
Beispiel #12
0
if __name__ == '__main__':

    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-e', '--exclude', action='append', dest='exclude', help='排除的主机ID', default=[], metavar='i-bbgthwwo')
    parser.add_option('-z', '--zone', action='store', dest='zone', help='处理的区域 默认:{0}'.format(config.zone),
                      default=config.zone, metavar=config.zone)
    option, args = parser.parse_args()

    # if len(sys.argv) == 1 or (len(sys.argv) > 3 and sys.argv[2] not in [ "exclude", "e"]):
        # raise SystemExit(usage)
    vxnet = args[0]
    exclude = option.exclude

    # 连接zone
    conn = iaas.connect_to_zone(option.zone, config.key, config.secret)

    # 关闭集群
    data = conn.describe_clusters(status=["active"])
    for cluster_info in data["cluster_set"]:
        cluster = cluster_info.get("cluster_id")
        if cluster_info["vxnet"]["vxnet_id"] != vxnet:
            continue
        if cluster in exclude:
            continue
        if any(tag['tag_id'] in exclude for tag in cluster_info["tags"]):
            continue
        conn.stop_clusters(clusters=[cluster])

    # 关闭主机
    data = conn.describe_instances(status=["running"])
Beispiel #13
0
STAND_BY_STATE = [
    "running",  # 主机准备好
    "available",  # ip准备好
]

response_resources_name = [
    "instance_set",  # 主机键值
    "eip_set",  # ip键值
]

CN_SERVER_NAME = 'server_cn'
CN_IP_NAME = 'ip_cn'

conn = connect_to_zone(
    'gd1',
    config.QC_GD1_KEY_ID,
    config.QC_GD1_ACCESS_KEY,
)


def show_all_image():
    rs = [(item['image_id'], item['image_name'])
          for item in conn.describe_images(
              zone='gd1', provider='system', limit=200)['image_set']]
    rs.sort()
    return rs


def ensure_keypair():
    """
    确保不会重新创建key