aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests/sdn/onos/teston/adapters/connection.py
blob: 3786945d214f91b9d9c06408d72c8bf53f48da87 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Description:
    This file is used to make connections
    Include ssh & exchange public-key to each other so that
    it can run without password

    lanqinglong@huawei.com

#
# 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 pexpect
import re

from foundation import Foundation
import functest.utils.functest_logger as ft_logger


class Connection(Foundation):

    logger = ft_logger.Logger("connection").getLogger()

    def __init__(self):
        Foundation.__init__(self)
        self.loginfo = Foundation()

    def AddKnownHost(self, handle, ipaddr, username, password):
        """
        Add an user to known host,so that onos can login in with onos $ipaddr.
        parameters:
        ipaddr:   ip address
        username: login user name
        password: login password
        """
        self.logger.info("Now Adding an user to known hosts " + ipaddr)
        login = handle
        login.sendline("ssh -l %s -p 8101 %s" % (username, ipaddr))
        index = 0
        while index != 2:
            index = login.expect(['assword:', 'yes/no', pexpect.EOF,
                                  pexpect.TIMEOUT])
            if index == 0:
                login.sendline(password)
                login.sendline("logout")
                index = login.expect(["closed", pexpect.EOF])
                if index == 0:
                    self.loginfo.log("Add SSH Known Host Success!")
                    break
                else:
                    self.loginfo.log("Add SSH Known Host Failed! "
                                     "Please Check!")
                    break
                login.prompt()

            if index == 1:
                login.sendline('yes')

    def GetEnvValue(self, handle, envname):
        """
        os.getenv only returns current user value
        GetEnvValue returns a environment value of
            current handle
        eg: GetEnvValue(handle,'HOME')
        """
        envhandle = handle
        envhandle.sendline('echo $' + envname)
        envhandle.prompt()
        reg = envname + '\r\n(.*)\r'
        envaluereg = re.compile(reg)
        envalue = envaluereg.search(envhandle.before)
        if envalue:
            return envalue.groups()[0]
        else:
            return None

    def Gensshkey(self, handle):
        """
        Generate ssh keys, used for some server have no sshkey.
        """
        self.logger.info("Now Generating SSH keys...")
        # Here file name may be id_rsa or id_ecdsa or others
        # So here will have a judgement
        keysub = handle
        filepath = self.GetEnvValue(keysub, 'HOME') + '/.ssh'
        filelist = os.listdir(filepath)
        for item in filelist:
            if 'id' in item:
                self.loginfo.log("SSH keys are exsit in ssh directory.")
                return True
        keysub.sendline("ssh-keygen -t rsa")
        Result = 0
        while Result != 2:
            Result = keysub.expect(["Overwrite", "Enter", pexpect.EOF,
                                    'PEXPECT]#', pexpect.TIMEOUT])
            if Result == 0:
                keysub.sendline("y")
            if Result == 1 or Result == 2:
                keysub.sendline("\n")
            if Result == 3:
                self.loginfo.log("Generate SSH key success.")
                keysub.prompt()
                break
            if Result == 4:
                self.loginfo.log("Generate SSH key failed.")
                keysub.prompt()
                break

    def GetRootAuth(self, password):
        """
        Get root user
        parameters:
        password: root login password
        """
        self.logger.info("Now changing to user root")
        login = pexpect.spawn("su - root")
        index = 0
        while index != 2:
            index = login.expect(['assword:', "failure",
                                  pexpect.EOF, pexpect.TIMEOUT])
            if index == 0:
                login.sendline(password)
            if index == 1:
                self.loginfo.log("Change user to root failed.")

        login.interact()

    def ReleaseRootAuth(self):
        """
        Exit root user.
        """
        self.logger.info("Now Release user root")
        login = pexpect.spawn("exit")
        index = login.expect(['logout', pexpect.EOF, pexpect.TIMEOUT])
        if index == 0:
            self.loginfo.log("Release root user success.")
        if index == 1:
            self.loginfo.log("Release root user failed.")

        login.interact()

    def AddEnvIntoBashrc(self, envalue):
        """
        Add Env var into /etc/profile.
        parameters:
        envalue: environment value to add
        """
        self.logger.info("Now Adding bash environment")
        fileopen = open("/etc/profile", 'r')
        findContext = 1
        while findContext:
            findContext = fileopen.readline()
            result = findContext.find(envalue)
            if result != -1:
                break
        fileopen.close
        if result == -1:
            envAdd = open("/etc/profile", 'a+')
            envAdd.writelines("\n" + envalue)
            envAdd.close()
        self.loginfo.log("Add env to bashrc success!")

    def OnosRootPathChange(self, onospath):
        """
        Change ONOS root path in file:bash_profile
        onospath: path of onos root
        """
        self.logger.info("Now Changing ONOS Root Path")
        filepath = onospath + 'onos/tools/dev/bash_profile'
        line = open(filepath, 'r').readlines()
        lenall = len(line) - 1
        for i in range(lenall):
            if "export ONOS_ROOT" in line[i]:
                line[i] = 'export ONOS_ROOT=' + onospath + 'onos\n'
        NewFile = open(filepath, 'w')
        NewFile.writelines(line)
        NewFile.close
        self.logger.info("Done!")

    def OnosConnectionSet(self):
        """
        Intergrate for ONOS connection setup
        """
        if self.masterusername == 'root':
            filepath = '/root/'
        else:
            filepath = '/home/' + self.masterusername + '/'
        filepath = os.path.join(filepath, "onos/tools/dev/bash_profile")
        self.AddEnvIntoBashrc("source " + filepath + "\n")
        self.AddEnvIntoBashrc("export OCT=" + self.OCT)
        self.AddEnvIntoBashrc("export OC1=" + self.OC1)
        self.AddEnvIntoBashrc("export OC2=" + self.OC2)
        self.AddEnvIntoBashrc("export OC3=" + self.OC3)
        self.AddEnvIntoBashrc("export OCN=" + self.OCN)
        self.AddEnvIntoBashrc("export OCN2=" + self.OCN2)
        self.AddEnvIntoBashrc("export localhost=" + self.localhost)
ass="p">} static int pca9532_set_blink(struct led_classdev *led_cdev, unsigned long *delay_on, unsigned long *delay_off) { struct pca9532_led *led = ldev_to_led(led_cdev); struct i2c_client *client = led->client; int psc; int err = 0; if (*delay_on == 0 && *delay_off == 0) { /* led subsystem ask us for a blink rate */ *delay_on = 1000; *delay_off = 1000; } if (*delay_on != *delay_off || *delay_on > 1690 || *delay_on < 6) return -EINVAL; /* Thecus specific: only use PSC/PWM 0 */ psc = (*delay_on * 152-1)/1000; err = pca9532_calcpwm(client, 0, psc, led_cdev->brightness); if (err) return err; schedule_work(&led->work); return 0; } static int pca9532_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct pca9532_data *data = input_get_drvdata(dev); if (!(type == EV_SND && (code == SND_BELL || code == SND_TONE))) return -1; /* XXX: allow different kind of beeps with psc/pwm modifications */ if (value > 1 && value < 32767) data->pwm[1] = 127; else data->pwm[1] = 0; schedule_work(&data->work); return 0; } static void pca9532_input_work(struct work_struct *work) { struct pca9532_data *data = container_of(work, struct pca9532_data, work); u8 maxleds = data->chip_info->num_leds; mutex_lock(&data->update_lock); i2c_smbus_write_byte_data(data->client, PCA9532_REG_PWM(maxleds, 1), data->pwm[1]); mutex_unlock(&data->update_lock); } static void pca9532_led_work(struct work_struct *work) { struct pca9532_led *led; led = container_of(work, struct pca9532_led, work); if (led->state == PCA9532_PWM0) pca9532_setpwm(led->client, 0); pca9532_setled(led); } #ifdef CONFIG_LEDS_PCA9532_GPIO static int pca9532_gpio_request_pin(struct gpio_chip *gc, unsigned offset) { struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio); struct pca9532_led *led = &data->leds[offset]; if (led->type == PCA9532_TYPE_GPIO) return 0; return -EBUSY; } static void pca9532_gpio_set_value(struct gpio_chip *gc, unsigned offset, int val) { struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio); struct pca9532_led *led = &data->leds[offset]; if (val) led->state = PCA9532_ON; else led->state = PCA9532_OFF; pca9532_setled(led); } static int pca9532_gpio_get_value(struct gpio_chip *gc, unsigned offset) { struct pca9532_data *data = container_of(gc, struct pca9532_data, gpio); unsigned char reg; reg = i2c_smbus_read_byte_data(data->client, PCA9532_REG_INPUT(offset)); return !!(reg & (1 << (offset % 8))); } static int pca9532_gpio_direction_input(struct gpio_chip *gc, unsigned offset) { /* To use as input ensure pin is not driven */ pca9532_gpio_set_value(gc, offset, 0); return 0; } static int pca9532_gpio_direction_output(struct gpio_chip *gc, unsigned offset, int val) { pca9532_gpio_set_value(gc, offset, val); return 0; } #endif /* CONFIG_LEDS_PCA9532_GPIO */ static int pca9532_destroy_devices(struct pca9532_data *data, int n_devs) { int i = n_devs; if (!data) return -EINVAL; while (--i >= 0) { switch (data->leds[i].type) { case PCA9532_TYPE_NONE: case PCA9532_TYPE_GPIO: break; case PCA9532_TYPE_LED: led_classdev_unregister(&data->leds[i].ldev); cancel_work_sync(&data->leds[i].work); break; case PCA9532_TYPE_N2100_BEEP: if (data->idev != NULL) { cancel_work_sync(&data->work); data->idev = NULL; } break; } } #ifdef CONFIG_LEDS_PCA9532_GPIO if (data->gpio.dev) gpiochip_remove(&data->gpio); #endif return 0; } static int pca9532_configure(struct i2c_client *client, struct pca9532_data *data, struct pca9532_platform_data *pdata) { int i, err = 0; int gpios = 0; u8 maxleds = data->chip_info->num_leds; for (i = 0; i < 2; i++) { data->pwm[i] = pdata->pwm[i]; data->psc[i] = pdata->psc[i]; i2c_smbus_write_byte_data(client, PCA9532_REG_PWM(maxleds, i), data->pwm[i]); i2c_smbus_write_byte_data(client, PCA9532_REG_PSC(maxleds, i), data->psc[i]); } for (i = 0; i < data->chip_info->num_leds; i++) { struct pca9532_led *led = &data->leds[i]; struct pca9532_led *pled = &pdata->leds[i]; led->client = client; led->id = i; led->type = pled->type; switch (led->type) { case PCA9532_TYPE_NONE: break; case PCA9532_TYPE_GPIO: gpios++; break; case PCA9532_TYPE_LED: led->state = pled->state; led->name = pled->name; led->ldev.name = led->name; led->ldev.brightness = LED_OFF; led->ldev.brightness_set = pca9532_set_brightness; led->ldev.blink_set = pca9532_set_blink; INIT_WORK(&led->work, pca9532_led_work); err = led_classdev_register(&client->dev, &led->ldev); if (err < 0) { dev_err(&client->dev, "couldn't register LED %s\n", led->name); goto exit; } pca9532_setled(led); break; case PCA9532_TYPE_N2100_BEEP: BUG_ON(data->idev); led->state = PCA9532_PWM1; pca9532_setled(led); data->idev = devm_input_allocate_device(&client->dev); if (data->idev == NULL) { err = -ENOMEM; goto exit; } data->idev->name = pled->name; data->idev->phys = "i2c/pca9532"; data->idev->id.bustype = BUS_HOST; data->idev->id.vendor = 0x001f; data->idev->id.product = 0x0001; data->idev->id.version = 0x0100; data->idev->evbit[0] = BIT_MASK(EV_SND); data->idev->sndbit[0] = BIT_MASK(SND_BELL) | BIT_MASK(SND_TONE); data->idev->event = pca9532_event; input_set_drvdata(data->idev, data); INIT_WORK(&data->work, pca9532_input_work); err = input_register_device(data->idev); if (err) { cancel_work_sync(&data->work); data->idev = NULL; goto exit; } break; } } #ifdef CONFIG_LEDS_PCA9532_GPIO if (gpios) { data->gpio.label = "gpio-pca9532"; data->gpio.direction_input = pca9532_gpio_direction_input; data->gpio.direction_output = pca9532_gpio_direction_output; data->gpio.set = pca9532_gpio_set_value; data->gpio.get = pca9532_gpio_get_value; data->gpio.request = pca9532_gpio_request_pin; data->gpio.can_sleep = 1; data->gpio.base = pdata->gpio_base; data->gpio.ngpio = data->chip_info->num_leds; data->gpio.dev = &client->dev; data->gpio.owner = THIS_MODULE; err = gpiochip_add(&data->gpio); if (err) { /* Use data->gpio.dev as a flag for freeing gpiochip */ data->gpio.dev = NULL; dev_warn(&client->dev, "could not add gpiochip\n"); } else { dev_info(&client->dev, "gpios %i...%i\n", data->gpio.base, data->gpio.base + data->gpio.ngpio - 1); } } #endif return 0; exit: pca9532_destroy_devices(data, i); return err; } static int pca9532_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pca9532_data *data = i2c_get_clientdata(client); struct pca9532_platform_data *pca9532_pdata = dev_get_platdata(&client->dev); if (!pca9532_pdata) return -EIO; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->chip_info = &pca9532_chip_info_tbl[id->driver_data]; dev_info(&client->dev, "setting platform data\n"); i2c_set_clientdata(client, data); data->client = client; mutex_init(&data->update_lock); return pca9532_configure(client, data, pca9532_pdata); } static int pca9532_remove(struct i2c_client *client) { struct pca9532_data *data = i2c_get_clientdata(client); int err; err = pca9532_destroy_devices(data, data->chip_info->num_leds); if (err) return err; return 0; } module_i2c_driver(pca9532_driver); MODULE_AUTHOR("Riku Voipio"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("PCA 9532 LED dimmer");