Completed
Push — master ( 32acac...19ae40 )
by Lakshmi
11:34
created

NodeCreate.run()   F

Complexity

Conditions 12

Size

Total Lines 113

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
c 0
b 0
f 0
dl 0
loc 113
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like NodeCreate.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
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import re
17
18
from lib.actions import OrionBaseAction
19
from lib.utils import send_user_error
20
21
22
class NodeCreate(OrionBaseAction):
23
    def run(self,
24
            node,
25
            ip_address,
26
            platform,
27
            poller,
28
            mon_protocol,
29
            std_community,
30
            community,
31
            status):
32
        """
33
        Create an node in an Orion monitoring platform.
34
        """
35
        results = {}
36
37
        self.logger.info("Connecting to Orion platform: {}".format(platform))
38
        self.connect(platform)
39
        results['platform'] = platform
40
41
        orion_node = self.get_node(node)
42
        if orion_node.npm:
43
            self.logger.error(
44
                "Node ({}) already in Orion platform: {}".format(orion_node,
45
                                                                 platform))
46
47
            send_user_error("Node and/or IP is already in Orion!")
48
            raise ValueError("Node and/or IP already exists!")
49
50
        orion_ip_address = self.get_node(ip_address)
51
        if orion_ip_address.npm:
52
            self.logger.error(
53
                "IP ({}) already in Orion platform: {}".format(
54
                    orion_ip_address,
55
                    platform))
56
57
            send_user_error("IP is already in Orion!")
58
            raise ValueError("IP already exists!")
59
60
        self.logger.info(
61
            "Checking node ({}) is not on Orion platform: {}".format(
62
                node,
63
                platform))
64
65
        # engineID if happens to be None, default to the primary.
66
        if poller is not None:
67
            engineID = self.get_engine_id(poller)
68
        else:
69
            engineID = 1
70
71
        kargs = {'Caption': node,
72
                 'EngineID': engineID,
73
                 'IPAddress': ip_address
74
                 }
75
76
        if mon_protocol == "snmpv2":
77
            kargs['ObjectSubType'] = "SNMP"
78
            kargs['SNMPVersion'] = 2
79
80
        if community is not None:
81
            kargs['Community'] = community
82
        elif std_community is not None:
83
            kargs['Community'] = self.config['defaults']['snmp'][std_community]
84
        elif std_community is None:
85
            raise ValueError("Need one of community or std_community")
86
87
        self.logger.info("Creating Orion Node: {}".format(kargs))
88
        orion_data = self.create('Orion.Nodes', **kargs)
89
90
        self.logger.info("orion_data: {}".format(orion_data))
91
92
        node_id = re.search('(\d+)$', orion_data).group(0)
93
        results['node_id'] = node_id
94
95
        self.logger.info("Created Orion Node: {}".format(results['node_id']))
96
97
        pollers_to_add = {
98
            'N.Details.SNMP.Generic': True,
99
            'N.Uptime.SNMP.Generic': True,
100
            'N.Cpu.SNMP.HrProcessorLoad': True,
101
            'N.Memory.SNMP.NetSnmpReal': True,
102
            'N.AssetInventory.Snmp.Generic': True,
103
            'N.Topology_Layer3.SNMP.ipNetToMedia': True,
104
            'N.Routing.SNMP.Ipv4CidrRoutingTable': False
105
        }
106
107
        if status == 'icmp':
108
            pollers_to_add['N.Status.ICMP.Native'] = True
109
            pollers_to_add['N.Status.SNMP.Native'] = False
110
            pollers_to_add['N.ResponseTime.ICMP.Native'] = True
111
            pollers_to_add['N.ResponseTime.SNMP.Native'] = False
112
        elif status == 'snmp':
113
            pollers_to_add['N.Status.ICMP.Native'] = False
114
            pollers_to_add['N.Status.SNMP.Native'] = True
115
            pollers_to_add['N.ResponseTime.ICMP.Native'] = False
116
            pollers_to_add['N.ResponseTime.SNMP.Native'] = True
117
118
        pollers = []
119
        for p in pollers_to_add:
120
            pollers.append({
121
                'PollerType': p,
122
                'NetObject': 'N:{}'.format(node_id),
123
                'NetObjectType': 'N',
124
                'NetObjectID': node_id,
125
                'Enabled': pollers_to_add[p]
126
            })
127
128
        for poller in pollers:
129
            response = self.create('Orion.Pollers', **poller)
130
            self.logger.info("Added {} ({}) poller: {}".format(
131
                poller['PollerType'],
132
                poller['Enabled'],
133
                response))
134
135
        return results
136