Esempio n. 1
0
def execCli(cmd):
    if cmd.find('|') > -1 or cmd.find('>') > -1:
        cmd = '"' + cmd + '"'

    cmd = 'sudo iocage exec {} -- {}'.format(JailName, cmd)
    print('Mock exec: {}'.format(cmd))
    util.execNWait(cmd)
Esempio n. 2
0
def destroyIfExist(TemplateName):
  templates = getTemplates(False)
  for temp in templates:
    if temp['name'] == TemplateName:
      util.execNWait('iocage destroy -f {}'.format(TemplateName))
      return True

  # nothing destroyed
  return False
Esempio n. 3
0
def setProps(BuildConfig):
  props = getJailProps(BuildConfig['name'])

  # stop jail if running
  if (props is not None and props['state'] == 'up'):
    print ('{} is running: stopping'.format(BuildConfig['name']))
    util.execNWait('iocage stop {}'.format(BuildConfig['name']))

  for key in BuildConfig['props'].keys():
    print ('{} = {}'.format(key, getPropValue(BuildConfig['props'][key])))
    util.execNWait('iocage set {}={} {}'.format(key, getPropValue(BuildConfig['props'][key]), BuildConfig['name']), isContinueOnError=True)
Esempio n. 4
0
def getTemplates(isTemplate = True):
  """Convert template list as returned from iocage as dictionary"""
  templates = []
  # switch between templates and jails
  TempString = '-t' if isTemplate else ''
  ExecResult = util.execNWait('iocage list {}'.format(TempString), isPrintRealtime = False)
  if ExecResult['ExitCode'] == 0:
    lines = ExecResult['output'].split('\n')
    if len(lines) > 3:
      lines.pop(0)
      lines.pop(0)
      lines.pop(0)

    for line in lines:
      columns = line.split('|')
      if len(columns) == 7:
        fields = {
          'jid': columns[1].strip(),
          'name': columns[2].strip(),
          c.JAILINFO_STATE: columns[3].strip(),
          'release': columns[4].strip(),
          'address': columns[5].strip(),
        }
        templates.append(fields)

  return templates
Esempio n. 5
0
def doTasks(opts):
    BuildConfig = opts['BuildConfig']
    vars = opts['vars']

    for task in BuildConfig['tasks']:
        print('TASK: {}'.format(task[c.KEY_NAME]))
        if (task['do'] == c.TASK_JAILEXEC):
            util.execNWait('iocage exec {} "{}"'.format(
                BuildConfig['name'], task['cmd']))
            continue
        if (task['do'] == c.TASK_JAILRESTART):
            util.execNWait('iocage restart {}'.format(BuildConfig['name']))
            continue
        if (task['do'] == c.TASK_COPY):
            taskCopy(opts, task, opts['WorkingPath'])
            continue
        if (task['do'] == c.TASK_RUNTEMPLATE):
            taskRunTemplate(opts, task)
            continue
Esempio n. 6
0
def execCopy(doc, cmd):
    source = cmd['source'].split(':')
    SourceType = source[0].strip()
    if SourceType == 'github':
        SourceRepo = source[1].strip()
        url = 'https://raw.githubusercontent.com/{}'.format(SourceRepo)
        ExecCmd = 'sudo iocage exec {} -- sudo -u {} -i -- sh -c "curl {} > {}"'.format(
            JailName, doc['user']['id'], url, cmd['dest'])
        print(ExecCmd)
        util.execNWait(ExecCmd)
        print('Copy from github')
    elif SourceType == 'http' or SourceType == 'https':
        url = cmd['source']
        ExecCmd = 'sudo iocage exec {} -- sudo -u {} -i -- sh -c "curl {} > {}"'.format(
            JailName, doc['user']['id'], url, cmd['dest'])
        print(ExecCmd)
        util.execNWait(ExecCmd)
        print('Copy from http(s)')
    else:
        raise Exception('Unhandled source type: {}'.format(SourceType))
Esempio n. 7
0
def execActions():
    if actions['GetProperty']['key'] != '':
        for JailName in actions['jails']:
            cmd = 'sudo iocage get {} {}'.format(actions['GetProperty']['key'],
                                                 JailName)
            resp = util.execNWait(cmd,
                                  isTest4Shell=False,
                                  isPrintRealtime=False)
            print('{}: {}'.format(JailName, resp['output'].strip()))
    elif actions['SetProperty']['key'] != '':
        for JailName in actions['jails']:
            cmd = 'sudo iocage set {}={} {}'.format(
                actions['SetProperty']['key'], actions['SetProperty']['value'],
                JailName)
            print('Mock exec: {}'.format(cmd))
            util.execNWait(cmd, isTest4Shell=False)
    elif actions['IsUpdate'] != '':
        for JailName in actions['jails']:
            cmd = 'sudo iocage update {}'.format(JailName)
            print('Mock exec: {}'.format(cmd))
Esempio n. 8
0
def loadTemplate():
    global JailVars

    # load host variables
    JailVars = readYamlFile(
        '{}/conf/createjail-defaultvars.yaml'.format(AppBasePath))
    if JailVarsHost != None:
        JailVars = readYamlFile('{}/hosts/{}/createjail-vars.yaml'.format(
            AppBasePath, JailVarsHost))
    JailVars['USER_HOME'] = '/home/{}/'.format(JailVars['UserId'])
    print(json.dumps(JailVars, indent=4, sort_keys=True))

    # load default/ base config
    doc = readYamlFile('{}/conf/createjail-default.yaml'.format(AppBasePath),
                       JailVars)

    # override template with JailTemplate if defined
    if JailTemplate != None:
        # this is recursive
        mergeJailTemplate(JailTemplate, doc)

    # load host template if defined
    # if JailVarsHost != None:
    #     MergeDoc = readYamlFile('{}/hosts/{}/createjail-vars.yaml'.format(AppBasePath, JailVarsHost))
    #     print (MergeDoc)
    #     for key in [YAMLKEY_PKG, YAMLKEY_SERVICE, YAMLKEY_CLI]:
    #         if key in MergeDoc:
    #             for item in MergeDoc[key]:
    #                 doc[key].append(item)

    #     if YAMLKEY_IOCAGE in MergeDoc:
    #         for key in MergeDoc[YAMLKEY_IOCAGE]:
    #             doc[YAMLKEY_IOCAGE][key] = MergeDoc[YAMLKEY_IOCAGE][key]

    if TemplateName != None:
        # convert jail to template
        util.execNWait('sudo iocage stop {}'.format(JailName))

    print('Jail name: {}'.format(JailName))
    print('Jail template: {}'.format(JailTemplate))
    return doc
Esempio n. 9
0
def taskCopy(opts, task, WorkingPath):
    if ('ApplyVars' in task and task['ApplyVars'] == True):
        # apply vars to text file
        print(task['src'])
        print(task['dest'])

        RawData = jailminlib.smartGetFile(opts['AppConfig'], task['src'], '{}',
                                          '')
        # InFile = open(task['src'],'r')
        # RawData = InFile.read()
        # InFile.close()

        vars = opts['vars']['vars']
        # replace vars in copy template
        for key in vars.keys():
            print('Replacing key {}'.format(key))
            RawData = RawData.replace('{{' + key + '}}',
                                      stringify4Template(vars[key]))

        # validate no unreplaced vars
        isMissingVars = False
        for key in re.findall('{{[A-Za-z]+}}', RawData):
            VarName = key[2:-2]
            isMissingVars = True
            print('ERROR: Variable {} not replaced'.format(VarName))
        if isMissingVars:
            sys.exit(1)

        TempFile = WorkingPath + os.path.basename(task['dest'])
        print('dest basename: {}'.format(os.path.basename(task['dest'])))
        OutFile = open(TempFile, 'w')
        OutFile.write(RawData)
        OutFile.close()

        util.execNWait('cp {} {}'.format(TempFile, task['dest']))
        # housekeeping
        os.remove(TempFile)
    else:
        # binary copy
        util.execNWait('cp {} {}'.format(task['src'], task['dest']))
Esempio n. 10
0
def getJailProps(JailName):
  """Get jail properties as returned by iocage"""
  RawJailProps = util.execNWait('iocage get all {}'.format(JailName), isPrintRealtime = False, isContinueOnError = True)
  if RawJailProps['ExitCode'] != 0:
    # jail does not exist
    return None

  props = {}
  for line in RawJailProps['output'].split('\n'):
    columns = line.split(':')
    if len(columns) > 1:
      props[columns[0]] = columns[1]
  return props
Esempio n. 11
0
def execTemplate(doc):
    try:
        execCreateJail(doc)
        execPkgInstall(doc)
        execUserCreate(doc)

        # start simple services
        for daemon in doc['service']:
            cmd = 'sudo iocage exec {} sysrc {}_enable=YES'.format(
                JailName, daemon)
            print('Mock exec: {}'.format(cmd))
            util.execNWait(cmd)

            cmd = 'sudo iocage exec {} service {} start'.format(
                JailName, daemon)
            print('Mock exec: {}'.format(cmd))
            util.execNWait(cmd)

        execTasks(doc)
    except Exception as err:
        print(err.args[0])
        return False
Esempio n. 12
0
def getJails():
    output = util.execNWait('sudo iocage list', isPrintRealtime=False)
    lines = output['output'].splitlines()
    jails = []
    isHeader = True
    for line in output['output'].splitlines():
        fields = line.split('|')
        if len(fields) == 7:
            if isHeader:
                isHeader = False
            else:
                fields.pop(0)
                jails.append({
                    'jid': fields[0].strip(),
                    'name': fields[1].strip(),
                    'state': fields[2].strip(),
                    'release': fields[3].strip(),
                    'ip4': fields[4].strip()
                })

    return jails
Esempio n. 13
0
def execCreateJail(doc):
    # core iocage commands
    cmd = 'sudo iocage create -r {} -n {}'.format(doc['iocage']['release'],
                                                  JailName)
    print('Mock exec: {}'.format(cmd))
    util.execNWait(cmd)
    for key in doc['iocage'].keys():
        # blacklist keys from being applied to jail config
        if key in ['release', 'whatev']:
            continue

        # apply key to jail config
        value = doc['iocage'][key]
        if isinstance(value, bool):
            value = 1 if value == True else 0
        cmd = 'sudo iocage set {}={} {}'.format(key, value, JailName)
        print('Mock exec: {}'.format(cmd))
        util.execNWait(cmd, isTest4Shell=False)

    # start jail (required to exec)
    cmd = 'sudo iocage start {}'.format(JailName)
    util.execNWait(cmd)
    print('Mock exec: {}'.format(cmd))
Esempio n. 14
0
def installPkgs(JailName, PkgList):
  PkgStr = ' '.join(PkgList)
  print ('Installing pkgs: {}'.format(PkgStr))
  util.execNWait('iocage exec {} "{}"'.format(JailName, 'pkg install -y {}'.format(PkgStr)))
Esempio n. 15
0
def execUserCreate(doc):
    # create user account
    cmd = 'echo {} | pw useradd {} -h 0 -m -s {}'.format(
        doc['user']['pwd'], doc['user']['id'], doc['user']['shell'])
    print('Create user: {}'.format(doc['user']['id']))
    util.execNWait('sudo iocage exec {} "{}"'.format(JailName, cmd))
Esempio n. 16
0
def execPkgInstall(doc):
    # install packages
    for PkgName in doc['pkg']:
        cmd = 'sudo iocage exec {} pkg install -y {}'.format(JailName, PkgName)
        print('Mock exec: {}'.format(cmd))
        util.execNWait(cmd)