Remove duplicated code in vnfs
[functest.git] / functest / core / cloudify.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2018 Orange and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """Cloudify testcase implementation."""
11
12 from __future__ import division
13
14 import logging
15 import time
16
17 from cloudify_rest_client import CloudifyClient
18 from cloudify_rest_client.executions import Execution
19
20 from functest.core import singlevm
21
22
23 class Cloudify(singlevm.SingleVm2):
24     """Cloudify Orchestrator Case."""
25
26     __logger = logging.getLogger(__name__)
27
28     filename = ('/home/opnfv/functest/images/'
29                 'cloudify-manager-premium-4.0.1.qcow2')
30     flavor_ram = 4096
31     flavor_vcpus = 2
32     flavor_disk = 40
33     username = 'centos'
34     ssh_connect_loops = 12
35     create_server_timeout = 600
36     ports = [80, 443, 5671, 53333]
37
38     def __init__(self, **kwargs):
39         """Initialize Cloudify testcase object."""
40         if "case_name" not in kwargs:
41             kwargs["case_name"] = "cloudify"
42         super(Cloudify, self).__init__(**kwargs)
43         self.cfy_client = None
44
45     def prepare(self):
46         super(Cloudify, self).prepare()
47         for port in self.ports:
48             self.cloud.create_security_group_rule(
49                 self.sec.id, port_range_min=port, port_range_max=port,
50                 protocol='tcp', direction='ingress')
51
52     def execute(self):
53         """
54         Deploy Cloudify Manager.
55         """
56         self.cfy_client = CloudifyClient(
57             host=self.fip.floating_ip_address,
58             username='admin', password='admin', tenant='default_tenant',
59             api_version='v3')
60         self.__logger.info("Attemps running status of the Manager")
61         for loop in range(10):
62             try:
63                 self.__logger.debug(
64                     "status %s", self.cfy_client.manager.get_status())
65                 cfy_status = self.cfy_client.manager.get_status()['status']
66                 self.__logger.info(
67                     "The current manager status is %s", cfy_status)
68                 if str(cfy_status) != 'running':
69                     raise Exception("Cloudify Manager isn't up and running")
70                 self.cfy_client.secrets.create("foo", "bar")
71                 self.__logger.debug(
72                     "List secrets: %s", self.cfy_client.secrets.list())
73                 self.cfy_client.secrets.delete("foo")
74                 self.__logger.info("Secrets API successfully reached")
75                 break
76             except Exception:  # pylint: disable=broad-except
77                 self.__logger.info(
78                     "try %s: Cloudify Manager isn't up and running", loop + 1)
79                 time.sleep(30)
80         else:
81             self.__logger.error("Cloudify Manager isn't up and running")
82             return 1
83         self.__logger.info("Cloudify Manager is up and running")
84         return 0
85
86
87 def wait_for_execution(client, execution, logger, timeout=3600, ):
88     """Wait for a workflow execution on Cloudify Manager."""
89     # if execution already ended - return without waiting
90     if execution.status in Execution.END_STATES:
91         return execution
92
93     if timeout is not None:
94         deadline = time.time() + timeout
95
96     # Poll for execution status and execution logs, until execution ends
97     # and we receive an event of type in WORKFLOW_END_TYPES
98     offset = 0
99     batch_size = 50
100     event_list = []
101     execution_ended = False
102     while True:
103         event_list = client.events.list(
104             execution_id=execution.id,
105             _offset=offset,
106             _size=batch_size,
107             include_logs=True,
108             sort='@timestamp').items
109
110         offset = offset + len(event_list)
111         for event in event_list:
112             logger.debug(event.get('message'))
113
114         if timeout is not None:
115             if time.time() > deadline:
116                 raise RuntimeError(
117                     'execution of operation {0} for deployment {1} '
118                     'timed out'.format(execution.workflow_id,
119                                        execution.deployment_id))
120             else:
121                 # update the remaining timeout
122                 timeout = deadline - time.time()
123
124         if not execution_ended:
125             execution = client.executions.get(execution.id)
126             execution_ended = execution.status in Execution.END_STATES
127
128         if execution_ended:
129             break
130
131         time.sleep(5)
132
133     return execution
134
135
136 def get_execution_id(client, deployment_id):
137     """
138     Get the execution id of a env preparation.
139
140     network, security group, fip, VM creation
141     """
142     executions = client.executions.list(deployment_id=deployment_id)
143     for execution in executions:
144         if execution.workflow_id == 'create_deployment_environment':
145             return execution
146     raise RuntimeError('Failed to get create_deployment_environment '
147                        'workflow execution.'
148                        'Available executions: {0}'.format(executions))