7709: Merge branch 'master' into 7709-api-rails4
[arvados.git] / services / nodemanager / arvnodeman / config.py
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, print_function
4
5 import ConfigParser
6 import importlib
7 import logging
8 import sys
9
10 import arvados
11 import httplib2
12 import pykka
13 from apiclient import errors as apierror
14
15 from .baseactor import BaseNodeManagerActor
16
17 # IOError is the base class for socket.error, ssl.SSLError, and friends.
18 # It seems like it hits the sweet spot for operations we want to retry:
19 # it's low-level, but unlikely to catch code bugs.
20 NETWORK_ERRORS = (IOError,)
21 ARVADOS_ERRORS = NETWORK_ERRORS + (apierror.Error,)
22
23 actor_class = BaseNodeManagerActor
24
25 class NodeManagerConfig(ConfigParser.SafeConfigParser):
26     """Node Manager Configuration class.
27
28     This a standard Python ConfigParser, with additional helper methods to
29     create objects instantiated with configuration information.
30     """
31
32     LOGGING_NONLEVELS = frozenset(['file'])
33
34     def __init__(self, *args, **kwargs):
35         # Can't use super() because SafeConfigParser is an old-style class.
36         ConfigParser.SafeConfigParser.__init__(self, *args, **kwargs)
37         for sec_name, settings in {
38             'Arvados': {'insecure': 'no',
39                         'timeout': '15'},
40             'Daemon': {'min_nodes': '0',
41                        'max_nodes': '1',
42                        'poll_time': '60',
43                        'max_poll_time': '300',
44                        'poll_stale_after': '600',
45                        'max_total_price': '0',
46                        'boot_fail_after': str(sys.maxint),
47                        'node_stale_after': str(60 * 60 * 2),
48                        'watchdog': '600',
49                        'node_mem_scaling': '0.95'},
50             'Manage': {'address': '127.0.0.1',
51                        'port': '-1'},
52             'Logging': {'file': '/dev/stderr',
53                         'level': 'WARNING'},
54         }.iteritems():
55             if not self.has_section(sec_name):
56                 self.add_section(sec_name)
57             for opt_name, value in settings.iteritems():
58                 if not self.has_option(sec_name, opt_name):
59                     self.set(sec_name, opt_name, value)
60
61     def get_section(self, section, transformer=None):
62         result = self._dict()
63         for key, value in self.items(section):
64             if transformer is not None:
65                 try:
66                     value = transformer(value)
67                 except (TypeError, ValueError):
68                     pass
69             result[key] = value
70         return result
71
72     def log_levels(self):
73         return {key: getattr(logging, self.get('Logging', key).upper())
74                 for key in self.options('Logging')
75                 if key not in self.LOGGING_NONLEVELS}
76
77     def dispatch_classes(self):
78         mod_name = 'arvnodeman.computenode.dispatch'
79         if self.has_option('Daemon', 'dispatcher'):
80             mod_name = '{}.{}'.format(mod_name,
81                                       self.get('Daemon', 'dispatcher'))
82         module = importlib.import_module(mod_name)
83         return (module.ComputeNodeSetupActor,
84                 module.ComputeNodeShutdownActor,
85                 module.ComputeNodeUpdateActor,
86                 module.ComputeNodeMonitorActor)
87
88     def new_arvados_client(self):
89         if self.has_option('Daemon', 'certs_file'):
90             certs_file = self.get('Daemon', 'certs_file')
91         else:
92             certs_file = None
93         insecure = self.getboolean('Arvados', 'insecure')
94         http = httplib2.Http(timeout=self.getint('Arvados', 'timeout'),
95                              ca_certs=certs_file,
96                              disable_ssl_certificate_validation=insecure)
97         return arvados.api(version='v1',
98                            host=self.get('Arvados', 'host'),
99                            token=self.get('Arvados', 'token'),
100                            insecure=insecure,
101                            http=http)
102
103     def new_cloud_client(self):
104         module = importlib.import_module('arvnodeman.computenode.driver.' +
105                                          self.get('Cloud', 'provider'))
106         auth_kwargs = self.get_section('Cloud Credentials')
107         if 'timeout' in auth_kwargs:
108             auth_kwargs['timeout'] = int(auth_kwargs['timeout'])
109         return module.ComputeNodeDriver(auth_kwargs,
110                                         self.get_section('Cloud List'),
111                                         self.get_section('Cloud Create'))
112
113     def node_sizes(self, all_sizes):
114         """Finds all acceptable NodeSizes for our installation.
115
116         Returns a list of (NodeSize, kwargs) pairs for each NodeSize object
117         returned by libcloud that matches a size listed in our config file.
118         """
119
120         size_kwargs = {}
121         for sec_name in self.sections():
122             sec_words = sec_name.split(None, 2)
123             if sec_words[0] != 'Size':
124                 continue
125             size_spec = self.get_section(sec_name, int)
126             if 'price' in size_spec:
127                 size_spec['price'] = float(size_spec['price'])
128             size_kwargs[sec_words[1]] = size_spec
129         # EC2 node sizes are identified by id. GCE sizes are identified by name.
130         matching_sizes = []
131         for size in all_sizes:
132             if size.id in size_kwargs:
133                 matching_sizes.append((size, size_kwargs[size.id]))
134             elif size.name in size_kwargs:
135                 matching_sizes.append((size, size_kwargs[size.name]))
136         return matching_sizes
137
138     def shutdown_windows(self):
139         return [int(n)
140                 for n in self.get('Cloud', 'shutdown_windows').split(',')]