下面列出了hudson.model.Saveable#hudson.slaves.NodeProperty 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void shouldShowNodeConfigurationPage() throws Exception {
EC2FleetCloud cloud = new EC2FleetCloud(null, null, null, null, null, null, null,
null, null, null, false, false,
0, 0, 0, 0, false, false,
false, 0, 0, false,
10, false);
j.jenkins.clouds.add(cloud);
j.jenkins.addNode(new EC2FleetNode("node-name", "", "", 1,
Node.Mode.EXCLUSIVE, "", new ArrayList<NodeProperty<?>>(), cloud,
j.createComputerLauncher(null)));
HtmlPage page = j.createWebClient().goTo("computer/node-name/configure");
assertTrue(StringUtils.isNotBlank(((HtmlTextInput) getElementsByNameWithoutJdk(page, "_.name").get(0)).getText()));
}
@Test
public void shouldReplaceCloudForNodesAfterConfigurationSave() throws Exception {
EC2FleetCloud cloud = new EC2FleetCloud(null, null, null, null, null, null, null,
null, null, null, false, false,
0, 0, 0, 0, false, false,
false, 0, 0, false,
10, false);
j.jenkins.clouds.add(cloud);
j.jenkins.addNode(new EC2FleetNode("mock", "", "", 1,
Node.Mode.EXCLUSIVE, "", new ArrayList<NodeProperty<?>>(), cloud,
j.createComputerLauncher(null)));
HtmlPage page = j.createWebClient().goTo("configure");
HtmlForm form = page.getFormByName("config");
((HtmlTextInput) getElementsByNameWithoutJdk(page, "_.name").get(0)).setText("a");
HtmlFormUtil.submit(form);
final Cloud newCloud = j.jenkins.clouds.get(0);
assertNotSame(cloud, newCloud);
assertSame(newCloud, ((EC2FleetNode) j.jenkins.getNode("mock")).getCloud());
}
public void createGlobalEnvironmentVariables(String key, String value){
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);
EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
EnvVars envVars = null;
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty);
envVars = newEnvVarsNodeProperty.getEnvVars();
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars();
}
envVars.put(key, value);
try {
instance.save();
} catch(Exception e) {
System.out.println("Failed to create env variable");
}
}
@Before
public void configureCloud() throws Exception {
cloud = setupCloud(this, name);
createSecret(cloud.connect(), cloud.getNamespace());
cloud.getTemplates().clear();
cloud.addTemplate(buildBusyboxTemplate("busybox"));
setupHost();
r.jenkins.clouds.add(cloud);
DescribableList<NodeProperty<?>, NodePropertyDescriptor> list = r.jenkins.getGlobalNodeProperties();
EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
list.add(newEnvVarsNodeProperty);
EnvVars envVars = newEnvVarsNodeProperty.getEnvVars();
envVars.put("GLOBAL", "GLOBAL");
envVars.put("JAVA_HOME_X", "java-home-x");
r.jenkins.save();
}
/**
* Get a list of all {@link NodePropertyDescriptor}s we can use to define DockerSlave NodeProperties.
*/
@SuppressWarnings("cast")
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() {
// Copy/paste hudson.model.Slave.SlaveDescriptor.nodePropertyDescriptors marked as @Restricted for reasons I don't get
List<NodePropertyDescriptor> result = new ArrayList<>();
Collection<NodePropertyDescriptor> list =
(Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : DescriptorVisibilityFilter.applyType(DockerTransientNode.class, list)) {
if (npd.isApplicable(DockerTransientNode.class)) {
result.add(npd);
}
}
final Iterator<NodePropertyDescriptor> iterator = result.iterator();
while (iterator.hasNext()) {
final NodePropertyDescriptor de = iterator.next();
// see https://issues.jenkins-ci.org/browse/JENKINS-47697
if ("org.jenkinsci.plugins.matrixauth.AuthorizationMatrixNodeProperty".equals(de.getKlass().toJavaClass().getName())) {
iterator.remove();
}
}
return result;
}
@Test
public void configure() throws Exception {
final Jenkins jenkins = Jenkins.get();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> nodeProperties = jenkins.getGlobalNodeProperties();
Set<Map.Entry<String, String>> entries = ((EnvironmentVariablesNodeProperty) nodeProperties.get(0)).getEnvVars().entrySet();
assertEquals(1, entries.size());
Map.Entry<String, String> envVar = entries.iterator().next();
assertEquals("FOO", envVar.getKey());
assertEquals("BAR", envVar.getValue());
}
@Test
@Issue("Issue #173")
@ConfiguredWithCode("SetEnvironmentVariable.yml")
public void shouldSetEnvironmentVariable() throws Exception {
final DescribableList<NodeProperty<?>, NodePropertyDescriptor> properties = Jenkins.get().getNodeProperties();
EnvVars env = new EnvVars();
for (NodeProperty<?> property : properties) {
property.buildEnvVars(env, TaskListener.NULL);
}
assertEquals("BAR", env.get("FOO"));
}
@Before
public void setup() throws Exception {
super.setup();
JavaGitContainer slaveContainer = slaveRule.get();
DumbSlave agent = new DumbSlave("remote", "", "/home/test/slave", "1", Node.Mode.NORMAL, "",
new SSHLauncher(slaveContainer.ipBound(22), slaveContainer.port(22), "test", "test", "", ""),
RetentionStrategy.INSTANCE, Collections.<NodeProperty<?>>emptyList());
jenkinsRule.jenkins.addNode(agent);
}
@DataBoundConstructor
public ParallelsDesktopVMSlave(ParallelsDesktopVM vm, ParallelsDesktopConnectorSlaveComputer connector)
throws IOException, Descriptor.FormException
{
super(vm.getSlaveName(), "", vm.getRemoteFS(), 1, Mode.NORMAL, vm.getLabels(), vm.getLauncher(),
new ParallelsDesktopCloudRetentionStrategy(), new ArrayList<NodeProperty<?>>());
this.connector = connector;
this.vm = vm;
}
@DataBoundConstructor
public ParallelsDesktopConnectorSlave(ParallelsDesktopCloud owner, String name, String remoteFS,
ComputerLauncher launcher, boolean useAsBuilder)
throws IOException, Descriptor.FormException
{
super(name, "", remoteFS, 1, Mode.NORMAL, "", launcher,
useAsBuilder ? new RetentionStrategy.Always() : new RetentionStrategy.Demand(1, 1),
new ArrayList<NodeProperty<?>>());
this.owner = owner;
this.useAsBuilder = useAsBuilder;
}
@Test
@LocalData()
public void upgradeFrom_0_10() throws Exception {
List<PodTemplate> templates = cloud.getTemplates();
PodTemplate template = templates.get(0);
DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = template.getNodeProperties();
assertEquals(1, nodeProperties.size());
ToolLocationNodeProperty property = (ToolLocationNodeProperty) nodeProperties.get(0);
assertEquals(1, property.getLocations().size());
ToolLocation location = property.getLocations().get(0);
assertEquals("Default", location.getName());
assertEquals("/custom/path", location.getHome());
assertEquals(GitTool.class, location.getType().clazz);
assertEquals(cloud.DEFAULT_WAIT_FOR_POD_SEC, cloud.getWaitForPodSec());
}
@SuppressWarnings("rawtypes")
public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) {
List<NodePropertyDescriptor> result = new ArrayList<>();
Collection<NodePropertyDescriptor> list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : list) {
if (npd.isApplicable(clazz)) {
result.add(npd);
}
}
return result;
}
/**
* FIXME DescribableList doesn't work with DBS https://gist.github.com/KostyaSha/3414f4f453ea7c7406b4
*/
@DataBoundConstructor
public DockerSlaveTemplate(@Nonnull String id, List<NodeProperty<?>> nodeProperties)
throws FormException {
this(id);
setNodeProperties(nodeProperties);
}
@CheckForNull
public List<? extends NodeProperty<?>> getNodeProperties() {
final List<? extends NodeProperty<?>> nullOrNotEmpty = fixEmpty(nodeProperties);
if (nullOrNotEmpty == null) {
return null;
}
return Collections.unmodifiableList(nullOrNotEmpty);
}
/**
* Workaround for JENKINS-51203. Retries setting node properties until we
* either give up or we succeed. If we give up, the exception thrown will be
* the last one encountered.
*
* @param node
* The node whose nodeProperties are to be set.
* @param nodeProperties
* The nodeProperties to be set on the node.
* @throws IOException
* if it all failed horribly every time we tried.
*/
private static void robustlySetNodeProperties(DockerTransientNode node,
List<? extends NodeProperty<?>> nodeProperties) throws IOException {
if (nodeProperties == null || nodeProperties.isEmpty()) {
// no point calling setNodeProperties if we've got nothing to set.
return;
}
final int maxAttempts = 10;
for (int attempt = 1;; attempt++) {
try {
// setNodeProperties can fail at random
// It does so because it's persisting all Nodes,
// and if lots of threads all do this at once then they'll
// collide and fail.
node.setNodeProperties(nodeProperties);
return;
} catch (IOException | RuntimeException ex) {
if (attempt > maxAttempts) {
throw ex;
}
final long delayInMilliseconds = 100L * attempt;
try {
Thread.sleep(delayInMilliseconds);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
}
@Restricted(NoExternalUse.class)
protected static void addEnvVars(@Nonnull final EnvVars vars, @Nullable final Iterable<? extends NodeProperty<?>> nodeProperties) throws IOException, InterruptedException {
if (nodeProperties != null) {
for (final NodeProperty<?> nodeProperty : nodeProperties) {
nodeProperty.buildEnvVars(vars, LOGGER_LISTENER);
}
}
}
public List<? extends NodeProperty<?>> getNodeProperties() {
return nodeProperties;
}
@DataBoundSetter
public void setNodeProperties(List<? extends NodeProperty<?>> nodeProperties) {
this.nodeProperties = nodeProperties;
}
/**
* https://github.com/jenkinsci/ec2-plugin/blob/master/src/main/java/hudson/plugins/ec2/EC2Cloud.java#L640
*
* @param ec2 ec2 client
* @param instance instance
*/
private void addNewSlave(final AmazonEC2 ec2, final Instance instance, FleetStateStats stats) throws Exception {
final String instanceId = instance.getInstanceId();
// instance state check enabled and not running, skip adding
if (addNodeOnlyIfRunning && InstanceStateName.Running != InstanceStateName.fromValue(instance.getState().getName()))
return;
final String address = privateIpUsed ? instance.getPrivateIpAddress() : instance.getPublicIpAddress();
// Check if we have the address to use. Nodes don't get it immediately.
if (address == null) {
if (!privateIpUsed) {
info("%s instance public IP address not assigned, it could take some time or" +
" Spot Request is not configured to assign public IPs", instance.getInstanceId());
}
return; // wait more time, probably IP address not yet assigned
}
// Generate a random FS root if one isn't specified
final String effectiveFsRoot;
if (StringUtils.isBlank(fsRoot)) {
effectiveFsRoot = "/tmp/jenkins-" + UUID.randomUUID().toString().substring(0, 8);
} else {
effectiveFsRoot = fsRoot;
}
final Double instanceTypeWeight = stats.getInstanceTypeWeights().get(instance.getInstanceType());
final int effectiveNumExecutors;
if (scaleExecutorsByWeight && instanceTypeWeight != null) {
effectiveNumExecutors = (int) Math.max(Math.round(numExecutors * instanceTypeWeight), 1);
} else {
effectiveNumExecutors = numExecutors;
}
final EC2FleetAutoResubmitComputerLauncher computerLauncher = new EC2FleetAutoResubmitComputerLauncher(
computerConnector.launch(address, TaskListener.NULL));
final Node.Mode nodeMode = restrictUsage ? Node.Mode.EXCLUSIVE : Node.Mode.NORMAL;
final EC2FleetNode node = new EC2FleetNode(instanceId, "Fleet slave for " + instanceId,
effectiveFsRoot, effectiveNumExecutors, nodeMode, labelString, new ArrayList<NodeProperty<?>>(),
this, computerLauncher);
// Initialize our retention strategy
node.setRetentionStrategy(new IdleRetentionStrategy());
final Jenkins jenkins = Jenkins.getInstance();
// jenkins automatically remove old node with same name if any
jenkins.addNode(node);
final SettableFuture<Node> future;
if (plannedNodesCache.isEmpty()) {
future = SettableFuture.create();
} else {
final NodeProvisioner.PlannedNode plannedNode = plannedNodesCache.iterator().next();
plannedNodesCache.remove(plannedNode);
future = ((SettableFuture<Node>) plannedNode.future);
}
// use getters for timeout and interval as they provide default value
// when user just install new version and did't recreate fleet
EC2FleetOnlineChecker.start(node, future,
TimeUnit.SECONDS.toMillis(getInitOnlineTimeoutSec()),
TimeUnit.SECONDS.toMillis(getInitOnlineCheckIntervalSec()));
}
public EC2FleetNode(final String name, final String nodeDescription, final String remoteFS, final int numExecutors, final Mode mode, final String label,
final List<? extends NodeProperty<?>> nodeProperties, final EC2FleetCloud cloud, ComputerLauncher launcher) throws IOException, Descriptor.FormException {
super(name, nodeDescription, remoteFS, numExecutors, mode, label,
launcher, RetentionStrategy.NOOP, nodeProperties);
this.cloud = cloud;
}
public PodTemplateToolLocation(Saveable owner, Collection<? extends NodeProperty<?>> initialList) {
super(owner,initialList);
}
@Override
public boolean start() throws Exception {
LOGGER.log(Level.FINE, "Starting container step.");
String containerName = step.getName();
String shell = step.getShell();
KubernetesNodeContext nodeContext = new KubernetesNodeContext(getContext());
EnvironmentExpander env = getContext().get(EnvironmentExpander.class);
EnvVars globalVars = null;
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties
.getAll(EnvironmentVariablesNodeProperty.class);
if (envVarsNodePropertyList != null && envVarsNodePropertyList.size() != 0) {
globalVars = envVarsNodePropertyList.get(0).getEnvVars();
}
EnvVars rcEnvVars = null;
Run run = getContext().get(Run.class);
TaskListener taskListener = getContext().get(TaskListener.class);
if(run!=null && taskListener != null) {
rcEnvVars = run.getEnvironment(taskListener);
}
decorator = new ContainerExecDecorator();
decorator.setNodeContext(nodeContext);
decorator.setContainerName(containerName);
decorator.setEnvironmentExpander(env);
decorator.setWs(getContext().get(FilePath.class));
decorator.setGlobalVars(globalVars);
decorator.setRunContextEnvVars(rcEnvVars);
decorator.setShell(shell);
getContext().newBodyInvoker()
.withContext(BodyInvoker
.mergeLauncherDecorators(getContext().get(LauncherDecorator.class), decorator))
.withCallback(new ContainerExecCallback(decorator))
.start();
return false;
}
@DataBoundSetter
public void setNodeProperties(List<? extends NodeProperty<?>> properties) {
this.getNodeProperties().clear();
this.getNodeProperties().addAll(properties);
}
@Override
public Boolean call() throws Throwable {
final Jenkins jenkins = Jenkins.getInstance();
String logName = "com.github.kostyasha.yad";
final LogRecorder logRecorder = new LogRecorder(logName);
logRecorder.targets.add(new LogRecorder.Target("com.github.kostyasha.yad", Level.ALL));
jenkins.getLog().logRecorders.put("logName", logRecorder);
logRecorder.save();
// prepare jenkins global (url, cred)
JenkinsLocationConfiguration.get().setUrl(String.format("http://%s:%d", dockerUri.getHost(), jenkinsPort));
SystemCredentialsProvider.getInstance().getCredentials().add(dockerServerCredentials);
//verify doTestConnection
final DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptor(DockerConnector.class);
checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
dockerServerCredentials.getId(), connectorType, 10 * 1000, 11 * 1000));
// checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
// dockerServerCredentials.getId(), JERSEY, 10 * 1000, 11 * 1000));
// checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
// dockerServerCredentials.getId(), OKHTTP, 10 * 1000, 11 * 1000));
// prepare Docker Cloud
final DockerConnector dockerConnector = new DockerConnector(dockerUri.toString());
dockerConnector.setCredentialsId(dockerServerCredentials.getId());
dockerConnector.setConnectTimeout(10 * 1000);
dockerConnector.setReadTimeout(0);
dockerConnector.setConnectorType(connectorType);
dockerConnector.testConnection();
//launcher
final DockerComputerJNLPLauncher launcher = new DockerComputerJNLPLauncher();
launcher.setNoCertificateCheck(true);
launcher.setJvmOpts("-XX:-PrintClassHistogram");
final DockerPullImage pullImage = new DockerPullImage();
pullImage.setPullStrategy(PULL_LATEST);
//remove
final DockerRemoveContainer removeContainer = new DockerRemoveContainer();
removeContainer.setRemoveVolumes(true);
removeContainer.setForce(true);
//lifecycle
final DockerContainerLifecycle containerLifecycle = new DockerContainerLifecycle();
containerLifecycle.setImage(slaveImage);
containerLifecycle.setPullImage(pullImage);
containerLifecycle.setRemoveContainer(removeContainer);
//template
final Entry entry = new Entry("super-key", TEST_VALUE);
final EnvironmentVariablesNodeProperty nodeProperty = new EnvironmentVariablesNodeProperty(entry);
final ArrayList<NodeProperty<?>> nodeProperties = new ArrayList<>();
nodeProperties.add(nodeProperty);
nodeProperties.add(new DockerNodeProperty(CONTAINER_ID, CLOUD_ID, DOCKER_HOST));
final DockerSlaveTemplate slaveTemplate = new DockerSlaveTemplate();
slaveTemplate.setMaxCapacity(4);
slaveTemplate.setLabelString(DOCKER_CLOUD_LABEL);
slaveTemplate.setLauncher(launcher);
slaveTemplate.setMode(Node.Mode.EXCLUSIVE);
slaveTemplate.setRetentionStrategy(new DockerOnceRetentionStrategy(10));
slaveTemplate.setDockerContainerLifecycle(containerLifecycle);
slaveTemplate.setNodeProperties(nodeProperties);
final List<DockerSlaveTemplate> templates = new ArrayList<>();
templates.add(slaveTemplate);
final DockerCloud dockerCloud = new DockerCloud(
DOCKER_CLOUD_NAME,
templates,
3,
dockerConnector
);
jenkins.clouds.add(dockerCloud);
jenkins.save(); // either xmls a half broken
return true;
}
@Nonnull
public List<NodeProperty<?>> getNodeProperties() {
return nonNull(nodeProperties) ? unmodifiableList(nodeProperties) : emptyList();
}
public void setNodeProperties(List<NodeProperty<?>> nodeProperties) {
this.nodeProperties = nodeProperties;
}
@DataBoundSetter
public void setNodeProperties(List<? extends NodeProperty<?>> nodeProperties) {
this.nodeProperties = fixEmpty(nodeProperties);
}