Completed
Pull Request — master (#353)
by James
02:04
created

CreateVMAction.run()   F

Complexity

Conditions 20

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 36
rs 2.6864
cc 20

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