Esempio n. 1
0
import apt
import apt.progress

from moulinette.core import MoulinetteError, init_authenticator
from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_info, app_upgrade, app_ssowatconf, app_list
from yunohost.domain import domain_add, domain_list, get_public_ip
from yunohost.dyndns import dyndns_subscribe
from yunohost.firewall import firewall_upnp, firewall_reload
from yunohost.service import service_status, service_regen_conf, service_log
from yunohost.monitor import monitor_disk, monitor_network, monitor_system
from yunohost.utils.packages import ynh_packages_version

apps_setting_path = '/etc/yunohost/apps/'

logger = getActionLogger('yunohost.tools')


def tools_ldapinit(auth):
    """
    YunoHost LDAP initialization


    """
    with open('/usr/share/yunohost/yunohost-config/moulinette/ldap_scheme.yml'
              ) as f:
        ldap_map = yaml.load(f)

    for rdn, attr_dict in ldap_map['parents'].items():
        try:
            auth.add(rdn, attr_dict)
Esempio n. 2
0
import sys
import datetime
import re
import shutil
import json
import yaml
import errno
import requests
from urllib import urlopen

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

from yunohost.service import service_regen_conf

logger = getActionLogger('yunohost.domain')


def domain_list(auth, filter=None, limit=None, offset=None):
    """
    List domains

    Keyword argument:
        filter -- LDAP filter used to search
        offset -- Starting number for domain fetching
        limit -- Maximum number of domain fetched

    """
    result_list = []

    # Set default arguments values
Esempio n. 3
0
from moulinette.utils import filesystem
from moulinette.utils.log import getActionLogger

from yunohost.app import (
    app_info, app_ssowatconf, _is_installed, _parse_app_instance_name
)
from yunohost.hook import (
    hook_info, hook_callback, hook_exec, custom_hook_folder
)
from yunohost.monitor import binary_to_human
from yunohost.tools import tools_postinstall

backup_path   = '/home/yunohost.backup'
archives_path = '%s/archives' % backup_path

logger = getActionLogger('yunohost.backup')


def backup_create(name=None, description=None, output_directory=None,
                  no_compress=False, ignore_hooks=False, hooks=[],
                  ignore_apps=False, apps=[]):
    """
    Create a backup local archive

    Keyword arguments:
        name -- Name of the backup archive
        description -- Short description of the backup
        output_directory -- Output directory for the backup
        no_compress -- Do not create an archive file
        hooks -- List of backup hooks names to execute
        ignore_hooks -- Do not execute backup hooks
Esempio n. 4
0
""" yunohost_permission.py

    Manage permissions
"""

import re
import copy
import grp
import random

from moulinette import m18n
from moulinette.utils.log import getActionLogger
from yunohost.utils.error import YunohostError
from yunohost.log import is_unit_operation

logger = getActionLogger('yunohost.user')

SYSTEM_PERMS = ["mail", "xmpp", "sftp", "ssh"]

#
#
#  The followings are the methods exposed through the "yunohost user permission" interface
#
#


def user_permission_list(short=False,
                         full=False,
                         ignore_system_perms=False,
                         absolute_urls=False):
    """
Esempio n. 5
0
from datetime import datetime

from moulinette import m18n
from moulinette.utils import log, filesystem
from moulinette.utils.process import check_output

from yunohost.utils.error import YunohostError
from yunohost.log import is_unit_operation
from yunohost.hook import hook_callback, hook_list

BASE_CONF_PATH = "/home/yunohost.conf"
BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, "backup")
PENDING_CONF_DIR = os.path.join(BASE_CONF_PATH, "pending")
REGEN_CONF_FILE = "/etc/yunohost/regenconf.yml"

logger = log.getActionLogger("yunohost.regenconf")


# FIXME : those ain't just services anymore ... what are we supposed to do with this ...
# FIXME : check for all reference of 'service' close to operation_logger stuff
@is_unit_operation([("names", "configuration")])
def regen_conf(
    operation_logger,
    names=[],
    with_diff=False,
    force=False,
    dry_run=False,
    list_pending=False,
):
    """
    Regenerate the configuration file(s)
Esempio n. 6
0
from datetime import datetime

from moulinette import m18n
from moulinette.utils import log, filesystem
from moulinette.utils.process import check_output

from yunohost.utils.error import YunohostError
from yunohost.log import is_unit_operation
from yunohost.hook import hook_callback, hook_list

BASE_CONF_PATH = '/home/yunohost.conf'
BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, 'backup')
PENDING_CONF_DIR = os.path.join(BASE_CONF_PATH, 'pending')
REGEN_CONF_FILE = '/etc/yunohost/regenconf.yml'

logger = log.getActionLogger('yunohost.regenconf')


# FIXME : those ain't just services anymore ... what are we supposed to do with this ...
# FIXME : check for all reference of 'service' close to operation_logger stuff
@is_unit_operation([('names', 'configuration')])
def regen_conf(operation_logger,
               names=[],
               with_diff=False,
               force=False,
               dry_run=False,
               list_pending=False):
    """
    Regenerate the configuration file(s)

    Keyword argument:
Esempio n. 7
0
import grp
import crypt
import random
import string
import subprocess
import copy

from moulinette import msignals, msettings, m18n
from moulinette.utils.log import getActionLogger
from moulinette.utils.process import check_output

from yunohost.utils.error import YunohostError
from yunohost.service import service_status
from yunohost.log import is_unit_operation

logger = getActionLogger("yunohost.user")


def user_list(fields=None):

    from yunohost.utils.ldap import _get_ldap_interface

    user_attrs = {
        "uid": "username",
        "cn": "fullname",
        "mail": "mail",
        "maildrop": "mail-forward",
        "loginShell": "shell",
        "homeDirectory": "home_path",
        "mailuserquota": "mailbox-quota",
    }
Esempio n. 8
0
import re
import sys
import tempfile
import mimetypes
from glob import iglob
from importlib import import_module

from moulinette import m18n, msettings
from yunohost.utils.error import YunohostError
from moulinette.utils import log
from moulinette.utils.filesystem import read_json

HOOK_FOLDER = "/usr/share/yunohost/hooks/"
CUSTOM_HOOK_FOLDER = "/etc/yunohost/hooks.d/"

logger = log.getActionLogger("yunohost.hook")


def hook_add(app, file):
    """
    Store hook script to filsystem

    Keyword argument:
        app -- App to link with
        file -- Script to add (/path/priority-file)

    """
    path, filename = os.path.split(file)
    priority, action = _extract_filename_parts(filename)

    try:
Esempio n. 9
0
import os
import json
import subprocess

from datetime import datetime
from collections import OrderedDict

from moulinette import m18n
from yunohost.utils.error import YunohostError, YunohostValidationError
from moulinette.utils.log import getActionLogger
from yunohost.regenconf import regen_conf
from yunohost.firewall import firewall_reload

logger = getActionLogger("yunohost.settings")

SETTINGS_PATH = "/etc/yunohost/settings.json"
SETTINGS_PATH_OTHER_LOCATION = "/etc/yunohost/settings-%s.json"


def is_boolean(value):
    """
    Ensure a string value is intended as a boolean

    Keyword arguments:
        arg -- The string to check

    Returns:
        (is_boolean, boolean_value)

    """
    if isinstance(value, bool):
Esempio n. 10
0
import calendar
import subprocess
import xmlrpclib
import os.path
import errno
import os
import dns.resolver
import cPickle as pickle
from datetime import datetime, timedelta

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

from yunohost.domain import get_public_ip

logger = getActionLogger('yunohost.monitor')

glances_uri = 'http://127.0.0.1:61209'
stats_path = '/var/lib/yunohost/stats'
crontab_path = '/etc/cron.d/yunohost-monitor'


def monitor_disk(units=None, mountpoint=None, human_readable=False):
    """
    Monitor disk space and usage

    Keyword argument:
        units -- Unit(s) to monitor
        mountpoint -- Device mountpoint
        human_readable -- Print sizes in human readable format
Esempio n. 11
0
import subprocess

from moulinette import m18n
from yunohost.utils.error import YunohostError
from moulinette.utils.log import getActionLogger

from yunohost.tools import Migration
from yunohost.utils.filesystem import free_space_in_directory, space_used_by_directory

logger = getActionLogger('yunohost.migration')


class MyMigration(Migration):

    "Migrate DBs from Postgresql 9.6 to 11 after migrating to Buster"

    dependencies = ["migrate_to_buster"]

    def run(self):

        if not self.package_is_installed("postgresql-9.6"):
            logger.warning(m18n.n("migration_0017_postgresql_96_not_installed"))
            return

        if not self.package_is_installed("postgresql-11"):
            raise YunohostError("migration_0017_postgresql_11_not_installed")

        # Make sure there's a 9.6 cluster
        try:
            self.runcmd("pg_lsclusters | grep -q '^9.6 '")
        except Exception:
Esempio n. 12
0
from datetime import datetime

from moulinette import m18n
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file

from yunohost.vendor.acme_tiny.acme_tiny import get_crt as sign_certificate
from yunohost.utils.error import YunohostError
from yunohost.utils.network import get_public_ip

from yunohost.diagnosis import Diagnoser
from yunohost.service import _run_service_command
from yunohost.regenconf import regen_conf
from yunohost.log import OperationLogger

logger = getActionLogger('yunohost.certmanager')

CERT_FOLDER = "/etc/yunohost/certs/"
TMP_FOLDER = "/tmp/acme-challenge-private/"
WEBROOT_FOLDER = "/tmp/acme-challenge-public/"

SELF_CA_FILE = "/etc/ssl/certs/ca-yunohost_crt.pem"
ACCOUNT_KEY_FILE = "/etc/yunohost/letsencrypt_account.pem"

SSL_DIR = '/usr/share/yunohost/yunohost-config/ssl/yunoCA'

KEY_SIZE = 3072

VALIDITY_LIMIT = 15  # days

# For tests
Esempio n. 13
0
from logging import FileHandler, getLogger, Formatter

from moulinette import m18n, msettings
from moulinette.core import MoulinetteError
from yunohost.utils.error import YunohostError
from yunohost.utils.packages import get_ynh_package_version
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file, read_yaml

CATEGORIES_PATH = '/var/log/yunohost/categories/'
OPERATIONS_PATH = '/var/log/yunohost/categories/operation/'
METADATA_FILE_EXT = '.yml'
LOG_FILE_EXT = '.log'
RELATED_CATEGORIES = ['app', 'domain', 'group', 'service', 'user']

logger = getActionLogger('yunohost.log')


def log_list(limit=None, with_details=False, with_suboperations=False):
    """
    List available logs

    Keyword argument:
        limit -- Maximum number of logs
        with_details -- Include details (e.g. if the operation was a success).
        Likely to increase the command time as it needs to open and parse the
        metadata file for each log...
        with_suboperations -- Include operations that are not the "main"
        operation but are sub-operations triggered by another ongoing operation
        ... (e.g. initializing groups/permissions when installing an app)
    """
Esempio n. 14
0
import glob
import base64
import subprocess

from moulinette import m18n
from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import write_to_file, read_file
from moulinette.utils.network import download_json

from yunohost.utils.error import YunohostError
from yunohost.domain import _get_maindomain, _build_dns_conf
from yunohost.utils.network import get_public_ip, dig
from yunohost.log import is_unit_operation

logger = getActionLogger("yunohost.dyndns")

DYNDNS_ZONE = "/etc/yunohost/dyndns/zone"

RE_DYNDNS_PRIVATE_KEY_MD5 = re.compile(r".*/K(?P<domain>[^\s\+]+)\.\+157.+\.private$")

RE_DYNDNS_PRIVATE_KEY_SHA512 = re.compile(
    r".*/K(?P<domain>[^\s\+]+)\.\+165.+\.private$"
)


def _dyndns_provides(provider, domain):
    """
    Checks if a provider provide/manage a given domain.

    Keyword arguments:
Esempio n. 15
0
import errno
try:
    import miniupnpc
except ImportError:
    sys.stderr.write('Error: Yunohost CLI Require miniupnpc lib\n')
    sys.exit(1)

from moulinette.core import MoulinetteError
from moulinette.utils import process
from moulinette.utils.log import getActionLogger
from moulinette.utils.text import prependlines

firewall_file = '/etc/yunohost/firewall.yml'
upnp_cron_job = '/etc/cron.d/yunohost-firewall-upnp'

logger = getActionLogger('yunohost.firewall')


def firewall_allow(port, protocol='TCP', ipv4_only=False, ipv6_only=False,
                   no_upnp=False, no_reload=False):
    """
    Allow connections on a port

    Keyword arguments:
        port -- Port or range of ports to open
        protocol -- Protocol type to allow (default: TCP)
        ipv4_only -- Only add a rule for IPv4 connections
        ipv6_only -- Only add a rule for IPv6 connections
        no_upnp -- Do not add forwarding of this port with UPnP
        no_reload -- Do not reload firewall rules
Esempio n. 16
0
""" yunohost_hook.py

    Manage hooks
"""
import os
import re
import errno
from glob import iglob

from moulinette.core import MoulinetteError
from moulinette.utils import log

hook_folder = '/usr/share/yunohost/hooks/'
custom_hook_folder = '/etc/yunohost/hooks.d/'

logger = log.getActionLogger('yunohost.hook')


def hook_add(app, file):
    """
    Store hook script to filsystem

    Keyword argument:
        app -- App to link with
        file -- Script to add (/path/priority-file)

    """
    path, filename = os.path.split(file)
    priority, action = _extract_filename_parts(filename)

    try:
Esempio n. 17
0
"""
import os
import sys
import re
import json
import errno
import subprocess
from glob import iglob

from moulinette.core import MoulinetteError
from moulinette.utils import log

hook_folder = '/usr/share/yunohost/hooks/'
custom_hook_folder = '/etc/yunohost/hooks.d/'

logger = log.getActionLogger('yunohost.hook')


def hook_add(app, file):
    """
    Store hook script to filsystem

    Keyword argument:
        app -- App to link with
        file -- Script to add (/path/priority-file)

    """
    path, filename = os.path.split(file)
    priority, action = _extract_filename_parts(filename)

    try: os.listdir(custom_hook_folder + action)
Esempio n. 18
0
import time
import yaml
import subprocess

from glob import glob
from datetime import datetime

from moulinette import m18n
from yunohost.utils.error import YunohostError
from moulinette.utils.process import check_output
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file, append_to_file, write_to_file

MOULINETTE_LOCK = "/var/run/moulinette_yunohost.lock"

logger = getActionLogger('yunohost.service')


def service_add(name, description=None, log=None, log_type=None, test_status=None, test_conf=None, needs_exposed_ports=None, need_lock=False, status=None):
    """
    Add a custom service

    Keyword argument:
        name -- Service name to add
        description -- description of the service
        log -- Absolute path to log file to display
        log_type -- (deprecated) Specify if the corresponding log is a file or a systemd log
        test_status -- Specify a custom bash command to check the status of the service. N.B. : it only makes sense to specify this if the corresponding systemd service does not return the proper information.
        test_conf -- Specify a custom bash command to check if the configuration of the service is valid or broken, similar to nginx -t.
        needs_exposed_ports -- A list of ports that needs to be publicly exposed for the service to work as intended.
        need_lock -- Use this option to prevent deadlocks if the service does invoke yunohost commands.
Esempio n. 19
0
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import write_to_json, read_yaml

from yunohost.user import user_list
from yunohost.app import (
    _installed_apps,
    _get_app_settings,
    _set_app_settings,
)
from yunohost.permission import (
    permission_create,
    user_permission_update,
    permission_sync_to_user,
)

logger = getActionLogger("yunohost.legacy")

LEGACY_PERMISSION_LABEL = {
    ("nextcloud", "skipped"): "api",  # .well-known
    ("libreto", "skipped"): "pad access",  # /[^/]+
    ("leed", "skipped"): "api",  # /action.php, for cron task ...
    ("mailman", "protected"): "admin",  # /admin
    ("prettynoemiecms", "protected"): "admin",  # /admin
    ("etherpad_mypads", "skipped"): "admin",  # /admin
    ("baikal", "protected"): "admin",  # /admin/
    ("couchpotato", "unprotected"): "api",  # /api
    ("freshrss", "skipped"): "api",  # /api/,
    ("portainer", "skipped"): "api",  # /api/webhooks/
    ("jeedom", "unprotected"): "api",  # /core/api/jeeApi.php
    ("bozon", "protected"): "user interface",  # /index.php
    (
Esempio n. 20
0
import os
import re
import sys
import json
import errno
import time
import shutil
import tarfile

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

backup_path   = '/home/yunohost.backup'
archives_path = '%s/archives' % backup_path

logger = getActionLogger('yunohost.backup')


def backup_create(name=None, description=None, output_directory=None,
                  no_compress=False, ignore_apps=False):
    """
    Create a backup local archive

    Keyword arguments:
        name -- Name of the backup archive
        description -- Short description of the backup
        output_directory -- Output directory for the backup
        no_compress -- Do not create an archive file
        ignore_apps -- Do not backup apps

    """
Esempio n. 21
0
    Manage firewall rules
"""
import os
import yaml
import miniupnpc

from moulinette import m18n
from yunohost.utils.error import YunohostError, YunohostValidationError
from moulinette.utils import process
from moulinette.utils.log import getActionLogger
from moulinette.utils.text import prependlines

FIREWALL_FILE = "/etc/yunohost/firewall.yml"
UPNP_CRON_JOB = "/etc/cron.d/yunohost-firewall-upnp"

logger = getActionLogger("yunohost.firewall")


def firewall_allow(
    protocol, port, ipv4_only=False, ipv6_only=False, no_upnp=False, no_reload=False
):
    """
    Allow connections on a port

    Keyword arguments:
        protocol -- Protocol type to allow (TCP/UDP/Both)
        port -- Port or range of ports to open
        ipv4_only -- Only add a rule for IPv4 connections
        ipv6_only -- Only add a rule for IPv6 connections
        no_upnp -- Do not add forwarding of this port with UPnP
        no_reload -- Do not reload firewall rules
Esempio n. 22
0
import apt
import apt.progress

from moulinette.core import MoulinetteError, init_authenticator
from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_info, app_upgrade, app_ssowatconf, app_list
from yunohost.domain import domain_add, domain_list, get_public_ip
from yunohost.dyndns import dyndns_subscribe
from yunohost.firewall import firewall_upnp, firewall_reload
from yunohost.service import service_status, service_regen_conf, service_log
from yunohost.monitor import monitor_disk, monitor_network, monitor_system
from yunohost.utils.packages import ynh_packages_version

apps_setting_path= '/etc/yunohost/apps/'

logger = getActionLogger('yunohost.tools')


def tools_ldapinit(auth):
    """
    YunoHost LDAP initialization


    """
    with open('/usr/share/yunohost/yunohost-config/moulinette/ldap_scheme.yml') as f:
        ldap_map = yaml.load(f)

    for rdn, attr_dict in ldap_map['parents'].items():
        try: auth.add(rdn, attr_dict)
        except: pass
Esempio n. 23
0
from datetime import datetime

from moulinette import m18n
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file

from yunohost.vendor.acme_tiny.acme_tiny import get_crt as sign_certificate
from yunohost.utils.error import YunohostError, YunohostValidationError
from yunohost.utils.network import get_public_ip

from yunohost.diagnosis import Diagnoser
from yunohost.service import _run_service_command
from yunohost.regenconf import regen_conf
from yunohost.log import OperationLogger

logger = getActionLogger("yunohost.certmanager")

CERT_FOLDER = "/etc/yunohost/certs/"
TMP_FOLDER = "/tmp/acme-challenge-private/"
WEBROOT_FOLDER = "/tmp/acme-challenge-public/"

SELF_CA_FILE = "/etc/ssl/certs/ca-yunohost_crt.pem"
ACCOUNT_KEY_FILE = "/etc/yunohost/letsencrypt_account.pem"

SSL_DIR = "/usr/share/yunohost/yunohost-config/ssl/yunoCA"

KEY_SIZE = 3072

VALIDITY_LIMIT = 15  # days

# For tests
Esempio n. 24
0
from yunohost.utils.error import YunohostError
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import write_to_file

from yunohost.app import (
    app_ssowatconf,
    _installed_apps,
    _get_app_settings,
    _get_conflicting_apps,
)
from yunohost.regenconf import regen_conf, _force_clear_hashes, _process_regen_conf
from yunohost.utils.network import get_public_ip
from yunohost.log import is_unit_operation
from yunohost.hook import hook_callback

logger = getActionLogger("yunohost.domain")


def domain_list(exclude_subdomains=False):
    """
    List domains

    Keyword argument:
        exclude_subdomains -- Filter out domains that are subdomains of other declared domains

    """
    from yunohost.utils.ldap import _get_ldap_interface

    ldap = _get_ldap_interface()
    result = [
        entry["virtualdomain"][0]
Esempio n. 25
0
import os
import time

from moulinette import m18n, msettings
from moulinette.utils import log
from moulinette.utils.filesystem import (
    read_json,
    write_to_json,
    read_yaml,
    write_to_yaml,
)

from yunohost.utils.error import YunohostError, YunohostValidationError
from yunohost.hook import hook_list, hook_exec

logger = log.getActionLogger("yunohost.diagnosis")

DIAGNOSIS_CACHE = "/var/cache/yunohost/diagnosis/"
DIAGNOSIS_CONFIG_FILE = "/etc/yunohost/diagnosis.yml"
DIAGNOSIS_SERVER = "diagnosis.yunohost.org"


def diagnosis_list():
    all_categories_names = [h for h, _ in _list_diagnosis_categories()]
    return {"categories": all_categories_names}


def diagnosis_get(category, item):

    # Get all the categories
    all_categories = _list_diagnosis_categories()
Esempio n. 26
0
from yunohost.firewall import firewall_upnp
from yunohost.service import service_start, service_enable
from yunohost.regenconf import regen_conf
from yunohost.utils.packages import (
    _dump_sources_list,
    _list_upgradable_apt_packages,
    ynh_packages_version,
)
from yunohost.utils.error import YunohostError, YunohostValidationError
from yunohost.log import is_unit_operation, OperationLogger

# FIXME this is a duplicate from apps.py
APPS_SETTING_PATH = "/etc/yunohost/apps/"
MIGRATIONS_STATE_PATH = "/etc/yunohost/migrations.yaml"

logger = getActionLogger("yunohost.tools")


def tools_versions():
    return ynh_packages_version()


def tools_adminpw(new_password, check_strength=True):
    """
    Change admin password

    Keyword argument:
        new_password

    """
    from yunohost.user import _hash_user_password
Esempio n. 27
0
import time
import yaml
import subprocess

from glob import glob
from datetime import datetime

from moulinette import m18n
from yunohost.utils.error import YunohostError, YunohostValidationError
from moulinette.utils.process import check_output
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file, append_to_file, write_to_file

MOULINETTE_LOCK = "/var/run/moulinette_yunohost.lock"

logger = getActionLogger("yunohost.service")


def service_add(
    name,
    description=None,
    log=None,
    log_type=None,
    test_status=None,
    test_conf=None,
    needs_exposed_ports=None,
    need_lock=False,
    status=None,
):
    """
    Add a custom service
Esempio n. 28
0
from logging import FileHandler, getLogger, Formatter

from moulinette import m18n, msettings
from moulinette.core import MoulinetteError
from yunohost.utils.error import YunohostError, YunohostValidationError
from yunohost.utils.packages import get_ynh_package_version
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file, read_yaml

CATEGORIES_PATH = "/var/log/yunohost/categories/"
OPERATIONS_PATH = "/var/log/yunohost/categories/operation/"
METADATA_FILE_EXT = ".yml"
LOG_FILE_EXT = ".log"
RELATED_CATEGORIES = ["app", "domain", "group", "service", "user"]

logger = getActionLogger("yunohost.log")


def log_list(limit=None, with_details=False, with_suboperations=False):
    """
    List available logs

    Keyword argument:
        limit -- Maximum number of logs
        with_details -- Include details (e.g. if the operation was a success).
        Likely to increase the command time as it needs to open and parse the
        metadata file for each log...
        with_suboperations -- Include operations that are not the "main"
        operation but are sub-operations triggered by another ongoing operation
        ... (e.g. initializing groups/permissions when installing an app)
    """
Esempio n. 29
0
import os
import subprocess

from moulinette import m18n
from yunohost.utils.error import YunohostError
from moulinette.utils.log import getActionLogger

from yunohost.firewall import firewall_reload
from yunohost.service import service_restart
from yunohost.tools import Migration

logger = getActionLogger("yunohost.migration")


class MyMigration(Migration):

    "Migrate legacy iptables rules from stretch that relied on xtable and should now rely on nftable"

    dependencies = ["migrate_to_buster"]

    def run(self):

        self.do_ipv4 = os.system("iptables -w -L >/dev/null") == 0
        self.do_ipv6 = os.system("ip6tables -w -L >/dev/null") == 0

        if not self.do_ipv4:
            logger.warning(m18n.n("iptables_unavailable"))
        if not self.do_ipv6:
            logger.warning(m18n.n("ip6tables_unavailable"))

        backup_folder = "/home/yunohost.backup/premigration/xtable_to_nftable/"
Esempio n. 30
0
import sys
import datetime
import re
import shutil
import json
import yaml
import errno
import requests
from urllib import urlopen

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

from yunohost.service import service_regen_conf

logger = getActionLogger('yunohost.domain')


def domain_list(auth, filter=None, limit=None, offset=None):
    """
    List domains

    Keyword argument:
        filter -- LDAP filter used to search
        offset -- Starting number for domain fetching
        limit -- Maximum number of domain fetched

    """
    result_list = []

    # Set default arguments values
Esempio n. 31
0
    Manage users
"""
import os
import crypt
import random
import string
import json
import errno
import subprocess
import math
import re

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

logger = getActionLogger('yunohost.user')


def user_list(auth, fields=None, filter=None, limit=None, offset=None):
    """
    List users

    Keyword argument:
        filter -- LDAP filter used to search
        offset -- Starting number for user fetching
        limit -- Maximum number of user fetched
        fields -- fields to fetch

    """
    user_attrs = { 'uid': 'username',
                   'cn': 'fullname',
Esempio n. 32
0
import errno
try:
    import miniupnpc
except ImportError:
    sys.stderr.write('Error: Yunohost CLI Require miniupnpc lib\n')
    sys.exit(1)

from moulinette.core import MoulinetteError
from moulinette.utils import process
from moulinette.utils.log import getActionLogger
from moulinette.utils.text import prependlines

firewall_file = '/etc/yunohost/firewall.yml'
upnp_cron_job = '/etc/cron.d/yunohost-firewall-upnp'

logger = getActionLogger('yunohost.firewall')


def firewall_allow(protocol,
                   port,
                   ipv4_only=False,
                   ipv6_only=False,
                   no_upnp=False,
                   no_reload=False):
    """
    Allow connections on a port

    Keyword arguments:
        protocol -- Protocol type to allow (TCP/UDP/Both)
        port -- Port or range of ports to open
        ipv4_only -- Only add a rule for IPv4 connections
Esempio n. 33
0
import errno
import shutil
import hashlib
from difflib import unified_diff

from moulinette.core import MoulinetteError
from moulinette.utils import log, filesystem

from yunohost.hook import hook_list, hook_callback


base_conf_path = '/home/yunohost.conf'
backup_conf_dir = os.path.join(base_conf_path, 'backup')
pending_conf_dir = os.path.join(base_conf_path, 'pending')

logger = log.getActionLogger('yunohost.service')


def service_add(name, status=None, log=None, runlevel=None):
    """
    Add a custom service

    Keyword argument:
        name -- Service name to add
        status -- Custom status command
        log -- Absolute path to log file to display
        runlevel -- Runlevel priority of the service

    """
    services = _get_services()
Esempio n. 34
0
import calendar
import subprocess
import xmlrpclib
import os.path
import errno
import os
import dns.resolver
import cPickle as pickle
from datetime import datetime, timedelta

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

from yunohost.domain import get_public_ip

logger = getActionLogger('yunohost.monitor')

glances_uri  = 'http://127.0.0.1:61209'
stats_path   = '/var/lib/yunohost/stats'
crontab_path = '/etc/cron.d/yunohost-monitor'


def monitor_disk(units=None, mountpoint=None, human_readable=False):
    """
    Monitor disk space and usage

    Keyword argument:
        units -- Unit(s) to monitor
        mountpoint -- Device mountpoint
        human_readable -- Print sizes in human readable format
Esempio n. 35
0
"""
import os
import re
import json
import glob
import base64
import errno
import requests
import subprocess

from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger

from yunohost.domain import get_public_ip

logger = getActionLogger('yunohost.dyndns')


class IPRouteLine(object):
    """ Utility class to parse an ip route output line

    The output of ip ro is variable and hard to parse completly, it would
    require a real parser, not just a regexp, so do minimal parsing here...

    >>> a = IPRouteLine('2001:: from :: via fe80::c23f:fe:1e:cafe dev eth0  src 2000:de:beef:ca:0:fe:1e:cafe  metric 0')
    >>> a.src_addr
    "2000:de:beef:ca:0:fe:1e:cafe"
    """
    regexp = re.compile(
        r'(?P<unreachable>unreachable)?.*src\s+(?P<src_addr>[0-9a-f:]+).*')
Esempio n. 36
0
import glob
import base64
import subprocess

from moulinette import m18n
from moulinette.core import MoulinetteError
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import write_to_file, read_file
from moulinette.utils.network import download_json

from yunohost.utils.error import YunohostError
from yunohost.domain import _get_maindomain, _build_dns_conf
from yunohost.utils.network import get_public_ip, dig
from yunohost.log import is_unit_operation

logger = getActionLogger('yunohost.dyndns')

DYNDNS_ZONE = '/etc/yunohost/dyndns/zone'

RE_DYNDNS_PRIVATE_KEY_MD5 = re.compile(
    r'.*/K(?P<domain>[^\s\+]+)\.\+157.+\.private$')

RE_DYNDNS_PRIVATE_KEY_SHA512 = re.compile(
    r'.*/K(?P<domain>[^\s\+]+)\.\+165.+\.private$')


def _dyndns_provides(provider, domain):
    """
    Checks if a provider provide/manage a given domain.

    Keyword arguments: