summaryrefslogtreecommitdiffstats
path: root/qtip/util/env.py
blob: 0585a4c14378acf518926eb3a2f356ec7fb36321 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
##############################################################################
# Copyright (c) 2016 Dell Inc, ZTE and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
import os
import socket
import time
from os import path

import paramiko

SCRIPT_DIR = path.join(path.dirname(__file__), path.pardir, 'scripts')
KEYNAME = 'QtipKey'
PRIVATE_KEY = '{0}/qtip/{1}'.format(os.environ['HOME'], KEYNAME)
PUBLIC_KEY = PRIVATE_KEY + '.pub'
HOST_FILE = '{0}/qtip/hosts'.format(os.environ['HOME'])


def all_files_exist(*files):
    if len(files) == 0:
        return False
    flag = True
    for f_item in files:
        flag &= path.isfile(f_item)
        print("Is {0} existed: {1}".format(f_item, flag))
    return flag


def clean_file(*files):
    if len(files) == 0:
        print('Nothing to clean')
        return False

    def clean(f):
        try:
            if all_files_exist(f):
                os.remove(f)
                print("Removed: {0}".format(f))
            else:
                print("Not exists: {0}".format(f))
            return True
        except OSError as error:
            print("Not able to Remove: {0}".format(f), error)
            return False

    results = map(clean, files)
    return len(results) == len(files) and False not in results


def generate_host_file(hostfile=HOST_FILE):
    installer_type = str(os.environ['INSTALLER_TYPE'].lower())
    installer_ip = str(os.environ['INSTALLER_IP'])

    if installer_type not in ["fuel"]:
        raise ValueError("%s is not supported" % installer_type)
    if not installer_ip:
        raise ValueError("The value of environment variable INSTALLER_IP is empty")

    cmd = "bash %s/generate_host_file.sh -i %s -a %s -d %s" % \
        (SCRIPT_DIR, installer_type, installer_ip, hostfile)
    os.system(cmd)
    return all_files_exist(hostfile)


def generate_keypair(keyname='QtipKey'):
    """Generating ssh keypair"""
    cmd = "ssh-keygen -t rsa -N "" -f {0} -q -b 2048".format(keyname)
    os.system(cmd)
    return all_files_exist(PRIVATE_KEY, PUBLIC_KEY)


def pass_keypair(ip, private_key=PRIVATE_KEY):
    os.system('ssh-keyscan %s >> /root/.ssh/known_hosts' % ip)
    time.sleep(2)

    ssh_cmd = '%s/qtip_creds.sh %s %s' % (SCRIPT_DIR, ip, private_key)
    os.system(ssh_cmd)


def ssh_is_ok(ip, private_key=PRIVATE_KEY, attempts=100):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, key_filename=private_key)

    for attempt in range(attempts):
        try:
            stdin, stdout, stderr = ssh.exec_command('uname')
            if not stderr.readlines():
                print("{0}: SSH test successful".format(ip))
                return True
        except socket.error:
            if attempt == (attempts - 1):
                return False
            print("%s times ssh test......failed" % attempt)
            time.sleep(2)
    return False