summaryrefslogtreecommitdiffstats
path: root/standalone-container/src/test/scala/com/yahoo/container/standalone/StandaloneContainer.scala
blob: b70eefe0681a0ad524e109a6ab2f4c2cb4e923fc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.standalone

import com.yahoo.config.model.producer.AbstractConfigProducerRoot
import com.yahoo.config.model.test.MockRoot
import com.yahoo.container.Container
import com.yahoo.jdisc.test.TestDriver
import scala.xml.Node
import com.yahoo.vespa.model.VespaModel
import com.yahoo.io.IOUtils
import java.nio.file.{Files, Path}
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking

/**
 * Creates a local application from vespa-services fragments.
 *
 * @author  tonytv
 */
object StandaloneContainer {
  def firstContainerId(root: AbstractConfigProducerRoot): String = {
    root.getConfigProducer("container").get().getConfigId
  }

  def withStandaloneContainer[T](containerNode: Node) {
    withTempDirectory { applicationDirectory =>
      System.setProperty(StandaloneContainerApplication.applicationLocationYinstVariable, applicationDirectory.toString)
      createServicesXml(applicationDirectory, containerNode)

      val driver = TestDriver.newInjectedApplicationInstance(classOf[StandaloneContainerApplication])
      driver.close()
      Container.resetInstance()
    }
  }

  def withContainerModel[T](containerNode: Node)(f: VespaModel => T) {
    withTempDirectory { applicationPath =>
      createServicesXml(applicationPath, containerNode)

      val distributedFiles = new LocalFileDb(applicationPath)
      val (root, container) = StandaloneContainerApplication.createContainerModel(
        applicationPath,
        distributedFiles,
        applicationPath.resolve("preprocesedApp").toFile,
        networkingOption = Networking.enable)
      f(root)
    }
  }

  private def withTempDirectory[T](f : Path => T) : T = {
    val directory = Files.createTempDirectory("application")
    try {
      f(directory)
    } finally {
      IOUtils.recursiveDeleteDir(directory.toFile)
    }
  }

  private def createServicesXml(applicationPath : Path,
                             containerNode: Node) {

    scala.xml.XML.save(applicationPath.resolve("services.xml").toFile.getAbsolutePath,
      containerNode, xmlDecl = true)
  }
}