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