Package org.platformlayer.ops

Examples of org.platformlayer.ops.Command


  @Handler
  public void doOperation(OpsTarget target) throws OpsException {
    // TODO: Make this idempotent
    LdifRecord configLdif;
    {
      Command ldapSearch = Command
          .build("ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=config olcRootDN=cn=admin,cn=config dn olcRootDN olcRootPW");

      List<LdifRecord> ldifs = LdifRecord.parse(target.executeCommand(ldapSearch).getStdOut());
      if (ldifs.size() != 1) {
        throw new OpsException("Expected exactly one LDIF record for config");
      }
      configLdif = ldifs.get(0);
    }

    {
      StringBuilder modify = new StringBuilder();

      modify.append("dn: " + configLdif.getLdapDn().toString() + "\n");
      modify.append("replace: olcRootPW\n");
      modify.append("olcRootPW: " + LdapPasswords.getLdapPasswordEncoded(ldapSecret.plaintext()) + "\n");
      modify.append("\n");

      File tempDir = target.createTempDir();
      File modifyFile = new File(tempDir, "modifypw.ldif");
      FileUpload.upload(target, modifyFile, modify.toString());

      Command ldapModify = Command.build("ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f {0}", modifyFile);

      target.executeCommand(ldapModify);
    }

    ldap.writeLdapServerPassword(target, ldapSecret);
View Full Code Here


      // TODO: Do timestamp based dependency checking?
      rebuild = false;
    }

    if (rebuild) {
      Command mkisoCommand = Command.build("genisoimage -input-charset utf-8 -R -o {0}", iso);
      if (volumeLabel != null) {
        mkisoCommand.addLiteral("-V").addQuoted(volumeLabel);
      }
      mkisoCommand.addFile(srcDir);

      target.executeCommand(mkisoCommand);
    }
  }
View Full Code Here

  public Provider<String> bridgeName;

  @Handler
  public void handler(OpsTarget target) throws OpsException {
    if (OpsContext.isConfigure()) {
      Command findCommand = Command.build("/sbin/ifconfig {0}", interfaceName);
      boolean found = false;
      try {
        target.executeCommand(findCommand);
        found = true;
      } catch (ProcessExecutionException e) {
        ProcessExecution execution = e.getExecution();
        if (execution.getExitCode() == 1 && execution.getStdErr().contains("Device not found")) {
          found = false;
        } else {
          throw new OpsException("Error checking for interface", e);
        }
      }

      if (!found) {
        // This is actually idempotent, but I think it's scary to rely on it being so
        Command command = Command.build("/usr/sbin/tunctl -t {0}", interfaceName);
        target.executeCommand(command);
      }

      {
        // TODO: Safe to re-run?
        Command command = Command.build("ifconfig {0} up", interfaceName);
        target.executeCommand(command);
      }

      if (bridgeName != null) {
        // TODO: Safe to re-run?

        Command command = Command.build("brctl addif {0} {1}", bridgeName.get(), interfaceName);
        try {
          target.executeCommand(command);
        } catch (ProcessExecutionException e) {
          ProcessExecution execution = e.getExecution();
          if (execution.getExitCode() == 1 && execution.getStdErr().contains("already a member of a bridge")) {
View Full Code Here

      }
    };
  }

  private Command buildKvmCommand() {
    Command command = Command.build("/usr/bin/kvm");

    if (this.vnc != null) {
      InetSocketAddress vnc = this.vnc.get();
      if (vnc != null) {
        int port = vnc.getPort();
        int vncPort = port - 5900;
        command.addLiteral("-vnc");
        InetAddress address = vnc.getAddress();
        if (!address.isAnyLocalAddress()) {
          command.addQuoted(address.getHostAddress() + ":" + vncPort);
        } else {
          command.addQuoted("0.0.0.0:" + vncPort);
        }
      }
    }

    command.addLiteral("-m").addQuoted(Integer.toString(memoryMb));
    command.addLiteral("-smp").addQuoted(Integer.toString(vcpus));
    command.addLiteral("-name").addQuoted(id);
    // command.addLiteral("-nodefconfig");
    command.addLiteral("-nodefaults");
    command.addLiteral("-vga").addQuoted("cirrus");
    command.addLiteral("-usb");
    command.addLiteral("-readconfig").addFile(getDeviceConfigPath());

    if (!disableKvm) {
      command.addLiteral("-enable-kvm");
    }

    return command;
  }
View Full Code Here

    if (OpsContext.isConfigure()) {
      if (target.getFilesystemInfoFile(confDir) == null) {
        File exampleConfDir = new File(template.getInstallDir(), "example/solr/conf/");

        Command copy = Command.build("cp -r {0} {1}", exampleConfDir, dataDir);
        target.executeCommand(copy);

        target.chown(confDir, "solr", "solr", true, false);
      }
    }
View Full Code Here

    if (OpsContext.isConfigure()) {
      if (target.getFilesystemInfoFile(targetDir) != null) {
        log.warn("Directory already exists; skipping clone (should we update?)");
      } else {
        File checkoutDir = targetDir.getParentFile();
        Command command = Command.build("cd {0}; git clone {1}", checkoutDir, source);
        command.setTimeout(TimeSpan.FIVE_MINUTES);
        target.executeCommand(command);
      }
    }
  }
View Full Code Here

    if (supportLxc) {
      apt.install(target, "fakechroot", "fakeroot");
    }

    Command command;

    File rootfsDir;
    File imageFile;
    File loopbackPartition = null;

    if (!buildTar) {
      apt.install(target, "mbr");
      apt.install(target, "parted");
      apt.install(target, "kpartx");
      apt.install(target, "extlinux");

      // Same with qemu-kvm
      // (needed for qemu-img convert ... a lot of extra stuff for just the
      // utils!)
      String qemuImgPackage = "qemu-utils"; // packageHelpers.getPackageFor("qemu-img", operatingSystem);
      apt.install(target, qemuImgPackage);

      // Use local ephemeral storage...
      imageFile = new File(tempDir, "image.raw");
      command = Command.build("dd if=/dev/null bs=1M seek=8180 of={0}", imageFile);
      target.executeCommand(command);

      // Create partitions
      target.executeCommand(Command.build("parted -s {0} mklabel msdos", imageFile));
      target.executeCommand(Command.build("parted -s {0} mkpart primary 0% 100%", imageFile));
      target.executeCommand(Command.build("parted -s {0} set 1 boot on", imageFile));

      // Install Master Boot Record
      target.executeCommand(Command.build("install-mbr {0}", imageFile));

      // Mount the partitions
      // Hopefully it’s loop0p1...
      target.executeCommand(Command.build("modprobe dm-mod"));

      // boolean isMounted = false;
      //
      // {
      // ProcessExecution mountExecution = target.executeCommand(Command.build("mount", imageFile));
      // String stdout = mountExecution.getStdOut();
      // System.out.println(stdout);
      //
      // for (String line : Splitter.on('\n').split(stdout)) {
      // line = line.trim();
      // if (line.isEmpty()) {
      // continue;
      // }
      //
      // List<String> tokens = Lists.newArrayList(Splitter.on(' ').split(line));
      // if (tokens.size() < 3) {
      // throw new IllegalStateException("Cannot parse mount line: " + line);
      // }
      //
      // String mountDir = tokens.get(2);
      // if (mountDir.equals(mntDir.getAbsolutePath())) {
      // isMounted = true;
      // loopbackPartition = new File(tokens.get(0));
      // break;
      // }
      // }
      //
      // // /dev/sda1 on / type ext4 (rw,errors=remount-ro)
      // // tmpfs on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
      // // proc on /proc type proc (rw,noexec,nosuid,nodev)
      // // sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
      // // udev on /dev type tmpfs (rw,mode=0755)
      // // tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
      // // devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=620)
      // // /dev/mapper/loop0p1 on /tmp/8389210e66cd0df6/mnt type ext3 (rw)
      // // proc on /tmp/8389210e66cd0df6/mnt/proc type proc (rw)
      // }
      //
      // if (!isMounted)
      {
        ProcessExecution kpartxExecution = target.executeCommand(Command.build("kpartx -av {0}", imageFile));
        String stdout = kpartxExecution.getStdOut();
        List<String> tokens = Lists.newArrayList(Splitter.on(' ').split(stdout));
        if (tokens.size() != 9) {
          throw new IllegalStateException("Cannot parse kpartx stdout: " + stdout);
        }
        // add map loop6p1 (253:6): 0 16750592 linear /dev/loop6 2048
        String partitionDevice = tokens.get(2);
        if (!partitionDevice.startsWith("loop")) {
          throw new IllegalStateException("kpartx output does not look like a partition: " + stdout);
        }
        loopbackPartition = new File("/dev/mapper/" + partitionDevice);
      }

      // Format filesystem
      command = Command.build("yes | mkfs." + filesystem + " {0}", loopbackPartition);
      command.setTimeout(TimeSpan.FIVE_MINUTES);
      target.executeCommand(command);

      // Get this onto disk now, so we don't delay later commands
      target.executeCommand(Command.build("sync").setTimeout(TimeSpan.FIVE_MINUTES));

      // Don’t force a check based on dates
      target.executeCommand(Command.build("tune2fs -i 0 {0}", loopbackPartition)
          .setTimeout(TimeSpan.FIVE_MINUTES));

      // Get this onto disk now, so we don't delay later commands
      target.executeCommand(Command.build("sync").setTimeout(TimeSpan.FIVE_MINUTES));

      // Mount on mnt/
      File mntDir = new File(tempDir, "mnt");
      target.executeCommand("mkdir {0}", mntDir);

      target.executeCommand(Command.build("mount {0} {1}", loopbackPartition, mntDir).setTimeout(
          TimeSpan.FIVE_MINUTES));

      rootfsDir = mntDir;
    } else {
      rootfsDir = new File(tempDir, "rootfs");
      imageFile = new File(tempDir, "image.tar.bz2");
    }

    if (buildTar) {
      apt.install(target, "bzip2");
    }

    // Do debootstrap

    if (supportLxc) {
      command = Command.build("fakechroot fakeroot debootstrap");
    } else {
      command = Command.build("debootstrap");
    }

    command.addLiteral("--verbose");
    command.addLiteral("--resolve-deps");
    if (supportLxc) {
      // Lxc has problems with mounting etc; fakechroot avoids this
      command.addLiteral("--variant=fakechroot");
      // command.addLiteral("--variant=minbase");
    }
    command.addQuoted("--include=", Joiner.on(",").join(packages));
    command.addLiteral(operatingSystem.getVersion());
    command.addFile(rootfsDir);
    // command.addQuoted(aptSource);

    command.setEnvironment(httpProxyEnv);

    command.setTimeout(TimeSpan.THIRTY_MINUTES);

    try {
      target.executeCommand(command);
    } catch (ProcessExecutionException e) {
      String debootstrapLog = target.readTextFile(new File(rootfsDir, "debootstrap/debootstrap.log"));
      log.warn("Debootstrap log: " + debootstrapLog);

      throw new OpsException("Error running debootstrap", e);
    }

    // TODO: Switch to ChrootOpsTarget, so we can move this stuff into utility functions
    ChrootOpsTarget chrootTarget = new ChrootOpsTarget(rootfsDir, new File("/tmp"), target);

    FileUpload.upload(target, new File(rootfsDir, "etc/hostname"), hostname);

    {
      // Stop services being started in the chroot
      String policy = ResourceUtils.get(getClass(), "usr.sbin.policy-rc.d");
      File policyFile = new File(rootfsDir, "usr/sbin/policy-rc.d");
      FileUpload.upload(target, policyFile, policy);
      target.chmod(policyFile, "755");
    }

    target.executeCommand("mount -t proc proc {0}", new File(rootfsDir, "proc"));

    apt.update(chrootTarget, true);
    target.executeCommand("chroot {0} locale-gen en_US.utf8", rootfsDir);

    target.executeCommand("chroot {0} /bin/bash -c \"DEBIAN_FRONTEND=noninteractive dpkg-reconfigure locales\"",
        rootfsDir);

    if (!buildTar) {
      {
        File kernelImgConf = new File(rootfsDir, "etc/kernel-img.conf");

        String preseedData = ResourceUtils.get(getClass(), "kernel-img.conf");
        FileUpload.upload(target, kernelImgConf, preseedData);
      }

      {
        File preseedTmpDir = target.createTempDir();
        File preseedFile = new File(preseedTmpDir, "kernel.preseed");

        String preseedData = ResourceUtils.get(getClass(), "kernel.preseed");
        FileUpload.upload(target, preseedFile, preseedData);

        target.executeCommand(Command.build("cat {0} | chroot {1} debconf-set-selections", preseedFile,
            rootfsDir));
        apt.install(chrootTarget, kernelPackage);
      }
    }

    preconfigurePackages(chrootTarget, recipe.configurePackage);

    if (recipe.repositoryKey != null) {
      addRepositoryKeys(chrootTarget, recipe.repositoryKey);
    }

    if (recipe.repository != null) {
      addRepositories(chrootTarget, recipe.repository);

      apt.update(chrootTarget, true);
    }

    if (recipe.addPackage != null) {
      apt.install(chrootTarget, recipe.addPackage);

      if (recipe.addPackage.contains("jenkins")) {
        // It looks like jenkins doesn't honor policy-rc.d (?)
        // TODO: Fix this monstrosity...
        log.warn("Hard-coding service stop after jenkins installation");
        target.executeCommand(Command.build("chroot {0} /etc/init.d/jenkins stop", rootfsDir));
      }
    }

    apt.upgrade(chrootTarget);
    apt.clean(chrootTarget);

    if (!buildTar) {
      String uuid;
      {
        ProcessExecution uuidExecution = target.executeCommand("blkid -o value -s UUID {0}", loopbackPartition);
        uuid = uuidExecution.getStdOut().trim();
      }

      // Set up /etc/fstab
      String fstab = "# /etc/fstab: static file system information.\n";
      // TODO: Swap
      fstab += "proc\t/proc\tproc\tnodev,noexec,nosuid\t0\t0\n";
      // fstab += "/dev/sda1\t/\t" + filesystem +
      // "\terrors=remount-ro\t0\t1\n";
      fstab += String.format("UUID=%s\t/\t%s\terrors=remount-ro\t0\t1\n", uuid, filesystem);

      if (supportCloudConfigDisk) {
        if (useConfigDriveSymlinks) {
          // Use configuration from cloud_config mount
          target.mkdir(new File(rootfsDir, "media/config"));
          fstab += "/dev/disk/by-label/" + configDriveLabel + "\t/media/config\tudf,iso9660\tro\t0\t0\n";
        }
      }

      FileUpload.upload(target, new File(rootfsDir, "etc/fstab"), fstab);
      log.info("fstab = " + fstab);

      // Set up extlinux
      {
        ProcessExecution kernelExecution = target.executeCommand("chroot {0} find boot/ -name \"vmlinuz-*\"",
            rootfsDir);
        List<String> kernels = Lists.newArrayList();
        for (String kernel : kernelExecution.getStdOut().split("\n")) {
          kernel = kernel.trim();
          if (kernel.isEmpty()) {
            continue;
          }
          kernels.add(kernel);
        }

        if (kernels.size() > 1) {
          throw new IllegalStateException("Multiple kernels found");
        } else if (kernels.size() != 1) {
          throw new IllegalStateException("No kernels found");
        }

        ProcessExecution initrdExecution = target.executeCommand("chroot {0} find boot/ -name \"initrd*\"",
            rootfsDir);
        List<String> initrds = Lists.newArrayList();
        for (String initrd : initrdExecution.getStdOut().split("\n")) {
          initrd = initrd.trim();
          if (initrd.isEmpty()) {
            continue;
          }
          if (initrd.endsWith(".bak")) {
            continue;
          }
          initrds.add(initrd);
        }

        if (initrds.size() > 1) {
          throw new IllegalStateException("Multiple initrds found");
        } else if (initrds.size() != 1) {
          throw new IllegalStateException("No initrds found");
        }

        String conf = String.format(
            "default linux\ntimeout 1\n\nlabel linux\nkernel %s\nappend initrd=%s root=UUID=%s ro quiet",
            kernels.get(0), initrds.get(0), uuid);
        FileUpload.upload(target, new File(rootfsDir, "extlinux.conf"), conf);
        log.info("extlinux.conf = " + conf);
      }
      target.executeCommand(Command.build("extlinux --install  {0}", rootfsDir).setTimeout(TimeSpan.FIVE_MINUTES));
    }

    if (supportCloudConfigDisk) {
      if (useConfigDriveSymlinks) {
        target.rm(new File(rootfsDir, "etc/network/interfaces"));
        target.executeCommand("ln -s /media/config/etc/network/interfaces {0}", new File(rootfsDir,
            "etc/network/interfaces"));

        target.mkdir(new File(rootfsDir, "root/.ssh"));
        target.executeCommand("ln -s /media/config/root/.ssh/authorized_keys {0}", new File(rootfsDir,
            "root/.ssh/authorized_keys"));
      } else {
        String initScript = ResourceUtils.get(getClass(), "openstack-config");
        File initScriptFile = new File(rootfsDir, "etc/init.d/openstack-config");

        FileUpload.upload(target, initScriptFile, initScript);
        target.executeCommand("chmod +x {0}", initScriptFile);

        chrootTarget.executeCommand("/usr/sbin/update-rc.d openstack-config defaults");
      }
    }

    {
      // Remove policy file
      File policyFile = new File(rootfsDir, "usr/sbin/policy-rc.d");
      target.rm(policyFile);
    }

    target.executeCommand("sync");
    target.executeCommand("umount {0}", new File(rootfsDir, "proc"));

    if (!buildTar) {
      target.executeCommand("sync");
      target.executeCommand("umount {0}", rootfsDir);
      target.executeCommand("sync");
      target.executeCommand("kpartx -d {0}", imageFile);
      target.executeCommand("sync");
    }

    if (buildTar) {
      Command compress = Command.build("cd {0}; tar jcf {1} .", rootfsDir, imageFile);
      target.executeCommand(compress.setTimeout(TimeSpan.FIFTEEN_MINUTES));
    }

    FilesystemInfo imageInfo = target.getFilesystemInfoFile(imageFile);

    File uploadImageFile;
View Full Code Here

    PostgresqlServer server = OpsContext.get().getInstance(PostgresqlServer.class);

    backupContext.add(new BackupItem(server.getKey(), FORMAT, baseName));

    {
      Command dumpAll = Command.build("su postgres -c \"pg_dumpall --globals-only\"");
      Backup request = new Backup();
      request.target = target;
      request.objectName = baseName + "/pgdump_meta";
      backupContext.uploadStream(request, dumpAll);
    }

    for (String database : databases) {
      // template0 cannot be backed up
      if (database.equals("template0")) {
        continue;
      }

      // template1 can be backed up, even though it isn't typically very useful

      String fileName = "pgdump_db_" + database;
      Backup request = new Backup();
      request.target = target;
      request.objectName = baseName + "/" + fileName;

      Command dumpDatabase = Command.build("su postgres -c \"pg_dump --oids -Fc --verbose {0}\"", database);
      backupContext.uploadStream(request, dumpDatabase);
    }
  }
View Full Code Here

      backupContext.uploadStream(request, dumpDatabase);
    }
  }

  private List<String> listDatabases(OpsTarget target) throws OpsException {
    Command listDatabases = Command.build("su postgres -c \"psql -A -t -c 'select datname from pg_database'\"");
    ProcessExecution listDatabasesExecution = target.executeCommand(listDatabases);
    List<String> databases = Lists.newArrayList();
    for (String database : Splitter.on('\n').split(listDatabasesExecution.getStdOut())) {
      database = database.trim();
      if (database.isEmpty()) {
View Full Code Here

    String password = model.rootPassword.plaintext();

    String sql = String.format("ALTER USER postgres WITH PASSWORD '%s';", password);
    String psql = String.format("psql --command=\"%s\"", sql);
    Command command = Command.build("su postgres -c {0}", psql);

    target.executeCommand(command);
  }
View Full Code Here

TOP

Related Classes of org.platformlayer.ops.Command

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.