text:
local network = require 'common.network'
local debuger_factory = require 'frontend.debuger_factory'
local fs = require 'bee.filesystem'
local sp = require 'bee.subprocess'
local platform_os = require 'frontend.platform_os'
local server
local client
local initReq
local m = {}

local function getUnixAddress(pid)
    local path = WORKDIR / "tmp"
    fs.create_directories(path)
    return "@"..(path / ("pid_%d"):format(pid)):string()
end

local function ipc_send_latest(pid)
    fs.create_directories(WORKDIR / "tmp")
    local ipc = require "common.ipc"
    local fd = assert(ipc(WORKDIR, pid, "luaVersion", "w"))
    fd:write("latest")
    fd:close()
end

local function response_initialize(req)
    client.sendmsg {
        type = 'response',
        seq = 0,
        command = 'initialize',
        request_seq = req.seq,
        success = true,
        body = require 'common.capabilities',
    }
end

local function response_restart(req)
    client.sendmsg {
        type = 'response',
        seq = 0,
        command = 'restart',
        request_seq = req.seq,
        success = true,
    }
end

local function response_error(req, msg)
    client.sendmsg {
        type = 'response',
        seq = 0,
        command = req.command,
        request_seq = req.seq,
        success = false,
        message = msg,
    }
end

local function request_runinterminal(args)
    client.sendmsg {
        type = 'request',
        seq = 0,
        command = 'runInTerminal',
        arguments = args
    }
end

local function attach_process(pkg, pid)
    if pkg.args.luaVersion == "latest" then
        ipc_send_latest(pid)
    end
    local inject = require 'inject'
    if not inject.injectdll(pid
        , (WORKDIR / "bin" / "windows" / "launcher.x86.dll"):string()
        , (WORKDIR / "bin" / "windows" / "launcher.x64.dll"):string()
        , "attach"
    ) then
        return false
    end
    server = network(getUnixAddress(pid), true)
    server.sendmsg(initReq)
    server.sendmsg(pkg)
    return true
end

local function attach_tcp(pkg, args)
    server = network(args.address, args.client)
    server.sendmsg(initReq)
    server.sendmsg(pkg)
end

local function proxy_attach(pkg)
    local args = pkg.arguments
    platform_os.init(args)
    if platform_os() ~= "Windows" then
        attach_tcp(pkg, args)
        return
    end
    if args.processId then
        local processId = tonumber(args.processId)
        if not attach_process(pkg, processId) then
            response_error(pkg, ('Cannot attach process `%d`.'):format(processId))
        end
        return
    end
    if args.processName then
        local pids = require "frontend.query_process"(args.processName)
        if #pids == 0 then
            response_error(pkg, ('Cannot found process `%s`.'):format(args.processName))
            return
        elseif #pids > 1 then
            response_error(pkg, ('There are %d processes `%s`.'):format(#pids, args.processName))
            return
        end
        if not attach_process(pkg, pids[1]) then
            response_error(pkg, ('Cannot attach process `%s` `%d`.'):format(args.processName, pids[1]))
        end
        return
    end
    attach_tcp(pkg, args)
end

local function proxy_launch_terminal(pkg)
    local args = pkg.arguments
    if args.runtimeExecutable then
        --TODO: support runtimeExecutable's integratedTerminal/externalTerminal
        response_error(pkg, "`runtimeExecutable` is not supported in `"..args.console.."`.")
        return
    end
    local pid = sp.get_id()
    server = network(getUnixAddress(pid), true)
    local arguments, err = debuger_factory.create_luaexe_in_terminal(args, WORKDIR, pid)
    if not arguments then
        response_error(pkg, err)
        return
    end
    request_runinterminal(arguments)
    return true
end

local function proxy_launch_console(pkg)
    local args = pkg.arguments
    if args.runtimeExecutable then
        if platform_os() ~= "Windows" then
            response_error(pkg, "`runtimeExecutable` is not supported.")
            return
        end
        local process, err = debuger_factory.create_process_in_console(args, function (process)
            local pid = process:get_id()
            server = network(getUnixAddress(pid), true)
            if args.luaVersion == "latest" then
                ipc_send_latest(pid)
            end
        end)
        if not process then
            response_error(pkg, err)
            return
        end
    else
        local pid = sp.get_id()
        server = network(getUnixAddress(pid), true)
        local ok, err = debuger_factory.create_luaexe_in_console(args, WORKDIR, pid)
        if not ok then
            response_error(pkg, err)
            return
        end
    end
    return true
end

local function proxy_launch(pkg)
    local args = pkg.arguments
    platform_os.init(args)
    if args.console == 'integratedTerminal' or args.console == 'externalTerminal' then
        if not proxy_launch_terminal(pkg) then
            return
        end
    else
        if not proxy_launch_console(pkg) then
            return
        end
    end
    server.sendmsg(initReq)
    server.sendmsg(pkg)
end

local function proxy_start(pkg)
    if pkg.arguments.request == 'attach' then
        proxy_attach(pkg)
    elseif pkg.arguments.request == 'launch' then
        proxy_launch(pkg)
    end
end

function m.send(pkg)
    if server then
        if pkg.type == 'response' and pkg.command == 'runInTerminal' then
            return
        end
        server.sendmsg(pkg)
    elseif not initReq then
        if pkg.type == 'request' and pkg.command == 'initialize' then
            pkg.__norepl = true
            initReq = pkg
            response_initialize(pkg)
        else
            response_error(pkg, 'not initialized')
        end
    else
        if pkg.type == 'request' then
            if pkg.command == 'attach' or pkg.command == 'launch' then
                proxy_start(pkg)
            else
                response_error(pkg, 'error request')
            end
        end
    end
end

function m.update()
    if server then
        server.event_close(function()
            os.exit(0, true)
        end)
        while true do
            local pkg = server.recvmsg()
            if pkg then
                client.sendmsg(pkg)
            else
                break
            end
        end
    end
end

function m.init(io)
    client = io
end

return m


text:
require 'spec_helper'

describe Mongoid::Tree::Traversal do

  subject { OrderedNode }

  describe '#traverse' do

    subject { Node.new }

    [:depth_first, :breadth_first].each do |method|
      it "should support #{method} traversal" do
        expect { subject.traverse(method) {} }.to_not raise_error
      end
    end

    it "should complain about unsupported traversal methods" do
      expect { subject.traverse('non_existing') {} }.to raise_error NoMethodError
    end

    it "should default to depth_first traversal" do
      expect(subject).to receive(:depth_first_traversal)
      subject.traverse {}
    end
  end

  describe 'depth first traversal' do

    describe 'with unmodified tree' do
      before do
        setup_tree <<-ENDTREE
          node1:
            - node2:
              - node3
            - node4:
              - node5
              - node6
            - node7
        ENDTREE
      end

      it "should traverse correctly" do
        result = []
        node(:node1).traverse(:depth_first) { |node| result << node }
        expect(result.collect { |n| n.name.to_sym }).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
      end

      it "should return and array containing the results of the block for each node" do
        result = node(:node1).traverse(:depth_first) { |n| n.name.to_sym }
        expect(result).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
      end
    end

    describe 'with merged trees' do
      before do
        setup_tree <<-ENDTREE
          - node4:
            - node5
            - node6:
              - node7

          - node1:
            - node2:
              - node3
        ENDTREE

        node(:node1).children << node(:node4)
      end

      it "should traverse correctly" do
        result = node(:node1).traverse(:depth_first) { |n| n.name.to_sym }
        expect(result).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
      end
    end

    describe 'with reordered nodes' do

      before do
        setup_tree <<-ENDTREE
          node1:
            - node2:
              - node3
            - node4:
              - node6
              - node5
            - node7
        ENDTREE

        node(:node5).move_above(node(:node6))
      end

      it 'should iterate through the nodes in the correct order' do
        result = []
        node(:node1).traverse(:depth_first) { |node| result << node }
        expect(result.collect { |n| n.name.to_sym }).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
      end

      it 'should return the nodes in the correct order' do
        result = node(:node1).traverse(:depth_first)
        expect(result.collect { |n| n.name.to_sym }).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
      end

    end

  end

  describe 'breadth first traversal' do

    before do
      setup_tree <<-ENDTREE
        node1:
          - node2:
            - node5
          - node3:
            - node6
            - node7
          - node4
      ENDTREE
    end

    it "should traverse correctly" do
      result = []
      node(:node1).traverse(:breadth_first) { |n| result << n }
      expect(result.collect { |n| n.name.to_sym }).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
    end

    it "should return and array containing the results of the block for each node" do
      result = node(:node1).traverse(:breadth_first) { |n| n.name.to_sym }
      expect(result).to eq([:node1, :node2, :node3, :node4, :node5, :node6, :node7])
    end

  end

  describe '.traverse' do
    before :each do
      setup_tree <<-ENDTREE
        - root1
        - root2
      ENDTREE

      @root1 = node(:root1)
      @root2 = node(:root2)

      allow(Node).to receive(:roots).and_return [@root1, @root2]
    end

    it 'should grab each root' do
      expect(Node).to receive(:roots).and_return []

      expect(Node.traverse).to eq([])
    end

    it 'should default the "type" arg to :depth_first' do
      expect(@root1).to receive(:traverse).with(:depth_first).and_return([])
      expect(@root2).to receive(:traverse).with(:depth_first).and_return([])

      expect(Node.traverse).to eq([])
    end

    it 'should traverse each root' do
      expect(@root1).to receive(:traverse).and_return([1, 2])
      expect(@root2).to receive(:traverse).and_return([3, 4])

      expect(Node.traverse).to eq([1, 2, 3, 4])
    end

    describe 'when the "type" arg is :breadth_first' do

      it 'should traverse breadth-first' do
        expect(@root1).to receive(:traverse).with(:breadth_first).and_return([])
        expect(@root2).to receive(:traverse).with(:breadth_first).and_return([])

        Node.traverse :breadth_first
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129.label.xml
Template File: sources-sinks-84a.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Larger than zero but less than 10
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the upper bound
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84.h"

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84
{

#ifndef OMITBAD

void bad()
{
    int data;
    /* Initialize data */
    data = -1;
    CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_bad * badObject = new CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_bad(data);
    delete badObject;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_goodG2B * goodG2BObject = new CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_goodG2B(data);
    delete goodG2BObject;
}

/* goodG2B uses the BadSource with the GoodSink */
static void goodB2G()
{
    int data;
    /* Initialize data */
    data = -1;
    CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_goodB2G * goodB2GObject = new CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84_goodB2G(data);
    delete goodB2GObject;
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_84; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
title: '"Introduction to databases" by Fatemeh Salehian Kia'
text: This is an introductory course on Databases and SQL Querying. There are no pre-requisites for this workshop. If you are looking to get acquainted with the concept of Databases and Queries, this is the right workshop for you.
location: "Room 7200, Library Research Commons, SFU Burnaby Campus"
link: https://github.com/sciprog-sfu/sciprog-sfu.github.io/issues/224
date: 2020-01-31
startTime: '13:30'
endTime: '15:00'
---


text:
"""Functions for approximating derivatives.

Finite difference methods operate on GridVariable and return GridArray.
Evaluating finite differences requires boundary conditions, which are defined
for a GridVariable. But the operation of taking a derivative makes the boundary
condition undefined, which is why the return type is GridArray.

For example, if the variable c has the boundary condition c_b = 0, and we take
the derivate dc/dx, then it is unclear what the boundary condition on dc/dx
should be. So programmatically, after taking finite differences and doing
operations, the user has to explicitly assign boundary conditions to the result.

Example:
  c = GridVariable(c_array, c_boundary_condition)
  dcdx = finite_differences.forward_difference(c)  # returns GridArray
  c_new = c + dt * (-velocity * dcdx)  # operations on GridArrays
  c_new = GridVariable(c_new, c_boundary_condition)  # assocaite BCs
"""

import typing
from typing import Optional, Sequence, Tuple
from jax_cfd.base import grids
from jax_cfd.base import interpolation
import numpy as np

GridArray = grids.GridArray
GridVariable = grids.GridVariable
GridArrayTensor = grids.GridArrayTensor

def stencil_sum(*arrays: GridArray) -> GridArray:
  """Sum arrays across a stencil, with an averaged offset."""
  # pylint: disable=line-too-long
  offset = grids.averaged_offset(*arrays)
  # pytype appears to have a bad type signature for sum():
  # Built-in function sum was called with the wrong arguments [wrong-arg-types]
  #          Expected: (iterable: Iterable[complex])
  #   Actually passed: (iterable: Generator[Union[jax.interpreters.xla.DeviceArray, numpy.ndarray], Any, None])
  result = sum(array.data for array in arrays)  # type: ignore
  grid = grids.consistent_grid(*arrays)
  return grids.GridArray(result, offset, grid)

# incompatible with typing.overload
# pylint: disable=pointless-statement
# pylint: disable=function-redefined
# pylint: disable=unused-argument

@typing.overload
def central_difference(u: GridVariable, axis: int) -> GridArray:
  ...

@typing.overload
def central_difference(
    u: GridVariable, axis: Optional[Tuple[int, ...]]) -> Tuple[GridArray, ...]:
  ...

def central_difference(u, axis=None):
  """Approximates grads with central differences."""
  if axis is None:
    axis = range(u.grid.ndim)
  if not isinstance(axis, int):
    return tuple(central_difference(u, a) for a in axis)
  diff = stencil_sum(u.shift(+1, axis), -u.shift(-1, axis))
  return diff / (2 * u.grid.step[axis])

@typing.overload
def backward_difference(u: GridVariable, axis: int) -> GridArray:
  ...

@typing.overload
def backward_difference(
    u: GridVariable, axis: Optional[Tuple[int, ...]]) -> Tuple[GridArray, ...]:
  ...

def backward_difference(u, axis=None):
  """Approximates grads with finite differences in the backward direction."""
  if axis is None:
    axis = range(u.grid.ndim)
  if not isinstance(axis, int):
    return tuple(backward_difference(u, a) for a in axis)
  diff = stencil_sum(u.array, -u.shift(-1, axis))
  return diff / u.grid.step[axis]

@typing.overload
def forward_difference(u: GridVariable, axis: int) -> GridArray:
  ...

@typing.overload
def forward_difference(
    u: GridVariable,
    axis: Optional[Tuple[int, ...]] = ...) -> Tuple[GridArray, ...]:
  ...

def forward_difference(u, axis=None):
  """Approximates grads with finite differences in the forward direction."""
  if axis is None:
    axis = range(u.grid.ndim)
  if not isinstance(axis, int):
    return tuple(forward_difference(u, a) for a in axis)
  diff = stencil_sum(u.shift(+1, axis), -u.array)
  return diff / u.grid.step[axis]

def laplacian(u: GridVariable) -> GridArray:
  """Approximates the Laplacian of `u`."""
  scales = np.square(1 / np.array(u.grid.step, dtype=u.dtype))
  result = -2 * u.array * np.sum(scales)
  for axis in range(u.grid.ndim):
    result += stencil_sum(u.shift(-1, axis), u.shift(+1, axis)) * scales[axis]
  return result

def divergence(v: Sequence[GridVariable]) -> GridArray:
  """Approximates the divergence of `v` using backward differences."""
  grid = grids.consistent_grid(*v)
  if len(v) != grid.ndim:
    raise ValueError('The length of `v` must be equal to `grid.ndim`.'
                     f'Expected length {grid.ndim}; got {len(v)}.')
  differences = [backward_difference(u, axis) for axis, u in enumerate(v)]
  return sum(differences)

def centered_divergence(v: Sequence[GridVariable]) -> GridArray:
  """Approximates the divergence of `v` using centered differences."""
  grid = grids.consistent_grid(*v)
  if len(v) != grid.ndim:
    raise ValueError('The length of `v` must be equal to `grid.ndim`.'
                     f'Expected length {grid.ndim}; got {len(v)}.')
  differences = [central_difference(u, axis) for axis, u in enumerate(v)]
  return sum(differences)

@typing.overload
def gradient_tensor(v: GridVariable) -> GridArrayTensor:
  ...

@typing.overload
def gradient_tensor(v: Sequence[GridVariable]) -> GridArrayTensor:
  ...

def gradient_tensor(v):
  """Approximates the cell-centered gradient of `v`."""
  if not isinstance(v, GridVariable):
    return GridArrayTensor(np.stack([gradient_tensor(u) for u in v], axis=-1))
  grad = []
  for axis in range(v.grid.ndim):
    offset = v.offset[axis]
    if offset == 0:
      derivative = forward_difference(v, axis)
    elif offset == 1:
      derivative = backward_difference(v, axis)
    elif offset == 0.5:
      v_centered = interpolation.linear(v, v.grid.cell_center)
      derivative = central_difference(v_centered, axis)
    else:
      raise ValueError(f'expected offset values in {{0, 0.5, 1}}, got {offset}')
    grad.append(derivative)
  return GridArrayTensor(grad)

def curl_2d(v: Sequence[GridVariable]) -> GridArray:
  """Approximates the curl of `v` in 2D using forward differences."""
  if len(v) != 2:
    raise ValueError(f'Length of `v` is not 2: {len(v)}')
  grid = grids.consistent_grid(*v)
  if grid.ndim != 2:
    raise ValueError(f'Grid dimensionality is not 2: {grid.ndim}')
  return forward_difference(v[1], axis=0) - forward_difference(v[0], axis=1)

def curl_3d(
    v: Sequence[GridVariable]) -> Tuple[GridArray, GridArray, GridArray]:
  """Approximates the curl of `v` in 2D using forward differences."""
  if len(v) != 3:
    raise ValueError(f'Length of `v` is not 3: {len(v)}')
  grid = grids.consistent_grid(*v)
  if grid.ndim != 3:
    raise ValueError(f'Grid dimensionality is not 3: {grid.ndim}')
  curl_x = (forward_difference(v[2], axis=1) - forward_difference(v[1], axis=2))
  curl_y = (forward_difference(v[0], axis=2) - forward_difference(v[2], axis=0))
  curl_z = (forward_difference(v[1], axis=0) - forward_difference(v[0], axis=1))
  return (curl_x, curl_y, curl_z)


text:
from common_fixtures import *  # NOQA
from cattle import ApiError
import yaml

def _get_agent_for_container(context, container):
    agent = None
    for map in container.hosts()[0].instanceHostMaps():
        try:
            c = map.instance()
        except Exception:
            continue
        if c.agentId is not None:
            agent = c.agent()
            break

    if agent is None:
        client = context.client
        env = client.create_stack(name='env-' + random_str())
        labels = {'io.rancher.scheduler.global': 'true',
                  'io.rancher.container.create_agent':
                  'true'}
        svc = client.create_service(client, 'global',
                                    name='agentglobal' + random_str(),
                                    launchConfig={
                                        'imageUuid': context.image_uuid,
                                        "labels": labels
                                    }, stackId=env.id)
        svc = client.wait_success(svc)
        svc = client.wait_success(svc.activate())

    for map in container.hosts()[0].instanceHostMaps():
        try:
            c = map.instance()
        except Exception:
            continue
        if c.agentId is not None:
            agent = c.agent()
            break

    assert agent is not None
    return agent

def _get_agent_client(agent):
    creds = agent.account().credentials()

    api_key = [x for x in creds if x.kind == 'agentApiKey'][0]
    assert len(api_key)
    return api_client(api_key.publicValue, api_key.secretValue)

def test_upgrade_with_health(client, context, super_client):
    env = client.create_stack(name='env-' + random_str())

    image_uuid = context.image_uuid
    launch_config = {"imageUuid": image_uuid}

    svc = client.create_service(name=random_str(),
                                stackId=env.id,
                                launchConfig=launch_config,
                                scale=1)
    svc = client.wait_success(svc)
    assert svc.state == "inactive"

    env.activateservices()
    svc = client.wait_success(svc, 120)
    assert svc.state == "active"

    # upgrade the service and
    new_launch_config = {"imageUuid": image_uuid,
                         'healthCheck': {
                             'port': 80,
                         }}
    strategy = {"launchConfig": new_launch_config,
                "intervalMillis": 100}
    svc.upgrade_action(inServiceStrategy=strategy)

    def wait_for_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active')
        return len(m) == 2

    def wait_for_managed_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active',
                                  upgrade=False)
        return len(m) == 1

    wait_for_condition(client, svc, wait_for_map_count)
    wait_for_condition(client, svc, wait_for_managed_map_count)

    m = super_client. \
        list_serviceExposeMap(serviceId=svc.id, state='active', upgrade=False)

    c = super_client.reload(m[0].instance())

    wait_for(lambda: super_client.reload(c).state == 'running')

    c = super_client.reload(m[0].instance())

    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    # shouldn't become upgraded at this point
    try:
        wait_for(lambda: super_client.reload(svc).state == 'upgraded',
                 timeout=10)
    except Exception:
        pass

    _update_healthy(agent, hcihm, c, super_client)

    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: super_client.reload(svc).state == 'upgraded')
    super_client.reload(svc).remove()

def _create_and_activate_svc(client, count, **kw):
    svc = client.create_service(kw)
    svc = client.wait_success(svc)
    assert svc.state == "inactive"
    svc.activate()
    # wait for service instances to become running
    if count == 'global':
        time.sleep(2)
        dus = client.list_deploymentUnit(serviceId=svc.id)
        wait_for(lambda: len(client.reload(svc).instances()) >= len(dus))
    else:
        wait_for(lambda: len(client.reload(svc).instances()) == count)
    for i in client.reload(svc).instances():
        wait_for(lambda: client.reload(i).state == 'running')
    return client.reload(svc)

def test_upgrade_start_first_with_health(client, context, super_client):
    env = client.create_stack(name='env-' + random_str())

    image_uuid = context.image_uuid
    launch_config = {"imageUuid": image_uuid}

    svc = client.create_service(name=random_str(),
                                stackId=env.id,
                                launchConfig=launch_config,
                                scale=1)
    svc = client.wait_success(svc)
    assert svc.state == "inactive"

    env.activateservices()
    svc = client.wait_success(svc, 120)
    assert svc.state == "active"

    # upgrade the service and
    # check that c3 and c2 got the same ip
    new_launch_config = {"imageUuid": image_uuid,
                         'healthCheck': {
                             'port': 80,
                         }}
    strategy = {"launchConfig": new_launch_config,
                "intervalMillis": 100,
                "startFirst": True}
    svc.upgrade_action(inServiceStrategy=strategy)

    def wait_for_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active')
        return len(m) == 2

    def wait_for_managed_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active',
                                  upgrade=False)
        return len(m) == 1

    wait_for_condition(client, svc, wait_for_map_count)
    wait_for_condition(client, svc, wait_for_managed_map_count)

    m = super_client. \
        list_serviceExposeMap(serviceId=svc.id, state='active', upgrade=False)

    c = super_client.reload(m[0].instance())

    wait_for(lambda: super_client.reload(c).state == 'running')

    c = super_client.reload(m[0].instance())

    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    _update_healthy(agent, hcihm, c, super_client)

    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: super_client.reload(svc).state == 'upgraded')
    super_client.reload(svc).remove()

def test_health_check_create_instance(super_client, context):
    c = context.create_container(healthCheck={
        'port': 80,
    })

    assert c.healthCheck.port == 80

    c = super_client.reload(c)
    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)

    se = super_client.wait_success(se)
    assert se.state == 'created'
    assert se.accountId == c.accountId
    assert se.instanceId == c.id
    assert se.healthcheckInstanceId == hci.id

    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    assert hcihm.externalTimestamp == ts

    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

def _create_svc_w_healthcheck(client, context):
    env = client.create_stack(name='env-' + random_str())
    return _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

def test_health_check_create_service(super_client, context, client):
    service = _create_svc_w_healthcheck(client, context)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something Bad',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='INIT',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    # restart the instance
    c = super_client.wait_success(c.stop(stopSource='external'))
    wait_for(lambda: super_client.reload(c).state == 'running')
    wait_for(lambda: super_client.reload(c).healthState == 'reinitializing')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something bad',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'reinitializing')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='INIT',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something Bad',
                                     healthcheckUuid=hcihm.uuid)

    se = super_client.wait_success(se)
    assert se.state == 'created'
    assert se.accountId == c.accountId
    assert se.instanceId == c.id
    assert se.healthcheckInstanceId == hci.id

    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'unhealthy'
    assert hcihm.externalTimestamp == ts

    wait_for(lambda: super_client.reload(c).healthState == 'unhealthy')
    wait_for(lambda: len(service.serviceExposeMaps()) == 1)
    _remove_service(service)

def test_health_check_ip_retain(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id, retainIp=True)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c1 = super_client.reload(expose_map.instance())
    ip1 = c1.primaryIpAddress
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c1)

    assert hcihm.healthState == 'initializing'
    assert c1.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c1).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something Bad',
                                     healthcheckUuid=hcihm.uuid)

    se = super_client.wait_success(se)
    assert se.state == 'created'
    assert se.accountId == c1.accountId
    assert se.instanceId == c1.id
    assert se.healthcheckInstanceId == hci.id

    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'unhealthy'
    assert hcihm.externalTimestamp == ts

    wait_for(lambda: super_client.reload(c1).healthState == 'unhealthy')

    def check():
        s = super_client.reload(service)
        return s.instanceIds is not None and len(s.instanceIds) == 1 and \
            c1.id not in s.instanceIds

    wait_for(check)
    super_client.wait_success(c1)
    for e_map in service.serviceExposeMaps():
        if e_map.instance().id == c1.id:
            continue
        c2 = wait_state(super_client, e_map.instance(), 'running')
        assert c2.name == c1.name
        assert c2.primaryIpAddress == ip1
        break
    _remove_service(service)

def test_health_state_stack(super_client, context, client):
    c = client
    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

    i = 'initializing'
    wait_for(lambda: super_client.reload(service).healthState == i)
    wait_for(lambda: client.reload(env).healthState == i)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c1 = super_client.reload(expose_map.instance())
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c1)
    assert hcihm.healthState == 'initializing'
    assert c1.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c1).healthState == 'healthy')

    wait_for(lambda: super_client.reload(service).healthState == 'healthy')
    wait_for(lambda: c.reload(env).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something Bad',
                                     healthcheckUuid=hcihm.uuid)

    se = super_client.wait_success(se)
    assert se.state == 'created'
    assert se.accountId == c1.accountId
    assert se.instanceId == c1.id
    assert se.healthcheckInstanceId == hci.id

    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'unhealthy'
    assert hcihm.externalTimestamp == ts

    wait_for(lambda: super_client.reload(c1).healthState == 'unhealthy')

def test_health_state_start_once(super_client, context, client):
    c = client
    env = client.create_stack(name='env-' + random_str())
    labels = {"io.rancher.container.start_once": "true"}
    svc = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        },
        'labels': labels
    }, stackId=env.id)

    wait_for(lambda: super_client.reload(svc).healthState == 'initializing')
    wait_for(lambda: c.reload(env).healthState == 'initializing')

    maps = _wait_until_active_map_count(svc, 1, client)
    expose_map = maps[0]
    c1 = super_client.reload(expose_map.instance())
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c1)
    assert hcihm.healthState == 'initializing'
    assert c1.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c1).healthState == 'healthy')

    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: c.reload(env).healthState == 'healthy')

    super_client.wait_success(c1.stop())

    wait_for(lambda: super_client.reload(svc).healthState == 'started-once')
    wait_for(lambda: c.reload(env).healthState == 'started-once')
    _remove_service(svc)

def test_health_state_sidekick_start_once(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    labels = {"io.rancher.container.start_once": "true"}
    slc = {'imageUuid': context.image_uuid, 'name': "test1"}
    svc = _create_and_activate_svc(client, 2, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'labels': labels
    }, stackId=env.id, secondaryLaunchConfigs=[slc])

    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: client.reload(env).healthState == 'healthy')

def test_health_state_selectors(context, client):
    env = client.create_stack(name='env-' + random_str())
    labels = {'foo': "bar"}
    container1 = client.create_container(imageUuid=context.image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container1 = client.wait_success(container1)
    assert container1.state == "running"

    launch_config = {"imageUuid": "rancher/none"}
    service = _create_and_activate_svc(client, 1, name=random_str(),
                                       stackId=env.id,
                                       launchConfig=launch_config,
                                       selectorContainer="foo=bar")
    service = client.wait_success(service)
    assert service.selectorContainer == "foo=bar"

    wait_for(lambda: client.reload(service).healthState == 'healthy')
    wait_for(lambda: client.reload(env).healthState == 'healthy')
    _remove_service(service)

def test_svc_health_state(context, client):
    env = client.create_stack(name='env-' + random_str())

    launch_config = {"imageUuid": context.image_uuid}
    service = _create_and_activate_svc(client, 1, name=random_str(),
                                       stackId=env.id,
                                       launchConfig=launch_config)

    wait_for(lambda: client.reload(service).healthState == 'healthy')
    wait_for(lambda: client.reload(env).healthState == 'healthy')
    _remove_service(service)

def test_health_check_init_timeout(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
            'initializingTimeout': 2000,
        }
    }, stackId=env.id)
    h_c = service.launchConfig.healthCheck
    assert h_c.initializingTimeout == 2000

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    # wait for the instance to be removed
    wait_for_condition(client, c, lambda x: x.removed is None)
    _remove_service(service)

def test_health_check_reinit_timeout(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
            'reinitializingTimeout': 1,
        }
    }, stackId=env.id)
    h_c = service.launchConfig.healthCheck
    assert h_c.reinitializingTimeout == 1

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    # restart the instance
    c = super_client.wait_success(c.restart())
    wait_for(lambda: super_client.reload(c).state == 'running')
    wait_for(lambda: super_client.reload(c).healthState == 'reinitializing')

    # wait for the instance to be removed
    wait_for_condition(super_client, c,
                       lambda x: x.removed is not None)
    _remove_service(service)

def test_health_check_bad_external_timestamp(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    container = super_client.reload(expose_map.instance())
    hci = find_one(container.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, container)
    agent_client = _get_agent_client(agent)

    assert hcihm.healthState == 'initializing'

    with pytest.raises(ApiError) as e:
        agent_client.create_service_event(reportedHealth='Something Bad',
                                          healthcheckUuid=hcihm.uuid)
    assert e.value.error.code == 'MissingRequired'
    assert e.value.error.fieldName == 'externalTimestamp'
    _remove_service(service)

def test_health_check_noop(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    svc = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
            'strategy': 'none'
        }
    }, stackId=env.id)

    assert svc.launchConfig.healthCheck.strategy == 'none'

    maps = _wait_until_active_map_count(svc, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    hci = find_one(c.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c)

    assert hcihm.healthState == 'initializing'
    assert c.healthState == 'initializing'

    hcihm = _update_healthy(agent, hcihm, c, super_client)
    svc = wait_state(client, svc, 'active')

    _update_unhealthy(agent, hcihm, c, super_client)

    svc = wait_state(client, svc, 'active')

    assert len(svc.serviceExposeMaps()) == 1
    c = super_client.wait_success(c)
    assert c.state == 'running'
    _remove_service(svc)

def _remove_service(svc):
    for i in range(1, 3):
        try:
            svc.remove()
            return
        except Exception:
            pass
        time.sleep(1)

def test_health_check_default(super_client, context, client):
    env = client.create_stack(name='env-' + random_str())
    svc = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80
        }
    }, stackId=env.id)

    expose_maps = svc.serviceExposeMaps()
    c1 = super_client.reload(expose_maps[0].instance())
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(context, c1)

    assert hcihm.healthState == 'initializing'
    assert c1.healthState == 'initializing'

    hcihm = _update_healthy(agent, hcihm, c1, super_client)

    # update unheatlhy, the container should be removed
    _update_unhealthy(agent, hcihm, c1, super_client)
    c1 = super_client.wait_success(c1)
    wait_for_condition(client, c1,
                       lambda x: x.removed is not None)
    wait_for(lambda: len(svc.serviceExposeMaps()) == 1)
    _remove_service(svc)

def test_health_check_bad_agent(super_client, context, client):
    # Create another host to get the agent from that host
    host2 = super_client.reload(register_simulated_host(context))
    # register one more host to ensure
    # there is at least one more host
    # to schedule healtcheck on
    register_simulated_host(context)

    env = client.create_stack(name='env-' + random_str())
    s = _create_and_activate_svc(client, 'global', name='test', launchConfig={
        'imageUuid': context.image_uuid,
        'healthCheck': {
            'port': 80,
        },
        "labels": {
            'io.rancher.scheduler.global': 'true'
        }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(s, 3, client)
    expose_map = maps[0]
    container = super_client.reload(expose_map.instance())
    hci = find_one(container.healthcheckInstances)
    hcihm = None
    wait_for(lambda: len(hci.healthcheckInstanceHostMaps()) > 1)
    for h in hci.healthcheckInstanceHostMaps():
        if h.hostId != host2.id:
            hcihm = h
            break
    assert hcihm is not None
    agent_client = _get_agent_client(host2.agent())

    assert hcihm.healthState == 'initializing'

    ts = int(time.time())
    with pytest.raises(ApiError) as e:
        agent_client.create_service_event(externalTimestamp=ts,
                                          reportedHealth='Something Bad',
                                          healthcheckUuid=hcihm.uuid)
    assert e.value.error.code == 'CantVerifyHealthcheck'
    _remove_service(s)

def test_health_check_reconcile(super_client, new_context):
    super_client.reload(register_simulated_host(new_context))
    super_client.reload(register_simulated_host(new_context))
    client = new_context.client

    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    initial_len = len(c.healthcheckInstanceHostMaps())
    assert initial_len == 2

    for h in c.healthcheckInstanceHostMaps():
        assert h.healthState == c.healthState

    hcihm1 = c.healthcheckInstanceHostMaps()[0]
    hosts = super_client.list_host(uuid=hcihm1.host().uuid)
    assert len(hosts) == 1

    hcihm2 = c.healthcheckInstanceHostMaps()[1]
    hosts = super_client.list_host(uuid=hcihm2.host().uuid)
    assert len(hosts) == 1
    host2 = hosts[0]

    agent = _get_agent_for_container(new_context, c)

    assert hcihm1.healthState == 'initializing'
    assert hcihm2.healthState == 'initializing'
    assert c.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm1.uuid)
    super_client.wait_success(se)
    hcihm1 = super_client.wait_success(super_client.reload(hcihm1))
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm2.uuid)
    super_client.wait_success(se)
    super_client.wait_success(super_client.reload(hcihm2))
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something Bad',
                                     healthcheckUuid=hcihm1.uuid)
    super_client.wait_success(se)
    super_client.wait_success(super_client.reload(hcihm1))

    # still healthy as only one host reported healthy
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')
    # remove the host 1
    host2 = super_client.wait_success(host2.deactivate())
    host2 = super_client.wait_success(super_client.delete(host2))
    assert host2.state == 'removed'

    # should be unhealthy as the only health state reported is unhealthy
    wait_for(lambda: super_client.reload(c).healthState == 'unhealthy')
    _remove_service(service)

def test_health_check_all_hosts_removed_reconcile(super_client, new_context):
    super_client.reload(register_simulated_host(new_context))
    client = new_context.client

    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    wait_for(lambda: super_client.reload(c).state == 'running')
    initial_len = len(c.healthcheckInstanceHostMaps())
    assert initial_len == 1

    for h in c.healthcheckInstanceHostMaps():
        assert h.healthState == c.healthState

    hcihm1 = c.healthcheckInstanceHostMaps()[0]
    hosts = super_client.list_host(uuid=hcihm1.host().uuid)
    assert len(hosts) == 1
    host1 = hosts[0]

    agent = _get_agent_for_container(new_context, c)

    assert hcihm1.healthState == 'initializing'
    assert c.healthState == 'initializing'

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm1.uuid)
    super_client.wait_success(se)
    super_client.wait_success(super_client.reload(hcihm1))
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    # remove health checker host
    host1 = super_client.wait_success(host1.deactivate())
    host1 = super_client.wait_success(super_client.delete(host1))
    assert host1.state == 'removed'

    # instance should stay as healthy
    try:
        wait_for(lambda: super_client.reload(c).healthState == 'unhealthy',
                 timeout=5)
    except Exception:
        pass

    wait_for(lambda: super_client.reload(c).healthState == 'healthy')
    _remove_service(service)

def test_health_check_host_disconnected_reconcile(super_client, new_context):
    client = new_context.client

    # Create service
    env = client.create_stack(name='env-' + random_str())
    service = client.create_service(name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {'port': 80},
    }, stackId=env.id)
    service = client.wait_success(service).activate()

    # Get and check the healthcheck resources
    maps = _wait_until_active_map_count(service, 1, client)
    c = super_client.reload(maps[0].instance())
    wait_for(lambda: len(c.healthcheckInstanceHostMaps()) == 1)
    hcihm1 = c.healthcheckInstanceHostMaps()[0]
    assert len(super_client.list_host(uuid=hcihm1.host().uuid)) == 1

    # Send a healthcheck event
    agent = _get_agent_for_container(new_context, c)
    agent_client = _get_agent_client(agent)
    se = agent_client.create_service_event(externalTimestamp=int(time.time()),
                                           reportedHealth='UP',
                                           healthcheckUuid=hcihm1.uuid)
    super_client.wait_success(se)
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    # Cause the simulator to stop responding to pings
    cd = client.create_container(name='simDisconnectAgent',
                                 imageUuid=new_context.image_uuid)
    wait_for_condition(client, cd, lambda x: x.state == 'starting' or
                       x.state == 'running')

    # Forcibly move through reconnect and disconnect so we don't have to wait
    for i in range(20):
        super_agent = super_client.reload(
            new_context.agent.agents()[0].reconnect())
        wait_for(lambda: super_client.reload(super_agent).state ==
                 'reconnecting')
        super_agent = super_client.wait_success(super_agent.disconnect())
        if super_agent.state == 'active':
            continue
        assert super_agent.state == 'disconnected'
        break
    wait_for(lambda: len(c.healthcheckInstanceHostMaps()) == 0)

    # instance should stay as healthy
    try:
        wait_for(lambda: super_client.reload(c).healthState == 'unhealthy',
                 timeout=5)
    except Exception:
        pass
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')

    # Add a new host which causes the old instance to get a new hcihm
    register_simulated_host(new_context)
    assert len(c.healthcheckInstanceHostMaps()) == 1

    # Send an event for the new healthcheck to say the instance is unhealthy
    # This should cause the container to be removed
    hcihm1 = c.healthcheckInstanceHostMaps()[0]
    se = agent_client.create_service_event(externalTimestamp=int(time.time()),
                                           reportedHealth='DOWN',
                                           healthcheckUuid=hcihm1.uuid)
    super_client.wait_success(se)
    wait_for(lambda: super_client.reload(c).removed is not None)

    # Assert that a new container gets created for the service
    maps = _wait_until_active_map_count(service, 1, client)
    c2 = super_client.reload(maps[0].instance())
    assert c2.id != c.id

def test_hosts_removed_reconcile_when_init(super_client, new_context):
    super_client.reload(register_simulated_host(new_context))
    client = new_context.client

    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 1, name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    initial_len = len(c.healthcheckInstanceHostMaps())
    assert initial_len == 1

    for h in c.healthcheckInstanceHostMaps():
        assert h.healthState == c.healthState

    hcihm1 = c.healthcheckInstanceHostMaps()[0]
    hosts = super_client.list_host(uuid=hcihm1.host().uuid)
    assert len(hosts) == 1
    host1 = hosts[0]

    assert hcihm1.healthState == 'initializing'
    assert c.healthState == 'initializing'

    # remove the healthchecking host
    host1 = super_client.wait_success(host1.deactivate())
    host1 = super_client.wait_success(super_client.delete(host1))
    assert host1.state == 'removed'

    # instance should remain as healthy as there are no reporters at this point
    try:
        wait_for(lambda: super_client.reload(c).healthState == 'unhealthy',
                 timeout=5)
    except Exception:
        pass

    wait_for(lambda: super_client.reload(c).healthState == 'initializing')
    _remove_service(service)

def test_health_check_host_remove(super_client, new_context):
    client = new_context.client
    # create 4 hosts for healtcheck as one of them would be removed later
    super_client.reload(register_simulated_host(new_context))
    super_client.reload(register_simulated_host(new_context))
    super_client.reload(register_simulated_host(new_context))
    super_client.reload(register_simulated_host(new_context))

    env = client.create_stack(name='env-' + random_str())
    service = _create_and_activate_svc(client, 5, name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {
            'port': 80,
        }, "labels": {
            'io.rancher.scheduler.global': 'true'
            }
    }, stackId=env.id)

    maps = _wait_until_active_map_count(service, 5, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    initial_len = len(c.healthcheckInstanceHostMaps())
    assert initial_len == 3

    for h in c.healthcheckInstanceHostMaps():
        assert h.healthState == c.healthState

    hcihm = c.healthcheckInstanceHostMaps()[0]
    hosts = super_client.list_host(uuid=hcihm.host().uuid)
    assert len(hosts) == 1
    host = hosts[0]

    # remove the host
    host = super_client.wait_success(host.deactivate())
    host = super_client.wait_success(super_client.delete(host))
    assert host.state == 'removed'

    # verify that new hostmap was created for the instance
    wait_for(lambda: len(c.healthcheckInstanceHostMaps()) == initial_len)

    hcim = None
    for h in c.healthcheckInstanceHostMaps():
        if h.hostId == host.id:
            if hcihm.state == 'active':
                hcihm = h
                break

    assert hcim is None
    _remove_service(service)

def test_healtcheck(new_context, super_client):
    client = new_context.client
    image_uuid = new_context.image_uuid
    stack = client.create_stack(name='env-' + random_str())
    host = register_simulated_host(new_context)
    client.wait_success(host)

    health_check = {"name": "check1", "responseTimeout": 3,
                    "interval": 4, "healthyThreshold": 5,
                    "unhealthyThreshold": 6, "requestLine": "index.html",
                    "port": 200}
    launch_config = {"imageUuid": image_uuid, "healthCheck": health_check}
    service = _create_and_activate_svc(client, 1, name=random_str(),
                                       stackId=stack.id,
                                       launchConfig=launch_config)
    maps = _wait_until_active_map_count(service, 1, client)
    expose_map = maps[0]
    c = super_client.reload(expose_map.instance())
    c_host_id = super_client.reload(c).instanceHostMaps()[0].hostId
    health_c = super_client. \
        list_healthcheckInstance(accountId=service.accountId, instanceId=c.id)
    assert len(health_c) > 0
    health_id = health_c[0].id

    def validate_container_host(host_maps):
        for host_map in host_maps:
            assert host_map.hostId != c_host_id

    host_maps = _wait_health_host_count(super_client, health_id, 3)
    validate_container_host(host_maps)

    # restart the instance
    # verify that its still has less than 3 healthchecks
    c = client.wait_success(c.stop())
    c = client.wait_success(c.start())

    host_maps = _wait_health_host_count(super_client, health_id, 3)
    validate_container_host(host_maps)

    # stop instance, add 3 more hosts, start instance and verify
    # that healthcheckers number was completed to 3, excluding
    # container's host
    c = client.wait_success(c.stop())
    for i in range(0, 3):
        host = register_simulated_host(new_context)
        client.wait_success(host)

    c.start()

    host_maps = _wait_health_host_count(super_client, health_id, 3)
    validate_container_host(host_maps)
    _remove_service(service)

def _wait_health_host_count(super_client, health_id, count):
    def active_len():
        match = super_client. \
            list_healthcheckInstanceHostMap(healthcheckInstanceId=health_id,
                                            state='active')
        if len(match) <= count:
            return match

    return wait_for(active_len)

def test_external_svc_healthcheck(client, context):
    env = client.create_stack(name='env-' + random_str())

    # test that external service was set with healtcheck
    health_check = {"name": "check1", "responseTimeout": 3,
                    "interval": 4, "healthyThreshold": 5,
                    "unhealthyThreshold": 6, "requestLine": "index.html",
                    "port": 200}
    ips = ["72.22.16.5", '192.168.0.10']
    service = client.create_externalService(name=random_str(),
                                            stackId=env.id,
                                            externalIpAddresses=ips,
                                            healthCheck=health_check)
    service = client.wait_success(service)
    assert service.healthCheck.name == "check1"
    assert service.healthCheck.responseTimeout == 3
    assert service.healthCheck.interval == 4
    assert service.healthCheck.healthyThreshold == 5
    assert service.healthCheck.unhealthyThreshold == 6
    assert service.healthCheck.requestLine == "index.html"
    assert service.healthCheck.port == 200

    # test rancher-compose export
    compose_config = env.exportconfig()
    assert compose_config is not None
    document = yaml.load(compose_config.rancherComposeConfig)
    assert document['services'][service.name]['health_check'] is not None

def _update_healthy(agent, hcihm, c, super_client):
    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c).healthState == 'healthy')
    return hcihm

def _update_unhealthy(agent, hcihm, c, super_client):
    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='Something bad',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'unhealthy'
    wait_for(lambda: super_client.reload(c).healthState == 'unhealthy')

def _wait_until_active_map_count(service, count, client):
    def wait_for_map_count(service):
        m = client. \
            list_serviceExposeMap(serviceId=service.id, state='active')
        return len(m) == count

    wait_for_condition(client, service, wait_for_map_count)
    return client. \
        list_serviceExposeMap(serviceId=service.id, state='active')

def test_global_service_health(new_context):
    client = new_context.client
    host1 = new_context.host
    host2 = register_simulated_host(new_context)

    client.wait_success(host1)
    client.wait_success(host2)

    # create stack and services
    env = client.create_stack(name='env-' + random_str())
    image_uuid = new_context.image_uuid
    labels = {"io.rancher.container.start_once": "true"}
    secondary_lc = {"imageUuid": image_uuid, "name": "secondary",
                    "labels": labels}
    launch_config = {
        "imageUuid": image_uuid,
        "labels": {
            'io.rancher.scheduler.global': 'true'
        }
    }
    svc = client.create_service(name=random_str(),
                                stackId=env.id,
                                launchConfig=launch_config,
                                secondaryLaunchConfigs=[secondary_lc])
    svc = client.wait_success(svc)
    assert svc.state == "inactive"

    svc = client.wait_success(svc.activate(), 120)

    wait_for(lambda: client.reload(svc).healthState == 'healthy')

    # stop instances
    c1 = _validate_compose_instance_start(client, svc, env, "1",
                                          "secondary")
    c2 = _validate_compose_instance_start(client, svc, env, "2",
                                          "secondary")
    client.wait_success(c1.stop())
    client.wait_success(c2.stop())

    wait_for(lambda: client.reload(svc).healthState == 'healthy')
    wait_for(lambda: client.reload(env).healthState == 'healthy')
    wait_for(lambda: client.reload(new_context.
                                   project).healthState == 'healthy')

def _validate_compose_instance_start(client, service, env,
                                     number, launch_config_name=None):
    cn = launch_config_name + "-" if \
        launch_config_name is not None else ""
    name = env.name + "-" + service.name + "-" + cn + number

    def wait_for_map_count(service):
        instances = client. \
            list_container(name=name,
                           state="running")
        return len(instances) == 1

    wait_for(lambda: wait_for_condition(client, service,
                                        wait_for_map_count), timeout=5)

    instances = client. \
        list_container(name=name,
                       state="running")
    return instances[0]

def test_stack_health_state(super_client, context, client):
    c = client
    env = client.create_stack(name='env-' + random_str())
    svc = client.create_service(name='test', launchConfig={
        'imageUuid': context.image_uuid
    }, stackId=env.id)
    svc = client.wait_success(client.wait_success(svc).activate())
    assert svc.state == 'active'

    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: c.reload(env).healthState == 'healthy')
    _remove_service(svc)
    wait_for(lambda: super_client.reload(svc).state == 'removed')
    time.sleep(3)
    wait_for(lambda: c.reload(env).healthState == 'healthy')

# Skipped
def _test_du_removal(super_client, new_context):
    host = super_client.reload(register_simulated_host(new_context))
    super_client.wait_success(host)
    client = new_context.client
    env = client.create_stack(name='env-' + random_str())
    svc = client.create_service(name='test', launchConfig={
        'imageUuid': new_context.image_uuid,
        'healthCheck': {
            'port': 80,
        }
    }, stackId=env.id, scale=1)

    svc = client.wait_success(client.wait_success(svc).activate())
    assert svc.state == 'active'
    wait_for(lambda: super_client.reload(svc).healthState == 'initializing')
    wait_for(lambda: client.reload(env).healthState == 'initializing')

    maps = _wait_until_active_map_count(svc, 1, client)
    expose_map = maps[0]
    c1 = super_client.reload(expose_map.instance())
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c1)
    assert hcihm.healthState == 'initializing'
    assert c1.healthState == 'initializing'

    assert c1.healthcheckStates is not None
    assert len(c1.healthcheckStates) == 1
    assert c1.healthcheckStates[0].healthState == 'initializing'
    assert c1.healthcheckStates[0].hostId == hcihm.hostId

    wait_for(lambda: super_client.reload(svc).healthState == 'initializing')
    wait_for(lambda: super_client.reload(env).healthState == 'initializing')
    wait_for(lambda: client.reload(new_context.project).
             healthState == 'initializing')

    ts = int(time.time())
    client = _get_agent_client(agent)
    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='UP',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    hcihm = super_client.wait_success(super_client.reload(hcihm))
    assert hcihm.healthState == 'healthy'
    wait_for(lambda: super_client.reload(c1).healthState == 'healthy')
    wait_for(lambda: super_client.reload(svc).healthState == 'healthy')
    wait_for(lambda: super_client.reload(env).healthState == 'healthy')

    se = client.create_service_event(externalTimestamp=ts,
                                     reportedHealth='DOWN',
                                     healthcheckUuid=hcihm.uuid)
    super_client.wait_success(se)
    wait_for(lambda: super_client.reload(c1).state == 'removed')

    maps = _wait_until_active_map_count(svc, 1, super_client)
    expose_map = maps[0]
    c2 = super_client.reload(expose_map.instance())

    assert c1.deploymentUnitUuid != c2.deploymentUnitUuid

def test_balancer_svc_upgrade(client, context, super_client):
    env = client.create_stack(name='env-' + random_str())
    image_uuid = context.image_uuid

    launch_config = {"imageUuid": image_uuid}
    lb_svc = client. \
        create_loadBalancerService(name=random_str(),
                                   stackId=env.id,
                                   launchConfig=launch_config,
                                   lbConfig={})

    lb_svc = client.wait_success(lb_svc)
    lb_svc = lb_svc.activate()
    assert len(lb_svc.launchConfig.labels) == 2
    assert lb_svc.launchConfig.healthCheck is not None
    m = _wait_until_active_map_count(lb_svc, 1, client)
    c = super_client.reload(m[0].instance())
    wait_for(lambda: super_client.reload(c).state == 'running')
    c = super_client.reload(c)
    assert c.healthState == 'initializing'

    launch_config = {"imageUuid": image_uuid,
                     'labels': {'foo': 'bar'}}
    strategy = {"launchConfig": launch_config,
                "intervalMillis": 100}
    lb_svc.upgrade_action(inServiceStrategy=strategy)

    hci = find_one(c.healthcheckInstances)
    for hcihm in hci.healthcheckInstanceHostMaps():
        agent = _get_agent_for_container(context, c)
        assert hcihm.healthState == 'initializing'
        _update_healthy(agent, hcihm, c, super_client)

    def wait_for_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active')
        return len(m) == 2

    def wait_for_managed_map_count(service):
        m = super_client. \
            list_serviceExposeMap(serviceId=service.id, state='active',
                                  upgrade=False)
        return len(m) == 1

    m = super_client. \
        list_serviceExposeMap(serviceId=lb_svc.id,
                              state='active', upgrade=False)

    wait_for_condition(client, lb_svc, wait_for_map_count)
    wait_for_condition(client, lb_svc, wait_for_managed_map_count)

    m = super_client. \
        list_serviceExposeMap(serviceId=lb_svc.id, state='active',
                              upgrade=False)
    c = super_client.reload(m[0].instance())
    wait_for(lambda: super_client.reload(c).state == 'running')
    hci = find_one(c.healthcheckInstances)
    for hcihm in hci.healthcheckInstanceHostMaps():
        agent = _get_agent_for_container(context, c)
        assert hcihm.healthState == 'initializing'
        _update_healthy(agent, hcihm, c, super_client)

    lb_svc = client.wait_success(lb_svc)
    assert lb_svc.launchConfig.healthCheck is not None
    assert len(lb_svc.launchConfig.labels) == 3

def test_standalone_health_check_recreate(super_client, new_context):
    c1 = new_context.create_container(name='healthcheck-' + random_str(),
                                      healthCheck={'port': 80})

    assert c1.healthCheck.port == 80

    c1 = super_client.reload(c1)
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c1)
    assert hcihm.healthState == 'initializing'

    _update_healthy(agent, hcihm, c1, super_client)

    # update unheatlhy and make sure the container was recreated
    _update_unhealthy(agent, hcihm, c1, super_client)
    c1 = wait_state(super_client, c1, "removed")

    wait_for(lambda: len(super_client.list_container(name=c1.name,
                                                     state="running")) == 1)
    c2 = super_client.list_container(name=c1.name, state="running")[0]
    assert c1.name == c2.name
    assert c1.kind == c2.kind
    assert c2.healthState == "initializing"
    assert c1.deploymentUnitUuid == c2.deploymentUnitUuid

    # update the replacement, and make sure it was recreated again
    hci = find_one(c2.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c2)
    assert hcihm.healthState == 'initializing'
    _update_healthy(agent, hcihm, c2, super_client)
    _update_unhealthy(agent, hcihm, c2, super_client)
    c2 = wait_state(super_client, c2, "removed")

    wait_for(lambda: len(super_client.list_container(name=c1.name,
                                                     state="running")) == 1)
    c3 = super_client.list_container(name=c1.name, state="running")[0]
    assert c3.name == c2.name
    assert c3.kind == c2.kind
    assert c3.healthState == "initializing"
    assert c3.deploymentUnitUuid == c2.deploymentUnitUuid

    # remove the instance, and validate that it is not recreated
    c3 = super_client.wait_success(c3.stop())
    super_client.wait_success(c3.remove())
    wait_for(lambda: len(super_client.list_container(name=c3.name)) == 0)

def test_standalone_health_check_noop(super_client, new_context):
    c1 = new_context.create_container(name='healthcheck-' + random_str(),
                                      healthCheck={'port': 80,
                                                   'strategy': 'none'})

    assert c1.healthCheck.port == 80

    c1 = super_client.reload(c1)
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c1)
    assert hcihm.healthState == 'initializing'

    _update_healthy(agent, hcihm, c1, super_client)

    # update unheatlhy and make sure the container was NOT recreated
    _update_unhealthy(agent, hcihm, c1, super_client)
    try:
        wait_for(lambda: super_client.reload(c1).state == 'removed',
                 timeout=10)
    except Exception:
        pass

def test_standalone_container_lb_replacement(super_client, new_context):
    client = new_context.client
    c1 = new_context.create_container(name=random_str(),
                                      healthCheck={'port': 80})
    c1 = super_client.reload(c1)
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c1)
    assert hcihm.healthState == 'initializing'

    _update_healthy(agent, hcihm, c1, super_client)

    env = client.create_stack(name='env-' + random_str())
    launch_config = {"imageUuid": new_context.image_uuid}
    hostname = "foo"
    path = "bar"
    port = 32
    priority = 10
    protocol = "http"
    target_port = 42
    backend_name = "myBackend"
    config = "global maxconn 20"
    port_rule1 = {"hostname": hostname,
                  "path": path, "sourcePort": port, "priority": priority,
                  "protocol": protocol, "instanceId": c1.id,
                  "targetPort": target_port,
                  "backendName": backend_name}
    port_rules = [port_rule1]
    lb_config = {"portRules": port_rules,
                 "config": config}

    # create balancer
    lb_svc = client. \
        create_loadBalancerService(name=random_str(),
                                   stackId=env.id,
                                   launchConfig=launch_config,
                                   lbConfig=lb_config)
    lb_svc = client.wait_success(lb_svc)
    assert lb_svc.state == "inactive"
    assert len(lb_svc.lbConfig.portRules) == 1
    assert lb_svc.lbConfig.portRules[0].instanceId == c1.id

    # update container to unhealthy, verify it got recreated
    # and lb got a replacement assigned
    _update_unhealthy(agent, hcihm, c1, super_client)
    c1 = wait_state(super_client, c1, "removed")

    wait_for(lambda: len(super_client.list_container(name=c1.name,
                                                     state="running")) == 1)
    c2 = super_client.list_container(name=c1.name, state="running")[0]
    assert c1.name == c2.name
    assert c1.kind == c2.kind

    wait_for(lambda: len(super_client.reload(lb_svc).lbConfig.portRules) == 1)
    wait_for(lambda: super_client.reload(lb_svc).
             lbConfig.portRules[0].instanceId == c2.id)

def test_unheatlhy_du_volume(new_context, super_client):
    client = new_context.client
    image_uuid = new_context.image_uuid
    opts = {'foo': 'true', 'bar': 'true'}
    stack = client.create_stack(name=random_str())
    stack = client.wait_success(stack)

    client.create_volumeTemplate(name="foo", driver="nfs",
                                 driverOpts=opts,
                                 stackId=stack.id,
                                 perContainer=True)

    # create service
    launch_config = {"imageUuid": image_uuid, "dataVolumes": "foo:/bar",
                     "healthCheck": {'port': 80}}
    svc = _create_and_activate_svc(client, 1, name=random_str(),
                                   stackId=stack.id,
                                   launchConfig=launch_config,
                                   scale=1)

    c1 = _validate_compose_instance_start(client, svc, stack, "1")
    path_to_mount = c1.dataVolumeMounts
    assert len(path_to_mount) == 1
    for key, value in path_to_mount.iteritems():
        assert key == '/bar'
        assert value is not None

    c1 = super_client.reload(c1)

    du1 = c1.deploymentUnitUuid
    name = stack.name + "_foo_1"
    volumes = client.list_volume(name_like=name + "_%")
    assert len(volumes) == 1
    v1 = volumes[0]
    assert v1.driver == 'nfs'
    assert v1.driverOpts == opts

    # update unhealthy, validate instance got recreated and du was preserved
    c1 = super_client.reload(c1)
    wait_for(lambda: super_client.reload(c1).healthcheckInstances is not None)
    hci = find_one(c1.healthcheckInstances)
    hcihm = find_one(hci.healthcheckInstanceHostMaps)
    agent = _get_agent_for_container(new_context, c1)
    assert hcihm.healthState == 'initializing'

    _update_healthy(agent, hcihm, c1, super_client)
    _update_unhealthy(agent, hcihm, c1, super_client)

    wait_for_condition(client, c1,
                       lambda x: x.removed is not None)

    c2 = _validate_compose_instance_start(client, svc, stack, "1")
    assert c1.id != c2.id

    du2 = c2.deploymentUnitUuid
    assert du1 == du2
    name = stack.name + "_foo_1"
    volumes = client.list_volume(name_like=name + "_%")
    assert len(volumes) == 1
    v2 = volumes[0]
    assert v1.id == v2.id
    assert v2.driver == 'nfs'
    assert v2.driverOpts == opts
    _remove_service(svc)


text:
lib_sources = {
   "../../tiny_obj_loader.cc"
}

sources = {
   "obj_sticher.cc",
   "obj_writer.cc",
   }

-- premake4.lua
solution "ObjStickerSolution"
   configurations { "Release", "Debug" }

   if (os.is("windows")) then
      platforms { "x32", "x64" }
   else
      platforms { "native", "x32", "x64" }
   end

   includedirs {
      "../../"
   }

   -- A project defines one build target
   project "obj_sticher"
      kind "ConsoleApp"
      language "C++"
      files { lib_sources, sources }

      configuration "Debug"
         defines { "DEBUG" } -- -DDEBUG
         flags { "Symbols" }
         targetname "obj_sticher_debug"

      configuration "Release"
         -- defines { "NDEBUG" } -- -NDEBUG
         flags { "Symbols", "Optimize" }
         targetname "obj_sticher"


text:
SET MSBUILD=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
if %PROCESSOR_ARCHITECTURE% == x86 (
	SET MSBUILD=C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
)

%MSBUILD% ..\WorkQueue.sln /p:Configuration=Release /verbosity:m > build.log

xcopy ..\AGO.WorkQueue\bin\Release\AGO.WorkQueue.dll nuget\lib\ /Y >> build.log

cd nuget

..\..\.nuget\nuget pack workqueue.nuspec -OutputDirectory ..\ >> ..\build.log
cd ..

pause


text:
use std::error::Error;
use std::fmt;
use std::io;
use std::io::BufRead;

/// For less verbose possibilities, see:
///
///     https://stackoverflow.com/questions/42584368/how-do-you-define-custom-error-types-in-rust
///
/// but it appears that manual implementation of not just description() but also the Display
/// trait appears to be what we have without external crate support.
#[derive(Debug)]
struct InputError {
    desc: String,
}

impl Error for InputError {
    fn description(&self) -> &str {
        return &self.desc;
    }
}

impl fmt::Display for InputError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

fn main() {
    if let Err(e) = numstats() {
        eprintln!("error: {}", e);
        std::process::exit(1);
    }
}

fn numstats() -> Result<(), Box<Error>> {
    let stdin = io::stdin();
    let mut ns: Vec<f64> = read_floats(&mut stdin.lock())?;

    if ns.contains(&std::f64::NAN) {
        return Err(Box::new(InputError {
            desc: "NaN not supported".to_owned(),
        }));
    }
    sort_floats_by(&mut ns);

    let count = ns.len();

    let sum = ns.iter().fold(0.0, |a, &b| a + b);

    println!("count: {}", count);
    println!("sum:   {}", sum);

    if ns.is_empty() {
        println!("(empty set of numbers, remaining stats not available)");
    } else {
        println!("avg:   {}", sum / count as f64);
        println!("max:   {}", ns[count - 1]);
        println!("p999:  {}", ns[ns.len() * 999 / 1000]);
        println!("p99:   {}", ns[ns.len() * 99 / 100]);
        println!("p90:   {}", ns[ns.len() * 90 / 100]);
        println!("p50:   {}", ns[ns.len() * 50 / 100]);
        println!("min:   {}", ns[0]);
    }

    Ok(())
}

/// Sort a vector under the assumption that all elements in the vector, upon comparison, will
/// result in an order despite the fact the the type does not guarantee it.
///
/// Panics if a comparison fails by not returning an order.
///
/// Per #rust-beginners convo, there may not be a nice way of turning the case into an error.
/// The awkwardness of this is not unknown, e.g. here's an implementation of sort_float():
///
///    https://github.com/notriddle/quickersort#floating-point
///
/// For our purposes here though, I care about education and not performance :P
///
/// Further, unless this function is made specific to floats, it seems impossible to efficiently
/// perform the validation step. We can deduce and hope we're right, that the only special cases
/// that would cause a problem is that of NAN (see https://doc.rust-lang.org/std/f64/ for others).
/// The caller might know that it's a float and do an O(n) validation step. Validating upon a
/// generic T: PartialOrd would require comparing every element with every other element - more
/// expensie than the sort itself is supposed to be!
///
/// As a result, we make this specific to f64 and expect the caller to look for std::f64::NAN
/// prior to calling us.
///
/// Implementing this for both types of float w/o duplication can be done with some generalizations
/// over float types:
///
///    https://github.com/notriddle/quickersort/blob/daf2f70acce76142a56935c6c67e8f6b1c25d313/src/float.rs#L70
fn sort_floats_by(v: &mut Vec<f64>) {
    v.sort_by(|a, b| match a.partial_cmp(b) {
        Some(order) => order,
        None => panic!("sort failed due to partial order; expected an order between all elements"),
    });
}

fn read_floats(input: &mut io::BufRead) -> Result<Vec<f64>, Box<Error>> {
    let ns: Result<Vec<f64>, Box<Error>> = input
        .lines()
        .map(|line| -> Result<f64, Box<Error>> { Ok(line?.parse::<f64>()?) })
        .collect();

    ns
}


text:
package org.tomitribe.crest.table;

public class Line {
    private final String left;
    private final String right;
    private final String inner;
    private final String middle;

    public Line(final String left, final String right, final String inner, final String middle) {
        this.left = left;
        this.right = right;
        this.inner = inner;
        this.middle = middle;
    }

    public String getLeft() {
        return left;
    }

    public String getRight() {
        return right;
    }

    public String getMiddle() {
        return middle;
    }

    public String getInner() {
        return inner;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private String left;
        private String right;
        private String inner;
        private String middle;

        private Builder() {
        }

        public Builder all(String string) {
            this.left = string;
            this.right = string;
            this.middle = string;
            this.inner = string;
            return this;
        }

        public Builder left(String left) {
            this.left = left;
            return this;
        }

        public Builder right(String right) {
            this.right = right;
            return this;
        }

        public Builder inner(String inner) {
            this.inner = inner;
            return this;
        }

        public Builder middle(String middle) {
            this.middle = middle;
            return this;
        }

        public Line build() {
            return new Line(left, right, inner, middle);
        }
    }
}


text:
<ion-content padding>

Set your goals

Soon you will be able to set your own fitness goals.

Be active for {{goals.activity}} hours a day.

Walk {{goals.steps | number:0}} steps a day.

      Come back in {{backinDays | number:0}} day1">s.

</ion-content>