Completed
Pull Request — master (#338)
by James
03:01 queued 01:08
created

CreateVMAction.run()   F

Complexity

Conditions 18

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 37
rs 2.7088
cc 18

How to fix   Complexity   

Complexity

Complex classes like CreateVMAction.run() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from libcloud.compute.base import NodeSize
2
from libcloud.compute.base import NodeImage
3
from libcloud.compute.base import NodeLocation
4
5
from lib.actions import BaseAction
6
7
__all__ = [
8
    'CreateVMAction'
9
]
10
11
12
class CreateVMAction(BaseAction):
13
    api_type = 'compute'
14
15
    def run(self, credentials, name, size_id=None, image_id=None, size_name=None, image_name=None,
16
            location_id=None):
17
        driver = self._get_driver_for_credentials(credentials=credentials)
18
        location = NodeLocation(id=location_id, name=None,
19
                                country=None, driver=driver)
20
21
        if (not size_id and not size_name) or (size_id and size_name):
22
            raise ValueError('Either "size_id" or "size_name" needs to be provided')
23
24
        if (not image_id and not image_name) or (image_id and image_name):
25
            raise ValueError('Either "image_id" or "image_name" needs to be provided')
26
27
        if size_id is not None:
28
            size = NodeSize(id=size_id, name=None,
29
                            ram=None, disk=None, bandwidth=None,
30
                            price=None, driver=driver)
31
        elif size_name is not None:
32
            size = [s for s in driver.list_sizes() if size_name in s.name][0]
33
34
        if image_id is not None:
35
            image = NodeImage(id=image_id, name=None,
36
                              driver=driver)
37
        elif image_name is not None:
38
            image = [i for i in driver.list_images() if
39
                     image_name in i['extra'].get('displaytext', image.name)][0]
40
41
        kwargs = {'name': name, 'size': size, 'image': image}
42
43
        if location_id:
44
            kwargs['location'] = location
45
46
        self.logger.info('Creating node...')
47
48
        node = driver.create_node(**kwargs)
49
50
        self.logger.info('Node successfully created: %s' % (node))
51
        return node
52