def run(self, dc):
        self.set_progress(0, 'Checking Domain Controller service state')
        node = ConfigNode('service.dc', self.configstore).__getstate__()
        node.update(dc)
        if not node.get('volume'):
            raise TaskException(
                errno.ENXIO,
                'Domain controller service is hosted by the virtual machine.'
                'Please provide the valid zfs pool name for the virtual machine volume creation.'
            )

        else:
            try:
                self.dispatcher.call_sync(
                    'service.dc.check_dc_vm_availability')
            except RpcException:
                dc['vm_id'] = self.run_subtask_sync(
                    'vm.create', {
                        'name': 'zentyal_domain_controller',
                        'template': {
                            'name': 'zentyal-4.2'
                        },
                        'target': node['volume'],
                        'config': {
                            'autostart': True
                        }
                    },
                    progress_callback=lambda p, m, e=None: self.chunk_progress(
                        5, 100, 'Creating Domain Controller virtual machine: ',
                        p, m, e))
            finally:
                vm_config = self.dispatcher.call_sync(
                    'vm.query', [('id', '=', dc.get('vm_id', node['vm_id']))],
                    {
                        'select': 'config',
                        'single': True
                    })
                if not node['enable'] and vm_config['autostart']:
                    vm_config['autostart'] = False
                elif node['enable'] and not vm_config['autostart']:
                    vm_config['autostart'] = True

                self.run_subtask_sync(
                    'vm.update',
                    dc['vm_id'] if dc.get('vm_id') else node['vm_id'],
                    {'config': vm_config})

        try:
            node = ConfigNode('service.dc', self.configstore)
            node.update(dc)

            self.dispatcher.dispatch_event('service.dc.changed', {
                'operation': 'update',
                'ids': None,
            })

        except RpcException as e:
            raise TaskException(
                errno.ENXIO,
                'Cannot reconfigure DC vm service: {0}'.format(str(e)))
    def run(self, dc):
        self.set_progress(0, 'Checking Domain Controller service state')
        node = ConfigNode('service.dc', self.configstore).__getstate__()
        node.update(dc)
        if not node.get('volume'):
            raise TaskException(
                errno.ENXIO,
                'Domain controller service is hosted by the virtual machine.'
                'Please provide the valid zfs pool name for the virtual machine volume creation.'
            )

        else:
            try:
                self.dispatcher.call_sync('service.dc.check_dc_vm_availability')
            except RpcException:
                dc['vm_id'] = self.run_subtask_sync('vm.create', {
                    'name': 'zentyal_domain_controller',
                    'template': {'name': 'zentyal-4.2'},
                    'target': node['volume'],
                    'config': {'autostart': True}},
                    progress_callback=lambda p, m, e=None: self.chunk_progress(
                        5, 100, 'Creating Domain Controller virtual machine: ', p, m, e
                    )
                )
            finally:
                vm_config = self.dispatcher.call_sync(
                    'vm.query',
                    [('id', '=', dc.get('vm_id', node['vm_id']))],
                    {'select': 'config', 'single': True}
                )
                if not node['enable'] and vm_config['autostart']:
                    vm_config['autostart'] = False
                elif node['enable'] and not vm_config['autostart']:
                    vm_config['autostart'] = True

                self.run_subtask_sync(
                    'vm.update',
                    dc['vm_id'] if dc.get('vm_id') else node['vm_id'],
                    {'config': vm_config}
                )

        try:
            node = ConfigNode('service.dc', self.configstore)
            node.update(dc)

            self.dispatcher.dispatch_event('service.dc.changed', {
                'operation': 'update',
                'ids': None,
            })

        except RpcException as e:
            raise TaskException(errno.ENXIO,
                                'Cannot reconfigure DC vm service: {0}'.format(str(e)))
Example #3
0
    def verify(self, openvpn_updated):
        node = ConfigNode('service.openvpn', self.configstore).__getstate__()
        node.update(openvpn_updated)

        if node['dev'] not in ['tap', 'tun']:
            raise VerifyException(errno.EINVAL, '{0} Bad interface name. Allowed values tap/tun.'.format(node['dev']))

        if node['mode'] == 'pki' and (not node['ca'] or not node['cert']):
            raise VerifyException(errno.EINVAL, 'For pki VPN mode ca and certyficate values are required')

        if node['mode'] == 'psk':
            try:
                ipaddress.ip_address(node['psk_server_ip'])
                ipaddress.ip_address(node['psk_remote_ip'])
            except ValueError as e:
                raise VerifyException(errno.EINVAL, str(e))

        if node['mode'] == 'pki':
            if (node['keepalive_ping_interval'] * 2) >= node['keepalive_peer_down']:
                raise VerifyException(
                    errno.EINVAL,
                    'The second parameter to keepalive must be'
                    'at least twice the value of the first parameter.'
                    'Recommended setting is keepalive 10 60.'
                )

            try:
                ipaddress.IPv4Network(node['server_ip'] + '/' + node['server_netmask'])
            except ValueError as e:
                raise VerifyException(errno.EINVAL, str(e))


            for route in node.get('push_routes', []):
                route = route.split()
                if len(route) < 2:
                    raise VerifyException(errno.EINVAL, 'Wrong syntax for additional route.')
                try:
                    ipaddress.IPv4Network(route[0] + '/' + route[1])
                except ValueError as e:
                    raise VerifyException(errno.EINVAL, str(e))

        return ['system']
    def run(self, dc):
        self.set_progress(0, "Checking Domain Controller service state")
        node = ConfigNode("service.dc", self.configstore).__getstate__()
        node.update(dc)
        if not node.get("volume"):
            raise TaskException(
                errno.ENXIO,
                "Domain controller service is hosted by the virutal machine."
                "Please provide the valid zfs pool name for the virtual machine volume creation.",
            )

        else:
            try:
                self.dispatcher.call_sync("service.dc.check_dc_vm_availability")
            except RpcException:
                dc["vm_id"], = self.join_subtasks(
                    self.run_subtask(
                        "vm.create",
                        {
                            "name": "zentyal_domain_controller",
                            "template": {"name": "zentyal-4.2"},
                            "target": node["volume"],
                            "config": {"autostart": True},
                        },
                        progress_callback=lambda p, m, e=None: self.chunk_progress(
                            5, 100, "Creating Domain Controller virtual machine: ", p, m, e
                        ),
                    )
                )

        try:
            node = ConfigNode("service.dc", self.configstore)
            node.update(dc)

            self.dispatcher.dispatch_event("service.dc.changed", {"operation": "update", "ids": None})

        except RpcException as e:
            raise TaskException(errno.ENXIO, "Cannot reconfigure DC vm service: {0}".format(str(e)))
Example #5
0
    def send(self, mailmessage, mail=None):

        if mail is None:
            mail = ConfigNode("mail", self.configstore).__getstate__()
        if not mail.get("server") or not mail.get("port"):
            raise RpcException(errno.EINVAL, "You must provide an outgoing server and port when sending mail")

        to = mailmessage.get("to")
        attachments = mailmessage.get("attachments")
        subject = mailmessage.get("subject")
        extra_headers = mailmessage.get("extra_headers")

        if not to:
            to = self.dispatcher.call_sync("user.query", [("username", "=", "root")], {"single": True})
            if to and to.get("email"):
                to = [to["email"]]

        if attachments:
            msg = MIMEMultipart()
            msg.preamble = mailmessage["message"]
            list(map(lambda attachment: msg.attach(attachment), attachments))
        else:
            msg = MIMEText(mailmessage["message"], _charset="utf-8")
        if subject:
            msg["Subject"] = subject

        msg["From"] = mailmessage["from"] if mailmessage.get("from") else mail["from"]
        msg["To"] = ", ".join(to)
        msg["Date"] = formatdate()

        local_hostname = socket.gethostname()
        version = self.dispatcher.call_sync("system.info.version").split("-")[0].lower()

        msg["Message-ID"] = "<{0}-{1}.{2}@{3}>".format(
            version,
            datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"),
            base64.urlsafe_b64encode(os.urandom(3)),
            local_hostname,
        )

        if not extra_headers:
            extra_headers = {}
        for key, val in list(extra_headers.items()):
            if key in msg:
                msg.replace_header(key, val)
            else:
                msg[key] = val
        msg = msg.as_string()

        try:
            if mail["encryption"] == "SSL":
                klass = smtplib.SMTP_SSL
            else:
                klass = smtplib.SMTP
            server = klass(mail["server"], mail["port"], timeout=300, local_hostname=local_hostname)
            if mail["encryption"] == "TLS":
                server.starttls()

            if mail["auth"]:
                server.login(mail["user"], mail["pass"])
            server.sendmail(mail["from"], to, msg)
            server.quit()
        except smtplib.SMTPAuthenticationError as e:
            raise RpcException(errno.EACCES, "Authentication error: {0} {1}".format(e.smtp_code, e.smtp_error))
        except Exception as e:
            logger.error("Failed to send email: {0}".format(str(e)), exc_info=True)
            raise RpcException(errno.EFAULT, "Email send error: {0}".format(str(e)))
        except:
            raise RpcException(errno.EFAULT, "Unexpected error")
Example #6
0
    def send(self, mailmessage, mail=None):

        if mail is None:
            mail = ConfigNode('mail', self.configstore).__getstate__()
        if not mail.get('server') or not mail.get('port'):
            raise RpcException(
                errno.EINVAL,
                'You must provide an outgoing server and port when sending mail',
            )

        to = mailmessage.get('to')
        attachments = mailmessage.get('attachments')
        subject = mailmessage.get('subject')
        extra_headers = mailmessage.get('extra_headers')

        if not to:
            to = self.dispatcher.call_sync(
                'users.query', [('username', '=', 'root')], {'single': True})
            if to and to.get('email'):
                to = [to['email']]

        if attachments:
            msg = MIMEMultipart()
            msg.preamble = mailmessage['message']
            list(map(lambda attachment: msg.attach(attachment), attachments))
        else:
            msg = MIMEText(mailmessage['message'], _charset='utf-8')
        if subject:
            msg['Subject'] = subject

        msg['From'] = mailmessage['from'] if mailmessage.get('from') else mail['from']
        msg['To'] = ', '.join(to)
        msg['Date'] = formatdate()

        local_hostname = socket.gethostname()
        version = self.dispatcher.call_sync('system.info.version').split('-')[0].lower()

        msg['Message-ID'] = "<{0}-{1}.{2}@{3}>".format(
            version,
            datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"),
            base64.urlsafe_b64encode(os.urandom(3)),
            local_hostname)

        if not extra_headers:
            extra_headers = {}
        for key, val in list(extra_headers.items()):
            if key in msg:
                msg.replace_header(key, val)
            else:
                msg[key] = val
        msg = msg.as_string()

        try:
            if mail['encryption'] == 'SSL':
                klass = smtplib.SMTP_SSL
            else:
                klass = smtplib.SMTP
            server = klass(mail['server'], mail['port'], timeout=300, local_hostname=local_hostname)
            if mail['encryption'] == 'TLS':
                server.starttls()

            if mail['auth']:
                server.login(mail['user'], mail['pass'])
            server.sendmail(mail['from'], to, msg)
            server.quit()
        except smtplib.SMTPAuthenticationError as e:
            raise RpcException(errno.EACCES, 'Authentication error: {0} {1}'.format(
                e.smtp_code, e.smtp_error))
        except Exception as e:
            logger.error('Failed to send email: {0}'.format(str(e)), exc_info=True)
            raise RpcException(errno.EFAULT, 'Email send error: {0}'.format(str(e)))
        except:
            raise RpcException(errno.EFAULT, 'Unexpected error')
Example #7
0
    def send(self, mailmessage, mail=None):

        if mail is None:
            mail = ConfigNode('mail', self.configstore).__getstate__()
        if not mail.get('server') or not mail.get('port'):
            raise RpcException(
                errno.EINVAL,
                'You must provide an outgoing server and port when sending mail',
            )

        to = mailmessage.get('to')
        attachments = mailmessage.get('attachments')
        subject = mailmessage.get('subject')
        extra_headers = mailmessage.get('extra_headers')

        if not to:
            to = self.dispatcher.call_sync('users.query',
                                           [('username', '=', 'root')],
                                           {'single': True})
            if to and to.get('email'):
                to = [to['email']]

        if attachments:
            msg = MIMEMultipart()
            msg.preamble = mailmessage['message']
            map(lambda attachment: msg.attach(attachment), attachments)
        else:
            msg = MIMEText(mailmessage['message'], _charset='utf-8')
        if subject:
            msg['Subject'] = subject

        msg['From'] = mailmessage['from'] if mailmessage.get(
            'from') else mail['from']
        msg['To'] = ', '.join(to)
        msg['Date'] = formatdate()

        local_hostname = socket.gethostname()
        version = self.dispatcher.call_sync('system.info.version').split(
            '-')[0].lower()

        msg['Message-ID'] = "<{0}-{1}.{2}@{3}>".format(
            version,
            datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"),
            base64.urlsafe_b64encode(os.urandom(3)), local_hostname)

        if not extra_headers:
            extra_headers = {}
        for key, val in extra_headers.items():
            if key in msg:
                msg.replace_header(key, val)
            else:
                msg[key] = val
        msg = msg.as_string()

        try:
            if mail['encryption'] == 'SSL':
                klass = smtplib.SMTP_SSL
            else:
                klass = smtplib.SMTP
            server = klass(mail['server'],
                           mail['port'],
                           timeout=300,
                           local_hostname=local_hostname)
            if mail['encryption'] == 'TLS':
                server.starttls()

            if mail['auth']:
                server.login(mail['user'], mail['pass'])
            server.sendmail(mail['from'], to, msg)
            server.quit()
        except smtplib.SMTPAuthenticationError as e:
            raise RpcException(
                errno.EACCES,
                'Authentication error: {0} {1}'.format(e.smtp_code,
                                                       e.smtp_error))
        except Exception as e:
            logger.error('Failed to send email: {0}'.format(str(e)),
                         exc_info=True)
            raise RpcException(errno.EFAULT,
                               'Email send error: {0}'.format(str(e)))
        except:
            raise RpcException(errno.EFAULT, 'Unexpected error')