system.services.systemctl

Here are the examples of the python api system.services.systemctl taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

Example 1

Project: rockstor-core
Source File: afp_service.py
View license
    @classmethod
    def _switch_afpd(cls, switch):
        if (switch == 'start'):
            systemctl(cls.service_name, 'enable')
            systemctl(cls.service_name, 'start')
        else:
            systemctl(cls.service_name, 'disable')
            systemctl(cls.service_name, 'stop')

Example 2

Project: rockstor-core
Source File: bootstrap_service.py
View license
    def post(self, request, command):
        service = Service.objects.get(name=self.name)

        if (command == 'start'):
            systemctl(self.name, 'enable')
            systemctl(self.name, 'start')
        elif (command == 'stop'):
            systemctl(self.name, 'stop')
            systemctl(self.name, 'disable')
        return Response()

Example 3

Project: rockstor-core
Source File: ntp_service.py
View license
    @staticmethod
    def _switch_ntpd(switch):
        if (switch == 'start'):
            systemctl('ntpd', 'enable')
            systemctl('ntpd', 'start')
            systemctl('chronyd', 'stop')
            systemctl('chronyd', 'disable')
        else:
            systemctl('ntpd', 'disable')
            systemctl('ntpd', 'stop')
            systemctl('chronyd', 'enable')
            systemctl('chronyd', 'start')

Example 4

Project: rockstor-core
Source File: smartd_service.py
View license
    @classmethod
    def _switch(cls, switch):
        if (switch == 'start'):
            systemctl(cls.service_name, 'enable')
            systemctl(cls.service_name, 'start')
        else:
            systemctl(cls.service_name, 'disable')
            systemctl(cls.service_name, 'stop')

Example 5

Project: rockstor-core
Source File: snmp_service.py
View license
    @classmethod
    def _switch_snmp(cls, switch):
        if (switch == 'start'):
            systemctl(cls.service_name, 'enable')
            systemctl(cls.service_name, 'start')
        else:
            systemctl(cls.service_name, 'disable')
            systemctl(cls.service_name, 'stop')

Example 6

Project: rockstor-core
Source File: email_client.py
View license
    @transaction.atomic
    def delete(self, request):
        update_sasl('', '', '', '', revert=True)
        update_forward('', revert=True)
        update_generic('', revert=True)
        update_postfix('', '', revert=True)
        systemctl('postfix', 'restart')
        EmailClient.objects.all().delete()
        return Response()

Example 7

Project: rockstor-core
Source File: netatalk.py
View license
    @staticmethod
    def _refresh_and_reload(request):
        try:
            refresh_afp_config(list(NetatalkShare.objects.all()))
            return systemctl('netatalk', 'reload-or-restart')
        except Exception as e:
            e_msg = ('Failed to reload Netatalk server. Exception: %s' % e.__str__())
            handle_exception(Exception(e_msg), request)

Example 8

Project: rockstor-core
Source File: share.py
View license
    @staticmethod
    def _rockon_check(request, sname, force):
        s = Service.objects.get(name='docker')
        if (s.config is None):
            return

        config = json.loads(s.config)
        if (config.get('root_share') == sname):
            if (force):
                #turn off docker service, nullify config.
                systemctl(s.name, 'stop')
                systemctl(s.name, 'disable')
                s.config = None
                return s.save()
            e_msg = ('Share(%s) cannot be deleted because it is in use '
                     'by Rock-on service. If you must delete anyway, select '
                     'the force checkbox and try again.' % sname)
            handle_exception(Exception(e_msg), request)

Example 9

Project: rockstor-core
Source File: flash_optimize.py
View license
def fstrim_systemd():
    logging.debug('Setting up fstrim timer to run weekly once')
    with open(FSTRIM_SERVICE, 'w') as sfo:
        sfo.write('[Unit]\n')
        sfo.write('Description=Discard unused blocks\n\n')
        sfo.write('[Service]\n')
        sfo.write('Type=oneshot\n')
        sfo.write('ExecStart=/usr/sbin/fstrim -v /\n')
        sfo.write('ExecStart=/usr/sbin/fstrim -v /boot \n')
    logging.debug('Created %s' % FSTRIM_SERVICE)

    with open(FSTRIM_TIMER, 'w') as sto:
        sto.write('[Unit]\n')
        sto.write('Description=Discard unused blocks once a week\n')
        sto.write('Documentation=man:fstrim\n\n')
        sto.write('[Timer]\n')
        sto.write('OnCalendar=weekly\n')
        sto.write('AccuracySec=1h\n')
        sto.write('Persistent=true\n\n')
        sto.write('[Install]\n')
        sto.write('WantedBy=multi-user.target\n')
    logging.debug('Created %s' % FSTRIM_TIMER)

    service = '%s.timer' % FSTRIM_NAME
    systemctl(FSTRIM_NAME, 'enable')
    logging.info('Enabled %s' % FSTRIM_NAME)

Example 10

Project: rockstor-core
Source File: flash_optimize.py
View license
def main():
    loglevel = logging.INFO
    if (len(sys.argv) > 1 and sys.argv[1] == '-x'):
        loglevel = logging.DEBUG
    logging.basicConfig(format='%(asctime)s: %(message)s', level=loglevel)
    rd = root_disk()
    logging.debug('Root drive is %s' % rd)
    do_more = False
    if (trim_support(rd) is True):
        do_more = True
        logging.info('TRIM support is available for %s' % rd)
        fstrim_systemd()
        logging.debug('Finished setting up fstrim timer')
    do_more = do_more or is_flash(rd)

    if (do_more):
        update_sysctl()
        logging.info('updated sysctl')
        #emable tmpfs on /tmp
        tmpmnt = 'tmp.mount'
        systemctl(tmpmnt, 'enable')
        logging.info('enabled %s' % tmpmnt)
        systemctl(tmpmnt, 'start')
        logging.info('started %s' % tmpmnt)

        #mount stuff with noatime
        #add noatime to /, /home and /boot in /etc/fstab
        update_fstab()
        logging.info('updated fstab')
        for fs in ROOT_FS:
            run_command(['mount', fs, '-o', 'remount'])
            logging.info('remounted %s' % fs)

Example 11

Project: rockstor-core
Source File: active_directory.py
View license
    @staticmethod
    def _update_sssd(domain):
        #add enumerate = True in sssd so user/group lists will be
        #visible on the web-ui.
        el = 'enumerate = True\n'
        fh, npath = mkstemp()
        sssd_config = '/etc/sssd/sssd.conf'
        with open(sssd_config) as sfo, open(npath, 'w') as tfo:
            domain_section = False
            for line in sfo.readlines():
                if (domain_section is True):
                    if (len(line.strip()) == 0 or line[0] == '['):
                        #empty line or new section without empty line before it.
                        tfo.write(el)
                        domain_section = False
                elif (re.match('\[domain/%s]' % domain, line) is not None):
                    domain_section = True
                tfo.write(line)
            if (domain_section is True):
                #reached end of file, also coinciding with end of domain section
                tfo.write(el)
        shutil.move(npath, sssd_config)
        systemctl('sssd', 'restart')

Example 12

Project: rockstor-core
Source File: active_directory.py
View license
    @transaction.atomic
    def post(self, request, command):

        with self._handle_exception(request):
            method = 'winbind'
            service = Service.objects.get(name='active-directory')
            if (command == 'config'):
                config = request.data.get('config')
                self._validate_config(config, request)

                #1. Name resolution check
                self._resolve_check(config.get('domain'), request)

                #2. realm discover check?
                #@todo: phase our realm and just use net?
                domain = config.get('domain')
                try:
                    cmd = ['realm', 'discover', '--name-only', domain]
                    o, e, rc = run_command(cmd)
                except Exception, e:
                    e_msg = ('Failed to discover the given(%s) AD domain. '
                             'Error: %s' % (domain, e.__str__()))
                    handle_exception(Exception(e_msg), request)

                default_range = '10000 - 999999'
                idmap_range = config.get('idmap_range', '10000 - 999999')
                idmap_range = idmap_range.strip()
                if (len(idmap_range) > 0):
                    rfields = idmap_range.split()
                    if (len(rfields) != 3):
                        raise Exception('Invalid idmap range. valid format is '
                                        'two integers separated by a -. eg: '
                                        '10000 - 999999')
                    try:
                        rlow = int(rfields[0].strip())
                        rhigh = int(rfields[2].strip())
                    except Exception, e:
                        raise Exception('Invalid idmap range. Numbers in the '
                                        'range must be valid integers. '
                                        'Error: %s.' % e.__str__())
                    if (rlow >= rhigh):
                        raise Exception('Invalid idmap range. Numbers in the '
                                        'range must go from low to high. eg: '
                                        '10000 - 999999')
                else:
                    config['idmap_range'] = default_range

                self._save_config(service, config)

            elif (command == 'start'):
                config = self._config(service, request)
                smbo = Service.objects.get(name='smb')
                smb_config = self._get_config(smbo)
                domain = config.get('domain')
                #1. make sure ntpd is running, or else, don't start.
                self._ntp_check(request)
                #2. Name resolution check?
                self._resolve_check(config.get('domain'), request)

                if (method == 'winbind'):
                    cmd = ['/usr/sbin/authconfig', ]
                    #nss
                    cmd += ['--enablewinbind', '--enablewins',]
                    #pam
                    cmd += ['--enablewinbindauth',]
                    #smb
                    cmd += ['--smbsecurity', 'ads', '--smbrealm', domain.upper(),]
                    #kerberos
                    cmd += ['--krb5realm=%s' % domain.upper(),]
                    #winbind
                    cmd += ['--enablewinbindoffline', '--enablewinbindkrb5',
                            '--winbindtemplateshell=/bin/sh',]
                    #general
                    cmd += ['--update', '--enablelocauthorize',]
                    run_command(cmd)
                config['workgroup'] = self._domain_workgroup(domain, method=method)
                self._save_config(service, config)
                update_global_config(smb_config, config)
                self._join_domain(config, method=method)
                if (method == 'sssd' and config.get('enumerate') is True):
                    self._update_sssd(domain)

                if (method == 'winbind'):
                    systemctl('winbind', 'enable')
                    systemctl('winbind', 'start')
                systemctl('smb', 'restart')
                systemctl('nmb', 'restart')

            elif (command == 'stop'):
                config = self._config(service, request)
                try:
                    self._leave_domain(config, method=method)
                    smbo = Service.objects.get(name='smb')
                    smb_config = self._get_config(smbo)
                    update_global_config(smb_config)
                    systemctl('smb', 'restart')
                    systemctl('nmb', 'restart')
                except Exception, e:
                    e_msg = ('Failed to leave AD domain(%s). Error: %s' %
                             (config.get('domain'), e.__str__()))
                    handle_exception(Exception(e_msg), request)

            return Response()

Example 13

Project: rockstor-core
Source File: docker_service.py
View license
    @transaction.atomic
    def post(self, request, command):
        service = Service.objects.get(name=self.name)

        if (command == 'config'):
            config = request.data.get('config', None)
            root_share = config['root_share']
            self._validate_root(request, root_share)
            self._save_config(service, config)

        elif (command == 'start'):
            try:
                config = self._get_config(service)
            except:
                e_msg = ('Cannot start without configuration. '
                         'Please configure(System->Services) and try again.')
                handle_exception(Exception(e_msg), request)

            share = self._validate_root(request, config['root_share'])
            mnt_pt = ('%s%s' % (settings.MNT_PT, share.name))
            if (not is_share_mounted(share.name)):
                mount_share(share, mnt_pt)

            inf = ('%s/docker.service' % (settings.CONFROOT))
            outf = '/etc/systemd/system/docker.service'
            with open(inf) as ino, open(outf, 'w') as outo:
                for l in ino.readlines():
                    if (re.match('ExecStart=', l) is not None):
                        outo.write('%s %s\n' % (l.strip(), mnt_pt))
                    else:
                        outo.write(l)
            socket_file = ('%s/docker.socket' % (settings.CONFROOT))
            shutil.copy(socket_file, '/etc/systemd/system/docker.socket')
            systemctl(self.name, 'enable')
            systemctl(self.name, 'start')
        elif (command == 'stop'):
            systemctl(self.name, 'stop')
            systemctl(self.name, 'disable')
        return Response()

Example 14

Project: rockstor-core
Source File: nfs_service.py
View license
    @transaction.commit_on_success
    def post(self, request, command):
        """
        execute a command on the service
        """
        service = Service.objects.get(name='nfs')
        service_name = 'nfs-server'
        if (command == 'config'):
            #nothing to really configure atm. just save the model
            try:
                config = request.data['config']
                self._save_config(service, config)
            except Exception, e:
                e_msg = ('NFS could not be configured due to the following '
                         'exception. You could try again. %s' % e.__str__())
                handle_exception(Exception(e_msg), request)

        else:
            try:
                if (command == 'stop'):
                    systemctl(service_name, 'disable')
                    systemctl(service_name, 'stop')
                else:
                    systemctl(service_name, 'enable')
                    #chkconfig('rpcbind', 'on')
                    #init_service_op('rpcbind', command)
                    systemctl(service_name, 'restart')
                #init_service_op('nfs', command)
            except Exception, e:
                e_msg = ('Failed to %s NFS due to this error: %s' % (command, e.__str__()))
                handle_exception(Exception(e_msg), request)

        return Response()

Example 15

Project: rockstor-core
Source File: nut_service.py
View license
    @staticmethod
    def _switch_nut(switch, config):
        if switch == 'start':
            # empty config causes a type error before we get here, this we
            # catch and suggest settings but just in case we check here also.
            if not config:
                raise Exception("NUT un-configured; please configure first.")
            # don't start nut-server when in netclient mode.
            if config['mode'] == 'netclient':
                systemctl('nut-server', 'disable')
                systemctl('nut-server', 'stop')
            else:  # presumably starting in standalone or netserver mode
                systemctl('nut-server', 'enable')
                systemctl('nut-server', 'start')
            # in all three modes we always enable and reload nut-monitor
            systemctl('nut-monitor', 'enable')
            systemctl('nut-monitor', 'reload-or-restart')
        else:  # disable and stop monitor and server regardless of mode
            # just as well as config may have changed.
            systemctl('nut-monitor', 'disable')
            systemctl('nut-monitor', 'stop')
            systemctl('nut-server', 'disable')
            systemctl('nut-server', 'stop')

Example 16

Project: rockstor-core
Source File: samba_service.py
View license
    @transaction.commit_on_success
    def post(self, request, command):
        """
        execute a command on the service
        """
        service = Service.objects.get(name=self.service_name)
        
        if (command == 'config'):
            try:
                config = request.data.get('config', {})
                global_config = {}
                gc_lines = config['global_config'].split('\n')
                for l in gc_lines:
                    gc_param = l.strip().split('=')
                    if (len(gc_param) == 2):
                        global_config[gc_param[0].strip().lower()] = gc_param[1].strip()
                #Default set current workgroup to one got via samba config page
                global_config['workgroup'] = config['workgroup']
                #Check Active Directory config and status
                #if AD configured and ON set workgroup to AD retrieved workgroup
                #else AD not running and leave workgroup to one choosen by user
                adso = Service.objects.get(name='active-directory')
                adconfig = {}
                adso_status = 1
                if (adso.config is not None):
                    adconfig = self._get_config(adso)
                    adso_out, adso_err, adso_status = service_status('active-directory', adconfig)
                    if adso_status == 0:
                        global_config['workgroup'] = adconfig['workgroup']
                    else:
                        adconfig = None

                self._save_config(service, global_config)
                update_global_config(global_config, adconfig)
                restart_samba(hard=True)
            except Exception, e:
                e_msg = ('Samba could not be configured. Try again. '
                         'Exception: %s' % e.__str__())
                handle_exception(Exception(e_msg), request)
        else:
            try:
                if (command == 'stop'):
                    systemctl('smb', 'disable')
                    systemctl('nmb', 'disable')
                else:
                    systemd_name = '%s.service' % self.service_name
                    ss_dest = ('/etc/systemd/system/%s' % systemd_name)
                    ss_src = ('%s/%s' % (settings.CONFROOT, systemd_name))
                    sum1 = md5sum(ss_dest)
                    sum2 = md5sum(ss_src)
                    if (sum1 != sum2):
                        shutil.copy(ss_src, ss_dest)
                    systemctl('smb', 'enable')
                    systemctl('nmb', 'enable')
                systemctl('nmb', command)
                systemctl('smb', command)
            except Exception, e:
                e_msg = ('Failed to %s samba due to a system error: %s' % (command, e.__str__()))
                handle_exception(Exception(e_msg), request)
        return Response()

Example 17

View license
    def post(self, request, command):
        service = Service.objects.get(name=self.name)

        if (command == 'config'):
            config = request.data.get('config')
            self._save_config(service, config)
            shelltype = config.get('shelltype')
            css = config.get('css')
            update_shell_config(shelltype, css)
            restart_shell()
            
        elif (command == 'start'):
            systemctl(self.name, 'enable')
            systemctl(self.name, 'start')

        elif (command == 'stop'):
            systemctl(self.name, 'stop')
            systemctl(self.name, 'disable')
        
        return Response()

Example 18

Project: rockstor-core
Source File: smartd_service.py
View license
    @transaction.commit_on_success
    def post(self, request, command):
        """
        execute a command on the service
        """
        e_msg = ('Failed to %s S.M.A.R.T service due to system error.' %
                 command)
        with self._handle_exception(request, e_msg):
            if (not os.path.exists(SMART)):
                install_pkg('smartmontools')
            if (command == 'config'):
                service = Service.objects.get(name=self.service_name)
                config = request.DATA.get('config', {})
                logger.debug('config = %s' % config)
                self._save_config(service, config)
                if ('custom_config' in config):
                    config = config['custom_config']
                else:
                    config = ''
                smart.update_config(config)
                systemctl(self.service_name, 'enable')
                systemctl(self.service_name, 'restart')
            else:
                self._switch(command)
        return Response()

Example 19

Project: rockstor-core
Source File: command.py
View license
    @transaction.atomic
    def post(self, request, command):
        if (command == 'bootstrap'):

            self._refresh_pool_state()
            for p in Pool.objects.all():
                import_shares(p, request)

            for share in Share.objects.all():
                try:
                    if (share.pqgroup == settings.MODEL_DEFS['pqgroup']):
                        share.pqgroup = qgroup_create(share.pool)
                        share.save()
                    if (not is_share_mounted(share.name)):
                        mnt_pt = ('%s%s' % (settings.MNT_PT, share.name))
                        mount_share(share, mnt_pt)
                except Exception, e:
                    e_msg = ('Exception while mounting a share(%s) during '
                             'bootstrap: %s' % (share.name, e.__str__()))
                    logger.error(e_msg)
                    logger.exception(e)

                try:
                    import_snapshots(share)
                except Exception, e:
                    e_msg = ('Exception while importing Snapshots of '
                             'Share(%s): %s' % (share.name, e.__str__()))
                    logger.error(e_msg)
                    logger.exception(e)

            for snap in Snapshot.objects.all():
                if (snap.uvisible):
                    try:
                        mount_snap(snap.share, snap.real_name)
                    except Exception, e:
                        e_msg = ('Failed to make the Snapshot(%s) visible. '
                                 'Exception: %s' % (snap.real_name, e.__str__()))
                        logger.error(e_msg)

            mnt_map = sftp_mount_map(settings.SFTP_MNT_ROOT)
            for sftpo in SFTP.objects.all():
                try:
                    sftp_mount(sftpo.share, settings.MNT_PT,
                               settings.SFTP_MNT_ROOT, mnt_map, sftpo.editable)
                    sftp_snap_toggle(sftpo.share)
                except Exception, e:
                    e_msg = ('Exception while exportin a sftp share during '
                             'bootstrap: %s' % e.__str__())
                    logger.error(e_msg)

            try:
                adv_entries = [a.export_str for a in AdvancedNFSExport.objects.all()]
                exports_d = self.create_adv_nfs_export_input(adv_entries, request)
                exports = self.create_nfs_export_input(NFSExport.objects.all())
                exports.update(exports_d)
                self.refresh_wrapper(exports, request, logger)
            except Exception, e:
                e_msg = ('Exception while bootstrapping NFS: %s' % e.__str__())
                logger.error(e_msg)

            #  bootstrap services
            try:
                systemctl('firewalld', 'stop')
                systemctl('firewalld', 'disable')
                systemctl('nginx', 'stop')
                systemctl('nginx', 'disable')
                systemctl('atd', 'enable')
                systemctl('atd', 'start')
            except Exception, e:
                e_msg = ('Exception while setting service statuses during '
                         'bootstrap: %s' % e.__str__())
                logger.error(e_msg)
                handle_exception(Exception(e_msg), request)

            logger.debug('Bootstrap operations completed')
            return Response()

        if (command == 'utcnow'):
            return Response(datetime.utcnow().replace(tzinfo=utc))

        if (command == 'uptime'):
            return Response(uptime())

        if (command == 'kernel'):
            try:
                return Response(kernel_info(settings.SUPPORTED_KERNEL_VERSION))
            except Exception, e:
                handle_exception(e, request)

        if (command == 'update-check'):
            try:
                subo = None
                try:
                    subo = UpdateSubscription.objects.get(name='Stable', status='active')
                except UpdateSubscription.DoesNotExist:
                    try:
                        subo = UpdateSubscription.objects.get(name='Testing', status='active')
                    except UpdateSubscription.DoesNotExist:
                        pass
                return Response(update_check(subscription=subo))
            except Exception, e:
                e_msg = ('Unable to check update due to a system error: %s' % e.__str__())
                handle_exception(Exception(e_msg), request)

        if (command == 'update'):
            try:
                update_run()
                return Response('Done')
            except Exception, e:
                e_msg = ('Update failed due to this exception: %s' % e.__str__())
                handle_exception(Exception(e_msg), request)

        if (command == 'current-version'):
            try:
                return Response(current_version())
            except Exception, e:
                e_msg = ('Unable to check current version due to this '
                         'exception: ' % e.__str__())
                handle_exception(Exception(e_msg), request)

        if (command == 'shutdown'):
            msg = ('The system will now be shutdown')
            try:
                request.session.flush()
                system_shutdown()
            except Exception, e:
                msg = ('Failed to shutdown the system due to a low level '
                       'error: %s' % e.__str__())
                handle_exception(Exception(msg), request)
            finally:
                return Response(msg)

        if (command == 'reboot'):
            msg = ('The system will now reboot')
            try:
                request.session.flush()
                system_reboot()
            except Exception, e:
                msg = ('Failed to reboot the system due to a low level error: '
                       '%s' % e.__str__())
                handle_exception(Exception(msg), request)
            finally:
                return Response(msg)

        if (command == 'current-user'):
            return Response(request.user.username)

        if (command == 'auto-update-status'):
            status = True
            try:
                status = auto_update_status()
            except:
                status = False
            finally:
                return Response({'enabled': status, })

        if (command == 'enable-auto-update'):
            try:
                auto_update(enable=True)
                return Response({'enabled': True, })
            except Exception, e:
                msg = ('Failed to enable auto update due to this exception: '
                       '%s' % e.__str__())
                handle_exception(Exception(msg), request)

        if (command == 'disable-auto-update'):
            try:
                auto_update(enable=False)
                return Response({'enabled': False, })
            except Exception, e:
                msg = ('Failed to disable auto update due to this exception:  '
                       '%s' % e.__str__())
                handle_exception(Exception(msg), request)

        if (command == 'refresh-pool-state'):
            self._refresh_pool_state()
            return Response()

        if (command == 'refresh-share-state'):
            for p in Pool.objects.all():
                import_shares(p, request)
            return Response()

        if (command == 'refresh-snapshot-state'):
            for share in Share.objects.all():
                import_snapshots(share)
            return Response()

Example 20

Project: rockstor-core
Source File: email_client.py
View license
    @transaction.atomic
    def post(self, request, command=None):
        with self._handle_exception(request):

            commands_list = ['send-test-email', 'check-smtp-auth']
            if (command is not None):
                if (command not in commands_list):
                    e_msg = ('unknown command(%s) is not supported.' %
                             command)
                    handle_exception(Exception(e_msg), request)
                    
                if (command == 'send-test-email'):
                    if (EmailClient.objects.count() == 0):
                        e_msg = ('E-mail account must be setup first before test '
                                 'e-mail could be sent')
                        handle_exception(Exception(e_msg), request)

                    eco = EmailClient.objects.all()[0]
                    subject = ('Test message from Rockstor. Appliance id: %s' %
                               Appliance.objects.get(current_appliance=True).uuid)
                    send_test_email(eco, subject)
                    return Response()
                    
                elif (command == 'check-smtp-auth'):
                    mail_auth = {}
                    sender = request.data.get('sender')
                    username = request.data.get('username')
                    mail_auth['username'] = sender if not username else username 
                    mail_auth['password'] = request.data.get('password')
                    mail_auth['smtp_server'] = request.data.get('smtp_server')
                    mail_auth['port'] = int(request.data.get('port', 587))
                    
                    return Response(json.dumps({'smtp_auth': test_smtp_auth(mail_auth)}), content_type="application/json")
                    

            sender = request.data.get('sender')
            username = request.data.get('username') #collect new username field
            username = sender if not username else username #smtp auth - use username or if empty use sender
            smtp_server = request.data.get('smtp_server')
            port = int(request.data.get('port', 587))
            name = request.data.get('name')
            password = request.data.get('password')
            receiver = request.data.get('receiver')
            eco = EmailClient(smtp_server=smtp_server, port=port, name=name,
                              sender=sender, receiver=receiver, username=username)
            eco.save()
            update_sasl(smtp_server, port, username, password)
            update_forward(receiver)
            update_generic(sender)
            update_postfix(smtp_server, port)
            systemctl('postfix', 'restart')
            return Response(EmailClientSerializer(eco).data)

Example 21

Project: rockstor-core
Source File: netatalk.py
View license
    @transaction.atomic
    def post(self, request):
        if ('shares' not in request.data):
            e_msg = ('Must provide share names')
            handle_exception(Exception(e_msg), request)

        shares = [validate_share(s, request) for s in request.data['shares']]
        description = request.data.get('description', '')
        if (description == ''):
            description = self.def_description

        time_machine = request.data.get('time_machine', 'yes')
        if (time_machine != 'yes' and time_machine != 'no'):
            e_msg = ('time_machine must be yes or no. not %s' %
                     time_machine)
            handle_exception(Exception(e_msg), request)

        for share in shares:
            if (NetatalkShare.objects.filter(share=share).exists()):
                e_msg = ('Share(%s) is already exported via AFP' % share.name)
                handle_exception(Exception(e_msg), request)

        try:
            for share in shares:
                mnt_pt = ('%s%s' % (settings.MNT_PT, share.name))
                cur_description = '%s %s' % (share.name, description)
                if (len(shares) == 1 and description != self.def_description):
                    cur_description = description
                afpo = NetatalkShare(share=share, path=mnt_pt,
                                     description=cur_description,
                                     time_machine=time_machine)
                afpo.save()
                if (not is_share_mounted(share.name)):
                    mount_share(share, mnt_pt)
            refresh_afp_config(list(NetatalkShare.objects.all()))
            systemctl('netatalk', 'reload-or-restart')
            return Response()
        except RockStorAPIException:
            raise
        except Exception as e:
            handle_exception(e, request)