content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Java | Java | customize diagram/javadocs for doonterminate() | 747f97ed6fd67d25ee22600475d71ca74bf289a6 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final void onNext(T args) {
<ide> }
<ide>
<ide> /**
<del> * Modifies an Observable so that it invokes an action when it calls {@code onCompleted} or {@code onError} <p>
<del> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnCompleted.png">
<add> * Modifies an Observable so that it invokes an action when it calls {@code onCompleted} or {@code onError}.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnTerminate.png">
<ide> * <p>
<ide> * This differs from {@code finallyDo} in that this happens BEFORE onCompleted/onError are emitted.
<ide> *
<ide> * @param onTerminate
<ide> * the action to invoke when the source Observable calls {@code onCompleted} or {@code onError}
<ide> * @return the source Observable with the side-effecting behavior applied
<del> * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooncompleted">RxJava Wiki: doOnCompleted()</a>
<add> * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-doonterminate">RxJava Wiki: doOnTerminate()</a>
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
<ide> */
<ide> public final Observable<T> doOnTerminate(final Action0 onTerminate) { | 1 |
PHP | PHP | add tests in an attempt to reproduce | 18f68aaa36d72dbd91a5eccad790af45dbaebfaa | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testControlCheckbox()
<ide> {
<ide> $articles = TableRegistry::get('Articles');
<ide> $articles->schema()->addColumn('active', ['type' => 'boolean', 'default' => null]);
<add> $article = $articles->newEntity();
<add>
<add> $this->Form->create($article);
<add>
<add> $result = $this->Form->control('Articles.active');
<add> $expected = [
<add> 'div' => ['class' => 'input checkbox'],
<add> 'input' => ['type' => 'hidden', 'name' => 'Articles[active]', 'value' => '0'],
<add> 'label' => ['for' => 'articles-active'],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Articles[active]', 'value' => '1', 'id' => 'articles-active']],
<add> 'Active',
<add> '/label',
<add> '/div'
<add> ];
<add> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->control('Articles.active', ['label' => false, 'checked' => true]);
<ide> $expected = [ | 1 |
Text | Text | add examples for new explosion bot commands | f38aff4ec9a5022dad0f216e1b6cd74699b1d8a6 | <ide><path>extra/DEVELOPER_DOCS/ExplosionBot.md
<ide> To summon the robot, write a github comment on the issue/PR you wish to test. Th
<ide>
<ide> Some things to note:
<ide>
<del>* The `@explosion-bot please` must be the beginning of the command - you cannot add anything in front of this or else the robot won't know how to parse it. Adding anything at the end aside from the test name will also confuse the robot, so keep it simple!
<del>* The command name (such as `test_gpu`) must be one of the tests that the bot knows how to run. The available commands are documented in the bot's [workflow config](https://github.com/explosion/spaCy/blob/master/.github/workflows/explosionbot.yml#L26) and must match exactly one of the commands listed there.
<del>* The robot can't do multiple things at once, so if you want it to run multiple tests, you'll have to summon it with one comment per test.
<del>* For the `test_gpu` command, you can specify an optional thinc branch (from the spaCy repo) or a spaCy branch (from the thinc repo) with either the `--thinc-branch` or `--spacy-branch` flags. By default, the bot will pull in the PR branch from the repo where the command was issued, and the main branch of the other repository. However, if you need to run against another branch, you can say (for example):
<add>- The `@explosion-bot please` must be the beginning of the command - you cannot add anything in front of this or else the robot won't know how to parse it. Adding anything at the end aside from the test name will also confuse the robot, so keep it simple!
<add>- The command name (such as `test_gpu`) must be one of the tests that the bot knows how to run. The available commands are documented in the bot's [workflow config](https://github.com/explosion/spaCy/blob/master/.github/workflows/explosionbot.yml#L26) and must match exactly one of the commands listed there.
<add>- The robot can't do multiple things at once, so if you want it to run multiple tests, you'll have to summon it with one comment per test.
<ide>
<del>```
<del>@explosion-bot please test_gpu --thinc-branch develop
<del>```
<del>You can also specify a branch from an unmerged PR:
<del>```
<del>@explosion-bot please test_gpu --thinc-branch refs/pull/633/head
<del>```
<add>### Examples
<add>
<add>- Execute spaCy slow GPU tests with a custom thinc branch from a spaCy PR:
<add>
<add> ```
<add> @explosion-bot please test_slow_gpu --thinc-branch <branch_name>
<add> ```
<add>
<add> `branch_name` can either be a named branch, e.g: `develop`, or an unmerged PR, e.g: `refs/pull/<pr_number>/head`.
<add>
<add>- Execute spaCy Transformers GPU tests from a spaCy PR:
<add>
<add> ```
<add> @explosion-bot please test_gpu --run-on spacy-transformers --run-on-branch master --spacy-branch current_pr
<add> ```
<add>
<add> This will launch the GPU pipeline for the `spacy-transformers` repo on its `master` branch, using the current spaCy PR's branch to build spaCy.
<add>
<add>- General info about supported commands.
<add>
<add> ```
<add> @explosion-bot please info
<add> ```
<add>
<add>- Help text for a specific command
<add> ```
<add> @explosion-bot please <command> --help
<add> ```
<ide>
<ide> ## Troubleshooting
<ide>
<del>If the robot isn't responding to commands as expected, you can check its logs in the [Github Action](https://github.com/explosion/spaCy/actions/workflows/explosionbot.yml).
<add>If the robot isn't responding to commands as expected, you can check its logs in the [Github Action](https://github.com/explosion/spaCy/actions/workflows/explosionbot.yml).
<ide>
<ide> For each command sent to the bot, there should be a run of the `explosion-bot` workflow. In the `Install and run explosion-bot` step, towards the ends of the logs you should see info about the configuration that the bot was run with, as well as any errors that the bot encountered. | 1 |
Javascript | Javascript | add test for failed save in repl | 8ea6844d265dbcd24e18fd98dc5f598f682d0edc | <ide><path>test/parallel/test-repl-.save.load.js
<ide> putIn.write = function(data) {
<ide> };
<ide> putIn.run(['.load ' + loadFile]);
<ide>
<add>// clear the REPL
<add>putIn.run(['.clear']);
<add>
<add>// NUL (\0) is disallowed in filenames in UNIX-like operating systems and
<add>// Windows so we can use that to test failed saves
<add>const invalidFileName = join(common.tmpDir, '\0\0\0\0\0');
<ide>
<del>//TODO how do I do a failed .save test?
<add>// should not break
<add>putIn.write = function(data) {
<add> // make sure I get a failed to save message and not some other error
<add> assert.equal(data, 'Failed to save:' + invalidFileName + '\n');
<add> // reset to no-op
<add> putIn.write = function() {};
<add>};
<add>
<add>// save it to a file
<add>putIn.run(['.save ' + invalidFileName]); | 1 |
PHP | PHP | apply fixes from styleci | 4994f37c782672bd9d32b6d4277f9613e14d8429 | <ide><path>src/Illuminate/Contracts/Queue/Job.php
<ide> public function maxTries();
<ide> * @return int|null
<ide> */
<ide> public function timeout();
<del>
<add>
<ide> /**
<ide> * Get the name of the queued job class.
<ide> * | 1 |
Javascript | Javascript | remove @author in comment | 0dd467f297b2411bc59d8172ae727006baf9de2b | <ide><path>test/math/random-test.js
<ide> var suite = vows.describe("d3.random");
<ide> *
<ide> * More on RNG testing here:
<ide> * @see http://www.johndcook.com/Beautiful_Testing_ch10.pdf
<del> *
<del> * @author Daniel Goldbach
<ide> */
<ide>
<ide> // Arbitrarily chosen parameters for the normal RNG | 1 |
PHP | PHP | add test coverage for `label` key in radio options | ef930d3880127728c42de2330510357cb9c53b90 | <ide><path>tests/TestCase/View/Widget/RadioWidgetTest.php
<ide> public function testRenderComplex()
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<add> /**
<add> * Test rendering inputs with label options
<add> *
<add> * @return void
<add> */
<add> public function testRenderComplexLabelAttributes()
<add> {
<add> $label = new NestingLabelWidget($this->templates);
<add> $radio = new RadioWidget($this->templates, $label);
<add> $data = [
<add> 'name' => 'Crayons[color]',
<add> 'options' => [
<add> ['value' => 'r', 'text' => 'Red', 'label' => ['style' => 'color:red']],
<add> ['value' => 'b', 'text' => 'Black', 'label' => ['data-test' => 'yes']],
<add> ]
<add> ];
<add> $result = $radio->render($data, $this->context);
<add> $expected = [
<add> ['label' => ['for' => 'crayons-color-r', 'style' => 'color:red']],
<add> ['input' => [
<add> 'type' => 'radio',
<add> 'name' => 'Crayons[color]',
<add> 'value' => 'r',
<add> 'id' => 'crayons-color-r',
<add> ]],
<add> 'Red',
<add> '/label',
<add> ['label' => ['for' => 'crayons-color-b', 'data-test' => 'yes']],
<add> ['input' => [
<add> 'type' => 'radio',
<add> 'name' => 'Crayons[color]',
<add> 'value' => 'b',
<add> 'id' => 'crayons-color-b',
<add> ]],
<add> 'Black',
<add> '/label',
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<ide> /**
<ide> * Test that id suffixes are generated to not collide
<ide> * | 1 |
Javascript | Javascript | run more flags in variant tests | 7dfdff42af8e128326672608c9cf8980e289c423 | <ide><path>packages/react-interactions/events/src/dom/__tests__/Input-test.internal.js
<ide> describe('Input event responder', () => {
<ide> ref.current.dispatchEvent(
<ide> new Event('input', {bubbles: true, cancelable: true}),
<ide> );
<del> expect(onChangeCalled).toBe(0);
<del> expect(onValueChangeCalled).toBe(0);
<add>
<add> if (ReactFeatureFlags.disableInputAttributeSyncing) {
<add> // TODO: figure out why. This might be a bug.
<add> expect(onChangeCalled).toBe(1);
<add> expect(onValueChangeCalled).toBe(1);
<add> } else {
<add> expect(onChangeCalled).toBe(0);
<add> expect(onValueChangeCalled).toBe(0);
<add> }
<ide> });
<ide>
<ide> it('should consider initial checkbox checked=true to be current', () => {
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide>
<ide> export const warnAboutSpreadingKeyToJSX = __VARIANT__;
<ide> export const disableModulePatternComponents = __VARIANT__;
<add>export const disableInputAttributeSyncing = __VARIANT__;
<ide>
<ide> // These are already tested in both modes using the build type dimension,
<ide> // so we don't need to use __VARIANT__ to get extra coverage.
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
<ide> // Update the tests so that they pass in either mode, then set these
<ide> // to __VARIANT__.
<ide> export const enableTrustedTypesIntegration = false;
<del>export const disableInputAttributeSyncing = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<ide> export const enableModernEventSystem = false; | 2 |
Ruby | Ruby | switch `greedy` argument to a keyword | d45701cf9b6d369049053c675883b4178541f277 | <ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def select_outdated(formulae_or_casks, args:)
<ide> if formula_or_cask.is_a?(Formula)
<ide> formula_or_cask.outdated?(fetch_head: args.fetch_HEAD?)
<ide> else
<del> formula_or_cask.outdated?(args.greedy?)
<add> formula_or_cask.outdated?(greedy: args.greedy?)
<ide> end
<ide> end
<ide> end | 1 |
Go | Go | set more defaults | f73aadb2301d8033bed3fa137179e2b3ff5cb4ca | <ide><path>cmd/dockerd/config.go
<ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error {
<ide> flags.BoolVar(&conf.CriContainerd, "cri-containerd", false, "start containerd with cri")
<ide>
<ide> flags.IntVar(&conf.Mtu, "mtu", conf.Mtu, "Set the containers network MTU")
<del> flags.IntVar(&conf.NetworkControlPlaneMTU, "network-control-plane-mtu", config.DefaultNetworkMtu, "Network Control plane MTU")
<add> flags.IntVar(&conf.NetworkControlPlaneMTU, "network-control-plane-mtu", conf.NetworkControlPlaneMTU, "Network Control plane MTU")
<ide> flags.IntVar(&conf.NetworkDiagnosticPort, "network-diagnostic-port", 0, "TCP port number of the network diagnostic server")
<ide> _ = flags.MarkHidden("network-diagnostic-port")
<ide>
<ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error {
<ide> flags.Var(opts.NewNamedMapOpts("log-opts", conf.LogConfig.Config, nil), "log-opt", "Default log driver options for containers")
<ide>
<ide> flags.StringVar(&conf.CorsHeaders, "api-cors-header", "", "Set CORS headers in the Engine API")
<del> flags.IntVar(&conf.MaxConcurrentDownloads, "max-concurrent-downloads", config.DefaultMaxConcurrentDownloads, "Set the max concurrent downloads for each pull")
<del> flags.IntVar(&conf.MaxConcurrentUploads, "max-concurrent-uploads", config.DefaultMaxConcurrentUploads, "Set the max concurrent uploads for each push")
<del> flags.IntVar(&conf.MaxDownloadAttempts, "max-download-attempts", config.DefaultDownloadAttempts, "Set the max download attempts for each pull")
<del> flags.IntVar(&conf.ShutdownTimeout, "shutdown-timeout", config.DefaultShutdownTimeout, "Set the default shutdown timeout")
<add> flags.IntVar(&conf.MaxConcurrentDownloads, "max-concurrent-downloads", conf.MaxConcurrentDownloads, "Set the max concurrent downloads for each pull")
<add> flags.IntVar(&conf.MaxConcurrentUploads, "max-concurrent-uploads", conf.MaxConcurrentUploads, "Set the max concurrent uploads for each push")
<add> flags.IntVar(&conf.MaxDownloadAttempts, "max-download-attempts", conf.MaxDownloadAttempts, "Set the max download attempts for each pull")
<add> flags.IntVar(&conf.ShutdownTimeout, "shutdown-timeout", conf.ShutdownTimeout, "Set the default shutdown timeout")
<ide>
<ide> flags.StringVar(&conf.SwarmDefaultAdvertiseAddr, "swarm-default-advertise-addr", "", "Set default address or interface for swarm advertised address")
<ide> flags.BoolVar(&conf.Experimental, "experimental", false, "Enable experimental features")
<ide> flags.StringVar(&conf.MetricsAddress, "metrics-addr", "", "Set default address and port to serve the metrics api on")
<ide> flags.Var(opts.NewNamedListOptsRef("node-generic-resources", &conf.NodeGenericResources, opts.ValidateSingleGenericResource), "node-generic-resource", "Advertise user-defined resource")
<ide>
<del> flags.StringVar(&conf.ContainerdNamespace, "containerd-namespace", config.DefaultContainersNamespace, "Containerd namespace to use")
<del> flags.StringVar(&conf.ContainerdPluginNamespace, "containerd-plugins-namespace", config.DefaultPluginNamespace, "Containerd namespace to use for plugins")
<del> flags.StringVar(&conf.DefaultRuntime, "default-runtime", config.StockRuntimeName, "Default OCI runtime for containers")
<add> flags.StringVar(&conf.ContainerdNamespace, "containerd-namespace", conf.ContainerdNamespace, "Containerd namespace to use")
<add> flags.StringVar(&conf.ContainerdPluginNamespace, "containerd-plugins-namespace", conf.ContainerdPluginNamespace, "Containerd namespace to use for plugins")
<add> flags.StringVar(&conf.DefaultRuntime, "default-runtime", conf.DefaultRuntime, "Default OCI runtime for containers")
<ide>
<ide> flags.StringVar(&conf.HTTPProxy, "http-proxy", "", "HTTP proxy URL to use for outgoing traffic")
<ide> flags.StringVar(&conf.HTTPSProxy, "https-proxy", "", "HTTPS proxy URL to use for outgoing traffic")
<ide><path>cmd/dockerd/config_unix.go
<ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error {
<ide> }
<ide>
<ide> conf.Ulimits = make(map[string]*units.Ulimit)
<del> conf.NetworkConfig.DefaultAddressPools = opts.PoolsOpt{}
<ide>
<ide> // Set default value for `--default-shm-size`
<ide> conf.ShmSize = opts.MemBytes(config.DefaultShmSize)
<ide><path>daemon/config/config.go
<ide> func (conf *Config) IsValueSet(name string) bool {
<ide> func New() *Config {
<ide> return &Config{
<ide> CommonConfig: CommonConfig{
<add> ShutdownTimeout: DefaultShutdownTimeout,
<ide> LogConfig: LogConfig{
<ide> Config: make(map[string]string),
<ide> },
<del> Mtu: DefaultNetworkMtu,
<add> MaxConcurrentDownloads: DefaultMaxConcurrentDownloads,
<add> MaxConcurrentUploads: DefaultMaxConcurrentUploads,
<add> MaxDownloadAttempts: DefaultDownloadAttempts,
<add> Mtu: DefaultNetworkMtu,
<add> NetworkConfig: NetworkConfig{
<add> NetworkControlPlaneMTU: DefaultNetworkMtu,
<add> },
<add> ContainerdNamespace: DefaultContainersNamespace,
<add> ContainerdPluginNamespace: DefaultPluginNamespace,
<add> DefaultRuntime: StockRuntimeName,
<ide> },
<ide> }
<ide> } | 3 |
Text | Text | fix style for some text | 62d0d4e5d2f203d2c1694af363bce88cc1a5d483 | <ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md
<ide> Unlike all our other API endpoints, we don't want to use JSON, but instead just
<ide>
<ide> The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
<ide>
<del>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your snippets.views add:
<add>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets.views` add:
<ide>
<ide> from rest_framework import renderers
<ide> from rest_framework.response import Response | 1 |
Go | Go | fix a race in pkg/discovery/memory | 1f8fbbc0d830ad9a887d04a25152ea344688903b | <ide><path>pkg/discovery/memory/memory.go
<ide> package memory
<ide>
<ide> import (
<add> "sync"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/discovery"
<ide> )
<ide>
<del>// Discovery implements a descovery backend that keeps
<add>// Discovery implements a discovery backend that keeps
<ide> // data in memory.
<ide> type Discovery struct {
<ide> heartbeat time.Duration
<ide> values []string
<add> mu sync.Mutex
<ide> }
<ide>
<ide> func init() {
<ide> func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-c
<ide>
<ide> // Send the initial entries if available.
<ide> var currentEntries discovery.Entries
<add> var err error
<add>
<add> s.mu.Lock()
<ide> if len(s.values) > 0 {
<del> var err error
<ide> currentEntries, err = discovery.CreateEntries(s.values)
<del> if err != nil {
<del> errCh <- err
<del> } else {
<del> ch <- currentEntries
<del> }
<add> }
<add> s.mu.Unlock()
<add>
<add> if err != nil {
<add> errCh <- err
<add> } else if currentEntries != nil {
<add> ch <- currentEntries
<ide> }
<ide>
<ide> // Periodically send updates.
<ide> for {
<ide> select {
<ide> case <-ticker.C:
<add> s.mu.Lock()
<ide> newEntries, err := discovery.CreateEntries(s.values)
<add> s.mu.Unlock()
<ide> if err != nil {
<ide> errCh <- err
<ide> continue
<ide> func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-c
<ide>
<ide> // Register adds a new address to the discovery.
<ide> func (s *Discovery) Register(addr string) error {
<add> s.mu.Lock()
<ide> s.values = append(s.values, addr)
<add> s.mu.Unlock()
<ide> return nil
<ide> } | 1 |
Javascript | Javascript | add <page>/index.html url re-writes to next/router | 90991f176c5043e8bed388dfe651b0a9e2d12f2f | <ide><path>lib/router/router.js
<add>/* global __NEXT_DATA__ */
<add>
<ide> import { parse, format } from 'url'
<ide> import mitt from 'mitt'
<ide> import shallowEquals from '../shallow-equals'
<ide> export default class Router {
<ide> // If url and as provided as an object representation,
<ide> // we'll format them into the string version here.
<ide> const url = typeof _url === 'object' ? format(_url) : _url
<del> const as = typeof _as === 'object' ? format(_as) : _as
<add> let as = typeof _as === 'object' ? format(_as) : _as
<add>
<add> // Add the ending slash to the paths. So, we can serve the
<add> // "<page>/index.html" directly for the SSR page.
<add> const asEndsWithSlash = /\/$/.test(as)
<add> if (
<add> __NEXT_DATA__.nextExport &&
<add> !asEndsWithSlash
<add> ) {
<add> as = `${as}/`
<add> }
<ide>
<ide> this.abortComponentLoad(as)
<ide> const { pathname, query } = parse(url, true) | 1 |
Go | Go | privatize mountpath and zfspath | f5f7fee2ecc964314b2a7b910fda71a157c90f16 | <ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func (d *Driver) cloneFilesystem(name, parentName string) error {
<ide> return snapshot.Destroy(zfs.DestroyDeferDeletion)
<ide> }
<ide>
<del>// ZfsPath returns the filesystem path for the id provided.
<del>func (d *Driver) ZfsPath(id string) string {
<add>func (d *Driver) zfsPath(id string) string {
<ide> return d.options.fsName + "/" + id
<ide> }
<ide>
<del>// MountPath returns the mounted filesystem path for the id provided.
<del>func (d *Driver) MountPath(id string) string {
<add>func (d *Driver) mountPath(id string) string {
<ide> return path.Join(d.options.mountPath, "graph", getMountpoint(id))
<ide> }
<ide>
<ide> func (d *Driver) Create(id string, parent string) error {
<ide> return err
<ide> }
<ide>
<del> dataset := zfs.Dataset{Name: d.ZfsPath(id)}
<add> dataset := zfs.Dataset{Name: d.zfsPath(id)}
<ide> if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
<ide> return err
<ide> }
<ide> func (d *Driver) Create(id string, parent string) error {
<ide> }
<ide>
<ide> func (d *Driver) create(id, parent string) error {
<del> name := d.ZfsPath(id)
<add> name := d.zfsPath(id)
<ide> if parent == "" {
<ide> mountoptions := map[string]string{"mountpoint": "legacy"}
<ide> fs, err := zfs.CreateFilesystem(name, mountoptions)
<ide> func (d *Driver) create(id, parent string) error {
<ide> }
<ide> return err
<ide> }
<del> return d.cloneFilesystem(name, d.ZfsPath(parent))
<add> return d.cloneFilesystem(name, d.zfsPath(parent))
<ide> }
<ide>
<ide> // Remove deletes the dataset, filesystem and the cache for the given id.
<ide> func (d *Driver) Remove(id string) error {
<del> name := d.ZfsPath(id)
<add> name := d.zfsPath(id)
<ide> dataset := zfs.Dataset{Name: name}
<ide> err := dataset.Destroy(zfs.DestroyRecursive)
<ide> if err == nil {
<ide> func (d *Driver) Remove(id string) error {
<ide>
<ide> // Get returns the mountpoint for the given id after creating the target directories if necessary.
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<del> mountpoint := d.MountPath(id)
<del> filesystem := d.ZfsPath(id)
<add> mountpoint := d.mountPath(id)
<add> filesystem := d.zfsPath(id)
<ide> options := label.FormatMountLabel("", mountLabel)
<ide> logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
<ide>
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide>
<ide> // Put removes the existing mountpoint for the given id if it exists.
<ide> func (d *Driver) Put(id string) error {
<del> mountpoint := d.MountPath(id)
<add> mountpoint := d.mountPath(id)
<ide> logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
<ide>
<ide> if err := mount.Unmount(mountpoint); err != nil {
<ide> func (d *Driver) Put(id string) error {
<ide>
<ide> // Exists checks to see if the cache entry exists for the given id.
<ide> func (d *Driver) Exists(id string) bool {
<del> return d.filesystemsCache[d.ZfsPath(id)] == true
<add> return d.filesystemsCache[d.zfsPath(id)] == true
<ide> } | 1 |
Ruby | Ruby | remove useless preloader classes | de40c45f2b7d4a2ba47d28e9a4967134e45df91f | <ide><path>activerecord/lib/active_record/associations/preloader.rb
<ide> class Preloader #:nodoc:
<ide> extend ActiveSupport::Autoload
<ide>
<ide> eager_autoload do
<del> autoload :Association, "active_record/associations/preloader/association"
<del> autoload :SingularAssociation, "active_record/associations/preloader/singular_association"
<del> autoload :CollectionAssociation, "active_record/associations/preloader/collection_association"
<del> autoload :ThroughAssociation, "active_record/associations/preloader/through_association"
<del>
<del> autoload :HasMany, "active_record/associations/preloader/has_many"
<del> autoload :HasManyThrough, "active_record/associations/preloader/has_many_through"
<del> autoload :HasOne, "active_record/associations/preloader/has_one"
<del> autoload :HasOneThrough, "active_record/associations/preloader/has_one_through"
<del> autoload :BelongsTo, "active_record/associations/preloader/belongs_to"
<add> autoload :Association, "active_record/associations/preloader/association"
<add> autoload :ThroughAssociation, "active_record/associations/preloader/through_association"
<ide> end
<ide>
<ide> # Eager loads the named associations for the given Active Record record(s).
<ide> def preloaded_records
<ide> end
<ide>
<ide> # Returns a class containing the logic needed to load preload the data
<del> # and attach it to a relation. For example +Preloader::Association+ or
<del> # +Preloader::HasManyThrough+. The class returned implements a `run` method
<add> # and attach it to a relation. The class returned implements a `run` method
<ide> # that accepts a preloader.
<ide> def preloader_for(reflection, owners)
<ide> if owners.first.association(reflection.name).loaded?
<ide> return AlreadyLoaded
<ide> end
<ide> reflection.check_preloadable!
<ide>
<del> case reflection.macro
<del> when :has_many
<del> reflection.options[:through] ? HasManyThrough : HasMany
<del> when :has_one
<del> reflection.options[:through] ? HasOneThrough : HasOne
<del> when :belongs_to
<del> BelongsTo
<add> if reflection.options[:through]
<add> ThroughAssociation
<add> else
<add> Association
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/preloader/association.rb
<ide> def owner_key_name
<ide> end
<ide>
<ide> def associate_records_to_owner(owner, records)
<del> raise NotImplementedError
<add> association = owner.association(reflection.name)
<add> if reflection.collection?
<add> association.loaded!
<add> association.target.concat(records)
<add> else
<add> association.target = records.first
<add> end
<ide> end
<ide>
<ide> def owner_keys
<ide><path>activerecord/lib/active_record/associations/preloader/belongs_to.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class BelongsTo < SingularAssociation #:nodoc:
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/collection_association.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class CollectionAssociation < Association #:nodoc:
<del> private
<del> def associate_records_to_owner(owner, records)
<del> association = owner.association(reflection.name)
<del> association.loaded!
<del> association.target.concat(records)
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/has_many.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class HasMany < CollectionAssociation #:nodoc:
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/has_many_through.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class HasManyThrough < CollectionAssociation #:nodoc:
<del> include ThroughAssociation
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/has_one.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class HasOne < SingularAssociation #:nodoc:
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/has_one_through.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class HasOneThrough < SingularAssociation #:nodoc:
<del> include ThroughAssociation
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/singular_association.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class SingularAssociation < Association #:nodoc:
<del> private
<del> def associate_records_to_owner(owner, records)
<del> association = owner.association(reflection.name)
<del> association.target = records.first
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb
<ide> module ActiveRecord
<ide> module Associations
<ide> class Preloader
<del> module ThroughAssociation #:nodoc:
<add> class ThroughAssociation < Association # :nodoc:
<ide> def run(preloader)
<ide> already_loaded = owners.first.association(through_reflection.name).loaded?
<ide> through_scope = through_scope() | 10 |
Ruby | Ruby | add missing variable | 727d8546217eadf22924ece4100b1bf40c9169c8 | <ide><path>Library/Homebrew/cli/named_args.rb
<ide> def load_formula_or_cask(name, only: nil, method: nil)
<ide> if only != :formula
<ide> begin
<ide> return Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
<del> rescue Cask::CaskUnavailableError
<add> rescue Cask::CaskUnavailableError => e
<ide> raise e if only == :cask
<ide> end
<ide> end | 1 |
Text | Text | add missing determiner | 3fdbb5550656711b5344e7e24bd8ae6fedc88d0f | <ide><path>docs/basics/Actions.md
<ide> import { ADD_TODO, REMOVE_TODO } from '../actionTypes';
<ide>
<ide> >##### Note on Boilerplate
<ide>
<del>>You don’t have to define action type constants in a separate file, or even to define them at all. For a small project, it might be easier to just use string literals for action types. However, there are some benefits to explicitly declaring constants in larger codebases. Read [Reducing Boilerplate](../recipes/ReducingBoilerplate.md) for more practical tips on keeping your codebase clean.
<add>>You don’t have to define action type constants in a separate file, or even to define them at all. For a small project, it might be easier to just use string literals for action types. However, there are some benefits to explicitly declaring constants in larger codebases. Read [Reducing Boilerplate](../recipes/ReducingBoilerplate.md) for more practical tips on keeping your codebase clean.
<ide>
<ide> Other than `type`, the structure of an action object is really up to you. If you’re interested, check out [Flux Standard Action](https://github.com/acdlite/flux-standard-action) for recommendations on how actions could be constructed.
<ide>
<ide> We’ll add one more action type to describe a user ticking off a todo as comple
<ide> }
<ide> ```
<ide>
<del>It’s a good idea to pass as little data in action as possible. For example, it’s better to pass `index` than the whole todo object.
<add>It’s a good idea to pass as little data in each action as possible. For example, it’s better to pass `index` than the whole todo object.
<ide>
<ide> Finally, we’ll add one more action type for changing the currently visible todos.
<ide> | 1 |
PHP | PHP | use fqn in phpdocs | c75735eff4e1f0ac96ce8fd7dd46ef14415cf994 | <ide><path>src/Illuminate/Container/Container.php
<ide> public function singleton($abstract, $concrete = null)
<ide> * Wrap a Closure such that it is shared.
<ide> *
<ide> * @param \Closure $closure
<del> * @return Closure
<add> * @return \Closure
<ide> */
<ide> public function share(Closure $closure)
<ide> {
<ide><path>src/Illuminate/Database/Connection.php
<ide> public function getDoctrineConnection()
<ide> /**
<ide> * Get the current PDO connection.
<ide> *
<del> * @return PDO
<add> * @return \PDO
<ide> */
<ide> public function getPdo()
<ide> {
<ide> public function getPdo()
<ide> /**
<ide> * Get the current PDO connection used for reading.
<ide> *
<del> * @return PDO
<add> * @return \PDO
<ide> */
<ide> public function getReadPdo()
<ide> {
<ide><path>src/Illuminate/Database/Connectors/Connector.php
<ide> public function getOptions(array $config)
<ide> * @param string $dsn
<ide> * @param array $config
<ide> * @param array $options
<del> * @return PDO
<add> * @return \PDO
<ide> */
<ide> public function createConnection($dsn, array $config, array $options)
<ide> {
<ide><path>src/Illuminate/Database/Connectors/PostgresConnector.php
<ide> class PostgresConnector extends Connector implements ConnectorInterface {
<ide> * Establish a database connection.
<ide> *
<ide> * @param array $config
<del> * @return PDO
<add> * @return \PDO
<ide> */
<ide> public function connect(array $config)
<ide> {
<ide><path>src/Illuminate/Database/Connectors/SqlServerConnector.php
<ide> class SqlServerConnector extends Connector implements ConnectorInterface {
<ide> * Establish a database connection.
<ide> *
<ide> * @param array $config
<del> * @return PDO
<add> * @return \PDO
<ide> */
<ide> public function connect(array $config)
<ide> {
<ide><path>src/Illuminate/Exception/Handler.php
<ide> protected function handlesException(Closure $handler, $exception)
<ide> /**
<ide> * Determine if the given handler type hints the exception.
<ide> *
<del> * @param ReflectionFunction $reflection
<add> * @param \ReflectionFunction $reflection
<ide> * @param \Exception $exception
<ide> * @return bool
<ide> */
<ide><path>src/Illuminate/Foundation/Application.php
<ide> public function bound($abstract)
<ide> * (Overriding Container::extend)
<ide> *
<ide> * @param string $abstract
<del> * @param Closure $closure
<add> * @param \Closure $closure
<ide> * @return void
<ide> *
<ide> * @throws \InvalidArgumentException
<ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php
<ide> protected function getMethodPatterns($uri, $method)
<ide> /**
<ide> * Get after filters
<ide> *
<del> * @param Route $route
<add> * @param \Illuminate\Routing\Route $route
<ide> * @return string
<ide> */
<ide> protected function getAfterFilters($route)
<ide><path>src/Illuminate/Pagination/Paginator.php
<ide> public function getFactory()
<ide> /**
<ide> * Get an iterator for the items.
<ide> *
<del> * @return ArrayIterator
<add> * @return \ArrayIterator
<ide> */
<ide> public function getIterator()
<ide> {
<ide><path>src/Illuminate/Queue/BeanstalkdQueue.php
<ide> class BeanstalkdQueue extends Queue implements QueueInterface {
<ide> /**
<ide> * The Pheanstalk instance.
<ide> *
<del> * @var Pheanstalk
<add> * @var \Pheanstalk_Pheanstalk
<ide> */
<ide> protected $pheanstalk;
<ide>
<ide> class BeanstalkdQueue extends Queue implements QueueInterface {
<ide> /**
<ide> * Create a new Beanstalkd queue instance.
<ide> *
<del> * @param Pheanstalk $pheanstalk
<add> * @param \Pheanstalk_Pheanstalk $pheanstalk
<ide> * @param string $default
<ide> * @param int $timeToRun
<ide> * @return void
<ide> public function getQueue($queue)
<ide> /**
<ide> * Get the underlying Pheanstalk instance.
<ide> *
<del> * @return Pheanstalk
<add> * @return \Pheanstalk_Pheanstalk
<ide> */
<ide> public function getPheanstalk()
<ide> {
<ide><path>src/Illuminate/Queue/IronQueue.php
<ide> public function getQueue($queue)
<ide> /**
<ide> * Get the underlying IronMQ instance.
<ide> *
<del> * @return IronMQ
<add> * @return \IronMQ
<ide> */
<ide> public function getIron()
<ide> {
<ide><path>src/Illuminate/Queue/Jobs/BeanstalkdJob.php
<ide> class BeanstalkdJob extends Job {
<ide> /**
<ide> * The Pheanstalk instance.
<ide> *
<del> * @var Pheanstalk
<add> * @var \Pheanstalk_Pheanstalk
<ide> */
<ide> protected $pheanstalk;
<ide>
<ide> /**
<ide> * The Pheanstalk job instance.
<ide> *
<del> * @var Pheanstalk_Job
<add> * @var \Pheanstalk_Job
<ide> */
<ide> protected $job;
<ide>
<ide> public function getContainer()
<ide> /**
<ide> * Get the underlying Pheanstalk instance.
<ide> *
<del> * @return Pheanstalk
<add> * @return \Pheanstalk_Pheanstalk
<ide> */
<ide> public function getPheanstalk()
<ide> {
<ide> public function getPheanstalk()
<ide> /**
<ide> * Get the underlying Pheanstalk job.
<ide> *
<del> * @return Pheanstalk_Job
<add> * @return \Pheanstalk_Job
<ide> */
<ide> public function getPheanstalkJob()
<ide> {
<ide><path>src/Illuminate/Routing/ControllerInspector.php
<ide> public function getRoutable($controller, $prefix)
<ide> /**
<ide> * Determine if the given controller method is routable.
<ide> *
<del> * @param ReflectionMethod $method
<add> * @param \ReflectionMethod $method
<ide> * @param string $controller
<ide> * @return bool
<ide> */
<ide> public function isRoutable(ReflectionMethod $method, $controller)
<ide> /**
<ide> * Get the method data for a given method.
<ide> *
<del> * @param ReflectionMethod $method
<add> * @param \ReflectionMethod $method
<ide> * @param string $prefix
<ide> * @return array
<ide> */
<ide><path>src/Illuminate/Routing/RouteCollection.php
<ide> public function getRoutes()
<ide> /**
<ide> * Get an iterator for the items.
<ide> *
<del> * @return ArrayIterator
<add> * @return \ArrayIterator
<ide> */
<ide> public function getIterator()
<ide> {
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function toJson($options = 0)
<ide> /**
<ide> * Get an iterator for the items.
<ide> *
<del> * @return ArrayIterator
<add> * @return \ArrayIterator
<ide> */
<ide> public function getIterator()
<ide> {
<ide><path>src/Illuminate/View/Factory.php
<ide> public function composer($views, $callback, $priority = null)
<ide> * @param \Closure|string $callback
<ide> * @param string $prefix
<ide> * @param int|null $priority
<del> * @return Closure
<add> * @return \Closure
<ide> */
<ide> protected function addViewEvent($view, $callback, $prefix = 'composing: ', $priority = null)
<ide> { | 16 |
Text | Text | fix syntax in example | ada374f316579e55d5a350f4e9a1e5674af95106 | <ide><path>docs/reference/builder.md
<ide> it instead, as it enables setting any metadata you require, and can be viewed
<ide> easily, for example with `docker inspect`. To set a label corresponding to the
<ide> `MAINTAINER` field you could use:
<ide>
<del> LABEL maintainer "SvenDowideit@home.org.au"
<add> LABEL maintainer="SvenDowideit@home.org.au"
<ide>
<ide> This will then be visible from `docker inspect` with the other labels.
<ide> | 1 |
Javascript | Javascript | write pending data of opposite side | 14a8fb8bbe906b20ee393b67c1425773e0e0f7db | <ide><path>lib/tls.js
<ide> CryptoStream.prototype._read = function read(size) {
<ide>
<ide> // Try writing pending data
<ide> if (this._pending !== null) this._writePending();
<add> if (this._opposite._pending !== null) this._opposite._writePending();
<ide>
<ide> if (bytesRead === 0) {
<ide> // EOF when cleartext has finished and we have nothing to read
<ide><path>test/simple/test-tls-server-large-request.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var tls = require('tls');
<add>var fs = require('fs');
<add>var stream = require('stream');
<add>var util = require('util');
<add>
<add>var clientConnected = 0;
<add>var serverConnected = 0;
<add>var request = new Buffer(new Array(1024 * 256).join('ABCD')); // 1mb
<add>
<add>var options = {
<add> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem')
<add>};
<add>
<add>function Mediator() {
<add> stream.Writable.call(this);
<add> this.buf = '';
<add>};
<add>util.inherits(Mediator, stream.Writable);
<add>
<add>Mediator.prototype._write = function write(data, enc, cb) {
<add> this.buf += data;
<add> setTimeout(cb, 0);
<add>
<add> if (this.buf.length >= request.length) {
<add> assert.equal(this.buf, request.toString());
<add> server.close();
<add> }
<add>};
<add>
<add>var mediator = new Mediator();
<add>
<add>var server = tls.Server(options, function(socket) {
<add> socket.pipe(mediator);
<add> serverConnected++;
<add>});
<add>
<add>server.listen(common.PORT, function() {
<add> var client1 = tls.connect({
<add> port: common.PORT,
<add> rejectUnauthorized: false
<add> }, function() {
<add> ++clientConnected;
<add> client1.end(request);
<add> });
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.equal(clientConnected, 1);
<add> assert.equal(serverConnected, 1);
<add>}); | 2 |
Python | Python | fix typo in docs | b4da9c94739f9832115a84c0f22098c47f29e533 | <ide><path>keras/layers/recurrent.py
<ide> class LSTM(RNN):
<ide> recurrent_dropout: Float between 0 and 1.
<ide> Fraction of the units to drop for
<ide> the linear transformation of the recurrent state.
<del> return_sequences: Boolean. Whether to return the last output.
<add> return_sequences: Boolean. Whether to return the last output
<ide> in the output sequence, or the full sequence.
<ide> return_state: Boolean. Whether to return the last state
<ide> in addition to the output. | 1 |
Text | Text | make minor improvements to module.md | 665330134cafb6d40e39d134f3bef03b09fbd9ae | <ide><path>doc/api/module.md
<ide> added:
<ide> should be fetched.
<ide>
<ide> The `error` instance should be passed as the second parameter to `findSourceMap`
<del>in exceptional flows, e.g., when an overridden
<add>in exceptional flows, such as when an overridden
<ide> [`Error.prepareStackTrace(error, trace)`][] is invoked. Modules are not added to
<del>the module cache until they are successfully loaded, in these cases source maps
<del>will be associated with the `error` instance along with the `path`.
<add>the module cache until they are successfully loaded. In these cases, source maps
<add>are associated with the `error` instance along with the `path`.
<ide>
<ide> ### Class: `module.SourceMap`
<ide> <!-- YAML
<ide> consists of the following keys:
<ide> * originalLine: {number}
<ide> * originalColumn: {number}
<ide>
<add>[CommonJS]: modules.html
<add>[ES Modules]: esm.html
<ide> [Source map v3 format]: https://sourcemaps.info/spec.html#h.mofvlxcwqzej
<ide> [`--enable-source-maps`]: cli.html#cli_enable_source_maps
<ide> [`Error.prepareStackTrace(error, trace)`]: https://v8.dev/docs/stack-trace-api#customizing-stack-traces
<ide> [`NODE_V8_COVERAGE=dir`]: cli.html#cli_node_v8_coverage_dir
<ide> [`SourceMap`]: #module_class_module_sourcemap
<ide> [`createRequire()`]: #module_module_createrequire_filename
<add>[`module`]: modules.html#modules_the_module_object
<ide> [module wrapper]: modules_cjs.html#modules_cjs_the_module_wrapper
<ide> [source map include directives]: https://sourcemaps.info/spec.html#h.lmz475t4mvbx
<del>[`module`]: modules.html#modules_the_module_object
<del>[CommonJS]: modules.html
<del>[ES Modules]: esm.html | 1 |
Javascript | Javascript | remove unnecessary object.userdata check | 310491179af08eebbf245d0fd53a734fe13088eb | <ide><path>examples/js/exporters/GLTFExporter.js
<ide> THREE.GLTFExporter.prototype = {
<ide> */
<ide> function serializeUserData( object, gltfProperty ) {
<ide>
<del> if ( ! object.userData || Object.keys( object.userData ).length === 0 ) {
<add> if ( Object.keys( object.userData ).length === 0 ) {
<ide>
<ide> return;
<ide> | 1 |
Text | Text | fix typo in versioning docs | 000db8df18930b142e6f9b65213ae70703e8bdb9 | <ide><path>docs/api-guide/versioning.md
<ide> Your client requests would now look like this:
<ide> Host: example.com
<ide> Accept: application/vnd.megacorp.bookings+json; version=1.0
<ide>
<del>## URLParameterVersioning
<add>## URLPathVersioning
<ide>
<ide> This scheme requires the client to specify the version as part of the URL path.
<ide> | 1 |
Ruby | Ruby | put the create_table block in a transaction | 4fa2f10494260c0937ffe066aace09747e57d7c7 | <ide><path>activerecord/test/cases/adapters/postgresql/json_test.rb
<ide> class JsonDataType < ActiveRecord::Base
<ide> def setup
<ide> @connection = ActiveRecord::Base.connection
<ide> begin
<del> @connection.create_table('json_data_type') do |t|
<del> t.json 'payload', :default => {}
<add> @connection.transaction do
<add> @connection.create_table('json_data_type') do |t|
<add> t.json 'payload', :default => {}
<add> end
<ide> end
<ide> rescue ActiveRecord::StatementInvalid
<ide> return skip "do not test on PG without json" | 1 |
Javascript | Javascript | convert prerotations with builtin function | 370b0e859821621b890b12bc8016b073d7a29789 | <ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> if ( 'PreRotation' in node.properties ) {
<ide>
<del> var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( Math.PI / 180 ), 'ZYX' );
<add> var preRotations = new THREE.Euler().fromArray( node.properties.PreRotation.value.map( THREE.Math.degToRad ), 'ZYX' );
<ide> preRotations = new THREE.Quaternion().setFromEuler( preRotations );
<ide> var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
<ide> preRotations.multiply( currentRotation ); | 1 |
Javascript | Javascript | add missing semicolon i missed in #865 | 59cba3e9f72869620920102abaea511ae0ae4034 | <ide><path>src/core/ReactComponent.js
<ide> function validateExplicitKey(component) {
<ide> message += ' It was passed a child from ' + childOwnerName + '.';
<ide> }
<ide>
<del> message += ' See http://fb.me/react-warning-keys for more information.'
<add> message += ' See http://fb.me/react-warning-keys for more information.';
<ide> console.warn(message);
<ide> }
<ide> | 1 |
Python | Python | fix tests for mssql after sqla 1.4 upgrade | baf50cddd86ac07f064c8cbd95efb22d038b3832 | <ide><path>airflow/sensors/external_task.py
<ide> def get_count(self, dttm_filter, session, states) -> int:
<ide> """
<ide> TI = TaskInstance
<ide> DR = DagRun
<add> if not dttm_filter:
<add> return 0
<add>
<ide> if self.external_task_ids:
<ide> count = (
<ide> session.query(func.count()) # .count() is inefficient | 1 |
Javascript | Javascript | fix multi-line input | b5175003bca45e23bd20d9559096dafda3e0ad7c | <ide><path>lib/repl.js
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide> displayErrors: false
<ide> });
<ide> } catch (e) {
<del> err = e;
<ide> debug('parse error %j', code, e);
<add> if (isRecoverableError(e))
<add> err = new Recoverable(e);
<add> else
<add> err = e;
<ide> }
<ide>
<ide> if (!err) {
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide>
<ide> // If error was SyntaxError and not JSON.parse error
<ide> if (e) {
<del> if (isRecoverableError(e)) {
<add> if (e instanceof Recoverable) {
<ide> // Start buffering data like that:
<ide> // {
<ide> // ... x: 1
<ide> REPLServer.prototype.resetContext = function() {
<ide> };
<ide>
<ide> REPLServer.prototype.displayPrompt = function(preserveCursor) {
<del> var prompt = this._prompt;
<add> var initial = this._prompt;
<add> var prompt = initial;
<ide> if (this.bufferedCommand.length) {
<ide> prompt = '...';
<ide> var levelInd = new Array(this.lines.level.length).join('..');
<ide> prompt += levelInd + ' ';
<del> } else {
<del> this.setPrompt(prompt);
<ide> }
<add> this.setPrompt(prompt);
<ide> this.prompt(preserveCursor);
<add> this.setPrompt(initial);
<ide> };
<ide>
<ide> // A stream to push an array into a REPL
<ide> REPLServer.prototype.convertToContext = function(cmd) {
<ide> function isRecoverableError(e) {
<ide> return e &&
<ide> e.name === 'SyntaxError' &&
<del> /^Unexpected end of input/.test(e.message);
<add> /^(Unexpected end of input|Unexpected token :)/.test(e.message);
<add>}
<add>
<add>function Recoverable(err) {
<add> this.err = err;
<ide> }
<add>inherits(Recoverable, SyntaxError); | 1 |
Java | Java | improve ellipsizemode prop | cd1a86db36a02d93c8e1adb03b3a5773b7ebceb0 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java
<ide> public class ViewProps {
<ide> public static final String LINE_HEIGHT = "lineHeight";
<ide> public static final String NEEDS_OFFSCREEN_ALPHA_COMPOSITING = "needsOffscreenAlphaCompositing";
<ide> public static final String NUMBER_OF_LINES = "numberOfLines";
<del> public static final String LINE_BREAK_MODE = "ellipsizeMode";
<add> public static final String ELLIPSIZE_MODE = "ellipsizeMode";
<ide> public static final String ON = "on";
<ide> public static final String RESIZE_MODE = "resizeMode";
<ide> public static final String TEXT_ALIGN = "textAlign";
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java
<ide> import android.graphics.drawable.Drawable;
<ide> import android.text.Layout;
<ide> import android.text.Spanned;
<add>import android.text.TextUtils;
<ide> import android.view.Gravity;
<ide> import android.view.ViewGroup;
<ide> import android.widget.TextView;
<ide>
<ide> import com.facebook.csslayout.FloatUtil;
<ide> import com.facebook.react.uimanager.ReactCompoundView;
<add>import com.facebook.react.uimanager.ViewDefaults;
<add>
<add>import javax.annotation.Nullable;
<ide>
<ide> public class ReactTextView extends TextView implements ReactCompoundView {
<ide>
<ide> public class ReactTextView extends TextView implements ReactCompoundView {
<ide> private boolean mTextIsSelectable;
<ide> private float mLineHeight = Float.NaN;
<ide> private int mTextAlign = Gravity.NO_GRAVITY;
<add> private int mNumberOfLines = ViewDefaults.NUMBER_OF_LINES;
<add> private TextUtils.TruncateAt mEllipsizeLocation = TextUtils.TruncateAt.END;
<ide>
<ide> public ReactTextView(Context context) {
<ide> super(context);
<ide> public void onFinishTemporaryDetach() {
<ide> }
<ide> setGravity((getGravity() & ~Gravity.VERTICAL_GRAVITY_MASK) | gravityVertical);
<ide> }
<add>
<add> public void setNumberOfLines(int numberOfLines) {
<add> mNumberOfLines = numberOfLines == 0 ? ViewDefaults.NUMBER_OF_LINES : numberOfLines;
<add> setMaxLines(mNumberOfLines);
<add> }
<add>
<add> public void setEllipsizeLocation(TextUtils.TruncateAt ellipsizeLocation) {
<add> mEllipsizeLocation = ellipsizeLocation;
<add> }
<add>
<add> public void updateView() {
<add> @Nullable TextUtils.TruncateAt ellipsizeLocation = mNumberOfLines == ViewDefaults.NUMBER_OF_LINES ? null : mEllipsizeLocation;
<add> setEllipsize(ellipsizeLocation);
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java
<ide>
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.uimanager.BaseViewManager;
<del>import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide> import com.facebook.react.uimanager.ViewDefaults;
<ide> public ReactTextView createViewInstance(ThemedReactContext context) {
<ide> // maxLines can only be set in master view (block), doesn't really make sense to set in a span
<ide> @ReactProp(name = ViewProps.NUMBER_OF_LINES, defaultInt = ViewDefaults.NUMBER_OF_LINES)
<ide> public void setNumberOfLines(ReactTextView view, int numberOfLines) {
<del> view.setMaxLines(numberOfLines == 0 ? ViewDefaults.NUMBER_OF_LINES : numberOfLines);
<del> view.setEllipsize(TextUtils.TruncateAt.END);
<add> view.setNumberOfLines(numberOfLines);
<ide> }
<ide>
<del> @ReactProp(name = ViewProps.LINE_BREAK_MODE)
<del> public void setLineBreakMode(ReactTextView view, @Nullable String ellipsizeMode) {
<del> if(ellipsizeMode == null) {
<del> return;
<del> }
<del>
<del> if (ellipsizeMode.equals("head")) {
<del> view.setEllipsize(TextUtils.TruncateAt.START);
<add> @ReactProp(name = ViewProps.ELLIPSIZE_MODE)
<add> public void setEllipsizeMode(ReactTextView view, @Nullable String ellipsizeMode) {
<add> if (ellipsizeMode == null || ellipsizeMode.equals("tail")) {
<add> view.setEllipsizeLocation(TextUtils.TruncateAt.END);
<add> } else if (ellipsizeMode.equals("head")) {
<add> view.setEllipsizeLocation(TextUtils.TruncateAt.START);
<ide> } else if (ellipsizeMode.equals("middle")) {
<del> view.setEllipsize(TextUtils.TruncateAt.MIDDLE);
<del> } else if (ellipsizeMode.equals("tail")) {
<del> view.setEllipsize(TextUtils.TruncateAt.END);
<add> view.setEllipsizeLocation(TextUtils.TruncateAt.MIDDLE);
<add> } else {
<add> throw new JSApplicationIllegalArgumentException("Invalid ellipsizeMode: " + ellipsizeMode);
<ide> }
<ide> }
<ide>
<ide> public ReactTextShadowNode createShadowNodeInstance() {
<ide> public Class<ReactTextShadowNode> getShadowNodeClass() {
<ide> return ReactTextShadowNode.class;
<ide> }
<add>
<add> @Override
<add> protected void onAfterUpdateTransaction(ReactTextView view) {
<add> super.onAfterUpdateTransaction(view);
<add> view.updateView();
<add> }
<ide> } | 3 |
Python | Python | fix model collation | 24dfbb8a2853205c5fa27ac0657119a8c2699e39 | <ide><path>spacy/cli/train.py
<ide> def _collate_best_model(meta, output_path, components):
<ide> best_dest = output_path / 'model-best'
<ide> shutil.copytree(output_path / 'model-final', best_dest)
<ide> for component, best_component_src in bests.items():
<del> shutil.rmtree(best_dir / component)
<add> shutil.rmtree(best_dest / component)
<ide> shutil.copytree(best_component_src, best_dest / component)
<ide> with (best_component_src / 'accuracy.json').open() as file_:
<ide> accs = json.load(file_) | 1 |
Go | Go | fix race on reading endpoint data | 5abef06a158b437a020d59ffdba740d19613852e | <ide><path>daemon/list.go
<ide> import (
<ide> "github.com/docker/docker/pkg/graphdb"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/filters"
<add> networktypes "github.com/docker/engine-api/types/network"
<ide> "github.com/docker/go-connections/nat"
<ide> )
<ide>
<ide> func (daemon *Daemon) transformContainer(container *container.Container, ctx *li
<ide> newC.Created = container.Created.Unix()
<ide> newC.Status = container.State.String()
<ide> newC.HostConfig.NetworkMode = string(container.HostConfig.NetworkMode)
<del> newC.NetworkSettings = &types.SummaryNetworkSettings{container.NetworkSettings.Networks}
<add> // copy networks to avoid races
<add> networks := make(map[string]*networktypes.EndpointSettings)
<add> for name, network := range container.NetworkSettings.Networks {
<add> if network == nil {
<add> continue
<add> }
<add> networks[name] = &networktypes.EndpointSettings{
<add> EndpointID: network.EndpointID,
<add> Gateway: network.Gateway,
<add> IPAddress: network.IPAddress,
<add> IPPrefixLen: network.IPPrefixLen,
<add> IPv6Gateway: network.IPv6Gateway,
<add> GlobalIPv6Address: network.GlobalIPv6Address,
<add> GlobalIPv6PrefixLen: network.GlobalIPv6PrefixLen,
<add> MacAddress: network.MacAddress,
<add> }
<add> if network.IPAMConfig != nil {
<add> networks[name].IPAMConfig = &networktypes.EndpointIPAMConfig{
<add> IPv4Address: network.IPAMConfig.IPv4Address,
<add> IPv6Address: network.IPAMConfig.IPv6Address,
<add> }
<add> }
<add> }
<add> newC.NetworkSettings = &types.SummaryNetworkSettings{Networks: networks}
<ide>
<ide> newC.Ports = []types.Port{}
<ide> for port, bindings := range container.NetworkSettings.Ports { | 1 |
Text | Text | add missing link in changelog | e12b9bedecf664277b327c4353ac6f8995126034 | <ide><path>doc/changelogs/CHANGELOG_V7.md
<ide> </tr>
<ide> <tr>
<ide> <td>
<add><a href="#7.1.0">7.1.0</a><br/>
<ide> <a href="#7.0.0">7.0.0</a><br/>
<ide> </td>
<ide> </tr> | 1 |
Javascript | Javascript | remove overlooked slot | 0 defensive checks | 9b12fad68dba3ea23ca4e5c3f8cd428f0a19ab88 | <ide><path>editor/js/commands/SetMaterialColorCommand.js
<ide> var SetMaterialColorCommand = function ( object, attributeName, newValue, slot )
<ide>
<ide> this.object = object;
<ide> this.attributeName = attributeName;
<del> this.slot = slot | 0;
<add> this.slot = slot;
<ide>
<ide> var material = this.editor.getObjectMaterial( this.object, this.slot );
<ide>
<ide><path>editor/js/commands/SetMaterialCommand.js
<ide> var SetMaterialCommand = function ( object, newMaterial , slot) {
<ide>
<ide> this.object = object;
<ide>
<del> this.slot = slot | 0;
<add> this.slot = slot;
<ide>
<ide> var material = this.editor.getObjectMaterial( this.object, this.slot );
<ide> | 2 |
Javascript | Javascript | fix lint error | 91b3b4608cdef5244e1c6dde86d8d8590acd14ae | <ide><path>lib/Parser.js
<ide> Parser.prototype.walkExportNamedDeclaration = function walkExportNamedDeclaratio
<ide> this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, specifierIndex);
<ide> break;
<ide> }
<del> }
<add> }
<ide> }
<ide> };
<ide> | 1 |
PHP | PHP | import dispatcher contract | 9c9f817372a644a2e233c3af543b2120fcfcf2d9 | <ide><path>src/Illuminate/Foundation/Bus/DispatchesJobs.php
<ide> namespace Illuminate\Foundation\Bus;
<ide>
<ide> use ArrayAccess;
<add>use Illuminate\Contracts\Bus\Dispatcher;
<ide>
<ide> trait DispatchesJobs
<ide> {
<ide> trait DispatchesJobs
<ide> */
<ide> protected function dispatch($job)
<ide> {
<del> return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch($job);
<add> return app(Dispatcher::class)->dispatch($job);
<ide> }
<ide>
<ide> /**
<ide> protected function dispatch($job)
<ide> */
<ide> protected function dispatchFromArray($job, array $array)
<ide> {
<del> return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatchFromArray($job, $array);
<add> return app(Dispatcher::class)->dispatchFromArray($job, $array);
<ide> }
<ide>
<ide> /**
<ide> protected function dispatchFromArray($job, array $array)
<ide> */
<ide> protected function dispatchFrom($job, ArrayAccess $source, $extras = [])
<ide> {
<del> return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatchFrom($job, $source, $extras);
<add> return app(Dispatcher::class)->dispatchFrom($job, $source, $extras);
<ide> }
<ide> } | 1 |
Ruby | Ruby | move version detection to version class | 5fe7fdf1535eda627f74e0272b4bbf0618b9a498 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def abv
<ide> out<<`/usr/bin/du -hd0 #{to_s} | cut -d"\t" -f1`.strip
<ide> end
<ide>
<del> # attempts to retrieve the version component of this path, so generally
<del> # you'll call it on tarballs or extracted tarball directories, if you add
<del> # to this please provide amend the unittest
<ide> def version
<del> if directory?
<del> # directories don't have extnames
<del> stem=basename.to_s
<del> else
<del> # sourceforge /download
<del> if %r[((?:sourceforge.net|sf.net)/.*)/download$].match to_s
<del> stem=Pathname.new(dirname).stem
<del> else
<del> stem=self.stem
<del> end
<del> end
<del>
<del> # github tarballs, like v1.2.3
<del> %r[github.com/.*/(zip|tar)ball/v?((\d+\.)+\d+)$].match to_s
<del> return $2 if $2
<del>
<del> # eg. https://github.com/sam-github/libnet/tarball/libnet-1.1.4
<del> %r[github.com/.*/(zip|tar)ball/.*-((\d+\.)+\d+)$].match to_s
<del> return $2 if $2
<del>
<del> # dashed version
<del> # eg. github.com/isaacs/npm/tarball/v0.2.5-1
<del> %r[github.com/.*/(zip|tar)ball/v?((\d+\.)+\d+-(\d+))$].match to_s
<del> return $2 if $2
<del>
<del> # underscore version
<del> # eg. github.com/petdance/ack/tarball/1.93_02
<del> %r[github.com/.*/(zip|tar)ball/v?((\d+\.)+\d+_(\d+))$].match to_s
<del> return $2 if $2
<del>
<del> # eg. boost_1_39_0
<del> /((\d+_)+\d+)$/.match stem
<del> return $1.gsub('_', '.') if $1
<del>
<del> # eg. foobar-4.5.1-1
<del> # eg. ruby-1.9.1-p243
<del> /-((\d+\.)*\d\.\d+-(p|rc|RC)?\d+)$/.match stem
<del> return $1 if $1
<del>
<del> # eg. lame-398-1
<del> /-((\d)+-\d)/.match stem
<del> return $1 if $1
<del>
<del> # eg. foobar-4.5.1
<del> /-((\d+\.)*\d+)$/.match stem
<del> return $1 if $1
<del>
<del> # eg. foobar-4.5.1b
<del> /-((\d+\.)*\d+([abc]|rc|RC)\d*)$/.match stem
<del> return $1 if $1
<del>
<del> # eg foobar-4.5.0-beta1, or foobar-4.50-beta
<del> /-((\d+\.)*\d+-beta(\d+)?)$/.match stem
<del> return $1 if $1
<del>
<del> # eg. foobar4.5.1
<del> unless /^erlang-/.match basename
<del> /((\d+\.)*\d+)$/.match stem
<del> return $1 if $1
<del> end
<del>
<del> # eg foobar-4.5.0-bin
<del> /-((\d+\.)+\d+[abc]?)[-._](bin|dist|stable|src|sources?)$/.match stem
<del> return $1 if $1
<del>
<del> # Debian style eg dash_0.5.5.1.orig.tar.gz
<del> /_((\d+\.)+\d+[abc]?)[.]orig$/.match stem
<del> return $1 if $1
<del>
<del> # eg. otp_src_R13B (this is erlang's style)
<del> # eg. astyle_1.23_macosx.tar.gz
<del> stem.scan(/_([^_]+)/) do |match|
<del> return match.first if /\d/.match $1
<del> end
<del>
<del> # old erlang bottle style e.g. erlang-R14B03-bottle.tar.gz
<del> /-([^-]+)/.match stem
<del> return $1 if $1
<del>
<del> nil
<add> require 'version'
<add> version = Version.parse(self)
<add> version.to_s unless version.nil?
<ide> end
<ide>
<ide> def compression_type
<ide><path>Library/Homebrew/test/test_versions.rb
<ide>
<ide> module VersionAssertions
<ide> def assert_version url, version
<del> assert_equal version, Version.parse(url)
<add> assert_equal version, Version.parse(url).to_s
<ide> end
<ide>
<ide> def assert_version_nil url
<ide><path>Library/Homebrew/version.rb
<ide> class Version
<ide>
<ide> def initialize val
<ide> return val if val.is_a? Version or val.nil?
<del> @version = val.to_s.strip
<add> @version = val.to_s
<ide> end
<ide>
<ide> def head?
<ide> def to_s
<ide> alias_method :to_str, :to_s
<ide>
<ide> def self.parse spec
<del> Pathname.new(spec.to_s).version
<add> version = _parse(spec)
<add> Version.new(version) unless version.nil?
<add> end
<add>
<add> private
<add>
<add> def self._parse spec
<add> spec = Pathname.new(spec) unless spec.is_a? Pathname
<add>
<add> stem = if spec.directory?
<add> spec.basename.to_s
<add> elsif %r[((?:sourceforge.net|sf.net)/.*)/download$].match(spec.to_s)
<add> Pathname.new(spec.dirname).stem
<add> else
<add> spec.stem
<add> end
<add>
<add> # GitHub tarballs, e.g. v1.2.3
<add> m = %r[github.com/.+/(?:zip|tar)ball/v?((\d+\.)+\d+)$].match(spec.to_s)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. https://github.com/sam-github/libnet/tarball/libnet-1.1.4
<add> m = %r[github.com/.+/(?:zip|tar)ball/.*-((\d+\.)+\d+)$].match(spec.to_s)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. https://github.com/isaacs/npm/tarball/v0.2.5-1
<add> m = %r[github.com/.+/(?:zip|tar)ball/v?((\d+\.)+\d+-(\d+))$].match(spec.to_s)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. https://github.com/petdance/ack/tarball/1.93_02
<add> m = %r[github.com/.+/(?:zip|tar)ball/v?((\d+\.)+\d+_(\d+))$].match(spec.to_s)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. boost_1_39_0
<add> m = /((\d+_)+\d+)$/.match(stem)
<add> return m.captures.first.gsub('_', '.') unless m.nil?
<add>
<add> # e.g. foobar-4.5.1-1
<add> # e.g. ruby-1.9.1-p243
<add> m = /-((\d+\.)*\d\.\d+-(p|rc|RC)?\d+)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. lame-398-1
<add> m = /-((\d)+-\d)/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. foobar-4.5.1
<add> m = /-((\d+\.)*\d+)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. foobar-4.5.1b
<add> m = /-((\d+\.)*\d+([abc]|rc|RC)\d*)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. foobar-4.5.0-beta1, or foobar-4.50-beta
<add> m = /-((\d+\.)*\d+-beta(\d+)?)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. foobar4.5.1
<add> m = /((\d+\.)*\d+)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. foobar-4.5.0-bin
<add> m = /-((\d+\.)+\d+[abc]?)[-._](bin|dist|stable|src|sources?)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. dash_0.5.5.1.orig.tar.gz (Debian style)
<add> m = /_((\d+\.)+\d+[abc]?)[.]orig$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. erlang-R14B03-bottle.tar.gz (old erlang bottle style)
<add> m = /-([^-]+)/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. opt_src_R13B (erlang)
<add> m = /otp_src_(.+)/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. astyle_1.23_macosx.tar.gz
<add> m = /_([^_]+)/.match(stem)
<add> return m.captures.first unless m.nil?
<ide> end
<ide> end | 3 |
PHP | PHP | implement outputtimezone in a few methods | a688b0422f5ec0336a53c42152a6cf2db8245b44 | <ide><path>src/View/Helper/TimeHelper.php
<ide> class TimeHelper extends Helper
<ide>
<ide> use StringTemplateTrait;
<ide>
<add> /**
<add> * Config options
<add> *
<add> * @var array
<add> */
<add> protected $_defaultConfig = [
<add> 'outputTimezone' => null
<add> ];
<add>
<add> /**
<add> * Get a timezone.
<add> *
<add> * Will use the provided timezone, or default output timezone if defined.
<add> *
<add> * @param null|string|DateTimeZone $timezone The override timezone if applicable.
<add> * @return null|string|DateTimeZone The chosen timezone or null.
<add> */
<add> protected function _timezone($timezone)
<add> {
<add> if ($timezone) {
<add> return $timezone;
<add> }
<add> return $this->config('outputTimezone');
<add> }
<add>
<ide> /**
<ide> * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
<ide> *
<ide> public function fromString($dateString, $timezone = null)
<ide> */
<ide> public function nice($dateString = null, $timezone = null, $locale = null)
<ide> {
<add> $timezone = $this->_timezone($timezone);
<ide> return (new Time($dateString))->nice($timezone, $locale);
<ide> }
<ide>
<ide> public function toUnix($dateString, $timezone = null)
<ide> */
<ide> public function toAtom($dateString, $timezone = null)
<ide> {
<del> $timezone = $timezone ?: date_default_timezone_get();
<add> $timezone = $this->_timezone($timezone) ?: date_default_timezone_get();
<ide> return (new Time($dateString))->timezone($timezone)->toAtomString();
<ide> }
<ide>
<ide> public function toAtom($dateString, $timezone = null)
<ide> */
<ide> public function toRss($dateString, $timezone = null)
<ide> {
<del> $timezone = $timezone ?: date_default_timezone_get();
<add> $timezone = $this->_timezone($timezone) ?: date_default_timezone_get();
<ide> return (new Time($dateString))->timezone($timezone)->toRssString();
<ide> }
<ide>
<ide> public function toRss($dateString, $timezone = null)
<ide> public function timeAgoInWords($dateTime, array $options = [])
<ide> {
<ide> $element = null;
<add> $options += [
<add> 'element' => null,
<add> 'timezone' => null
<add> ];
<add> $options['timezone'] = $this->_timezone($options['timezone']);
<add> if ($options['timezone']) {
<add> $dateTime = $dateTime->timezone($options['timezone']);
<add> unset($options['timezone']);
<add> }
<ide>
<ide> if (!empty($options['element'])) {
<ide> $element = [
<ide> public function i18nFormat($date, $format = null, $invalid = false, $timezone =
<ide> if (!isset($date)) {
<ide> return $invalid;
<ide> }
<add> $timezone = $this->_timezone($timezone);
<ide>
<ide> try {
<ide> $time = new Time($date);
<ide><path>tests/TestCase/View/Helper/TimeHelperTest.php
<ide> public function testNice()
<ide> $this->assertTimeFormat('Apr 20, 2014, 4:00 PM', $result);
<ide> }
<ide>
<add> /**
<add> * test nice with outputTimezone
<add> *
<add> * @return void
<add> */
<add> public function testNiceOutputTimezone()
<add> {
<add> $this->Time->config('outputTimezone', 'America/Vancouver');
<add> $time = '2014-04-20 20:00';
<add> $this->assertTimeFormat('Apr 20, 2014, 1:00 PM', $this->Time->nice($time));
<add> }
<add>
<ide> /**
<ide> * testToUnix method
<ide> *
<ide> public function testToRss()
<ide> */
<ide> public function testToRssOutputTimezone()
<ide> {
<del> $this->markTestIncomplete();
<add> $this->Time->config('outputTimezone', 'America/Vancouver');
<add> $dateTime = new Time;
<add> $vancouver = clone $dateTime;
<add> $vancouver->timezone('America/Vancouver');
<add>
<add> $this->assertEquals($vancouver->format('r'), $this->Time->toRss($vancouver));
<ide> }
<ide>
<ide> /**
<ide> public function testIsToday()
<ide> {
<ide> $result = $this->Time->isToday('+1 day');
<ide> $this->assertFalse($result);
<add>
<ide> $result = $this->Time->isToday('+1 days');
<ide> $this->assertFalse($result);
<add>
<ide> $result = $this->Time->isToday('+0 day');
<ide> $this->assertTrue($result);
<add>
<ide> $result = $this->Time->isToday('-1 day');
<ide> $this->assertFalse($result);
<ide> }
<ide>
<del> /**
<del> * test isToday with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsTodayOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsFuture method
<ide> *
<ide> public function testIsFuture()
<ide> $this->assertFalse($this->Time->isFuture('-1 month'));
<ide> }
<ide>
<del> /**
<del> * test isFuture with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsFutureOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsPast method
<ide> *
<ide> public function testIsPast()
<ide> $this->assertTrue($this->Time->isPast('-1 month'));
<ide> }
<ide>
<del> /**
<del> * test isPast with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsPastOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsThisWeek method
<ide> *
<ide> public function testIsThisWeek()
<ide> $this->assertFalse($this->Time->isThisWeek('+' . $days[1] . ' days'));
<ide> }
<ide>
<del> /**
<del> * test isThisWeek with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsThisWeekOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsThisMonth method
<ide> *
<ide> public function testIsThisMonth()
<ide> $this->assertFalse($result);
<ide> }
<ide>
<del> /**
<del> * test isThisMonth with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsThisMonthOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsThisYear method
<ide> *
<ide> public function testIsThisYear()
<ide> $this->assertTrue($result);
<ide> }
<ide>
<del> /**
<del> * test isThisYear with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsThisYearOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testWasYesterday method
<ide> *
<ide> public function testWasYesterday()
<ide> $this->assertFalse($result);
<ide> }
<ide>
<del> /**
<del> * test wasYesterday with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testWasYesterdayOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testIsTomorrow method
<ide> *
<ide> public function testIsTomorrow()
<ide> $this->assertFalse($result);
<ide> }
<ide>
<del> /**
<del> * test isTomorrow with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsTomorrowOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testWasWithinLast method
<ide> *
<ide> public function testWasWithinLast()
<ide> $this->assertTrue($this->Time->wasWithinLast('1 ', '-23 hours -59 minutes -59 seconds'));
<ide> }
<ide>
<del> /**
<del> * test wasWithinLast with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testWasWithinLastOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * testWasWithinLast method
<ide> *
<ide> public function testIsWithinNext()
<ide> $this->assertTrue($this->Time->isWithinNext('1 month', '+1 month'));
<ide> }
<ide>
<del> /**
<del> * test isWithinNext with outputTimezone
<del> *
<del> * @return void
<del> */
<del> public function testIsWithinNextOutputTimezone()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * test formatting dates taking in account preferred i18n locale file
<ide> *
<ide> public function testFormat()
<ide> */
<ide> public function testFormatOutputTimezone()
<ide> {
<del> $this->markTestIncomplete();
<add> $this->Time->config('outputTimezone', 'America/Vancouver');
<add>
<add> $time = strtotime('Thu Jan 14 8:59:28 2010 UTC');
<add> $result = $this->Time->format($time);
<add> $expected = '1/14/10, 12:59 AM';
<add> $this->assertTimeFormat($expected, $result);
<add>
<add> $time = new Time('Thu Jan 14 8:59:28 2010', 'UTC');
<add> $result = $this->Time->format($time);
<add> $expected = '1/14/10, 12:59 AM';
<add> $this->assertTimeFormat($expected, $result);
<add> }
<add>
<add> /**
<add> * test i18nFormat with outputTimezone
<add> *
<add> * @return void
<add> */
<add> public function testI18nFormatOutputTimezone()
<add> {
<add> $this->Time->config('outputTimezone', 'America/Vancouver');
<add>
<add> $time = strtotime('Thu Jan 14 8:59:28 2010 UTC');
<add> $result = $this->Time->i18nFormat($time, \IntlDateFormatter::SHORT);
<add> $expected = '1/14/10, 12:59:28 AM';
<add> $this->assertStringStartsWith($expected, $result);
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | remove unused methods in `staged` module | b7cf925da84cbd5eeb5de4c94b917369d4f072fd | <ide><path>Library/Homebrew/cask/staged.rb
<ide>
<ide> module Cask
<ide> module Staged
<del> def info_plist_file(index = 0)
<del> index = 0 if index == :first
<del> index = 1 if index == :second
<del> index = -1 if index == :last
<del> @cask.artifacts.select { |a| a.is_a?(Artifact::App) }.at(index).target.join("Contents", "Info.plist")
<del> end
<del>
<del> def plist_exec(cmd)
<del> @command.run!("/usr/libexec/PlistBuddy", args: ["-c", cmd, info_plist_file])
<del> end
<del>
<del> def plist_set(key, value)
<del> plist_exec("Set #{key} #{value}")
<del> rescue => e
<del> raise CaskError, "#{@cask.token}: 'plist_set' failed with: #{e}"
<del> end
<del>
<del> def bundle_identifier
<del> plist_exec("Print CFBundleIdentifier").stdout.chomp
<del> rescue => e
<del> raise CaskError, "#{@cask.token}: 'bundle_identifier' failed with: #{e}"
<del> end
<del>
<ide> def set_permissions(paths, permissions_str)
<ide> full_paths = remove_nonexistent(paths)
<ide> return if full_paths.empty?
<ide><path>Library/Homebrew/test/cask/staged_spec.rb
<del># TODO: this test should be named after the corresponding class, once
<del># that class is abstracted from installer.rb. It makes little sense
<del># to be invoking bundle_identifier off of the installer instance.
<del>describe "Operations on staged Casks", :cask do
<del> describe "bundle ID" do
<del> let(:cask) { Cask::CaskLoader.load(cask_path("local-transmission")) }
<del> let(:installer) { Cask::Installer.new(cask) }
<del>
<del> it "fetches the bundle ID from a staged cask" do
<del> installer.install
<del> expect(installer.bundle_identifier).to eq("org.m0k.transmission")
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/test/support/helper/spec/shared_examples/cask_staged.rb
<ide> staged.system_command("echo", args: ["homebrew-cask", "rocks!"])
<ide> end
<ide>
<del> it "can get the Info.plist file for the primary app" do
<del> expect(staged.info_plist_file).to eq Cask::Config.global.appdir.join("TestCask.app/Contents/Info.plist")
<del> end
<del>
<del> it "can execute commands on the Info.plist file" do
<del> allow(staged).to receive(:bundle_identifier).and_return("com.example.BasicCask")
<del>
<del> FakeSystemCommand.expects_command(
<del> ["/usr/libexec/PlistBuddy", "-c", "Print CFBundleIdentifier", staged.info_plist_file],
<del> )
<del>
<del> staged.plist_exec("Print CFBundleIdentifier")
<del> end
<del>
<del> it "can set a key in the Info.plist file" do
<del> allow(staged).to receive(:bundle_identifier).and_return("com.example.BasicCask")
<del>
<del> FakeSystemCommand.expects_command(
<del> ["/usr/libexec/PlistBuddy", "-c", "Set :JVMOptions:JVMVersion 1.6+", staged.info_plist_file],
<del> )
<del>
<del> staged.plist_set(":JVMOptions:JVMVersion", "1.6+")
<del> end
<del>
<ide> it "can set the permissions of a file" do
<ide> fake_pathname = existing_path
<ide> allow(staged).to receive(:Pathname).and_return(fake_pathname) | 3 |
Java | Java | expose jms message listener container ids | 1bc41bdf0f4f491259c2079de48a93ed1dfbe9eb | <ide><path>spring-jms/src/main/java/org/springframework/jms/config/JmsListenerEndpointRegistry.java
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.Map;
<add>import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> public class JmsListenerEndpointRegistry implements DisposableBean, SmartLifecyc
<ide> * @param id the id of the container
<ide> * @return the container or {@code null} if no container with that id exists
<ide> * @see JmsListenerEndpoint#getId()
<add> * @see #getListenerContainerIds()
<ide> */
<ide> public MessageListenerContainer getListenerContainer(String id) {
<ide> Assert.notNull(id, "Container identifier must not be null");
<ide> return this.listenerContainers.get(id);
<ide> }
<ide>
<add> /**
<add> * Return the ids of the managed {@link MessageListenerContainer} instance(s).
<add> * @see #getListenerContainer(String)
<add> */
<add> public Set<String> getListenerContainerIds() {
<add> return Collections.unmodifiableSet(this.listenerContainers.keySet());
<add> }
<add>
<ide> /**
<ide> * Return the managed {@link MessageListenerContainer} instance(s).
<ide> */
<ide><path>spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java
<ide> public void testCustomConfiguration(ApplicationContext context) {
<ide>
<ide> JmsListenerEndpointRegistry customRegistry =
<ide> context.getBean("customRegistry", JmsListenerEndpointRegistry.class);
<add> assertEquals("Wrong number of containers in the registry", 2,
<add> customRegistry.getListenerContainerIds().size());
<ide> assertEquals("Wrong number of containers in the registry", 2,
<ide> customRegistry.getListenerContainers().size());
<ide> assertNotNull("Container with custom id on the annotation should be found",
<ide><path>spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointRegistrarTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void registerNullContainerFactoryIsAllowed() throws Exception {
<ide> registrar.afterPropertiesSet();
<ide> assertNotNull("Container not created", registry.getListenerContainer("some id"));
<ide> assertEquals(1, registry.getListenerContainers().size());
<add> assertEquals("some id", registry.getListenerContainerIds().iterator().next());
<ide> }
<ide>
<ide> @Test
<ide> public void registerContainerWithoutFactory() throws Exception {
<ide> registrar.afterPropertiesSet();
<ide> assertNotNull("Container not created", registry.getListenerContainer("myEndpoint"));
<ide> assertEquals(1, registry.getListenerContainers().size());
<add> assertEquals("myEndpoint", registry.getListenerContainerIds().iterator().next());
<ide> }
<ide>
<ide> } | 3 |
Java | Java | remove use of compositebytebuf in nettydatabuffer | e6893da9714cf557a36691dcefc8209bfff1e98d | <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/NettyDataBuffer.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import io.netty.buffer.ByteBuf;
<ide> import io.netty.buffer.ByteBufInputStream;
<ide> import io.netty.buffer.ByteBufOutputStream;
<del>import io.netty.buffer.CompositeByteBuf;
<del>import io.netty.buffer.Unpooled;
<ide>
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> * Implementation of the {@code DataBuffer} interface that wraps a Netty
<ide> public class NettyDataBuffer implements PooledDataBuffer {
<ide>
<ide> private final NettyDataBufferFactory dataBufferFactory;
<ide>
<del> private ByteBuf byteBuf;
<add> private final ByteBuf byteBuf;
<ide>
<ide>
<ide> /**
<ide> public NettyDataBuffer write(byte[] source, int offset, int length) {
<ide>
<ide> @Override
<ide> public NettyDataBuffer write(DataBuffer... buffers) {
<del> if (!ObjectUtils.isEmpty(buffers)) {
<del> if (buffers[0] instanceof NettyDataBuffer) {
<add> Assert.notNull(buffers, "'buffers' must not be null");
<add>
<add> if (buffers.length > 0) {
<add> if (hasNettyDataBuffers(buffers)) {
<ide> ByteBuf[] nativeBuffers = Arrays.stream(buffers)
<ide> .map(b -> ((NettyDataBuffer) b).getNativeBuffer())
<ide> .toArray(ByteBuf[]::new);
<ide> public NettyDataBuffer write(DataBuffer... buffers) {
<ide> return this;
<ide> }
<ide>
<add> private static boolean hasNettyDataBuffers(DataBuffer[] dataBuffers) {
<add> for (DataBuffer dataBuffer : dataBuffers) {
<add> if (!(dataBuffer instanceof NettyDataBuffer)) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<ide> @Override
<ide> public NettyDataBuffer write(ByteBuffer... buffers) {
<ide> Assert.notNull(buffers, "'buffers' must not be null");
<del> ByteBuf[] wrappedBuffers = Arrays.stream(buffers).map(Unpooled::wrappedBuffer)
<del> .toArray(ByteBuf[]::new);
<del> return write(wrappedBuffers);
<add>
<add> for (ByteBuffer buffer : buffers) {
<add> this.byteBuf.writeBytes(buffer);
<add> }
<add> return this;
<ide> }
<ide>
<ide> /**
<ide> public NettyDataBuffer write(ByteBuffer... buffers) {
<ide> public NettyDataBuffer write(ByteBuf... byteBufs) {
<ide> Assert.notNull(byteBufs, "'byteBufs' must not be null");
<ide>
<del> if (this.byteBuf instanceof CompositeByteBuf) {
<del> CompositeByteBuf composite = (CompositeByteBuf) this.byteBuf;
<del> composite.addComponents(true, byteBufs);
<del> }
<del> else {
<del> ByteBuf oldByteBuf = this.byteBuf;
<del> CompositeByteBuf composite = oldByteBuf.alloc().compositeBuffer(byteBufs.length + 1);
<del> composite.addComponent(true, oldByteBuf);
<del> composite.addComponents(true, byteBufs);
<del>
<del> this.byteBuf = composite;
<add> for (ByteBuf byteBuf : byteBufs) {
<add> this.byteBuf.writeBytes(byteBuf);
<ide> }
<ide> return this;
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void writeDataBuffer() {
<ide>
<ide> assertArrayEquals(new byte[]{'a', 'b', 'c', 'd'}, result);
<ide>
<del> release(buffer1);
<add> release(buffer1, buffer2, buffer3);
<ide> }
<ide>
<ide> @Test
<ide> public void slice() {
<ide> release(buffer);
<ide> }
<ide>
<add> @Test
<add> public void spr16351() {
<add> DataBuffer buffer = createDataBuffer(6);
<add> byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f'};
<add> buffer.write(bytes);
<add> DataBuffer slice = buffer.slice(3, 3);
<add> buffer.writePosition(3);
<add> buffer.write(slice);
<add>
<add> assertEquals(6, buffer.readableByteCount());
<add> byte[] result = new byte[6];
<add> buffer.read(result);
<add>
<add> assertArrayEquals(bytes, result);
<add>
<add> release(buffer);
<add> }
<add>
<ide>
<ide> }
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | call resume() after setrawmode() | 6822488c93ddc683061cfbeb6063ad140417a365 | <ide><path>lib/readline.js
<ide> function Interface(input, output, completer, terminal) {
<ide>
<ide> this.output = output;
<ide> this.input = input;
<del> input.resume();
<ide>
<ide> // Check arity, 2 - for async, 1 for sync
<ide> this.completer = completer.length === 2 ? completer : function(v, callback) {
<ide> function Interface(input, output, completer, terminal) {
<ide> output.removeListener('resize', onresize);
<ide> });
<ide> }
<add>
<add> input.resume();
<ide> }
<ide>
<ide> inherits(Interface, EventEmitter); | 1 |
PHP | PHP | add doc blocks | 46ce40b639a9e6d0ff42e41bbcbaec8164917e86 | <ide><path>src/View/Input/Radio.php
<ide> protected function _isDisabled($radio, $disabled) {
<ide> return (!is_array($disabled) || in_array((string)$radio['value'], $disabled, !$isNumeric));
<ide> }
<ide>
<add>/**
<add> * Renders a label element for a given radio button.
<add> *
<add> * In the future this might be refactored into a separate widget as other
<add> * input types (multi-checkboxes) will also need labels generated.
<add> *
<add> * @param array $radio The input properties.
<add> * @param false|string|array $label The properties for a label.
<add> * @param boolean $escape Whether or not to HTML escape the label.
<add> * @return string Generated label.
<add> */
<ide> protected function _renderLabel($radio, $label, $escape) {
<ide> if (!$label) {
<ide> return false; | 1 |
Go | Go | add another symlink breakout test | 1cd89729d59948a4bdc9d6c8a4ab01cedaeb193f | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func TestBuildExoticShellInterpolation(t *testing.T) {
<ide>
<ide> logDone("build - exotic shell interpolation")
<ide> }
<add>
<add>func TestBuildSymlinkBreakout(t *testing.T) {
<add> name := "testbuildsymlinkbreakout"
<add> tmpdir, err := ioutil.TempDir("", name)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer os.RemoveAll(tmpdir)
<add> ctx := filepath.Join(tmpdir, "context")
<add> if err := os.MkdirAll(ctx, 0755); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
<add> from busybox
<add> add symlink.tar /
<add> add inject /symlink/
<add> `), 0644); err != nil {
<add> t.Fatal(err)
<add> }
<add> inject := filepath.Join(ctx, "inject")
<add> if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
<add> t.Fatal(err)
<add> }
<add> f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> w := tar.NewWriter(f)
<add> w.WriteHeader(&tar.Header{
<add> Name: "symlink2",
<add> Typeflag: tar.TypeSymlink,
<add> Linkname: "/../../../../../../../../../../../../../../",
<add> Uid: os.Getuid(),
<add> Gid: os.Getgid(),
<add> })
<add> w.WriteHeader(&tar.Header{
<add> Name: "symlink",
<add> Typeflag: tar.TypeSymlink,
<add> Linkname: filepath.Join("symlink2", tmpdir),
<add> Uid: os.Getuid(),
<add> Gid: os.Getgid(),
<add> })
<add> w.Close()
<add> f.Close()
<add> if _, err := buildImageFromContext(name, &FakeContext{Dir: ctx}, false); err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
<add> t.Fatal("symlink breakout - inject")
<add> } else if !os.IsNotExist(err) {
<add> t.Fatalf("unexpected error: %v", err)
<add> }
<add> logDone("build - symlink breakout")
<add>} | 1 |
Go | Go | fix race between with event timer stopping early | b38cee9f9c79d1f12001348303b78462d99664ed | <ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> return err
<ide> }
<ide>
<del> timer := time.NewTimer(0)
<del> timer.Stop()
<add> var timeout <-chan time.Time
<ide> if until > 0 || untilNano > 0 {
<ide> dur := time.Unix(until, untilNano).Sub(time.Now())
<del> timer = time.NewTimer(dur)
<add> timeout = time.NewTimer(dur).C
<ide> }
<ide>
<ide> ef, err := filters.FromParam(r.Form.Get("filters"))
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> if err := enc.Encode(jev); err != nil {
<ide> return err
<ide> }
<del> case <-timer.C:
<add> case <-timeout:
<ide> return nil
<ide> case <-ctx.Done():
<ide> logrus.Debug("Client context cancelled, stop sending events") | 1 |
Text | Text | revise windows docker instructions | 3faba5fbe264425ac6d15bdfdf3c5a72e25643cb | <ide><path>docs/installation/windows.md
<ide> small ~24MB download, and boots in approximately 5s.
<ide>
<ide> ## Requirements
<ide>
<del>Your machine must be running Windows 7.1, 8/8.1 or newer to run Docker. Windows 10 is not currently supported. To find out what version of Windows you have:
<add>Your machine must be running Windows 7, 8/8.1 or newer to run Docker. Windows 10 is not currently supported. To find out what version of Windows you have:
<ide>
<del>1. Right click the Windows message and choose **System**.
<add>1. Right click the Windows Start Menu and choose **System**.
<ide>
<ide> 
<ide>
<del> If you aren't using a supported version, you could consider upgrading your
<del> operating system.
<add> If you are using an unsupported version of Windows, you should consider
<add> upgrading your operating system in order to try out Docker.
<ide>
<del>2. Make sure your Windows system supports Hardware Virtualization Technology and that virtualization is enabled.
<add>2. Make sure your CPU supports [virtualization technology](https://en.wikipedia.org/wiki/X86_virtualization)
<add>and virtualzation support is enabled in BIOS and recognized by Windows.
<ide>
<ide> #### For Windows 8 or 8.1
<ide>
<ide> Your machine must be running Windows 7.1, 8/8.1 or newer to run Docker. Windows
<ide>
<ide> If virtualization is not enabled on your system, follow the manufacturer's instructions for enabling it.
<ide>
<del> ### For Windows 7
<add> #### For Windows 7
<ide>
<ide> Run the <a
<ide> href="http://www.microsoft.com/en-us/download/details.aspx?id=592"
<ide> installer.
<ide> installation. By default, the standard Docker Toolbox installation:
<ide>
<ide> * installs executables for the Docker tools in `C:\Program Files\Docker Toolbox`
<del> * updates any existing VirtualBox installation
<add> * install VirtualBox; or updates any existing installation
<ide> * adds a Docker Inc. folder to your program shortcuts
<ide> * updates your `PATH` environment variable
<ide> * adds desktop icons for the Docker Quickstart Terminal and Kitematic
<ide> installer.
<ide>
<ide> 
<ide>
<del>7. Press "Close" to exit.
<add>7. Press "Finish" to exit.
<ide>
<ide> ## Running a Docker Container
<ide>
<ide> VirtualBox VM, it maintains its configuration between uses.
<ide> There are several ways to use the installed tools, from the Docker Quickstart Terminal or
<ide> [from your shell](#from-your-shell).
<ide>
<del>### From the Docker Quickstart Terminal
<add>### Using the Docker Quickstart Terminal
<ide>
<ide> 1. Find the Docker Quickstart Terminal icon on your Desktop and double-click to launch it.
<ide>
<ide> The application:
<ide>
<ide> * opens a terminal window
<del> * creates a `default` if it doesn't exist, starts the VM if it does
<add> * creates a `default` VM if it doesn't exist, and starts the VM after
<ide> * points the terminal environment to this VM
<ide>
<ide> Once the launch completes, you can run `docker` commands.
<ide> There are several ways to use the installed tools, from the Docker Quickstart Te
<ide> http://docs.docker.com/userguide/
<ide>
<ide>
<del>## Using Docker from Windows Command Line Prompt (cmd.exe)
<add>### Using Docker from Windows Command Prompt (cmd.exe)
<ide>
<del>1. Launch a Windows Command Line Prompt (cmd.exe).
<add>1. Launch a Windows Command Prompt (cmd.exe).
<ide>
<ide> The `docker-machine` command requires `ssh.exe` in your `PATH` environment
<ide> variable. This `.exe` is in the MsysGit `bin` folder.
<ide> There are several ways to use the installed tools, from the Docker Quickstart Te
<ide>
<ide> C:\Users\mary> docker run hello-world
<ide>
<del>## Using Docker from PowerShell
<add>### Using Docker from PowerShell
<ide>
<ide> 1. Launch a Windows PowerShell window.
<ide>
<ide> There are several ways to use the installed tools, from the Docker Quickstart Te
<ide>
<ide> Toolbox installs the Docker Engine binary in the `C:\Program Files\Docker
<ide> Toolbox` directory. When you use the Docker Quickstart Terminal or create a
<del>`default` manually, Docker Machine updates the
<add>`default` VM manually, Docker Machine updates the
<ide> `C:\USERS\USERNAME\.docker\machine\machines\default` folder to your
<ide> system. This folder contains the configuration for the VM.
<ide>
<del>You can create multiple VMs on your system with Docker Machine. So, you may have
<del>more than one VM folder if you have more than one VM. To remove a VM, use the
<del>`docker-machine rm <machine-name>` command.
<add>You can create multiple VMs on your system with Docker Machine. Therefore, you
<add>may end up with multiple VM folders if you have created more than one VM. To
<add>remove a VM, use the `docker-machine rm <machine-name>` command.
<ide>
<ide> ## Migrate from Boot2Docker
<ide>
<ide> installer](https://www.docker.com/toolbox).
<ide>
<ide> ## Container port redirection
<ide>
<del>If you are curious, the username for the Docker default user is `docker` and the
<add>If you are curious, the username for the Docker default VM is `docker` and the
<ide> password is `tcuser`. The latest version of `docker-machine` sets up a host only
<ide> network adaptor which provides access to the container's ports.
<ide> | 1 |
Python | Python | add relu function | 5e3eb12a7b78092cd6bc31892b76e5ef976ad462 | <ide><path>maths/relu.py
<add>"""
<add>This script demonstrates the implementation of the ReLU function.
<add>
<add>It's a kind of activation function defined as the positive part of its argument in the context of neural network.
<add>The function takes a vector of K real numbers as input and then argmax(x, 0).
<add>After through ReLU, the element of the vector always 0 or real number.
<add>
<add>Script inspired from its corresponding Wikipedia article
<add>https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
<add>"""
<add>
<add>import numpy as np
<add>from typing import List
<add>
<add>
<add>def relu(vector: List[float]):
<add> """
<add> Implements the relu function
<add>
<add> Parameters:
<add> vector (np.array,list,tuple): A numpy array of shape (1,n)
<add> consisting of real values or a similar list,tuple
<add>
<add>
<add> Returns:
<add> relu_vec (np.array): The input numpy array, after applying
<add> relu.
<add>
<add> >>> vec = np.array([-1, 0, 5])
<add> >>> relu(vec)
<add> array([0, 0, 5])
<add> """
<add>
<add> # compare two arrays and then return element-wise maxima.
<add> return np.maximum(0, vector)
<add>
<add>
<add>if __name__ == "__main__":
<add> print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5] | 1 |
Mixed | Javascript | remove fixturesdir from common module | f29992206807ca3c483301a88688f456cbcd3bf6 | <ide><path>test/common/README.md
<ide> Returns a new promise that will propagate `promise` resolution or rejection if
<ide> that happens within the `timeoutMs` timespan, or rejects with `error` as
<ide> a reason otherwise.
<ide>
<del>### fixturesDir
<del>* [<String>]
<del>
<del>Path to the 'fixtures' directory.
<del>
<ide> ### getArrayBufferViews(buf)
<ide> * `buf` [<Buffer>]
<ide> * return [<ArrayBufferView[]>]
<ide><path>test/common/index.js
<ide> const testRoot = process.env.NODE_TEST_DIR ?
<ide>
<ide> const noop = () => {};
<ide>
<del>exports.fixturesDir = fixturesDir;
<del>
<ide> // Using a `.` prefixed name, which is the convention for "hidden" on POSIX,
<ide> // gets tools to ignore it by default or by simple rules, especially eslint.
<ide> let tmpDirName = '.tmp';
<ide> exports.childShouldThrowAndAbort = function() {
<ide>
<ide> exports.ddCommand = function(filename, kilobytes) {
<ide> if (exports.isWindows) {
<del> const p = path.resolve(exports.fixturesDir, 'create-file.js');
<add> const p = path.resolve(fixturesDir, 'create-file.js');
<ide> return `"${process.argv[0]}" "${p}" "${filename}" ${kilobytes * 1024}`;
<ide> } else {
<ide> return `dd if=/dev/zero of="${filename}" bs=1024 count=${kilobytes}`; | 2 |
PHP | PHP | remove dependency on htmlhelper | ec87bbc779bf96fa7df88a042d3360291532192c | <ide><path>Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\View\Helper\FormHelper;
<del>use Cake\View\Helper\HtmlHelper;
<del>use Cake\View\Helper\JsHelper;
<ide> use Cake\View\Helper\PaginatorHelper;
<ide> use Cake\View\View;
<ide>
<ide> public function setUp() {
<ide> )
<ide> )
<ide> ));
<del> $this->Paginator->Html = new HtmlHelper($this->View);
<ide>
<ide> Configure::write('Routing.prefixes', array());
<ide> Router::reload();
<ide><path>Cake/View/Helper/PaginatorHelper.php
<ide> *
<ide> * PaginationHelper encloses all methods needed when working with pagination.
<ide> *
<del> * @property HtmlHelper $Html
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
<ide> */
<ide> class PaginatorHelper extends Helper {
<ide>
<del>/**
<del> * Helper dependencies
<del> *
<del> * @var array
<del> */
<del> public $helpers = ['Html'];
<del>
<ide> /**
<ide> * Holds the default options for pagination links
<ide> * | 2 |
Text | Text | add title of license to license file. fixes | d7117bc79235f23832cec04568cad8a808f82737 | <ide><path>LICENSE.md
<add>The MIT License (MIT)
<ide> Copyright (c) 2013-2016 Nick Downie
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | 1 |
PHP | PHP | get migration path from parent | ad981a10ee3b46fa08afc36e8dadb76a12df6486 | <ide><path>src/Illuminate/Database/Console/Migrations/StatusCommand.php
<ide> public function fire()
<ide> */
<ide> protected function getAllMigrationFiles()
<ide> {
<del> return $this->migrator->getMigrationFiles($this->laravel['path.database'].'/migrations');
<add> return $this->migrator->getMigrationFiles($this->getMigrationPath());
<ide> }
<ide>
<ide> } | 1 |
Javascript | Javascript | use arrow functions for callbacks | b3b5fc7c065c6aba1eca34a61dd085c2987a55f5 | <ide><path>test/parallel/test-stream-pipe-flow.js
<ide> const { Readable, Writable, PassThrough } = require('stream');
<ide> .pipe(new PassThrough({ objectMode: true, highWaterMark: 2 }))
<ide> .pipe(new PassThrough({ objectMode: true, highWaterMark: 2 }));
<ide>
<del> pt.on('end', function() {
<add> pt.on('end', () => {
<ide> wrapper.push(null);
<ide> });
<ide>
<ide> const wrapper = new Readable({
<ide> objectMode: true,
<ide> read: () => {
<del> process.nextTick(function() {
<add> process.nextTick(() => {
<ide> let data = pt.read();
<ide> if (data === null) {
<del> pt.once('readable', function() {
<add> pt.once('readable', () => {
<ide> data = pt.read();
<ide> if (data !== null) wrapper.push(data);
<ide> }); | 1 |
Javascript | Javascript | use mongodb+srv url protocol | ed08ec088a138bfde86ccba29f4c933b28b18e4a | <ide><path>api-server/server/datasources.production.js
<ide> var secrets = require('../../config/secrets');
<ide> module.exports = {
<ide> db: {
<ide> connector: 'mongodb',
<add> protocol: 'mongodb+srv',
<ide> connectionTimeout: 10000,
<ide> url: secrets.db,
<ide> useNewUrlParser: true, | 1 |
Javascript | Javascript | fix node 0.12 tests | d5bd2782f71116e65fe3ff1ed150427e87c2dc97 | <ide><path>src/test/locale/ar-ly.js
<ide> test('no leading zeros in long date formats', function (assert) {
<ide>
<ide> // locale-specific
<ide> test('ar-ly strict mode parsing works', function (assert) {
<del> const m = moment().locale('ar-ly');
<del> const formattedDate = m.format('l');
<add> var m, formattedDate;
<add> m = moment().locale('ar-ly');
<add> formattedDate = m.format('l');
<ide> assert.equal(moment.utc(formattedDate, 'l', 'ar-ly', false).isValid(), true, 'Non-strict parsing works');
<ide> assert.equal(moment.utc(formattedDate, 'l', 'ar-ly', true).isValid(), true,'Strict parsing must work');
<ide> });
<ide><path>src/test/locale/ar.js
<ide> test('no leading zeros in long date formats', function (assert) {
<ide>
<ide> // locale-specific
<ide> test('ar strict mode parsing works', function (assert) {
<del> const m = moment().locale('ar');
<del> const formattedDate = m.format('l');
<add> var m, formattedDate;
<add> m = moment().locale('ar');
<add> formattedDate = m.format('l');
<ide> assert.equal(moment.utc(formattedDate, 'l', 'ar', false).isValid(), true, 'Non-strict parsing works');
<ide> assert.equal(moment.utc(formattedDate, 'l', 'ar', true).isValid(), true,'Strict parsing must work');
<ide> }); | 2 |
Text | Text | fix typo in repl.md | e5410322769482029aa07a41a1c06cc7586bad1b | <ide><path>doc/api/repl.md
<ide> triggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward and
<ide> <kbd>Ctrl</kbd>+<kbd>S</kbd> to search
<ide> forwards.
<ide>
<del>Duplicated history entires will be skipped.
<add>Duplicated history entries will be skipped.
<ide>
<ide> Entries are accepted as soon as any key is pressed that doesn't correspond
<ide> with the reverse search. Cancelling is possible by pressing <kbd>Esc</kbd> or | 1 |
Javascript | Javascript | use relative imports | aa76fcff3346304f4612868c15490d5872f43e43 | <ide><path>packages/ember-glimmer/lib/index.js
<del>export { default as Environment } from 'ember-glimmer/environment';
<add>export { default as Environment } from './environment';
<ide> export { default as template } from './template';
<ide><path>packages/ember-glimmer/lib/setup-registry.js
<ide> import { privatize as P } from 'container/registry';
<del>import { InteractiveRenderer, InertRenderer } from 'ember-glimmer/renderer';
<del>import { DOMChanges, DOMTreeConstruction } from 'ember-glimmer/dom';
<del>import OutletView from 'ember-glimmer/views/outlet';
<del>import TextField from 'ember-glimmer/components/text_field';
<del>import TextArea from 'ember-glimmer/components/text_area';
<del>import Checkbox from 'ember-glimmer/components/checkbox';
<del>import LinkToComponent from 'ember-glimmer/components/link-to';
<del>import ComponentTemplate from 'ember-glimmer/templates/component';
<del>import RootTemplate from 'ember-glimmer/templates/root';
<del>import OutletTemplate from 'ember-glimmer/templates/outlet';
<del>import Environment from 'ember-glimmer/environment';
<add>import { InteractiveRenderer, InertRenderer } from './renderer';
<add>import { DOMChanges, DOMTreeConstruction } from './dom';
<add>import OutletView from './views/outlet';
<add>import TextField from './components/text_field';
<add>import TextArea from './components/text_area';
<add>import Checkbox from './components/checkbox';
<add>import LinkToComponent from './components/link-to';
<add>import ComponentTemplate from './templates/component';
<add>import RootTemplate from './templates/root';
<add>import OutletTemplate from './templates/outlet';
<add>import Environment from './environment';
<ide>
<ide> export function setupApplicationRegistry(registry) {
<ide> registry.injection('service:-glimmer-environment', 'appendOperations', 'service:-dom-tree-construction');
<ide><path>packages/ember-metal/lib/alias.js
<del>import { assert } from 'ember-metal/debug';
<del>import { get } from 'ember-metal/property_get';
<del>import { set } from 'ember-metal/property_set';
<del>import EmberError from 'ember-metal/error';
<add>import { assert } from './debug';
<add>import { get } from './property_get';
<add>import { set } from './property_set';
<add>import EmberError from './error';
<ide> import {
<ide> Descriptor,
<ide> defineProperty
<del>} from 'ember-metal/properties';
<del>import { ComputedProperty } from 'ember-metal/computed';
<del>import { inspect } from 'ember-metal/utils';
<del>import { meta } from 'ember-metal/meta';
<add>} from './properties';
<add>import { ComputedProperty } from './computed';
<add>import { inspect } from './utils';
<add>import { meta } from './meta';
<ide> import {
<ide> addDependentKeys,
<ide> removeDependentKeys
<del>} from 'ember-metal/dependent_keys';
<add>} from './dependent_keys';
<ide>
<ide> export default function alias(altKey) {
<ide> return new AliasedProperty(altKey);
<ide><path>packages/ember-metal/lib/binding.js
<ide> import Logger from 'ember-console';
<ide> import { context, ENV } from 'ember-environment';
<del>import run from 'ember-metal/run_loop';
<del>import { assert, deprecate } from 'ember-metal/debug';
<del>import { get } from 'ember-metal/property_get';
<del>import { trySet } from 'ember-metal/property_set';
<del>import { guidFor } from 'ember-metal/utils';
<del>import { addListener } from 'ember-metal/events';
<add>import run from './run_loop';
<add>import { assert, deprecate } from './debug';
<add>import { get } from './property_get';
<add>import { trySet } from './property_set';
<add>import { guidFor } from './utils';
<add>import { addListener } from './events';
<ide> import {
<ide> addObserver,
<ide> removeObserver,
<ide> _suspendObserver
<del>} from 'ember-metal/observer';
<add>} from './observer';
<ide> import {
<ide> isGlobalPath,
<ide> getFirstKey,
<ide> getTailPath
<del>} from 'ember-metal/path_cache';
<add>} from './path_cache';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-metal/lib/cache.js
<del>import EmptyObject from 'ember-metal/empty_object';
<add>import EmptyObject from './empty_object';
<ide>
<ide> export default class Cache {
<ide> constructor(limit, func, key, store) {
<ide><path>packages/ember-metal/lib/chains.js
<del>import { get } from 'ember-metal/property_get';
<del>import { meta as metaFor, peekMeta } from 'ember-metal/meta';
<del>import { watchKey, unwatchKey } from 'ember-metal/watch_key';
<del>import EmptyObject from 'ember-metal/empty_object';
<add>import { get } from './property_get';
<add>import { meta as metaFor, peekMeta } from './meta';
<add>import { watchKey, unwatchKey } from './watch_key';
<add>import EmptyObject from './empty_object';
<ide>
<ide> const FIRST_KEY = /^([^\.]+)/;
<ide>
<ide><path>packages/ember-metal/lib/computed.js
<del>import { assert, warn } from 'ember-metal/debug';
<del>import { set } from 'ember-metal/property_set';
<del>import { inspect } from 'ember-metal/utils';
<del>import { meta as metaFor, peekMeta } from 'ember-metal/meta';
<del>import expandProperties from 'ember-metal/expand_properties';
<del>import EmberError from 'ember-metal/error';
<add>import { assert, warn } from './debug';
<add>import { set } from './property_set';
<add>import { inspect } from './utils';
<add>import { meta as metaFor, peekMeta } from './meta';
<add>import expandProperties from './expand_properties';
<add>import EmberError from './error';
<ide> import {
<ide> Descriptor,
<ide> defineProperty
<del>} from 'ember-metal/properties';
<add>} from './properties';
<ide> import {
<ide> propertyWillChange,
<ide> propertyDidChange
<del>} from 'ember-metal/property_events';
<add>} from './property_events';
<ide> import {
<ide> addDependentKeys,
<ide> removeDependentKeys
<del>} from 'ember-metal/dependent_keys';
<add>} from './dependent_keys';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-metal/lib/dependent_keys.js
<ide> import {
<ide> watch,
<ide> unwatch
<del>} from 'ember-metal/watching';
<add>} from './watching';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-metal/lib/deprecate_property.js
<ide> @submodule ember-metal
<ide> */
<ide>
<del>import { deprecate } from 'ember-metal/debug';
<del>import { get } from 'ember-metal/property_get';
<del>import { set } from 'ember-metal/property_set';
<add>import { deprecate } from './debug';
<add>import { get } from './property_get';
<add>import { set } from './property_set';
<ide>
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/events.js
<ide> @module ember
<ide> @submodule ember-metal
<ide> */
<del>import { assert } from 'ember-metal/debug';
<del>import { applyStr } from 'ember-metal/utils';
<del>import { meta as metaFor, peekMeta } from 'ember-metal/meta';
<del>import { deprecate } from 'ember-metal/debug';
<add>import { assert } from './debug';
<add>import { applyStr } from './utils';
<add>import { meta as metaFor, peekMeta } from './meta';
<add>import { deprecate } from './debug';
<ide>
<del>import { ONCE, SUSPENDED } from 'ember-metal/meta_listeners';
<add>import { ONCE, SUSPENDED } from './meta_listeners';
<ide>
<ide>
<ide> /*
<ide><path>packages/ember-metal/lib/expand_properties.js
<del>import { assert } from 'ember-metal/debug';
<add>import { assert } from './debug';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-metal/lib/features.js
<ide> import { ENV } from 'ember-environment';
<del>import assign from 'ember-metal/assign';
<add>import assign from './assign';
<ide> import DEFAULT_FEATURES from 'ember/features';
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/get_properties.js
<del>import { get } from 'ember-metal/property_get';
<add>import { get } from './property_get';
<ide>
<ide> /**
<ide> To get multiple properties at once, call `Ember.getProperties`
<ide><path>packages/ember-metal/lib/index.js
<ide> import require, { has } from 'require';
<ide> import { ENV, context } from 'ember-environment';
<ide> import VERSION from 'ember/version';
<del>import Ember from 'ember-metal/core'; // reexports
<del>import { deprecate, deprecateFunc } from 'ember-metal/debug';
<del>import isEnabled, { FEATURES } from 'ember-metal/features';
<del>import assign from 'ember-metal/assign';
<del>import merge from 'ember-metal/merge';
<add>import Ember from './core'; // reexports
<add>import { deprecate, deprecateFunc } from './debug';
<add>import isEnabled, { FEATURES } from './features';
<add>import assign from './assign';
<add>import merge from './merge';
<ide> import {
<ide> instrument,
<ide> reset as instrumentationReset,
<ide> subscribe as instrumentationSubscribe,
<ide> unsubscribe as instrumentationUnsubscribe
<del>} from 'ember-metal/instrumentation';
<add>} from './instrumentation';
<ide> import {
<ide> GUID_KEY,
<ide> apply,
<ide> import {
<ide> tryInvoke,
<ide> uuid,
<ide> wrap
<del>} from 'ember-metal/utils';
<add>} from './utils';
<ide> import {
<ide> META_DESC,
<ide> meta
<del>} from 'ember-metal/meta';
<del>import EmberError from 'ember-metal/error';
<del>import Cache from 'ember-metal/cache';
<add>} from './meta';
<add>import EmberError from './error';
<add>import Cache from './cache';
<ide> import Logger from 'ember-console';
<ide>
<ide> import {
<ide> _getPath,
<ide> get,
<ide> getWithDefault
<del>} from 'ember-metal/property_get';
<add>} from './property_get';
<ide>
<ide> import {
<ide> accumulateListeners,
<ide> import {
<ide> suspendListener,
<ide> suspendListeners,
<ide> watchedEvents
<del>} from 'ember-metal/events';
<add>} from './events';
<ide>
<del>import ObserverSet from 'ember-metal/observer_set';
<add>import ObserverSet from './observer_set';
<ide>
<ide> import {
<ide> beginPropertyChanges,
<ide> import {
<ide> overrideChains,
<ide> propertyDidChange,
<ide> propertyWillChange
<del>} from 'ember-metal/property_events';
<add>} from './property_events';
<ide>
<ide> import {
<ide> defineProperty
<del>} from 'ember-metal/properties';
<add>} from './properties';
<ide> import {
<ide> set,
<ide> trySet
<del>} from 'ember-metal/property_set';
<add>} from './property_set';
<ide>
<del>import WeakMap from 'ember-metal/weak_map';
<add>import WeakMap from './weak_map';
<ide> import {
<ide> Map,
<ide> MapWithDefault,
<ide> OrderedSet
<del>} from 'ember-metal/map';
<add>} from './map';
<ide>
<del>import getProperties from 'ember-metal/get_properties';
<del>import setProperties from 'ember-metal/set_properties';
<add>import getProperties from './get_properties';
<add>import setProperties from './set_properties';
<ide> import {
<ide> watchKey,
<ide> unwatchKey
<del>} from 'ember-metal/watch_key';
<add>} from './watch_key';
<ide> import {
<ide> ChainNode,
<ide> finishChains,
<ide> removeChainWatcher
<del>} from 'ember-metal/chains';
<add>} from './chains';
<ide> import {
<ide> watchPath,
<ide> unwatchPath
<del>} from 'ember-metal/watch_path';
<add>} from './watch_path';
<ide> import {
<ide> destroy,
<ide> isWatching,
<ide> rewatch,
<ide> unwatch,
<ide> watch
<del>} from 'ember-metal/watching';
<del>import expandProperties from 'ember-metal/expand_properties';
<add>} from './watching';
<add>import expandProperties from './expand_properties';
<ide> import {
<ide> ComputedProperty,
<ide> computed,
<ide> cacheFor
<del>} from 'ember-metal/computed';
<add>} from './computed';
<ide>
<del>import alias from 'ember-metal/alias';
<add>import alias from './alias';
<ide>
<ide> computed.alias = alias;
<ide>
<ide> import {
<ide> addObserver,
<ide> observersFor,
<ide> removeObserver
<del>} from 'ember-metal/observer';
<add>} from './observer';
<ide> import {
<ide> NAME_KEY,
<ide> Mixin,
<ide> import {
<ide> mixin,
<ide> observer,
<ide> required
<del>} from 'ember-metal/mixin';
<add>} from './mixin';
<ide> import {
<ide> Binding,
<ide> bind
<del>} from 'ember-metal/binding';
<add>} from './binding';
<ide> import {
<ide> isGlobalPath
<del>} from 'ember-metal/path_cache';
<add>} from './path_cache';
<ide>
<ide> import {
<ide> isTesting,
<ide> setTesting
<del>} from 'ember-metal/testing';
<add>} from './testing';
<ide> import {
<ide> getOnerror,
<ide> setOnerror
<del>} from 'ember-metal/error_handler';
<del>
<del>import run from 'ember-metal/run_loop';
<del>import libraries from 'ember-metal/libraries';
<del>import isNone from 'ember-metal/is_none';
<del>import isEmpty from 'ember-metal/is_empty';
<del>import isBlank from 'ember-metal/is_blank';
<del>import isPresent from 'ember-metal/is_present';
<add>} from './error_handler';
<add>
<add>import run from './run_loop';
<add>import libraries from './libraries';
<add>import isNone from './is_none';
<add>import isEmpty from './is_empty';
<add>import isBlank from './is_blank';
<add>import isPresent from './is_present';
<ide> import Backburner from 'backburner';
<ide>
<ide> // END IMPORTS
<ide><path>packages/ember-metal/lib/injected_property.js
<del>import { assert } from 'ember-metal/debug';
<del>import { ComputedProperty } from 'ember-metal/computed';
<del>import { AliasedProperty } from 'ember-metal/alias';
<del>import { Descriptor } from 'ember-metal/properties';
<add>import { assert } from './debug';
<add>import { ComputedProperty } from './computed';
<add>import { AliasedProperty } from './alias';
<add>import { Descriptor } from './properties';
<ide> import { getOwner } from 'container/owner';
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/instrumentation.js
<ide> import { ENV } from 'ember-environment';
<del>import isEnabled from 'ember-metal/features';
<add>import isEnabled from './features';
<ide>
<ide> /**
<ide> The purpose of the Ember Instrumentation module is
<ide><path>packages/ember-metal/lib/is_blank.js
<del>import isEmpty from 'ember-metal/is_empty';
<add>import isEmpty from './is_empty';
<ide>
<ide> /**
<ide> A value is blank if it is empty or a whitespace string.
<ide><path>packages/ember-metal/lib/is_empty.js
<del>import { get } from 'ember-metal/property_get';
<del>import isNone from 'ember-metal/is_none';
<add>import { get } from './property_get';
<add>import isNone from './is_none';
<ide>
<ide> /**
<ide> Verifies that a value is `null` or an empty string, empty array,
<ide><path>packages/ember-metal/lib/is_present.js
<del>import isBlank from 'ember-metal/is_blank';
<add>import isBlank from './is_blank';
<ide>
<ide> /**
<ide> A value is present if it not `isBlank`.
<ide><path>packages/ember-metal/lib/libraries.js
<del>import { warn } from 'ember-metal/debug';
<del>import isEnabled from 'ember-metal/features';
<add>import { warn } from './debug';
<add>import isEnabled from './features';
<ide>
<ide> /**
<ide> Helper class that allows you to register your library with Ember.
<ide><path>packages/ember-metal/lib/map.js
<ide> Map is mocked out to look like an Ember object, so you can do
<ide> `Ember.Map.create()` for symmetry with other Ember classes.
<ide> */
<del>import { guidFor } from 'ember-metal/utils';
<del>import EmptyObject from 'ember-metal/empty_object';
<add>import { guidFor } from './utils';
<add>import EmptyObject from './empty_object';
<ide>
<ide> function missingFunction(fn) {
<ide> throw new TypeError(`${Object.prototype.toString.call(fn)} is not a function`);
<ide><path>packages/ember-metal/lib/meta.js
<ide> // Remove "use strict"; from transpiled module until
<ide> // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed
<ide>
<del>import isEnabled from 'ember-metal/features';
<del>import { protoMethods as listenerMethods } from 'ember-metal/meta_listeners';
<del>import EmptyObject from 'ember-metal/empty_object';
<del>import { lookupDescriptor } from 'ember-metal/utils';
<del>import symbol from 'ember-metal/symbol';
<add>import isEnabled from './features';
<add>import { protoMethods as listenerMethods } from './meta_listeners';
<add>import EmptyObject from './empty_object';
<add>import { lookupDescriptor } from './utils';
<add>import symbol from './symbol';
<ide>
<ide> /**
<ide> @module ember-metal
<ide><path>packages/ember-metal/lib/mixin.js
<ide> @module ember
<ide> @submodule ember-metal
<ide> */
<del>import EmberError from 'ember-metal/error';
<del>import { debugSeal, assert, deprecate, runInDebug } from 'ember-metal/debug';
<del>import assign from 'ember-metal/assign';
<add>import EmberError from './error';
<add>import { debugSeal, assert, deprecate, runInDebug } from './debug';
<add>import assign from './assign';
<ide> import {
<ide> guidFor,
<ide> GUID_KEY,
<ide> wrap,
<ide> makeArray
<del>} from 'ember-metal/utils';
<del>import { meta as metaFor, peekMeta } from 'ember-metal/meta';
<del>import expandProperties from 'ember-metal/expand_properties';
<add>} from './utils';
<add>import { meta as metaFor, peekMeta } from './meta';
<add>import expandProperties from './expand_properties';
<ide> import {
<ide> Descriptor,
<ide> defineProperty
<del>} from 'ember-metal/properties';
<del>import { ComputedProperty } from 'ember-metal/computed';
<del>import { Binding } from 'ember-metal/binding';
<add>} from './properties';
<add>import { ComputedProperty } from './computed';
<add>import { Binding } from './binding';
<ide> import {
<ide> addObserver,
<ide> removeObserver,
<ide> _addBeforeObserver,
<ide> _removeBeforeObserver
<del>} from 'ember-metal/observer';
<add>} from './observer';
<ide> import {
<ide> addListener,
<ide> removeListener
<del>} from 'ember-metal/events';
<add>} from './events';
<ide>
<ide> function ROOT() {}
<ide> ROOT.__hasSuper = false;
<ide><path>packages/ember-metal/lib/observer.js
<ide> import {
<ide> watch,
<ide> unwatch
<del>} from 'ember-metal/watching';
<add>} from './watching';
<ide> import {
<ide> listenersFor,
<ide> addListener,
<ide> removeListener,
<ide> suspendListeners,
<ide> suspendListener
<del>} from 'ember-metal/events';
<add>} from './events';
<ide> /**
<ide> @module ember-metal
<ide> */
<ide><path>packages/ember-metal/lib/observer_set.js
<del>import { guidFor } from 'ember-metal/utils';
<del>import { sendEvent } from 'ember-metal/events';
<add>import { guidFor } from './utils';
<add>import { sendEvent } from './events';
<ide>
<ide> /*
<ide> this.observerSet = {
<ide><path>packages/ember-metal/lib/path_cache.js
<del>import Cache from 'ember-metal/cache';
<add>import Cache from './cache';
<ide>
<ide> const IS_GLOBAL = /^[A-Z$]/;
<ide> const IS_GLOBAL_PATH = /^[A-Z$].*[\.]/;
<ide><path>packages/ember-metal/lib/properties.js
<ide> @module ember-metal
<ide> */
<ide>
<del>import { assert } from 'ember-metal/debug';
<del>import isEnabled from 'ember-metal/features';
<del>import { meta as metaFor, peekMeta } from 'ember-metal/meta';
<del>import { overrideChains } from 'ember-metal/property_events';
<add>import { assert } from './debug';
<add>import isEnabled from './features';
<add>import { meta as metaFor, peekMeta } from './meta';
<add>import { overrideChains } from './property_events';
<ide> // ..........................................................
<ide> // DESCRIPTOR
<ide> //
<ide><path>packages/ember-metal/lib/property_events.js
<ide> import {
<ide> guidFor
<del>} from 'ember-metal/utils';
<add>} from './utils';
<ide> import {
<ide> peekMeta
<del>} from 'ember-metal/meta';
<add>} from './meta';
<ide> import {
<ide> sendEvent,
<ide> accumulateListeners
<del>} from 'ember-metal/events';
<add>} from './events';
<ide> import {
<ide> markObjectAsDirty
<ide> } from './tags';
<del>import ObserverSet from 'ember-metal/observer_set';
<del>import symbol from 'ember-metal/symbol';
<del>import isEnabled from 'ember-metal/features';
<del>import { assertNotRendered } from 'ember-metal/transaction';
<add>import ObserverSet from './observer_set';
<add>import symbol from './symbol';
<add>import isEnabled from './features';
<add>import { assertNotRendered } from './transaction';
<ide>
<ide> export let PROPERTY_DID_CHANGE = symbol('PROPERTY_DID_CHANGE');
<ide>
<ide><path>packages/ember-metal/lib/property_get.js
<ide> @module ember-metal
<ide> */
<ide>
<del>import { assert } from 'ember-metal/debug';
<del>import { isPath, hasThis } from 'ember-metal/path_cache';
<add>import { assert } from './debug';
<add>import { isPath, hasThis } from './path_cache';
<ide>
<ide> const ALLOWABLE_TYPES = {
<ide> object: true,
<ide><path>packages/ember-metal/lib/property_set.js
<del>import { assert } from 'ember-metal/debug';
<del>import isEnabled from 'ember-metal/features';
<del>import { _getPath as getPath } from 'ember-metal/property_get';
<add>import { assert } from './debug';
<add>import isEnabled from './features';
<add>import { _getPath as getPath } from './property_get';
<ide> import {
<ide> propertyWillChange,
<ide> propertyDidChange
<del>} from 'ember-metal/property_events';
<add>} from './property_events';
<ide>
<del>import EmberError from 'ember-metal/error';
<add>import EmberError from './error';
<ide> import {
<ide> isPath,
<ide> hasThis as pathHasThis
<del>} from 'ember-metal/path_cache';
<add>} from './path_cache';
<ide> import {
<ide> peekMeta
<del>} from 'ember-metal/meta';
<add>} from './meta';
<ide>
<ide> import {
<ide> toString
<del>} from 'ember-metal/utils';
<add>} from './utils';
<ide>
<ide> /**
<ide> Sets the value of a property on an object, respecting computed properties
<ide><path>packages/ember-metal/lib/run_loop.js
<del>import { assert } from 'ember-metal/debug';
<del>import { isTesting } from 'ember-metal/testing';
<add>import { assert } from './debug';
<add>import { isTesting } from './testing';
<ide> import {
<ide> getOnerror,
<ide> setOnerror
<del>} from 'ember-metal/error_handler';
<add>} from './error_handler';
<ide> import {
<ide> GUID_KEY
<del>} from 'ember-metal/utils';
<add>} from './utils';
<ide> import {
<ide> beginPropertyChanges,
<ide> endPropertyChanges
<del>} from 'ember-metal/property_events';
<add>} from './property_events';
<ide> import Backburner from 'backburner';
<ide>
<ide> function onBegin(current) {
<ide><path>packages/ember-metal/lib/set_properties.js
<del>import { changeProperties } from 'ember-metal/property_events';
<del>import { set } from 'ember-metal/property_set';
<add>import { changeProperties } from './property_events';
<add>import { set } from './property_set';
<ide>
<ide> /**
<ide> Set a list of properties on an object. These properties are set inside
<ide><path>packages/ember-metal/lib/symbol.js
<del>import { GUID_KEY, intern } from 'ember-metal/utils';
<add>import { GUID_KEY, intern } from './utils';
<ide>
<ide> export default function symbol(debugName) {
<ide> // TODO: Investigate using platform symbols, but we do not
<ide><path>packages/ember-metal/lib/transaction.js
<ide> import { meta as metaFor } from './meta';
<del>import { assert, runInDebug, deprecate } from 'ember-metal/debug';
<del>import isEnabled from 'ember-metal/features';
<add>import { assert, runInDebug, deprecate } from './debug';
<add>import isEnabled from './features';
<ide>
<ide> let runInTransaction, didRender, assertNotRendered;
<ide>
<ide><path>packages/ember-metal/lib/watch_key.js
<del>import isEnabled from 'ember-metal/features';
<add>import isEnabled from './features';
<ide> import {
<ide> meta as metaFor
<del>} from 'ember-metal/meta';
<add>} from './meta';
<ide> import {
<ide> MANDATORY_SETTER_FUNCTION,
<ide> DEFAULT_GETTER_FUNCTION,
<ide> INHERITING_GETTER_FUNCTION
<del>} from 'ember-metal/properties';
<del>import { lookupDescriptor } from 'ember-metal/utils';
<add>} from './properties';
<add>import { lookupDescriptor } from './utils';
<ide>
<ide> let handleMandatorySetter;
<ide>
<ide><path>packages/ember-metal/lib/watch_path.js
<ide> import {
<ide> meta as metaFor
<del>} from 'ember-metal/meta';
<del>import { ChainNode } from 'ember-metal/chains';
<add>} from './meta';
<add>import { ChainNode } from './chains';
<ide>
<ide> // get the chains for the current object. If the current object has
<ide> // chains inherited from the proto they will be cloned and reconfigured for
<ide><path>packages/ember-metal/lib/watching.js
<ide>
<ide> import {
<ide> removeChainWatcher
<del>} from 'ember-metal/chains';
<add>} from './chains';
<ide> import {
<ide> watchKey,
<ide> unwatchKey
<del>} from 'ember-metal/watch_key';
<add>} from './watch_key';
<ide> import {
<ide> watchPath,
<ide> unwatchPath
<del>} from 'ember-metal/watch_path';
<add>} from './watch_path';
<ide> import {
<ide> isPath
<del>} from 'ember-metal/path_cache';
<add>} from './path_cache';
<ide> import {
<ide> peekMeta,
<ide> deleteMeta
<del>} from 'ember-metal/meta';
<add>} from './meta';
<ide>
<ide> /**
<ide> Starts watching a property on an object. Whenever the property changes,
<ide><path>packages/ember-metal/lib/weak_map.js
<del>import { GUID_KEY } from 'ember-metal/utils';
<add>import { GUID_KEY } from './utils';
<ide> import {
<ide> peekMeta,
<ide> meta as metaFor
<del>} from 'ember-metal/meta';
<add>} from './meta';
<ide>
<ide> let id = 0;
<ide> function UNDEFINED() {}
<ide><path>packages/ember-runtime/lib/compare.js
<del>import { typeOf } from 'ember-runtime/utils';
<del>import Comparable from 'ember-runtime/mixins/comparable';
<add>import { typeOf } from './utils';
<add>import Comparable from './mixins/comparable';
<ide>
<ide> const TYPE_ORDER = {
<ide> 'undefined': 0,
<ide><path>packages/ember-runtime/lib/computed/reduce_computed_macros.js
<ide> import { get } from 'ember-metal/property_get';
<ide> import EmberError from 'ember-metal/error';
<ide> import { ComputedProperty, computed } from 'ember-metal/computed';
<ide> import { addObserver, removeObserver } from 'ember-metal/observer';
<del>import compare from 'ember-runtime/compare';
<del>import { isArray } from 'ember-runtime/utils';
<del>import { A as emberA } from 'ember-runtime/system/native_array';
<add>import compare from '../compare';
<add>import { isArray } from '../utils';
<add>import { A as emberA } from '../system/native_array';
<ide> import isNone from 'ember-metal/is_none';
<ide> import getProperties from 'ember-metal/get_properties';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide><path>packages/ember-runtime/lib/controllers/controller.js
<ide> import { assert } from 'ember-metal/debug';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import Mixin from 'ember-runtime/mixins/controller';
<del>import { createInjectionHelper } from 'ember-runtime/inject';
<del>import { deprecateUnderscoreActions } from 'ember-runtime/mixins/action_handler';
<add>import EmberObject from '../system/object';
<add>import Mixin from '../mixins/controller';
<add>import { createInjectionHelper } from '../inject';
<add>import { deprecateUnderscoreActions } from '../mixins/action_handler';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-runtime/lib/copy.js
<ide> import { assert } from 'ember-metal/debug';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import Copyable from 'ember-runtime/mixins/copyable';
<add>import EmberObject from './system/object';
<add>import Copyable from './mixins/copyable';
<ide>
<ide> function _copy(obj, deep, seen, copies) {
<ide> let ret, loc, key;
<ide><path>packages/ember-runtime/lib/ext/string.js
<ide> import {
<ide> underscore,
<ide> capitalize,
<ide> classify
<del>} from 'ember-runtime/system/string';
<add>} from '../system/string';
<ide>
<ide> const StringPrototype = String.prototype;
<ide>
<ide><path>packages/ember-runtime/lib/index.js
<ide>
<ide> // BEGIN IMPORTS
<ide> import Ember from 'ember-metal'; // reexports
<del>import isEqual from 'ember-runtime/is-equal';
<del>import compare from 'ember-runtime/compare';
<del>import copy from 'ember-runtime/copy';
<del>import inject from 'ember-runtime/inject';
<add>import isEqual from './is-equal';
<add>import compare from './compare';
<add>import copy from './copy';
<add>import inject from './inject';
<ide>
<ide> import Namespace, {
<ide> isSearchDisabled as isNamespaceSearchDisabled,
<ide> setSearchDisabled as setNamespaceSearchDisabled
<del>} from 'ember-runtime/system/namespace';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import { Container, Registry, getOwner, setOwner } from 'ember-runtime/system/container';
<del>import ArrayProxy from 'ember-runtime/system/array_proxy';
<del>import ObjectProxy from 'ember-runtime/system/object_proxy';
<del>import CoreObject from 'ember-runtime/system/core_object';
<del>
<del>import NativeArray from 'ember-runtime/system/native_array';
<del>import EmberStringUtils from 'ember-runtime/system/string';
<add>} from './system/namespace';
<add>import EmberObject from './system/object';
<add>import { Container, Registry, getOwner, setOwner } from './system/container';
<add>import ArrayProxy from './system/array_proxy';
<add>import ObjectProxy from './system/object_proxy';
<add>import CoreObject from './system/core_object';
<add>
<add>import NativeArray from './system/native_array';
<add>import EmberStringUtils from './system/string';
<ide> import {
<ide> onLoad,
<ide> runLoadHooks
<del>} from 'ember-runtime/system/lazy_load';
<add>} from './system/lazy_load';
<ide>
<del>import EmberArray from 'ember-runtime/mixins/array';
<del>import Comparable from 'ember-runtime/mixins/comparable';
<del>import Copyable from 'ember-runtime/mixins/copyable';
<del>import Enumerable from 'ember-runtime/mixins/enumerable';
<add>import EmberArray from './mixins/array';
<add>import Comparable from './mixins/comparable';
<add>import Copyable from './mixins/copyable';
<add>import Enumerable from './mixins/enumerable';
<ide> import {
<ide> Freezable,
<ide> FROZEN_ERROR
<del>} from 'ember-runtime/mixins/freezable';
<del>import _ProxyMixin from 'ember-runtime/mixins/-proxy';
<add>} from './mixins/freezable';
<add>import _ProxyMixin from './mixins/-proxy';
<ide>
<del>import Observable from 'ember-runtime/mixins/observable';
<del>import ActionHandler from 'ember-runtime/mixins/action_handler';
<del>import MutableEnumerable from 'ember-runtime/mixins/mutable_enumerable';
<del>import MutableArray from 'ember-runtime/mixins/mutable_array';
<del>import TargetActionSupport from 'ember-runtime/mixins/target_action_support';
<del>import Evented from 'ember-runtime/mixins/evented';
<del>import PromiseProxyMixin from 'ember-runtime/mixins/promise_proxy';
<add>import Observable from './mixins/observable';
<add>import ActionHandler from './mixins/action_handler';
<add>import MutableEnumerable from './mixins/mutable_enumerable';
<add>import MutableArray from './mixins/mutable_array';
<add>import TargetActionSupport from './mixins/target_action_support';
<add>import Evented from './mixins/evented';
<add>import PromiseProxyMixin from './mixins/promise_proxy';
<ide>
<ide> import isEnabled from 'ember-metal/features';
<ide>
<ide> import {
<ide> and,
<ide> or,
<ide> any
<del>} from 'ember-runtime/computed/computed_macros';
<add>} from './computed/computed_macros';
<ide>
<ide> import {
<ide> sum,
<ide> import {
<ide> union,
<ide> intersect,
<ide> collect
<del>} from 'ember-runtime/computed/reduce_computed_macros';
<add>} from './computed/reduce_computed_macros';
<ide>
<del>import Controller from 'ember-runtime/controllers/controller';
<del>import ControllerMixin from 'ember-runtime/mixins/controller';
<add>import Controller from './controllers/controller';
<add>import ControllerMixin from './mixins/controller';
<ide>
<del>import Service from 'ember-runtime/system/service';
<add>import Service from './system/service';
<ide>
<del>import RSVP from 'ember-runtime/ext/rsvp'; // just for side effect of extending Ember.RSVP
<del>import 'ember-runtime/ext/string'; // just for side effect of extending String.prototype
<del>import 'ember-runtime/ext/function'; // just for side effect of extending Function.prototype
<add>import RSVP from './ext/rsvp'; // just for side effect of extending Ember.RSVP
<add>import './ext/string'; // just for side effect of extending String.prototype
<add>import './ext/function'; // just for side effect of extending Function.prototype
<ide>
<del>import { isArray, typeOf } from 'ember-runtime/utils';
<add>import { isArray, typeOf } from './utils';
<ide>
<del>import RegistryProxyMixin from 'ember-runtime/mixins/registry_proxy';
<del>import ContainerProxyMixin from 'ember-runtime/mixins/container_proxy';
<add>import RegistryProxyMixin from './mixins/registry_proxy';
<add>import ContainerProxyMixin from './mixins/container_proxy';
<ide>
<ide> import {
<ide> getStrings,
<ide> setStrings
<del>} from 'ember-runtime/string_registry';
<add>} from './string_registry';
<ide>
<ide> // END IMPORTS
<ide>
<ide><path>packages/ember-runtime/lib/mixins/-proxy.js
<ide> import {
<ide> propertyWillChange,
<ide> propertyDidChange
<ide> } from 'ember-metal/property_events';
<del>import { bool } from 'ember-runtime/computed/computed_macros';
<del>import { POST_INIT } from 'ember-runtime/system/core_object';
<add>import { bool } from '../computed/computed_macros';
<add>import { POST_INIT } from '../system/core_object';
<ide> import { defineProperty } from 'ember-metal/properties';
<ide> import { Mixin, observer } from 'ember-metal/mixin';
<ide> import { tagFor } from 'ember-metal/tags';
<ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> import {
<ide> cacheFor
<ide> } from 'ember-metal/computed';
<ide> import isNone from 'ember-metal/is_none';
<del>import Enumerable from 'ember-runtime/mixins/enumerable';
<add>import Enumerable from './enumerable';
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import {
<ide> propertyWillChange,
<ide> import {
<ide> } from 'ember-metal/events';
<ide> import { meta as metaFor } from 'ember-metal/meta';
<ide> import { markObjectAsDirty } from 'ember-metal/tags';
<del>import EachProxy from 'ember-runtime/system/each_proxy';
<add>import EachProxy from '../system/each_proxy';
<ide> import { deprecate } from 'ember-metal/debug';
<ide> import isEnabled from 'ember-metal/features';
<ide>
<ide><path>packages/ember-runtime/lib/mixins/controller.js
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import alias from 'ember-metal/alias';
<del>import ActionHandler from 'ember-runtime/mixins/action_handler';
<del>import ControllerContentModelAliasDeprecation from 'ember-runtime/mixins/controller_content_model_alias_deprecation';
<add>import ActionHandler from './action_handler';
<add>import ControllerContentModelAliasDeprecation from './controller_content_model_alias_deprecation';
<ide>
<ide> /**
<ide> @class ControllerMixin
<ide><path>packages/ember-runtime/lib/mixins/copyable.js
<ide> import { deprecate } from 'ember-metal/debug';
<ide> import { get } from 'ember-metal/property_get';
<ide> import { Mixin } from 'ember-metal/mixin';
<del>import { Freezable } from 'ember-runtime/mixins/freezable';
<add>import { Freezable } from './freezable';
<ide> import EmberError from 'ember-metal/error';
<ide>
<ide> /**
<ide><path>packages/ember-runtime/lib/mixins/enumerable.js
<ide> import {
<ide> sendEvent,
<ide> hasListeners
<ide> } from 'ember-metal/events';
<del>import compare from 'ember-runtime/compare';
<add>import compare from '../compare';
<ide> import require from 'require';
<ide> import { assert, deprecate } from 'ember-metal/debug';
<ide>
<ide><path>packages/ember-runtime/lib/mixins/mutable_array.js
<ide> */
<ide>
<ide>
<del>// require('ember-runtime/mixins/array');
<del>// require('ember-runtime/mixins/mutable_enumerable');
<del>
<del>// ..........................................................
<del>// CONSTANTS
<del>//
<del>
<ide> const OUT_OF_RANGE_EXCEPTION = 'Index out of range';
<ide> const EMPTY = [];
<ide>
<ide> const EMPTY = [];
<ide> import { get } from 'ember-metal/property_get';
<ide> import EmberError from 'ember-metal/error';
<ide> import { Mixin } from 'ember-metal/mixin';
<del>import EmberArray, { objectAt } from 'ember-runtime/mixins/array';
<del>import MutableEnumerable from 'ember-runtime/mixins/mutable_enumerable';
<del>import Enumerable from 'ember-runtime/mixins/enumerable';
<add>import EmberArray, { objectAt } from './array';
<add>import MutableEnumerable from './mutable_enumerable';
<add>import Enumerable from './enumerable';
<ide> import isEnabled from 'ember-metal/features';
<ide>
<ide> export function removeAt(array, start, len) {
<ide><path>packages/ember-runtime/lib/mixins/mutable_enumerable.js
<del>import Enumerable from 'ember-runtime/mixins/enumerable';
<add>import Enumerable from './enumerable';
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import {beginPropertyChanges, endPropertyChanges} from 'ember-metal/property_events';
<ide>
<ide><path>packages/ember-runtime/lib/mixins/promise_proxy.js
<ide> import { get } from 'ember-metal/property_get';
<ide> import setProperties from 'ember-metal/set_properties';
<ide> import { computed } from 'ember-metal/computed';
<del>import { not, or } from 'ember-runtime/computed/computed_macros';
<add>import { not, or } from '../computed/computed_macros';
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import EmberError from 'ember-metal/error';
<ide>
<ide><path>packages/ember-runtime/lib/system/application.js
<del>import Namespace from 'ember-runtime/system/namespace';
<add>import Namespace from './namespace';
<ide>
<ide> export default Namespace.extend();
<ide><path>packages/ember-runtime/lib/system/array_proxy.js
<ide> import { assert } from 'ember-metal/debug';
<ide> import { get } from 'ember-metal/property_get';
<ide> import {
<ide> isArray
<del>} from 'ember-runtime/utils';
<add>} from '../utils';
<ide> import { computed } from 'ember-metal/computed';
<ide> import {
<ide> _beforeObserver,
<ide> import {
<ide> endPropertyChanges
<ide> } from 'ember-metal/property_events';
<ide> import EmberError from 'ember-metal/error';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import MutableArray from 'ember-runtime/mixins/mutable_array';
<del>import Enumerable from 'ember-runtime/mixins/enumerable';
<add>import EmberObject from './object';
<add>import MutableArray from '../mixins/mutable_array';
<add>import Enumerable from '../mixins/enumerable';
<ide> import alias from 'ember-metal/alias';
<ide> import {
<ide> addArrayObserver,
<ide> removeArrayObserver,
<ide> arrayContentDidChange,
<ide> arrayContentWillChange,
<ide> objectAt
<del>} from 'ember-runtime/mixins/array';
<add>} from '../mixins/array';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> import {
<ide> REQUIRED
<ide> } from 'ember-metal/mixin';
<ide> import EmberError from 'ember-metal/error';
<del>import ActionHandler from 'ember-runtime/mixins/action_handler';
<add>import ActionHandler from '../mixins/action_handler';
<ide> import { defineProperty } from 'ember-metal/properties';
<ide> import { Binding } from 'ember-metal/binding';
<ide> import { ComputedProperty, computed } from 'ember-metal/computed';
<ide> import InjectedProperty from 'ember-metal/injected_property';
<ide> import run from 'ember-metal/run_loop';
<ide> import { destroy } from 'ember-metal/watching';
<del>import { validatePropertyInjections } from 'ember-runtime/inject';
<add>import { validatePropertyInjections } from '../inject';
<ide> import symbol from 'ember-metal/symbol';
<ide>
<ide> export let POST_INIT = symbol('POST_INIT');
<ide><path>packages/ember-runtime/lib/system/each_proxy.js
<ide> import {
<ide> propertyWillChange
<ide> } from 'ember-metal/property_events';
<ide> import EmptyObject from 'ember-metal/empty_object';
<del>import { objectAt } from 'ember-runtime/mixins/array';
<add>import { objectAt } from '../mixins/array';
<ide>
<ide> /**
<ide> This is the object instance returned when you get the `@each` property on an
<ide><path>packages/ember-runtime/lib/system/namespace.js
<ide> import {
<ide> NAME_KEY
<ide> } from 'ember-metal/mixin';
<ide>
<del>import EmberObject from 'ember-runtime/system/object';
<add>import EmberObject from './object';
<ide>
<ide> let searchDisabled = false;
<ide>
<ide><path>packages/ember-runtime/lib/system/native_array.js
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import EmberArray, {
<ide> arrayContentDidChange,
<ide> arrayContentWillChange
<del>} from 'ember-runtime/mixins/array';
<del>import MutableArray from 'ember-runtime/mixins/mutable_array';
<del>import Observable from 'ember-runtime/mixins/observable';
<del>import Copyable from 'ember-runtime/mixins/copyable';
<del>import { FROZEN_ERROR } from 'ember-runtime/mixins/freezable';
<del>import copy from 'ember-runtime/copy';
<add>} from '../mixins/array';
<add>import MutableArray from '../mixins/mutable_array';
<add>import Observable from '../mixins/observable';
<add>import Copyable from '../mixins/copyable';
<add>import { FROZEN_ERROR } from '../mixins/freezable';
<add>import copy from '../copy';
<ide>
<ide> // Add Ember.Array to Array.prototype. Remove methods with native
<ide> // implementations and supply some more optimized versions of generic methods
<ide><path>packages/ember-runtime/lib/system/object.js
<ide> @submodule ember-runtime
<ide> */
<ide>
<del>import CoreObject from 'ember-runtime/system/core_object';
<del>import Observable from 'ember-runtime/mixins/observable';
<add>import CoreObject from './core_object';
<add>import Observable from '../mixins/observable';
<ide>
<ide> /**
<ide> `Ember.Object` is the main base class for all Ember objects. It is a subclass
<ide><path>packages/ember-runtime/lib/system/object_proxy.js
<del>import EmberObject from 'ember-runtime/system/object';
<del>import _ProxyMixin from 'ember-runtime/mixins/-proxy';
<add>import EmberObject from './object';
<add>import _ProxyMixin from '../mixins/-proxy';
<ide>
<ide> /**
<ide> `Ember.ObjectProxy` forwards all properties not defined by the proxy itself
<ide><path>packages/ember-runtime/lib/system/service.js
<del>import EmberObject from 'ember-runtime/system/object';
<del>import { createInjectionHelper } from 'ember-runtime/inject';
<add>import EmberObject from './object';
<add>import { createInjectionHelper } from '../inject';
<ide>
<ide>
<ide> /**
<ide><path>packages/ember-runtime/lib/system/string.js
<ide> import { deprecate } from 'ember-metal/debug';
<ide> import {
<ide> inspect as emberInspect
<ide> } from 'ember-metal/utils';
<del>import { isArray } from 'ember-runtime/utils';
<add>import { isArray } from '../utils';
<ide> import {
<ide> get as getString
<del>} from 'ember-runtime/string_registry';
<add>} from '../string_registry';
<ide>
<ide> import Cache from 'ember-metal/cache';
<ide>
<ide><path>packages/ember-runtime/lib/utils.js
<del>import EmberArray from 'ember-runtime/mixins/array';
<del>import EmberObject from 'ember-runtime/system/object';
<add>import EmberArray from './mixins/array';
<add>import EmberObject from './system/object';
<ide>
<ide> // ........................................
<ide> // TYPING & ARRAY MESSAGING | 63 |
Python | Python | set unique vector names in tests | 139428c20f357f7d5b474c1b996e9a8a79f636ed | <ide><path>spacy/tests/regression/test_issue1501-2000.py
<ide> def test_issue1799():
<ide>
<ide> def test_issue1807():
<ide> """Test vocab.set_vector also adds the word to the vocab."""
<del> vocab = Vocab()
<add> vocab = Vocab(vectors_name="test_issue1807")
<ide> assert "hello" not in vocab
<ide> vocab.set_vector("hello", numpy.ones((50,), dtype="f"))
<ide> assert "hello" in vocab
<ide><path>spacy/tests/regression/test_issue2501-3000.py
<ide> def test_issue2833(en_vocab):
<ide> def test_issue2871():
<ide> """Test that vectors recover the correct key for spaCy reserved words."""
<ide> words = ["dog", "cat", "SUFFIX"]
<del> vocab = Vocab()
<add> vocab = Vocab(vectors_name="test_issue2871")
<ide> vocab.vectors.resize(shape=(3, 10))
<ide> vector_data = numpy.zeros((3, 10), dtype="f")
<ide> for word in words:
<ide><path>spacy/tests/vocab_vectors/test_vectors.py
<ide> def test_vectors_doc_doc_similarity(vocab, text1, text2):
<ide>
<ide>
<ide> def test_vocab_add_vector():
<del> vocab = Vocab()
<add> vocab = Vocab(vectors_name="test_vocab_add_vector")
<ide> data = numpy.ndarray((5, 3), dtype="f")
<ide> data[0] = 1.0
<ide> data[1] = 2.0
<ide> def test_vocab_add_vector():
<ide>
<ide>
<ide> def test_vocab_prune_vectors():
<del> vocab = Vocab()
<add> vocab = Vocab(vectors_name="test_vocab_prune_vectors")
<ide> _ = vocab["cat"] # noqa: F841
<ide> _ = vocab["dog"] # noqa: F841
<ide> _ = vocab["kitten"] # noqa: F841 | 3 |
Go | Go | run sleep instead of cat /bin/zero. fixes #737 | fb86dcfb17444089aea31cdf6c9b09c4421731c7 | <ide><path>container_test.go
<ide> func TestKill(t *testing.T) {
<ide> defer nuke(runtime)
<ide> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"cat", "/dev/zero"},
<add> Cmd: []string{"sleep", "2"},
<ide> },
<ide> )
<ide> if err != nil {
<ide> func TestMultipleContainers(t *testing.T) {
<ide>
<ide> container1, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"cat", "/dev/zero"},
<add> Cmd: []string{"sleep", "2"},
<ide> },
<ide> )
<ide> if err != nil {
<ide> func TestMultipleContainers(t *testing.T) {
<ide>
<ide> container2, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"cat", "/dev/zero"},
<add> Cmd: []string{"sleep", "2"},
<ide> },
<ide> )
<ide> if err != nil { | 1 |
Javascript | Javascript | drop superfluous argument to sendreq | 3b5ba8779730c21897c2f18f5daaec9bc5550951 | <ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide> }
<ide>
<ide> // send request
<del> return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
<add> return sendReq(config, reqData).then(transformResponse, transformResponse);
<ide> };
<ide>
<ide> var chain = [serverRequest, undefined];
<ide> function $HttpProvider() {
<ide> * !!! ACCESSES CLOSURE VARS:
<ide> * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
<ide> */
<del> function sendReq(config, reqData, reqHeaders) {
<add> function sendReq(config, reqData) {
<ide> var deferred = $q.defer(),
<ide> promise = deferred.promise,
<ide> cache,
<ide> cachedResp,
<add> reqHeaders = config.headers,
<ide> url = buildUrl(config.url, config.params);
<ide>
<ide> $http.pendingRequests.push(config); | 1 |
Java | Java | fix package references | 95fe5f90330ab4d17744d55ea647d36323c0af67 | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/ResultActions.java
<ide> * request.
<ide> *
<ide> * <p>See static factory methods in
<del> * {@code org.springframework.test.web.server.result.MockMvcResultMatchers}
<del> * {@code org.springframework.test.web.server.result.MockMvcResultHandlers}
<add> * {@code org.springframework.test.web.servlet.result.MockMvcResultMatchers}
<add> * {@code org.springframework.test.web.servlet.result.MockMvcResultHandlers}
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 3.2 | 1 |
Javascript | Javascript | add failing tests for ember-cli/6026 | 3bac3e88ebcaa95f0ac5757f6b8b1b669d9cdd4a | <ide><path>node-tests/blueprints/route-test.js
<ide> describe('Acceptance: ember generate and destroy route', function() {
<ide> .to.not.contain('path: \':foo_id/show\''));
<ide> });
<ide>
<add> it('route --reset-namespace', function() {
<add> var args = ['route', 'parent/child', '--reset-namespace'];
<add>
<add> return emberNew()
<add> .then(() => emberGenerateDestroy(args, (_file) => {
<add> expect(_file('app/routes/child.js'))
<add> .to.contain('import Ember from \'ember\';')
<add> .to.contain('export default Ember.Route.extend({\n});');
<add>
<add> expect(_file('app/templates/child.hbs'))
<add> .to.contain('{{outlet}}');
<add>
<add> expect(_file('tests/unit/routes/child-test.js'))
<add> .to.contain('import { moduleFor, test } from \'ember-qunit\';')
<add> .to.contain('moduleFor(\'route:child\'');
<add>
<add> expect(file('app/router.js'))
<add> .to.contain('this.route(\'parent\', {')
<add> .to.contain('this.route(\'child\', {')
<add> .to.contain('resetNamespace: true')
<add> .to.contain('});');
<add> }));
<add> });
<add>
<add> it('route --reset-namespace --pod', function() {
<add> var args = ['route', 'parent/child', '--reset-namespace', '--pod'];
<add>
<add> return emberNew()
<add> .then(() => emberGenerateDestroy(args, (_file) => {
<add> expect(_file('app/child/route.js'))
<add> .to.contain('import Ember from \'ember\';')
<add> .to.contain('export default Ember.Route.extend({\n});');
<add>
<add> expect(_file('app/child/template.hbs'))
<add> .to.contain('{{outlet}}');
<add>
<add> expect(_file('tests/unit/child/route-test.js'))
<add> .to.contain('import { moduleFor, test } from \'ember-qunit\';')
<add> .to.contain('moduleFor(\'route:child\'');
<add>
<add> expect(file('app/router.js'))
<add> .to.contain('this.route(\'parent\', {')
<add> .to.contain('this.route(\'child\', {')
<add> .to.contain('resetNamespace: true')
<add> .to.contain('});');
<add> }));
<add> });
<add>
<ide> it('route index', function() {
<ide> var args = ['route', 'index'];
<ide> | 1 |
Ruby | Ruby | extract precision from datetime and time columns | 4b38a99e7a5eccf06a856cbda8517eb6039ab433 | <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def find_type(field)
<ide>
<ide> def initialize_type_map(m) # :nodoc:
<ide> super
<del> m.register_type %r(datetime)i, Fields::DateTime.new
<del> m.register_type %r(time)i, Fields::Time.new
<add> register_class_with_precision m, %r(datetime)i, Fields::DateTime
<add> register_class_with_precision m, %r(time)i, Fields::Time
<ide> end
<ide>
<ide> def exec_without_stmt(sql, name = 'SQL') # :nodoc:
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def initialize_type_map(m) # :nodoc:
<ide> register_class_with_limit m, 'varbit', OID::BitVarying
<ide> m.alias_type 'timestamptz', 'timestamp'
<ide> m.register_type 'date', Type::Date.new
<del> m.register_type 'time', Type::Time.new
<ide>
<ide> m.register_type 'money', OID::Money.new
<ide> m.register_type 'bytea', OID::Bytea.new
<ide> def initialize_type_map(m) # :nodoc:
<ide> m.alias_type 'lseg', 'varchar'
<ide> m.alias_type 'box', 'varchar'
<ide>
<del> m.register_type 'timestamp' do |_, _, sql_type|
<del> precision = extract_precision(sql_type)
<del> OID::DateTime.new(precision: precision)
<del> end
<add> register_class_with_precision m, 'time', Type::Time
<add> register_class_with_precision m, 'timestamp', OID::DateTime
<ide>
<ide> m.register_type 'numeric' do |_, fmod, sql_type|
<ide> precision = extract_precision(sql_type)
<ide><path>activerecord/test/cases/helper.rb
<ide> def in_memory_db?
<ide> end
<ide>
<ide> def mysql_56?
<del> current_adapter?(:Mysql2Adapter) &&
<add> current_adapter?(:MysqlAdapter, :Mysql2Adapter) &&
<ide> ActiveRecord::Base.connection.send(:version).join(".") >= "5.6.0"
<ide> end
<ide> | 3 |
Text | Text | add article for react portals | 4392455ff73202832c642321635ccde805ce58e5 | <ide><path>guide/english/react/portals/index.md
<add>---
<add>title: Portals
<add>---
<add>## Portals
<add>
<add>Portals were introduced with React 16.0. Portal provides a mechanism for a component to render its children in a DOM node that is outside the DOM hierarchy of parent component. In other words, a component that returns a portal from its render method can cause its children to be rendered as children of a completely different DOM node in the DOM tree. As a result, the position of the portal will be different in DOM tree versus the React tree.
<add>
<add>A portal can be created like so
<add>```javascript
<add>ReactDOM.createPortal(child, container)
<add>```
<add>Here `child` is a element, string, or fragment and `container` is a DOM element.
<add>
<add>A detailed explanation with example can be found in the official documentation. The difference in postion of the portal can be observed in the browser's dev tools by comparing the 'Elements' and 'React' tabs.
<add>
<add>#### More Information
<add>[React Portals](https://reactjs.org/docs/portals.html) | 1 |
Javascript | Javascript | fix package.json key | 2996d9ddeddbe656da137b04ca956f7bd560dbf9 | <ide><path>src/url-handler-registry.js
<ide> const {Disposable} = require('event-kit')
<ide> // automatically installing the package right away is not.
<ide> //
<ide> // Packages can register their desire to handle URLs via a special key in their
<del>// `package.json` called "urlHandlers". The value of this key should be an object
<add>// `package.json` called "urlHandler". The value of this key should be an object
<ide> // that contains, at minimum, a key named "method". This is the name of the method
<ide> // on your package object that Atom will call when it receives a URL your package
<ide> // is responsible for handling. It will pass the full URL as the only argument, and you
<ide> // are free to do your own URL parsing to handle it.
<ide> //
<ide> // If your package can defer activation until a URL it needs to handle is triggered,
<del>// you can additionally specify the `"defer": true` option in your "urlHandlers" object.
<add>// you can additionally specify the `"deferActivation": true` option in your "urlHandler" object.
<ide> // When Atom receives a request for a URL in your package's namespace, it will activate your
<ide> // pacakge and then call `methodName` on it as before.
<ide> //
<ide> // If your package specifies a deprecated `urlMain` property, you cannot register URL handlers
<del>// via the `urlHandlers` key.
<add>// via the `urlHandler` key.
<ide> //
<ide> // ## Example
<ide> //
<ide> const {Disposable} = require('event-kit')
<ide> // {
<ide> // "name": "my-package",
<ide> // "main": "./lib/my-package.js",
<del>// "urlHandlers": {
<add>// "urlHandler": {
<ide> // "method": "handleUrl",
<ide> // "deferActivation": true,
<ide> // } | 1 |
PHP | PHP | add missing space | b150ec691074e99a23506e4c9a3c5d6e1792e5a8 | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> public function mutexName()
<ide> /**
<ide> * Set the mutex name resolver callback.
<ide> *
<del> * @param \Closure $callback
<add> * @param \Closure $callback
<ide> * @return $this
<ide> */
<ide> public function createMutexNameUsing(Closure $callback) | 1 |
Javascript | Javascript | upgrade amdplugin to es6 | f22035d99a1da20f0bc92c4b6817855c45a226c3 | <ide><path>lib/dependencies/AMDPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var path = require("path");
<del>var AMDRequireDependency = require("./AMDRequireDependency");
<del>var AMDRequireItemDependency = require("./AMDRequireItemDependency");
<del>var AMDRequireArrayDependency = require("./AMDRequireArrayDependency");
<del>var AMDRequireContextDependency = require("./AMDRequireContextDependency");
<del>var AMDDefineDependency = require("./AMDDefineDependency");
<del>var UnsupportedDependency = require("./UnsupportedDependency");
<del>var LocalModuleDependency = require("./LocalModuleDependency");
<del>
<del>var NullFactory = require("../NullFactory");
<del>
<del>var AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin");
<del>var AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin");
<del>
<del>var AliasPlugin = require("enhanced-resolve/lib/AliasPlugin");
<del>
<del>var BasicEvaluatedExpression = require("../BasicEvaluatedExpression");
<del>var ParserHelpers = require("../ParserHelpers");
<del>
<del>function AMDPlugin(options, amdOptions) {
<del> this.amdOptions = amdOptions;
<del> this.options = options;
<del>}
<del>module.exports = AMDPlugin;
<del>
<del>AMDPlugin.prototype.apply = function(compiler) {
<del> var options = this.options;
<del> var amdOptions = this.amdOptions;
<del> compiler.plugin("compilation", function(compilation, params) {
<del> var normalModuleFactory = params.normalModuleFactory;
<del> var contextModuleFactory = params.contextModuleFactory;
<del>
<del> compilation.dependencyFactories.set(AMDRequireDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(AMDRequireDependency, new AMDRequireDependency.Template());
<del>
<del> compilation.dependencyFactories.set(AMDRequireItemDependency, normalModuleFactory);
<del> compilation.dependencyTemplates.set(AMDRequireItemDependency, new AMDRequireItemDependency.Template());
<del>
<del> compilation.dependencyFactories.set(AMDRequireArrayDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(AMDRequireArrayDependency, new AMDRequireArrayDependency.Template());
<del>
<del> compilation.dependencyFactories.set(AMDRequireContextDependency, contextModuleFactory);
<del> compilation.dependencyTemplates.set(AMDRequireContextDependency, new AMDRequireContextDependency.Template());
<del>
<del> compilation.dependencyFactories.set(AMDDefineDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(AMDDefineDependency, new AMDDefineDependency.Template());
<del>
<del> compilation.dependencyFactories.set(UnsupportedDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(UnsupportedDependency, new UnsupportedDependency.Template());
<del>
<del> compilation.dependencyFactories.set(LocalModuleDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(LocalModuleDependency, new LocalModuleDependency.Template());
<del>
<del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
<del>
<del> if(typeof parserOptions.amd !== "undefined" && !parserOptions.amd)
<del> return;
<del>
<del> function setExpressionToModule(expr, module) {
<del> parser.plugin("expression " + expr, function(expr) {
<del> var dep = new AMDRequireItemDependency(module, expr.range);
<del> dep.userRequest = expr;
<add>"use strict";
<add>
<add>const path = require("path");
<add>const AMDRequireDependency = require("./AMDRequireDependency");
<add>const AMDRequireItemDependency = require("./AMDRequireItemDependency");
<add>const AMDRequireArrayDependency = require("./AMDRequireArrayDependency");
<add>const AMDRequireContextDependency = require("./AMDRequireContextDependency");
<add>const AMDDefineDependency = require("./AMDDefineDependency");
<add>const UnsupportedDependency = require("./UnsupportedDependency");
<add>const LocalModuleDependency = require("./LocalModuleDependency");
<add>
<add>const NullFactory = require("../NullFactory");
<add>
<add>const AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin");
<add>const AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin");
<add>
<add>const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin");
<add>
<add>const BasicEvaluatedExpression = require("../BasicEvaluatedExpression");
<add>const ParserHelpers = require("../ParserHelpers");
<add>
<add>class AMDPlugin {
<add> constructor(options, amdOptions) {
<add> this.amdOptions = amdOptions;
<add> this.options = options;
<add> }
<add>
<add> apply(compiler) {
<add> const options = this.options;
<add> const amdOptions = this.amdOptions;
<add> compiler.plugin("compilation", (compilation, params) => {
<add> const normalModuleFactory = params.normalModuleFactory;
<add> const contextModuleFactory = params.contextModuleFactory;
<add>
<add> compilation.dependencyFactories.set(AMDRequireDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(AMDRequireDependency, new AMDRequireDependency.Template());
<add>
<add> compilation.dependencyFactories.set(AMDRequireItemDependency, normalModuleFactory);
<add> compilation.dependencyTemplates.set(AMDRequireItemDependency, new AMDRequireItemDependency.Template());
<add>
<add> compilation.dependencyFactories.set(AMDRequireArrayDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(AMDRequireArrayDependency, new AMDRequireArrayDependency.Template());
<add>
<add> compilation.dependencyFactories.set(AMDRequireContextDependency, contextModuleFactory);
<add> compilation.dependencyTemplates.set(AMDRequireContextDependency, new AMDRequireContextDependency.Template());
<add>
<add> compilation.dependencyFactories.set(AMDDefineDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(AMDDefineDependency, new AMDDefineDependency.Template());
<add>
<add> compilation.dependencyFactories.set(UnsupportedDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(UnsupportedDependency, new UnsupportedDependency.Template());
<add>
<add> compilation.dependencyFactories.set(LocalModuleDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(LocalModuleDependency, new LocalModuleDependency.Template());
<add>
<add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<add>
<add> if(typeof parserOptions.amd !== "undefined" && !parserOptions.amd)
<add> return;
<add>
<add> function setExpressionToModule(expr, module) {
<add> parser.plugin("expression " + expr, (expr) => {
<add> const dep = new AMDRequireItemDependency(module, expr.range);
<add> dep.userRequest = expr;
<add> dep.loc = expr.loc;
<add> parser.state.current.addDependency(dep);
<add> return true;
<add> });
<add> }
<add>
<add> parser.apply(
<add> new AMDRequireDependenciesBlockParserPlugin(options),
<add> new AMDDefineDependencyParserPlugin(options)
<add> );
<add> setExpressionToModule("require.amd", "!!webpack amd options");
<add> setExpressionToModule("define.amd", "!!webpack amd options");
<add> setExpressionToModule("define", "!!webpack amd define");
<add> parser.plugin("expression __webpack_amd_options__", () =>
<add> parser.state.current.addVariable("__webpack_amd_options__", JSON.stringify(amdOptions)));
<add> parser.plugin("evaluate typeof define.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<add> parser.plugin("evaluate typeof require.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<add> parser.plugin("evaluate Identifier define.amd", (expr) => {
<add> return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
<add> });
<add> parser.plugin("evaluate Identifier require.amd", (expr) => {
<add> return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
<add> });
<add> parser.plugin("typeof define", ParserHelpers.toConstantDependency("function"));
<add> parser.plugin("evaluate typeof define", ParserHelpers.evaluateToString("function"));
<add> parser.plugin("can-rename define", () => true);
<add> parser.plugin("rename define", (expr) => {
<add> const dep = new AMDRequireItemDependency("!!webpack amd define", expr.range);
<add> dep.userRequest = "define";
<ide> dep.loc = expr.loc;
<del> this.state.current.addDependency(dep);
<del> return true;
<add> parser.state.current.addDependency(dep);
<add> return false;
<ide> });
<del> }
<del>
<del> parser.apply(
<del> new AMDRequireDependenciesBlockParserPlugin(options),
<del> new AMDDefineDependencyParserPlugin(options)
<del> );
<del> setExpressionToModule("require.amd", "!!webpack amd options");
<del> setExpressionToModule("define.amd", "!!webpack amd options");
<del> setExpressionToModule("define", "!!webpack amd define");
<del> parser.plugin("expression __webpack_amd_options__", function() {
<del> return this.state.current.addVariable("__webpack_amd_options__", JSON.stringify(amdOptions));
<del> });
<del> parser.plugin("evaluate typeof define.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<del> parser.plugin("evaluate typeof require.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<del> parser.plugin("evaluate Identifier define.amd", function(expr) {
<del> return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
<add> parser.plugin("typeof require", ParserHelpers.toConstantDependency("function"));
<add> parser.plugin("evaluate typeof require", ParserHelpers.evaluateToString("function"));
<ide> });
<del> parser.plugin("evaluate Identifier require.amd", function(expr) {
<del> return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
<del> });
<del> parser.plugin("typeof define", ParserHelpers.toConstantDependency("function"));
<del> parser.plugin("evaluate typeof define", ParserHelpers.evaluateToString("function"));
<del> parser.plugin("can-rename define", function() {
<del> return true;
<del> });
<del> parser.plugin("rename define", function(expr) {
<del> var dep = new AMDRequireItemDependency("!!webpack amd define", expr.range);
<del> dep.userRequest = "define";
<del> dep.loc = expr.loc;
<del> this.state.current.addDependency(dep);
<del> return false;
<del> });
<del> parser.plugin("typeof require", ParserHelpers.toConstantDependency("function"));
<del> parser.plugin("evaluate typeof require", ParserHelpers.evaluateToString("function"));
<ide> });
<del> });
<del> compiler.plugin("after-resolvers", function() {
<del> compiler.resolvers.normal.apply(
<del> new AliasPlugin("described-resolve", {
<del> name: "amdefine",
<del> alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
<del> }, "resolve"),
<del> new AliasPlugin("described-resolve", {
<del> name: "webpack amd options",
<del> alias: path.join(__dirname, "..", "..", "buildin", "amd-options.js")
<del> }, "resolve"),
<del> new AliasPlugin("described-resolve", {
<del> name: "webpack amd define",
<del> alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
<del> }, "resolve")
<del> );
<del> });
<del>};
<add> compiler.plugin("after-resolvers", () => {
<add> compiler.resolvers.normal.apply(
<add> new AliasPlugin("described-resolve", {
<add> name: "amdefine",
<add> alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
<add> }, "resolve"),
<add> new AliasPlugin("described-resolve", {
<add> name: "webpack amd options",
<add> alias: path.join(__dirname, "..", "..", "buildin", "amd-options.js")
<add> }, "resolve"),
<add> new AliasPlugin("described-resolve", {
<add> name: "webpack amd define",
<add> alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
<add> }, "resolve")
<add> );
<add> });
<add> }
<add>}
<add>module.exports = AMDPlugin; | 1 |
Javascript | Javascript | report error only when enabled | c2a0443486699d2ef68521fe743a255958609eb6 | <ide><path>server/middlewares/error-reporter.js
<ide> const log = debug('fcc:middlewares:error-reporter');
<ide>
<ide> const isOpbeatDisabled = !opbeat.appId;
<ide> export default function errrorReporter() {
<del> if (process.env.NODE_ENV !== 'production') {
<add> if (process.env.NODE_ENV !== 'production' && process.env.ERROR_REPORTER) {
<ide> return (err, req, res, next) => {
<ide> if (isHandledError(err)) {
<ide> // log out user messages in development | 1 |
Python | Python | add support for unique_together | c4b2a3262cc79383d6562cfc7e9af20135c8e0bf | <ide><path>django/db/backends/schema.py
<ide> class BaseDatabaseSchemaEditor(object):
<ide>
<ide> # Overrideable SQL templates
<ide> sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
<add> sql_create_table_unique = "UNIQUE (%(columns)s)"
<ide> sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
<ide> sql_delete_table = "DROP TABLE %(table)s CASCADE"
<ide>
<ide> class BaseDatabaseSchemaEditor(object):
<ide> sql_create_fk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) REFERENCES %(to_table)s (%(to_column)s) DEFERRABLE INITIALLY DEFERRED"
<ide> sql_delete_fk = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
<ide>
<del> sql_create_index = "CREATE %(unique)s INDEX %(name)s ON %(table)s (%(columns)s)%s;"
<add> sql_create_index = "CREATE %(unique)s INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s;"
<ide> sql_delete_index = "DROP INDEX %(name)s"
<ide>
<ide> sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(constraint)s PRIMARY KEY (%(columns)s)"
<ide> def create_model(self, model):
<ide> definition,
<ide> ))
<ide> params.extend(extra_params)
<add> # Indexes
<add> if field.db_index:
<add> self.deferred_sql.append(
<add> self.sql_create_index % {
<add> "unique": "",
<add> "name": self._create_index_name(model, [field.column], suffix=""),
<add> "table": self.quote_name(model._meta.db_table),
<add> "columns": self.quote_name(field.column),
<add> "extra": "",
<add> }
<add> )
<ide> # FK
<ide> if field.rel:
<ide> to_table = field.rel.to._meta.db_table
<ide> def create_model(self, model):
<ide> "to_column": self.quote_name(to_column),
<ide> }
<ide> )
<add> # Add any unique_togethers
<add> for fields in model._meta.unique_together:
<add> columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
<add> column_sqls.append(self.sql_create_table_unique % {
<add> "columns": ", ".join(self.quote_name(column) for column in columns),
<add> })
<ide> # Make the table
<ide> sql = self.sql_create_table % {
<ide> "table": model._meta.db_table,
<ide> def delete_model(self, model):
<ide> "table": self.quote_name(model._meta.db_table),
<ide> })
<ide>
<add> def alter_unique_together(self, model, old_unique_together, new_unique_together):
<add> """
<add> Deals with a model changing its unique_together.
<add> Note: The input unique_togethers must be doubly-nested, not the single-
<add> nested ["foo", "bar"] format.
<add> """
<add> olds = set(frozenset(fields) for fields in old_unique_together)
<add> news = set(frozenset(fields) for fields in new_unique_together)
<add> # Deleted uniques
<add> for fields in olds.difference(news):
<add> columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
<add> constraint_names = self._constraint_names(model, list(columns), unique=True)
<add> if len(constraint_names) != 1:
<add> raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
<add> len(constraint_names),
<add> model._meta.db_table,
<add> ", ".join(columns),
<add> ))
<add> self.execute(
<add> self.sql_delete_unique % {
<add> "table": self.quote_name(model._meta.db_table),
<add> "name": constraint_names[0],
<add> },
<add> )
<add> # Created uniques
<add> for fields in news.difference(olds):
<add> columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
<add> self.execute(self.sql_create_unique % {
<add> "table": self.quote_name(model._meta.db_table),
<add> "name": self._create_index_name(model, columns, suffix="_uniq"),
<add> "columns": ", ".join(self.quote_name(column) for column in columns),
<add> })
<add>
<ide> def create_field(self, model, field, keep_default=False):
<ide> """
<ide> Creates a field on a model.
<ide><path>tests/modeltests/schema/models.py
<ide> class Meta:
<ide> class Tag(models.Model):
<ide> title = models.CharField(max_length=255)
<ide> slug = models.SlugField(unique=True)
<add>
<add> class Meta:
<add> managed = False
<add>
<add>
<add>class UniqueTest(models.Model):
<add> year = models.IntegerField()
<add> slug = models.SlugField(unique=False)
<add>
<add> class Meta:
<add> managed = False
<add> unique_together = ["year", "slug"]
<ide><path>tests/modeltests/schema/tests.py
<ide> from django.db.models.fields import IntegerField, TextField, CharField, SlugField
<ide> from django.db.models.fields.related import ManyToManyField
<ide> from django.db.models.loading import cache
<del>from .models import Author, Book, AuthorWithM2M, Tag
<add>from .models import Author, Book, AuthorWithM2M, Tag, UniqueTest
<ide>
<ide>
<ide> class SchemaTests(TestCase):
<ide> class SchemaTests(TestCase):
<ide> as the code it is testing.
<ide> """
<ide>
<del> models = [Author, Book, AuthorWithM2M, Tag]
<add> models = [Author, Book, AuthorWithM2M, Tag, UniqueTest]
<ide>
<ide> # Utility functions
<ide>
<ide> def test_unique(self):
<ide> Tag.objects.create(title="foo", slug="foo")
<ide> self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
<ide> connection.rollback()
<add>
<add> def test_unique_together(self):
<add> """
<add> Tests removing and adding unique_together constraints on a model.
<add> """
<add> # Create the table
<add> editor = connection.schema_editor()
<add> editor.start()
<add> editor.create_model(UniqueTest)
<add> editor.commit()
<add> # Ensure the fields are unique to begin with
<add> UniqueTest.objects.create(year=2012, slug="foo")
<add> UniqueTest.objects.create(year=2011, slug="foo")
<add> UniqueTest.objects.create(year=2011, slug="bar")
<add> self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
<add> connection.rollback()
<add> # Alter the model to it's non-unique-together companion
<add> editor = connection.schema_editor()
<add> editor.start()
<add> editor.alter_unique_together(
<add> UniqueTest,
<add> UniqueTest._meta.unique_together,
<add> [],
<add> )
<add> editor.commit()
<add> # Ensure the fields are no longer unique
<add> UniqueTest.objects.create(year=2012, slug="foo")
<add> UniqueTest.objects.create(year=2012, slug="foo")
<add> connection.rollback()
<add> # Alter it back
<add> new_new_field = SlugField(unique=True)
<add> new_new_field.set_attributes_from_name("slug")
<add> editor = connection.schema_editor()
<add> editor.start()
<add> editor.alter_unique_together(
<add> UniqueTest,
<add> [],
<add> UniqueTest._meta.unique_together,
<add> )
<add> editor.commit()
<add> # Ensure the fields are unique again
<add> UniqueTest.objects.create(year=2012, slug="foo")
<add> self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
<add> connection.rollback() | 3 |
Python | Python | fix tempfile failures on window | 29a33301d7c90fb22e8ee6533195b0a7c203de91 | <ide><path>numpy/core/tests/test_longdouble.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import locale
<del>from tempfile import NamedTemporaryFile
<ide>
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> run_module_suite, assert_, assert_equal, dec, assert_raises,
<del> assert_array_equal, TestCase
<add> assert_array_equal, TestCase, temppath,
<ide> )
<ide> from numpy.compat import sixu
<ide> from test_print import in_foreign_locale
<ide> def test_fromstring_missing():
<ide>
<ide>
<ide> class FileBased(TestCase):
<del> def setUp(self):
<del> self.o = 1 + np.finfo(np.longdouble).eps
<del> self.f = NamedTemporaryFile(mode="wt")
<ide>
<del> def tearDown(self):
<del> self.f.close()
<del> del self.f
<add> ldbl = 1 + np.finfo(np.longdouble).eps
<add> tgt = np.array([ldbl]*5)
<add> out = ''.join([repr(t) + '\n' for t in tgt])
<ide>
<ide> def test_fromfile_bogus(self):
<del> self.f.write("1. 2. 3. flop 4.\n")
<del> self.f.flush()
<del> F = open(self.f.name, "rt")
<del> try:
<del> assert_equal(np.fromfile(F, dtype=float, sep=" "),
<del> np.array([1., 2., 3.]))
<del> finally:
<del> F.close()
<add> with temppath() as path:
<add> with open(path, 'wt') as f:
<add> f.write("1. 2. 3. flop 4.\n")
<add> res = np.fromfile(path, dtype=float, sep=" ")
<add> assert_equal(res, np.array([1., 2., 3.]))
<ide>
<ide> @dec.knownfailureif(string_to_longdouble_inaccurate, "Need strtold_l")
<ide> def test_fromfile(self):
<del> for i in range(5):
<del> self.f.write(repr(self.o) + "\n")
<del> self.f.flush()
<del> a = np.array([self.o]*5)
<del> F = open(self.f.name, "rt")
<del> b = np.fromfile(F,
<del> dtype=np.longdouble,
<del> sep="\n")
<del> F.close()
<del> F = open(self.f.name, "rt")
<del> s = F.read()
<del> F.close()
<del> assert_equal(b, a, err_msg="decoded %s as %s" % (repr(s), repr(b)))
<add> with temppath() as path:
<add> with open(path, 'wt') as f:
<add> f.write(self.out)
<add> res = np.fromfile(path, dtype=np.longdouble, sep="\n")
<add> assert_equal(res, self.tgt)
<ide>
<ide> @dec.knownfailureif(string_to_longdouble_inaccurate, "Need strtold_l")
<ide> def test_genfromtxt(self):
<del> for i in range(5):
<del> self.f.write(repr(self.o) + "\n")
<del> self.f.flush()
<del> a = np.array([self.o]*5)
<del> assert_equal(np.genfromtxt(self.f.name, dtype=np.longdouble), a)
<add> with temppath() as path:
<add> with open(path, 'wt') as f:
<add> f.write(self.out)
<add> res = np.genfromtxt(path, dtype=np.longdouble)
<add> assert_equal(res, self.tgt)
<ide>
<ide> @dec.knownfailureif(string_to_longdouble_inaccurate, "Need strtold_l")
<ide> def test_loadtxt(self):
<del> for i in range(5):
<del> self.f.write(repr(self.o) + "\n")
<del> self.f.flush()
<del> a = np.array([self.o]*5)
<del> assert_equal(np.loadtxt(self.f.name, dtype=np.longdouble), a)
<add> with temppath() as path:
<add> with open(path, 'wt') as f:
<add> f.write(self.out)
<add> res = np.loadtxt(path, dtype=np.longdouble)
<add> assert_equal(res, self.tgt)
<ide>
<ide> @dec.knownfailureif(string_to_longdouble_inaccurate, "Need strtold_l")
<ide> def test_tofile_roundtrip(self):
<del> a = np.array([self.o]*3)
<del> a.tofile(self.f.name, sep=" ")
<del> F = open(self.f.name, "rt")
<del> try:
<del> assert_equal(np.fromfile(F, dtype=np.longdouble, sep=" "),
<del> a)
<del> finally:
<del> F.close()
<add> with temppath() as path:
<add> self.tgt.tofile(path, sep=" ")
<add> res = np.fromfile(path, dtype=np.longdouble, sep=" ")
<add> assert_equal(res, self.tgt)
<ide>
<ide>
<ide> @in_foreign_locale | 1 |
PHP | PHP | improve docs for errortrap | 3b048bff7405db49608b57c040b756e503c80dd0 | <ide><path>src/Error/ErrorTrap.php
<ide> class ErrorTrap
<ide> }
<ide>
<ide> /**
<del> * See the `Error` key in you `config/app.php`
<del> * for details on the keys and their values.
<add> * Configuration options. Generally these are defined in config/app.php
<add> *
<add> * - `errorLevel` - int - The level of errors you are interested in capturing.
<add> * - `errorRenderer` - string - The class name of render errors with. Defaults
<add> * to choosing between Html and Console based on the SAPI.
<add> * - `log` - boolean - Whether or not you want errors logged.
<add> * - `logger` - string - The class name of the error logger to use.
<add> * - `trace` - boolean - Whether or not backtraces should be included in
<add> * logged errors.
<ide> *
<ide> * @var array<string, mixed>
<ide> */
<ide> protected $_defaultConfig = [
<ide> 'errorLevel' => E_ALL,
<add> 'errorRenderer' => null,
<ide> 'log' => true,
<ide> 'logger' => ErrorLogger::class,
<del> 'errorRenderer' => null,
<ide> 'trace' => false,
<ide> ];
<ide> | 1 |
Javascript | Javascript | use jquery reference not sizzle | 3b9057a18de31b838bd0dd25ea466993b62f9dd9 | <ide><path>test/unit/selector.js
<ide> asyncTest( "Iframe dispatch should not affect jQuery (#13936)", 1, function() {
<ide>
<ide> try {
<ide> iframeDoc = this.contentDocument || this.contentWindow.document;
<del> form = Sizzle( "#navigate", iframeDoc )[ 0 ];
<add> form = jQuery( "#navigate", iframeDoc )[ 0 ];
<ide> } catch ( e ) {
<ide> thrown = e;
<ide> }
<ide>
<ide> if ( loaded ) {
<del> strictEqual( thrown, false, "No error thrown from post-reload Sizzle call" );
<add> strictEqual( thrown, false, "No error thrown from post-reload jQuery call" );
<add>
<add> // clean up
<add> jQuery( iframe ).off();
<add>
<ide> start();
<ide> } else {
<ide> loaded = true; | 1 |
Javascript | Javascript | remove unreferenced slideriosexample | 049639cfdd001bf1b770d511bcc57d15f9c91cf5 | <ide><path>Examples/UIExplorer/js/SliderIOSExample.js
<del>/**
<del> * Copyright (c) 2013-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> *
<del> * The examples provided by Facebook are for non-commercial testing and
<del> * evaluation purposes only.
<del> *
<del> * Facebook reserves all rights not expressly granted.
<del> *
<del> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<del> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
<del> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<del> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<del> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<del> *
<del> * @flow
<del> */
<del>'use strict';
<del>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {
<del> SliderIOS,
<del> Text,
<del> StyleSheet,
<del> View,
<del>} = ReactNative;
<del>
<del>class SliderExample extends React.Component {
<del> state = {
<del> value: 0,
<del> };
<del>
<del> render() {
<del> return (
<del> <View>
<del> <Text style={styles.text} >
<del> {this.state.value}
<del> </Text>
<del> <SliderIOS
<del> {...this.props}
<del> onValueChange={(value) => this.setState({value: value})} />
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>var styles = StyleSheet.create({
<del> slider: {
<del> height: 10,
<del> margin: 10,
<del> },
<del> text: {
<del> fontSize: 14,
<del> textAlign: 'center',
<del> fontWeight: '500',
<del> margin: 10,
<del> },
<del>});
<del>
<del>exports.title = '<SliderIOS>';
<del>exports.displayName = 'SliderExample';
<del>exports.description = 'Slider input for numeric values';
<del>exports.examples = [
<del> {
<del> title: 'Default settings',
<del> render(): ReactElement<any> {
<del> return <SliderExample />;
<del> }
<del> },
<del> {
<del> title: 'minimumValue: -1, maximumValue: 2',
<del> render(): ReactElement<any> {
<del> return (
<del> <SliderExample
<del> minimumValue={-1}
<del> maximumValue={2}
<del> />
<del> );
<del> }
<del> },
<del> {
<del> title: 'step: 0.25',
<del> render(): ReactElement<any> {
<del> return <SliderExample step={0.25} />;
<del> }
<del> },
<del> {
<del> title: 'Custom min/max track tint color',
<del> render(): ReactElement<any> {
<del> return (
<del> <SliderExample
<del> minimumTrackTintColor={'red'}
<del> maximumTrackTintColor={'green'}
<del> />
<del> );
<del> }
<del> },
<del> {
<del> title: 'Custom thumb image',
<del> render(): ReactElement<any> {
<del> return <SliderExample thumbImage={require('./uie_thumb_big.png')} />;
<del> }
<del> },
<del> {
<del> title: 'Custom track image',
<del> render(): ReactElement<any> {
<del> return <SliderExample trackImage={require('./slider.png')} />;
<del> }
<del> },
<del> {
<del> title: 'Custom min/max track image',
<del> render(): ReactElement<any> {
<del> return (
<del> <SliderExample
<del> minimumTrackImage={require('./slider-left.png')}
<del> maximumTrackImage={require('./slider-right.png')}
<del> />
<del> );
<del> }
<del> },
<del>]; | 1 |
Mixed | Text | add japanese translated readme | 38e5b71abbf3f04925beb0a81af69fd17476405c | <ide><path>README.md
<ide> limitations under the License.
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hans.md">简体中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hant.md">繁體中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_ko.md">한국어</a> |
<del> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ja.md">日本語</a>
<ide> <p>
<ide> </h4>
<ide>
<ide><path>README_es.md
<ide> limitations under the License.
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hans.md">简体中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hant.md">繁體中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_ko.md">한국어</a> |
<del> <b>Español</b>
<add> <b>Español</b> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ja.md">日本語</a>
<ide> <p>
<ide> </h4>
<ide>
<ide><path>README_ja.md
<add><!---
<add>Copyright 2020 The HuggingFace Team. All rights reserved.
<add>
<add>Licensed under the Apache License, Version 2.0 (the "License");
<add>you may not use this file except in compliance with the License.
<add>You may obtain a copy of the License at
<add>
<add> http://www.apache.org/licenses/LICENSE-2.0
<add>
<add>Unless required by applicable law or agreed to in writing, software
<add>distributed under the License is distributed on an "AS IS" BASIS,
<add>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add>See the License for the specific language governing permissions and
<add>limitations under the License.
<add>-->
<add>
<add><!---
<add>A useful guide for English-Traditional Japanese translation of Hugging Face documentation
<add>- Use square quotes, e.g.,「引用」
<add>
<add>Dictionary
<add>
<add>API: API(翻訳しない)
<add>add: 追加
<add>checkpoint: チェックポイント
<add>code: コード
<add>community: コミュニティ
<add>confidence: 信頼度
<add>dataset: データセット
<add>documentation: ドキュメント
<add>example: 例
<add>finetune: 微調整
<add>Hugging Face: Hugging Face(翻訳しない)
<add>implementation: 実装
<add>inference: 推論
<add>library: ライブラリ
<add>module: モジュール
<add>NLP/Natural Language Processing: NLPと表示される場合は翻訳されず、Natural Language Processingと表示される場合は翻訳される
<add>online demos: オンラインデモ
<add>pipeline: pipeline(翻訳しない)
<add>pretrained/pretrain: 学習済み
<add>Python data structures (e.g., list, set, dict): リスト、セット、ディクショナリと訳され、括弧内は原文英語
<add>repository: repository(翻訳しない)
<add>summary: 概要
<add>token-: token-(翻訳しない)
<add>Trainer: Trainer(翻訳しない)
<add>transformer: transformer(翻訳しない)
<add>tutorial: チュートリアル
<add>user: ユーザ
<add>-->
<add>
<add><p align="center">
<add> <br>
<add> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers_logo_name.png" width="400"/>
<add> <br>
<add><p>
<add><p align="center">
<add> <a href="https://circleci.com/gh/huggingface/transformers">
<add> <img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/main">
<add> </a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/LICENSE">
<add> <img alt="GitHub" src="https://img.shields.io/github/license/huggingface/transformers.svg?color=blue">
<add> </a>
<add> <a href="https://huggingface.co/docs/transformers/index">
<add> <img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/transformers/index.svg?down_color=red&down_message=offline&up_message=online">
<add> </a>
<add> <a href="https://github.com/huggingface/transformers/releases">
<add> <img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg">
<add> </a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md">
<add> <img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg">
<add> </a>
<add> <a href="https://zenodo.org/badge/latestdoi/155220641"><img src="https://zenodo.org/badge/155220641.svg" alt="DOI"></a>
<add></p>
<add>
<add><h4 align="center">
<add> <p>
<add> <a href="https://github.com/huggingface/transformers/">English</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hans.md">简体中文</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hant.md">繁體中文</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ko.md">한국어</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a> |
<add> <b>日本語</b>
<add> <p>
<add></h4>
<add>
<add><h3 align="center">
<add> <p>JAX、PyTorch、TensorFlowのための最先端機械学習</p>
<add></h3>
<add>
<add><h3 align="center">
<add> <a href="https://hf.co/course"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/course_banner.png"></a>
<add></h3>
<add>
<add>🤗Transformersは、テキスト、視覚、音声などの異なるモダリティに対してタスクを実行するために、事前に学習させた数千のモデルを提供します。
<add>
<add>これらのモデルは次のような場合に適用できます:
<add>
<add>* 📝 テキストは、テキストの分類、情報抽出、質問応答、要約、翻訳、テキスト生成などのタスクのために、100以上の言語に対応しています。
<add>* 🖼️ 画像分類、物体検出、セグメンテーションなどのタスクのための画像。
<add>* 🗣️ 音声は、音声認識や音声分類などのタスクに使用します。
<add>
<add>トランスフォーマーモデルは、テーブル質問応答、光学文字認識、スキャン文書からの情報抽出、ビデオ分類、視覚的質問応答など、**複数のモダリティを組み合わせた**タスクも実行可能です。
<add>
<add>🤗Transformersは、与えられたテキストに対してそれらの事前学習されたモデルを素早くダウンロードして使用し、あなた自身のデータセットでそれらを微調整し、私たちの[model hub](https://huggingface.co/models)でコミュニティと共有するためのAPIを提供します。同時に、アーキテクチャを定義する各Pythonモジュールは完全にスタンドアロンであり、迅速な研究実験を可能にするために変更することができます。
<add>
<add>🤗Transformersは[Jax](https://jax.readthedocs.io/en/latest/)、[PyTorch](https://pytorch.org/)、[TensorFlow](https://www.tensorflow.org/)という3大ディープラーニングライブラリーに支えられ、それぞれのライブラリをシームレスに統合しています。片方でモデルを学習してから、もう片方で推論用にロードするのは簡単なことです。
<add>
<add>## オンラインデモ
<add>
<add>[model hub](https://huggingface.co/models)から、ほとんどのモデルのページで直接テストすることができます。また、パブリックモデル、プライベートモデルに対して、[プライベートモデルのホスティング、バージョニング、推論API](https://huggingface.co/pricing)を提供しています。
<add>
<add>以下はその一例です:
<add>
<add> 自然言語処理にて:
<add>- [BERTによるマスクドワード補完](https://huggingface.co/bert-base-uncased?text=Paris+is+the+%5BMASK%5D+of+France)
<add>- [Electraによる名前実体認識](https://huggingface.co/dbmdz/electra-large-discriminator-finetuned-conll03-english?text=My+name+is+Sarah+and+I+live+in+London+city)
<add>- [GPT-2によるテキスト生成](https://huggingface.co/gpt2?text=A+long+time+ago%2C+)
<add>- [RoBERTaによる自然言語推論](https://huggingface.co/roberta-large-mnli?text=The+dog+was+lost.+Nobody+lost+any+animal)
<add>- [BARTによる要約](https://huggingface.co/facebook/bart-large-cnn?text=The+tower+is+324+metres+%281%2C063+ft%29+tall%2C+about+the+same+height+as+an+81-storey+building%2C+and+the+tallest+structure+in+Paris.+Its+base+is+square%2C+measuring+125+metres+%28410+ft%29+on+each+side.+During+its+construction%2C+the+Eiffel+Tower+surpassed+the+Washington+Monument+to+become+the+tallest+man-made+structure+in+the+world%2C+a+title+it+held+for+41+years+until+the+Chrysler+Building+in+New+York+City+was+finished+in+1930.+It+was+the+first+structure+to+reach+a+height+of+300+metres.+Due+to+the+addition+of+a+broadcasting+aerial+at+the+top+of+the+tower+in+1957%2C+it+is+now+taller+than+the+Chrysler+Building+by+5.2+metres+%2817+ft%29.+Excluding+transmitters%2C+the+Eiffel+Tower+is+the+second+tallest+free-standing+structure+in+France+after+the+Millau+Viaduct)
<add>- [DistilBERTによる質問応答](https://huggingface.co/distilbert-base-uncased-distilled-squad?text=Which+name+is+also+used+to+describe+the+Amazon+rainforest+in+English%3F&context=The+Amazon+rainforest+%28Portuguese%3A+Floresta+Amaz%C3%B4nica+or+Amaz%C3%B4nia%3B+Spanish%3A+Selva+Amaz%C3%B3nica%2C+Amazon%C3%ADa+or+usually+Amazonia%3B+French%3A+For%C3%AAt+amazonienne%3B+Dutch%3A+Amazoneregenwoud%29%2C+also+known+in+English+as+Amazonia+or+the+Amazon+Jungle%2C+is+a+moist+broadleaf+forest+that+covers+most+of+the+Amazon+basin+of+South+America.+This+basin+encompasses+7%2C000%2C000+square+kilometres+%282%2C700%2C000+sq+mi%29%2C+of+which+5%2C500%2C000+square+kilometres+%282%2C100%2C000+sq+mi%29+are+covered+by+the+rainforest.+This+region+includes+territory+belonging+to+nine+nations.+The+majority+of+the+forest+is+contained+within+Brazil%2C+with+60%25+of+the+rainforest%2C+followed+by+Peru+with+13%25%2C+Colombia+with+10%25%2C+and+with+minor+amounts+in+Venezuela%2C+Ecuador%2C+Bolivia%2C+Guyana%2C+Suriname+and+French+Guiana.+States+or+departments+in+four+nations+contain+%22Amazonas%22+in+their+names.+The+Amazon+represents+over+half+of+the+planet%27s+remaining+rainforests%2C+and+comprises+the+largest+and+most+biodiverse+tract+of+tropical+rainforest+in+the+world%2C+with+an+estimated+390+billion+individual+trees+divided+into+16%2C000+species)
<add>- [T5による翻訳](https://huggingface.co/t5-base?text=My+name+is+Wolfgang+and+I+live+in+Berlin)
<add>
<add>コンピュータビジョンにて:
<add>- [ViTによる画像分類](https://huggingface.co/google/vit-base-patch16-224)
<add>- [DETRによる物体検出](https://huggingface.co/facebook/detr-resnet-50)
<add>- [SegFormerによるセマンティックセグメンテーション](https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512)
<add>- [DETRによるパノプティックセグメンテーション](https://huggingface.co/facebook/detr-resnet-50-panoptic)
<add>
<add>オーディオにて:
<add>- [Wav2Vec2による自動音声認識](https://huggingface.co/facebook/wav2vec2-base-960h)
<add>- [Wav2Vec2によるキーワード検索](https://huggingface.co/superb/wav2vec2-base-superb-ks)
<add>
<add>マルチモーダルなタスクにて:
<add>- [ViLTによる視覚的質問応答](https://huggingface.co/dandelin/vilt-b32-finetuned-vqa)
<add>
<add>Hugging Faceチームによって作られた **[トランスフォーマーを使った書き込み](https://transformer.huggingface.co)** は、このリポジトリのテキスト生成機能の公式デモである。
<add>
<add>## Hugging Faceチームによるカスタム・サポートをご希望の場合
<add>
<add><a target="_blank" href="https://huggingface.co/support">
<add> <img alt="HuggingFace Expert Acceleration Program" src="https://cdn-media.huggingface.co/marketing/transformers/new-support-improved.png" style="max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);">
<add></a><br>
<add>
<add>## クイックツアー
<add>
<add>与えられた入力(テキスト、画像、音声、...)に対してすぐにモデルを使うために、我々は`pipeline`というAPIを提供しております。pipelineは、学習済みのモデルと、そのモデルの学習時に使用された前処理をグループ化したものです。以下は、肯定的なテキストと否定的なテキストを分類するためにpipelineを使用する方法です:
<add>
<add>```python
<add>>>> from transformers import pipeline
<add>
<add># Allocate a pipeline for sentiment-analysis
<add>>>> classifier = pipeline('sentiment-analysis')
<add>>>> classifier('We are very happy to introduce pipeline to the transformers repository.')
<add>[{'label': 'POSITIVE', 'score': 0.9996980428695679}]
<add>```
<add>
<add>2行目のコードでは、pipelineで使用される事前学習済みモデルをダウンロードしてキャッシュし、3行目では与えられたテキストに対してそのモデルを評価します。ここでは、答えは99.97%の信頼度で「ポジティブ」です。
<add>
<add>自然言語処理だけでなく、コンピュータビジョンや音声処理においても、多くのタスクにはあらかじめ訓練された`pipeline`が用意されている。例えば、画像から検出された物体を簡単に抽出することができる:
<add>
<add>``` python
<add>>>> import requests
<add>>>> from PIL import Image
<add>>>> from transformers import pipeline
<add>
<add># Download an image with cute cats
<add>>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png"
<add>>>> image_data = requests.get(url, stream=True).raw
<add>>>> image = Image.open(image_data)
<add>
<add># Allocate a pipeline for object detection
<add>>>> object_detector = pipeline('object-detection')
<add>>>> object_detector(image)
<add>[{'score': 0.9982201457023621,
<add> 'label': 'remote',
<add> 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
<add> {'score': 0.9960021376609802,
<add> 'label': 'remote',
<add> 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
<add> {'score': 0.9954745173454285,
<add> 'label': 'couch',
<add> 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
<add> {'score': 0.9988006353378296,
<add> 'label': 'cat',
<add> 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
<add> {'score': 0.9986783862113953,
<add> 'label': 'cat',
<add> 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}]
<add>```
<add>
<add>ここでは、画像から検出されたオブジェクトのリストが得られ、オブジェクトを囲むボックスと信頼度スコアが表示されます。左側が元画像、右側が予測結果を表示したものです:
<add>
<add><h3 align="center">
<add> <a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png" width="400"></a>
<add> <a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample_post_processed.png" width="400"></a>
<add></h3>
<add>
<add>[このチュートリアル](https://huggingface.co/docs/transformers/task_summary)では、`pipeline`APIでサポートされているタスクについて詳しく説明しています。
<add>
<add>`pipeline`に加えて、与えられたタスクに学習済みのモデルをダウンロードして使用するために必要なのは、3行のコードだけです。以下はPyTorchのバージョンです:
<add>```python
<add>>>> from transformers import AutoTokenizer, AutoModel
<add>
<add>>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
<add>>>> model = AutoModel.from_pretrained("bert-base-uncased")
<add>
<add>>>> inputs = tokenizer("Hello world!", return_tensors="pt")
<add>>>> outputs = model(**inputs)
<add>```
<add>
<add>And here is the equivalent code for TensorFlow:
<add>```python
<add>>>> from transformers import AutoTokenizer, TFAutoModel
<add>
<add>>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
<add>>>> model = TFAutoModel.from_pretrained("bert-base-uncased")
<add>
<add>>>> inputs = tokenizer("Hello world!", return_tensors="tf")
<add>>>> outputs = model(**inputs)
<add>```
<add>
<add>トークナイザは学習済みモデルが期待するすべての前処理を担当し、単一の文字列 (上記の例のように) またはリストに対して直接呼び出すことができます。これは下流のコードで使用できる辞書を出力します。また、単純に ** 引数展開演算子を使用してモデルに直接渡すこともできます。
<add>
<add>モデル自体は通常の[Pytorch `nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) または [TensorFlow `tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) (バックエンドによって異なる)で、通常通り使用することが可能です。[このチュートリアル](https://huggingface.co/docs/transformers/training)では、このようなモデルを従来のPyTorchやTensorFlowの学習ループに統合する方法や、私たちの`Trainer`APIを使って新しいデータセットで素早く微調整を行う方法について説明します。
<add>
<add>## なぜtransformersを使う必要があるのでしょうか?
<add>
<add>1. 使いやすい最新モデル:
<add> - 自然言語理解・生成、コンピュータビジョン、オーディオの各タスクで高いパフォーマンスを発揮します。
<add> - 教育者、実務者にとっての低い参入障壁。
<add> - 学習するクラスは3つだけで、ユーザが直面する抽象化はほとんどありません。
<add> - 学習済みモデルを利用するための統一されたAPI。
<add>
<add>1. 低い計算コスト、少ないカーボンフットプリント:
<add> - 研究者は、常に再トレーニングを行うのではなく、トレーニングされたモデルを共有することができます。
<add> - 実務家は、計算時間や生産コストを削減することができます。
<add> - すべてのモダリティにおいて、60,000以上の事前学習済みモデルを持つ数多くのアーキテクチャを提供します。
<add>
<add>1. モデルのライフタイムのあらゆる部分で適切なフレームワークを選択可能:
<add> - 3行のコードで最先端のモデルをトレーニング。
<add> - TF2.0/PyTorch/JAXフレームワーク間で1つのモデルを自在に移動させる。
<add> - 学習、評価、生産に適したフレームワークをシームレスに選択できます。
<add>
<add>1. モデルやサンプルをニーズに合わせて簡単にカスタマイズ可能:
<add> - 原著者が発表した結果を再現するために、各アーキテクチャの例を提供しています。
<add> - モデル内部は可能な限り一貫して公開されています。
<add> - モデルファイルはライブラリとは独立して利用することができ、迅速な実験が可能です。
<add>
<add>## なぜtransformersを使ってはいけないのでしょうか?
<add>
<add>- このライブラリは、ニューラルネットのためのビルディングブロックのモジュール式ツールボックスではありません。モデルファイルのコードは、研究者が追加の抽象化/ファイルに飛び込むことなく、各モデルを素早く反復できるように、意図的に追加の抽象化でリファクタリングされていません。
<add>- 学習APIはどのようなモデルでも動作するわけではなく、ライブラリが提供するモデルで動作するように最適化されています。一般的な機械学習のループには、別のライブラリ(おそらく[Accelerate](https://huggingface.co/docs/accelerate))を使用する必要があります。
<add>- 私たちはできるだけ多くの使用例を紹介するよう努力していますが、[examples フォルダ](https://github.com/huggingface/transformers/tree/main/examples) にあるスクリプトはあくまで例です。あなたの特定の問題に対してすぐに動作するわけではなく、あなたのニーズに合わせるために数行のコードを変更する必要があることが予想されます。
<add>
<add>## インストール
<add>
<add>### pipにて
<add>
<add>このリポジトリは、Python 3.6+, Flax 0.3.2+, PyTorch 1.3.1+, TensorFlow 2.3+ でテストされています。
<add>
<add>🤗Transformersは[仮想環境](https://docs.python.org/3/library/venv.html)にインストールする必要があります。Pythonの仮想環境に慣れていない場合は、[ユーザーガイド](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)を確認してください。
<add>
<add>まず、使用するバージョンのPythonで仮想環境を作成し、アクティベートします。
<add>
<add>その後、Flax, PyTorch, TensorFlowのうち少なくとも1つをインストールする必要があります。
<add>[TensorFlowインストールページ](https://www.tensorflow.org/install/)、[PyTorchインストールページ](https://pytorch.org/get-started/locally/#start-locally)、[Flax](https://github.com/google/flax#quick-install)、[Jax](https://github.com/google/jax#installation)インストールページで、お使いのプラットフォーム別のインストールコマンドを参照してください。
<add>
<add>これらのバックエンドのいずれかがインストールされている場合、🤗Transformersは以下のようにpipを使用してインストールすることができます:
<add>
<add>```bash
<add>pip install transformers
<add>```
<add>
<add>もしサンプルを試したい、またはコードの最先端が必要で、新しいリリースを待てない場合は、[ライブラリをソースからインストール](https://huggingface.co/docs/transformers/installation#installing-from-source)する必要があります。
<add>
<add>### condaにて
<add>
<add>Transformersバージョン4.0.0から、condaチャンネルを搭載しました: `huggingface`。
<add>
<add>🤗Transformersは以下のようにcondaを使って設置することができます:
<add>
<add>```shell script
<add>conda install -c huggingface transformers
<add>```
<add>
<add>Flax、PyTorch、TensorFlowをcondaでインストールする方法は、それぞれのインストールページに従ってください。
<add>
<add>> **_注意:_** Windowsでは、キャッシュの恩恵を受けるために、デベロッパーモードを有効にするよう促されることがあります。このような場合は、[このissue](https://github.com/huggingface/huggingface_hub/issues/1062)でお知らせください。
<add>
<add>## モデルアーキテクチャ
<add>
<add>🤗Transformersが提供する **[全モデルチェックポイント](https://huggingface.co/models)** は、[ユーザー](https://huggingface.co/users)や[組織](https://huggingface.co/organizations)によって直接アップロードされるhuggingface.co [model hub](https://huggingface.co)からシームレスに統合されています。
<add>
<add>現在のチェックポイント数: 
<add>
<add>🤗Transformersは現在、以下のアーキテクチャを提供しています(それぞれのハイレベルな要約は[こちら](https://huggingface.co/docs/transformers/model_summary)を参照してください):
<add>
<add>1. **[ALBERT](https://huggingface.co/docs/transformers/model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
<add>1. **[BART](https://huggingface.co/docs/transformers/model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
<add>1. **[BARThez](https://huggingface.co/docs/transformers/model_doc/barthez)** (from École polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
<add>1. **[BARTpho](https://huggingface.co/docs/transformers/model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
<add>1. **[BEiT](https://huggingface.co/docs/transformers/model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
<add>1. **[BERT](https://huggingface.co/docs/transformers/model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
<add>1. **[BERT For Sequence Generation](https://huggingface.co/docs/transformers/model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
<add>1. **[BERTweet](https://huggingface.co/docs/transformers/model_doc/bertweet)** (from VinAI Research) released with the paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen.
<add>1. **[BigBird-Pegasus](https://huggingface.co/docs/transformers/model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
<add>1. **[BigBird-RoBERTa](https://huggingface.co/docs/transformers/model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
<add>1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
<add>1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
<add>1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (from BigScience workshop) released by the [BigSicence Workshop](https://bigscience.huggingface.co/).
<add>1. **[BORT](https://huggingface.co/docs/transformers/model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
<add>1. **[ByT5](https://huggingface.co/docs/transformers/model_doc/byt5)** (from Google Research) released with the paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
<add>1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
<add>1. **[CANINE](https://huggingface.co/docs/transformers/model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
<add>1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
<add>1. **[CodeGen](https://huggingface.co/docs/transformers/model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
<add>1. **[Conditional DETR](https://huggingface.co/docs/transformers/model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
<add>1. **[ConvBERT](https://huggingface.co/docs/transformers/model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
<add>1. **[ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
<add>1. **[CPM](https://huggingface.co/docs/transformers/model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun.
<add>1. **[CTRL](https://huggingface.co/docs/transformers/model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
<add>1. **[CvT](https://huggingface.co/docs/transformers/model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
<add>1. **[Data2Vec](https://huggingface.co/docs/transformers/model_doc/data2vec)** (from Facebook) released with the paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
<add>1. **[DeBERTa](https://huggingface.co/docs/transformers/model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
<add>1. **[DeBERTa-v2](https://huggingface.co/docs/transformers/model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
<add>1. **[Decision Transformer](https://huggingface.co/docs/transformers/model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
<add>1. **[Deformable DETR](https://huggingface.co/docs/transformers/model_doc/deformable_detr)** (from SenseTime Research) released with the paper [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
<add>1. **[DeiT](https://huggingface.co/docs/transformers/model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
<add>1. **[DETR](https://huggingface.co/docs/transformers/model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
<add>1. **[DialoGPT](https://huggingface.co/docs/transformers/model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
<add>1. **[DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
<add>1. **[DiT](https://huggingface.co/docs/transformers/model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
<add>1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
<add>1. **[DPR](https://huggingface.co/docs/transformers/model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
<add>1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
<add>1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
<add>1. **[EncoderDecoder](https://huggingface.co/docs/transformers/model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
<add>1. **[ERNIE](https://huggingface.co/docs/transformers/model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
<add>1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2** was released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
<add>1. **[FLAN-T5](https://huggingface.co/docs/transformers/main/model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
<add>1. **[FlauBERT](https://huggingface.co/docs/transformers/model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
<add>1. **[FLAVA](https://huggingface.co/docs/transformers/model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
<add>1. **[FNet](https://huggingface.co/docs/transformers/model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
<add>1. **[Funnel Transformer](https://huggingface.co/docs/transformers/model_doc/funnel)** (from CMU/Google Brain) released with the paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
<add>1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
<add>1. **[GPT](https://huggingface.co/docs/transformers/model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
<add>1. **[GPT Neo](https://huggingface.co/docs/transformers/model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
<add>1. **[GPT NeoX](https://huggingface.co/docs/transformers/model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745) by Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, Samuel Weinbach
<add>1. **[GPT NeoX Japanese](https://huggingface.co/docs/transformers/model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
<add>1. **[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
<add>1. **[GPT-J](https://huggingface.co/docs/transformers/model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki.
<add>1. **[GroupViT](https://huggingface.co/docs/transformers/model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
<add>1. **[Hubert](https://huggingface.co/docs/transformers/model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
<add>1. **[I-BERT](https://huggingface.co/docs/transformers/model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
<add>1. **[ImageGPT](https://huggingface.co/docs/transformers/model_doc/imagegpt)** (from OpenAI) released with the paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
<add>1. **[LayoutLM](https://huggingface.co/docs/transformers/model_doc/layoutlm)** (from Microsoft Research Asia) released with the paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
<add>1. **[LayoutLMv2](https://huggingface.co/docs/transformers/model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
<add>1. **[LayoutLMv3](https://huggingface.co/docs/transformers/model_doc/layoutlmv3)** (from Microsoft Research Asia) released with the paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
<add>1. **[LayoutXLM](https://huggingface.co/docs/transformers/model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
<add>1. **[LED](https://huggingface.co/docs/transformers/model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
<add>1. **[LeViT](https://huggingface.co/docs/transformers/model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
<add>1. **[LiLT](https://huggingface.co/docs/transformers/main/model_doc/lilt)** (from South China University of Technology) released with the paper [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
<add>1. **[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
<add>1. **[LongT5](https://huggingface.co/docs/transformers/model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
<add>1. **[LUKE](https://huggingface.co/docs/transformers/model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
<add>1. **[LXMERT](https://huggingface.co/docs/transformers/model_doc/lxmert)** (from UNC Chapel Hill) released with the paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
<add>1. **[M-CTC-T](https://huggingface.co/docs/transformers/model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
<add>1. **[M2M100](https://huggingface.co/docs/transformers/model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
<add>1. **[MarianMT](https://huggingface.co/docs/transformers/model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team.
<add>1. **[MarkupLM](https://huggingface.co/docs/transformers/model_doc/markuplm)** (from Microsoft Research Asia) released with the paper [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding](https://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
<add>1. **[MaskFormer](https://huggingface.co/docs/transformers/model_doc/maskformer)** (from Meta and UIUC) released with the paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
<add>1. **[mBART](https://huggingface.co/docs/transformers/model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
<add>1. **[mBART-50](https://huggingface.co/docs/transformers/model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
<add>1. **[Megatron-BERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
<add>1. **[Megatron-GPT2](https://huggingface.co/docs/transformers/model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
<add>1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
<add>1. **[MobileBERT](https://huggingface.co/docs/transformers/model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
<add>1. **[MobileViT](https://huggingface.co/docs/transformers/model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
<add>1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
<add>1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
<add>1. **[MVP](https://huggingface.co/docs/transformers/model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
<add>1. **[Nezha](https://huggingface.co/docs/transformers/model_doc/nezha)** (from Huawei Noah’s Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
<add>1. **[NLLB](https://huggingface.co/docs/transformers/model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
<add>1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
<add>1. **[OPT](https://huggingface.co/docs/transformers/master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
<add>1. **[OWL-ViT](https://huggingface.co/docs/transformers/model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby.
<add>1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
<add>1. **[PEGASUS-X](https://huggingface.co/docs/transformers/model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
<add>1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira.
<add>1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen.
<add>1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
<add>1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng.
<add>1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
<add>1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
<add>1. **[RAG](https://huggingface.co/docs/transformers/model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela.
<add>1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
<add>1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
<add>1. **[RegNet](https://huggingface.co/docs/transformers/model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár.
<add>1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
<add>1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
<add>1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
<add>1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
<add>1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
<add>1. **[SEW](https://huggingface.co/docs/transformers/model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
<add>1. **[SEW-D](https://huggingface.co/docs/transformers/model_doc/sew_d)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
<add>1. **[SpeechToTextTransformer](https://huggingface.co/docs/transformers/model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
<add>1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
<add>1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
<add>1. **[SqueezeBERT](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
<add>1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
<add>1. **[Swin Transformer V2](https://huggingface.co/docs/transformers/model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/2111.09883) by Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo.
<add>1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
<add>1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
<add>1. **[Table Transformer](https://huggingface.co/docs/transformers/main/model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
<add>1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos.
<add>1. **[TAPEX](https://huggingface.co/docs/transformers/model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
<add>1. **[Time Series Transformer](https://huggingface.co/docs/transformers/model_doc/time_series_transformer)** (from HuggingFace).
<add>1. **[Trajectory Transformer](https://huggingface.co/docs/transformers/model_doc/trajectory_transformers)** (from the University of California at Berkeley) released with the paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
<add>1. **[Transformer-XL](https://huggingface.co/docs/transformers/model_doc/transfo-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
<add>1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
<add>1. **[UL2](https://huggingface.co/docs/transformers/model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
<add>1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
<add>1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
<add>1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
<add>1. **[VideoMAE](https://huggingface.co/docs/transformers/model_doc/videomae)** (from Multimedia Computing Group, Nanjing University) released with the paper [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
<add>1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
<add>1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
<add>1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
<add>1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick.
<add>1. **[ViTMSN](https://huggingface.co/docs/transformers/model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
<add>1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
<add>1. **[Wav2Vec2-Conformer](https://huggingface.co/docs/transformers/model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
<add>1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
<add>1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei.
<add>1. **[Whisper](https://huggingface.co/docs/transformers/model_doc/whisper)** (from OpenAI) released with the paper [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.
<add>1. **[X-CLIP](https://huggingface.co/docs/transformers/model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
<add>1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li.
<add>1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
<add>1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
<add>1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
<add>1. **[XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/model_doc/xlm-roberta-xl)** (from Facebook AI), released together with the paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
<add>1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (from Google/CMU) released with the paper [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
<add>1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli.
<add>1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
<add>1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
<add>1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
<add>1. 新しいモデルを投稿したいですか?新しいモデルを追加するためのガイドとして、**詳細なガイドとテンプレート**が追加されました。これらはリポジトリの[`templates`](./templates)フォルダにあります。PRを始める前に、必ず[コントリビューションガイド](./CONTRIBUTING.md)を確認し、メンテナに連絡するか、フィードバックを収集するためにissueを開いてください。
<add>
<add>各モデルがFlax、PyTorch、TensorFlowで実装されているか、🤗Tokenizersライブラリに支えられた関連トークナイザを持っているかは、[この表](https://huggingface.co/docs/transformers/index#supported-frameworks)を参照してください。
<add>
<add>これらの実装はいくつかのデータセットでテストされており(サンプルスクリプトを参照)、オリジナルの実装の性能と一致するはずである。性能の詳細は[documentation](https://github.com/huggingface/transformers/tree/main/examples)のExamplesセクションで見ることができます。
<add>
<add>
<add>## さらに詳しく
<add>
<add>| セクション | 概要 |
<add>|-|-|
<add>| [ドキュメント](https://huggingface.co/docs/transformers/) | 完全なAPIドキュメントとチュートリアル |
<add>| [タスク概要](https://huggingface.co/docs/transformers/task_summary) | 🤗Transformersがサポートするタスク |
<add>| [前処理チュートリアル](https://huggingface.co/docs/transformers/preprocessing) | モデル用のデータを準備するために`Tokenizer`クラスを使用 |
<add>| [トレーニングと微調整](https://huggingface.co/docs/transformers/training) | PyTorch/TensorFlowの学習ループと`Trainer`APIで🤗Transformersが提供するモデルを使用 |
<add>| [クイックツアー: 微調整/使用方法スクリプト](https://github.com/huggingface/transformers/tree/main/examples) | 様々なタスクでモデルの微調整を行うためのスクリプト例 |
<add>| [モデルの共有とアップロード](https://huggingface.co/docs/transformers/model_sharing) | 微調整したモデルをアップロードしてコミュニティで共有する |
<add>| [マイグレーション](https://huggingface.co/docs/transformers/migration) | `pytorch-transformers`または`pytorch-pretrained-bert`から🤗Transformers に移行する |
<add>
<add>## 引用
<add>
<add>🤗 トランスフォーマーライブラリに引用できる[論文](https://www.aclweb.org/anthology/2020.emnlp-demos.6/)が出来ました:
<add>```bibtex
<add>@inproceedings{wolf-etal-2020-transformers,
<add> title = "Transformers: State-of-the-Art Natural Language Processing",
<add> author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
<add> booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
<add> month = oct,
<add> year = "2020",
<add> address = "Online",
<add> publisher = "Association for Computational Linguistics",
<add> url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
<add> pages = "38--45"
<add>}
<add>```
<ide><path>README_ko.md
<ide> limitations under the License.
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hans.md">简体中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hant.md">繁體中文</a> |
<ide> <b>한국어</b> |
<del> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ja.md">日本語</a>
<ide> <p>
<ide> </h4>
<ide>
<ide><path>README_zh-hans.md
<ide> checkpoint: 检查点
<ide> <b>简体中文</b> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hant.md">繁體中文</a> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_ko.md">한국어</a> |
<del> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ja.md">日本語</a>
<ide> <p>
<ide> </h4>
<ide>
<ide><path>README_zh-hant.md
<ide> user: 使用者
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_zh-hans.md">简体中文</a> |
<ide> <b>繁體中文</b> |
<ide> <a href="https://github.com/huggingface/transformers/blob/main/README_ko.md">한국어</a> |
<del> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a>
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_es.md">Español</a> |
<add> <a href="https://github.com/huggingface/transformers/blob/main/README_ja.md">日本語</a>
<ide> <p>
<ide> </h4>
<ide>
<ide><path>utils/check_copies.py
<ide> " {paper_authors}.{supplements}"
<ide> ),
<ide> },
<add> "README_ja.md": {
<add> "start_prompt": "🤗Transformersは現在、以下のアーキテクチャを提供しています",
<add> "end_prompt": "1. 新しいモデルを投稿したいですか?",
<add> "format_model_list": (
<add> "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by"
<add> " {paper_authors}.{supplements}"
<add> ),
<add> },
<ide> }
<ide>
<ide> | 7 |
PHP | PHP | fix lint error | 4eb433522250ae5d0fb820e38de95a422ccb0242 | <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> use Cake\View\Helper\HtmlHelper;
<ide> use Cake\View\View;
<ide>
<del>
<ide> /**
<ide> * HtmlHelperTest class
<ide> * | 1 |
Ruby | Ruby | remove unused command_args | 77728abbfc4c913ed91856e8c33d0911db0dc486 | <ide><path>Library/Homebrew/cask/lib/hbc/utils.rb
<ide> def self.gain_permissions_remove(path, command: SystemCommand)
<ide> p.rmtree
<ide> else
<ide> command.run("/bin/rm",
<del> args: command_args + ["-r", "-f", "--", p],
<add> args: ["-r", "-f", "--", p],
<ide> sudo: true)
<ide> end
<ide> end | 1 |
Go | Go | use mount to determine the cgroup mountpoint | f3e89fae287778cb8b7056e228170e0073c9a046 | <ide><path>runtime.go
<ide> func NewRuntime() (*Runtime, error) {
<ide> log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
<ide> }
<ide>
<del> _, err1 := ioutil.ReadFile("/sys/fs/cgroup/memory/memory.limit_in_bytes")
<del> _, err2 := ioutil.ReadFile("/sys/fs/cgroup/memory/memory.soft_limit_in_bytes")
<add> cgroupMemoryMountpoint, err := FindCgroupMountpoint("memory")
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> _, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "/memory.limit_in_bytes"))
<add> _, err2 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.soft_limit_in_bytes"))
<ide> runtime.capabilities.MemoryLimit = err1 == nil && err2 == nil
<ide>
<del> _, err = ioutil.ReadFile("/sys/fs/cgroup/memory/memeory.memsw.limit_in_bytes")
<add> _, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memeory.memsw.limit_in_bytes"))
<ide> runtime.capabilities.SwapLimit = err == nil
<ide>
<ide> return runtime, nil
<ide><path>utils.go
<ide> import (
<ide> "os"
<ide> "os/exec"
<ide> "path/filepath"
<add> "regexp"
<ide> "runtime"
<ide> "strconv"
<ide> "strings"
<ide> func CompareKernelVersion(a, b *KernelVersionInfo) int {
<ide> }
<ide> return 0
<ide> }
<add>
<add>func FindCgroupMountpoint(cgroupType string) (string, error) {
<add> output, err := exec.Command("mount").CombinedOutput()
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> reg := regexp.MustCompile(`^cgroup on (.*) type cgroup \(.*` + cgroupType + `[,\)]`)
<add> for _, line := range strings.Split(string(output), "\n") {
<add> r := reg.FindStringSubmatch(line)
<add> if len(r) == 2 {
<add> return r[1], nil
<add> }
<add> fmt.Printf("line: %s (%d)\n", line, len(r))
<add> }
<add> return "", fmt.Errorf("cgroup mountpoint not found")
<add>} | 2 |
PHP | PHP | add test for between validation rule | 6fb604f43a5f2dbce928c704532fde291f313416 | <ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateBetween()
<ide> $v = new Validator($trans, ['foo' => '123'], ['foo' => 'Numeric|Between:50,100']);
<ide> $this->assertFalse($v->passes());
<ide>
<add> // inclusive on min
<add> $v = new Validator($trans, ['foo' => '123'], ['foo' => 'Numeric|Between:123,200']);
<add> $this->assertTrue($v->passes());
<add>
<add> // inclusive on max
<add> $v = new Validator($trans, ['foo' => '123'], ['foo' => 'Numeric|Between:0,123']);
<add> $this->assertTrue($v->passes());
<add>
<add> // can work with float
<add> $v = new Validator($trans, ['foo' => '0.02'], ['foo' => 'Numeric|Between:0.01,0.02']);
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, ['foo' => '0.02'], ['foo' => 'Numeric|Between:0.01,0.03']);
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, ['foo' => '0.001'], ['foo' => 'Numeric|Between:0.01,0.03']);
<add> $this->assertFalse($v->passes());
<add>
<ide> $v = new Validator($trans, ['foo' => '3'], ['foo' => 'Numeric|Between:1,5']);
<ide> $this->assertTrue($v->passes());
<ide> | 1 |
Python | Python | simplify bidirectional test | 7c5057b42c63337446dc4eb79c433a216520864d | <ide><path>tests/keras/layers/wrappers_test.py
<ide> def test_Bidirectional():
<ide> model.compile(loss='mse', optimizer='sgd')
<ide> model.fit(x, y, epochs=1, batch_size=1)
<ide>
<del> # test with functional API
<del> inputs = Input((timesteps, dim))
<del> outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate,
<del> recurrent_dropout=dropout_rate),
<del> merge_mode=mode)(inputs)
<del> model = Model(inputs, outputs)
<del> model.compile(loss='mse', optimizer='sgd')
<del> model.fit(x, y, epochs=1, batch_size=1)
<del>
<ide> # Bidirectional and stateful
<ide> inputs = Input(batch_shape=(1, timesteps, dim))
<ide> outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), | 1 |
PHP | PHP | fix falling test on windows | 1c31727543b4708bae3178e504b1aadfb3b0af5b | <ide><path>tests/TestCase/Shell/PluginAssetsShellTest.php
<ide> public function testSymlinkWhenVendorDirectoryExits() {
<ide> $this->shell->symlink();
<ide> $path = WWW_ROOT . 'company' . DS . 'test_plugin_three';
<ide> $link = new \SplFileInfo($path);
<del> $this->assertTrue($link->isLink());
<add> if (DIRECTORY_SEPARATOR === '\\') {
<add> $this->assertTrue($link->isDir());
<add> } else {
<add> $this->assertTrue($link->isLink());
<add> }
<ide> $this->assertTrue(file_exists($path . DS . 'css' . DS . 'company.css'));
<ide> $folder = new Folder(WWW_ROOT . 'company');
<ide> $folder->delete(); | 1 |
Ruby | Ruby | increase default max_iterations | b7a43604331fb8a7c8ba2b42d1caccb1d3eb97f9 | <ide><path>Library/Homebrew/utils/curl.rb
<ide> def http_status_ok?(status)
<ide> # @return [Hash] A hash containing an array of response hashes and the body
<ide> # content, if found.
<ide> sig { params(output: String, max_iterations: Integer).returns(T::Hash[Symbol, T.untyped]) }
<del> def parse_curl_output(output, max_iterations: 5)
<add> def parse_curl_output(output, max_iterations: 25)
<ide> responses = []
<ide>
<ide> iterations = 0 | 1 |
PHP | PHP | apply fixes from styleci | 9111e0eaace063a96ff6321618bbf23e7267599e | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> namespace Illuminate\Routing;
<ide>
<ide> use Closure;
<del>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Contracts\Routing\UrlRoutable;
<del>use Illuminate\Routing\Exceptions\UrlGenerationException;
<ide> use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
<ide>
<ide> class UrlGenerator implements UrlGeneratorContract
<ide> protected function extractQueryString($path)
<ide> if (($queryPosition = strpos($path, '?')) !== false) {
<ide> return [
<ide> substr($path, 0, $queryPosition),
<del> substr($path, $queryPosition)
<add> substr($path, $queryPosition),
<ide> ];
<ide> }
<ide> | 1 |
Ruby | Ruby | extract the value casting to a method | 2b60a6b664606b0b52851ff811231728b7c65032 | <ide><path>activerecord/lib/active_record/connection_adapters/connection_specification.rb
<ide> def connection_url_to_hash(url) # :nodoc:
<ide> :port => config.port,
<ide> :database => config.path.sub(%r{^/},""),
<ide> :host => config.host }
<add>
<ide> spec.reject!{ |_,value| value.blank? }
<add>
<ide> uri_parser = URI::Parser.new
<add>
<ide> spec.map { |key,value| spec[key] = uri_parser.unescape(value) if value.is_a?(String) }
<add>
<ide> if config.query
<ide> options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
<del> # If anything looks numeric, make it numeric (e.g. pool count, timeout values, etc.)
<del> options.map do |key,value|
<del> options[key] = case value
<del> when SIMPLE_INT
<del> value.to_i
<del> when SIMPLE_FLOAT
<del> value.to_f
<del> when 'true'
<del> true
<del> when 'false'
<del> false
<del> else
<del> value
<del> end
<del> end
<add>
<add> options.each { |key, value| options[key] = type_cast_value(value) }
<add>
<ide> spec.merge!(options)
<ide> end
<add>
<ide> spec
<ide> end
<add>
<add> def type_cast_value(value)
<add> case value
<add> when SIMPLE_INT
<add> value.to_i
<add> when SIMPLE_FLOAT
<add> value.to_f
<add> when 'true'
<add> true
<add> when 'false'
<add> false
<add> else
<add> value
<add> end
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Mixed | Javascript | fix pbr material order | 5e204c261f4dd697c0509ab903c6ef320c450618 | <ide><path>threejs/lessons/resources/threejs-materials.js
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> const material = new MatCtor({
<ide> color,
<ide> roughness: r / (numRough - 1),
<del> metalness: m / (numMetal - 1),
<add> metalness: 1 - m / (numMetal - 1),
<ide> });
<ide> const mesh = new THREE.Mesh(highPolySphereGeometry, material);
<ide> row.push(mesh);
<ide><path>threejs/lessons/threejs-materials.md
<ide> have hard reflections whereas something that's not rough, like a billiard ball,
<ide> is very shiny. Roughness goes from 0 to 1.
<ide>
<ide> The other setting, [`metalness`](MeshStandardMaterial.metalness), says
<del>how metal the material is. Metals behave differently than non-metals. For
<del>some reason this setting is un-intuitive and goes from 1, not metal at all,
<del>to 0, most metal like.
<add>how metal the material is. Metals behave differently than non-metals. 0
<add>for non-metal and 1 for metal.
<ide>
<ide> Here's a quick sample of `MeshStandardMaterial` with `roughness` from 0 to 1
<ide> across and `metalness` from 0 to 1 down. | 2 |
Text | Text | add docs for custom image loaders. | 9afc0f58c4f3120a8e04b03d48973433f335324a | <ide><path>docs/api-reference/next/image.md
<ide> description: Enable Image Optimization with the built-in Image component.
<ide>
<ide> | Version | Changes |
<ide> | --------- | ------------------------ |
<add>| `v10.0.5` | `loader` prop added. |
<ide> | `v10.0.1` | `layout` prop added. |
<ide> | `v10.0.0` | `next/image` introduced. |
<ide>
<ide> Try it out:
<ide> - [Demo the `fill` layout](https://image-component.nextjs.gallery/layout-fill)
<ide> - [Demo background image](https://image-component.nextjs.gallery/background)
<ide>
<add>### loader
<add>
<add>A custom function used to resolve URLs. Defaults to [`images` object in `next.config.js`](/docs/basic-features/image-optimization.md#loader).
<add>
<add>`loader` is a function returning a string, given the following parameters:
<add>
<add>- [`src`](#src)
<add>- [`width`](#width)
<add>- [`quality`](#quality)
<add>
<add>```js
<add>import Image from 'next/image'
<add>
<add>const myLoader = ({ src, width, quality }) => {
<add> return `https://example.com/${src}?w=${width}&q=${quality || 75}`
<add>}
<add>
<add>const MyImage = (props) => {
<add> return (
<add> <Image
<add> loader={myLoader}
<add> src="/me.png"
<add> alt="Picture of the author"
<add> width={500}
<add> height={500}
<add> />
<add> )
<add>}
<add>```
<add>
<ide> ### sizes
<ide>
<ide> A string mapping media queries to device sizes. Defaults to `100vw`.
<ide><path>docs/basic-features/image-optimization.md
<ide> module.exports = {
<ide> }
<ide> ```
<ide>
<del>The following Image Optimization cloud providers are supported:
<add>The following Image Optimization cloud providers are included:
<ide>
<ide> - [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/next.js/image-optimization)
<ide> - [Imgix](https://www.imgix.com): `loader: 'imgix'`
<ide> - [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
<ide> - [Akamai](https://www.akamai.com): `loader: 'akamai'`
<ide> - Default: Works automatically with `next dev`, `next start`, or a custom server
<ide>
<add>If you need a different provider, you can use the [`loader`](/docs/api-reference/next/image.md#loader) prop with `next/image`.
<add>
<ide> ## Caching
<ide>
<ide> The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation. | 2 |
Text | Text | fix typo in http.server.requesttimout docs | 8354ca5fc57765212b33e6aa7f8eebbc370939b3 | <ide><path>doc/api/http.md
<ide> the client.
<ide> If the timeout expires, the server responds with status 408 without
<ide> forwarding the request to the request listener and then closes the connection.
<ide>
<del>It must be set to a non-zero value (e.g. 120 seconds) to proctect against
<add>It must be set to a non-zero value (e.g. 120 seconds) to protect against
<ide> potential Denial-of-Service attacks in case the server is deployed without a
<ide> reverse proxy in front.
<ide> | 1 |
Ruby | Ruby | fix some typo in method names, variables | d745d62616bb2b309c0a805387dae2d4e1814d3f | <ide><path>activesupport/test/core_ext/numeric_ext_test.rb
<ide> def test_chaining_duration_operations
<ide> assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
<ide> end
<ide>
<del> def test_duration_after_convertion_is_no_longer_accurate
<add> def test_duration_after_conversion_is_no_longer_accurate
<ide> assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now)
<ide> assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now)
<ide> assert_equal 30.days.to_i.since(@dtnow), 1.month.to_i.since(@dtnow)
<ide><path>activesupport/test/core_ext/range_ext_test.rb
<ide> def test_should_compare_identical_exclusive
<ide> assert((1...10) === (1...10))
<ide> end
<ide>
<del> def test_should_compare_other_with_exlusive_end
<add> def test_should_compare_other_with_exclusive_end
<ide> assert((1..10) === (1...10))
<ide> end
<ide>
<ide><path>activesupport/test/json/encoding_test.rb
<ide> def test_nested_hash_with_float
<ide> assert_nothing_raised do
<ide> hash = {
<ide> "CHI" => {
<del> :dislay_name => "chicago",
<add> :display_name => "chicago",
<ide> :latitude => 123.234
<ide> }
<ide> }
<ide><path>activesupport/test/rescuable_test.rb
<ide> def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
<ide> assert_equal expected, result
<ide> end
<ide>
<del> def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended
<add> def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended
<ide> expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
<ide> result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
<ide> assert_equal expected, result | 4 |
Go | Go | address initial feedback from pr | de083400b8d7c2074d71a30a92e4f3c8bcd8bad8 | <ide><path>docker/docker.go
<ide> import (
<ide> )
<ide>
<ide> func main() {
<del> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || strings.Contains(selfPath, ".dockerinit") {
<add> if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
<ide> // Running in init mode
<ide> sysinit.SysInit()
<ide> return
<ide><path>execdriver/native/driver.go
<ide> package native
<ide>
<ide> import (
<ide> "encoding/json"
<del> "errors"
<ide> "fmt"
<ide> "github.com/dotcloud/docker/execdriver"
<ide> "github.com/dotcloud/docker/pkg/cgroups"
<ide> const (
<ide> Version = "0.1"
<ide> )
<ide>
<del>var (
<del> ErrNotSupported = errors.New("not supported")
<del>)
<del>
<ide> func init() {
<ide> execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error {
<ide> var (
<ide> func (d *driver) Restore(c *execdriver.Command) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> defer f.Close()
<ide> if _, err := fmt.Fscanf(f, "%d", &nspid); err != nil {
<add> f.Close()
<ide> return err
<ide> }
<add> f.Close()
<add> defer os.Remove(p)
<add>
<ide> proc, err := os.FindProcess(nspid)
<ide> if err != nil {
<ide> return err
<ide><path>integration/runtime_test.go
<ide> func init() {
<ide> os.Setenv("TEST", "1")
<ide>
<ide> // Hack to run sys init during unit testing
<del> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || strings.Contains(selfPath, ".dockerinit") {
<add> if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
<ide> sysinit.SysInit()
<ide> return
<ide> }
<ide><path>pkg/system/setns_linux.go
<ide> package system
<ide>
<ide> import (
<add> "errors"
<add> "fmt"
<add> "runtime"
<ide> "syscall"
<ide> )
<ide>
<add>var (
<add> ErrNotSupportedPlatform = errors.New("platform and architecture is not supported")
<add>)
<add>
<add>// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
<add>//
<add>// We need different setns values for the different platforms and arch
<add>// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
<add>var setNsMap = map[string]uintptr{
<add> "linux/amd64": 308,
<add>}
<add>
<ide> func Setns(fd uintptr, flags uintptr) error {
<del> _, _, err := syscall.RawSyscall(SYS_SETNS, fd, flags, 0)
<add> ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
<add> if !exists {
<add> return ErrNotSupportedPlatform
<add> }
<add> _, _, err := syscall.RawSyscall(ns, fd, flags, 0)
<ide> if err != 0 {
<ide> return err
<ide> }
<ide><path>pkg/system/setns_linux_amd64.go
<del>// +build linux,amd64
<del>
<del>package system
<del>
<del>// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
<del>const (
<del> SYS_SETNS = 308
<del>) | 5 |
Go | Go | fix verbose for partial overlay id | 2e0990f1655d151b741e7f7f78ac55e14398339f | <ide><path>api/server/router/network/network_routes.go
<ide> func (n *networkRouter) getNetwork(ctx context.Context, w http.ResponseWriter, r
<ide> // return the network. Skipped using isMatchingScope because it is true if the scope
<ide> // is not set which would be case if the client API v1.30
<ide> if strings.HasPrefix(nwk.ID, term) || (netconst.SwarmScope == scope) {
<add> // If we have a previous match "backend", return it, we need verbose when enabled
<add> // ex: overlay/partial_ID or name/swarm_scope
<add> if nwv, ok := listByPartialID[nwk.ID]; ok {
<add> nwk = nwv
<add> } else if nwv, ok := listByFullName[nwk.ID]; ok {
<add> nwk = nwv
<add> }
<ide> return httputils.WriteJSON(w, http.StatusOK, nwk)
<ide> }
<ide> }
<ide><path>integration/network/inspect_test.go
<add>package network
<add>
<add>import (
<add> "fmt"
<add> "runtime"
<add> "testing"
<add> "time"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/filters"
<add> "github.com/docker/docker/api/types/swarm"
<add> "github.com/docker/docker/client"
<add> "github.com/docker/docker/integration-cli/daemon"
<add> "github.com/docker/docker/integration-cli/request"
<add> "github.com/gotestyourself/gotestyourself/poll"
<add> "github.com/stretchr/testify/require"
<add> "golang.org/x/net/context"
<add>)
<add>
<add>const defaultSwarmPort = 2477
<add>const dockerdBinary = "dockerd"
<add>
<add>func TestInspectNetwork(t *testing.T) {
<add> defer setupTest(t)()
<add> d := newSwarm(t)
<add> defer d.Stop(t)
<add> client, err := request.NewClientForHost(d.Sock())
<add> require.NoError(t, err)
<add>
<add> overlayName := "overlay1"
<add> networkCreate := types.NetworkCreate{
<add> CheckDuplicate: true,
<add> Driver: "overlay",
<add> }
<add>
<add> netResp, err := client.NetworkCreate(context.Background(), overlayName, networkCreate)
<add> require.NoError(t, err)
<add> overlayID := netResp.ID
<add>
<add> var instances uint64 = 4
<add> serviceName := "TestService"
<add> serviceSpec := swarmServiceSpec(serviceName, instances)
<add> serviceSpec.TaskTemplate.Networks = append(serviceSpec.TaskTemplate.Networks, swarm.NetworkAttachmentConfig{Target: overlayName})
<add>
<add> serviceResp, err := client.ServiceCreate(context.Background(), serviceSpec, types.ServiceCreateOptions{
<add> QueryRegistry: false,
<add> })
<add> require.NoError(t, err)
<add>
<add> pollSettings := func(config *poll.Settings) {
<add> if runtime.GOARCH == "arm" {
<add> config.Timeout = 30 * time.Second
<add> config.Delay = 100 * time.Millisecond
<add> }
<add> }
<add>
<add> serviceID := serviceResp.ID
<add> poll.WaitOn(t, serviceRunningTasksCount(client, serviceID, instances), pollSettings)
<add>
<add> _, _, err = client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{})
<add> require.NoError(t, err)
<add>
<add> // Test inspect verbose with full NetworkID
<add> networkVerbose, err := client.NetworkInspect(context.Background(), overlayID, types.NetworkInspectOptions{
<add> Verbose: true,
<add> })
<add> require.NoError(t, err)
<add> require.True(t, validNetworkVerbose(networkVerbose, serviceName, instances))
<add>
<add> // Test inspect verbose with partial NetworkID
<add> networkVerbose, err = client.NetworkInspect(context.Background(), overlayID[0:11], types.NetworkInspectOptions{
<add> Verbose: true,
<add> })
<add> require.NoError(t, err)
<add> require.True(t, validNetworkVerbose(networkVerbose, serviceName, instances))
<add>
<add> // Test inspect verbose with Network name and swarm scope
<add> networkVerbose, err = client.NetworkInspect(context.Background(), overlayName, types.NetworkInspectOptions{
<add> Verbose: true,
<add> Scope: "swarm",
<add> })
<add> require.NoError(t, err)
<add> require.True(t, validNetworkVerbose(networkVerbose, serviceName, instances))
<add>
<add> err = client.ServiceRemove(context.Background(), serviceID)
<add> require.NoError(t, err)
<add>
<add> poll.WaitOn(t, serviceIsRemoved(client, serviceID), pollSettings)
<add> poll.WaitOn(t, noTasks(client), pollSettings)
<add>
<add> serviceResp, err = client.ServiceCreate(context.Background(), serviceSpec, types.ServiceCreateOptions{
<add> QueryRegistry: false,
<add> })
<add> require.NoError(t, err)
<add>
<add> serviceID2 := serviceResp.ID
<add> poll.WaitOn(t, serviceRunningTasksCount(client, serviceID2, instances), pollSettings)
<add>
<add> err = client.ServiceRemove(context.Background(), serviceID2)
<add> require.NoError(t, err)
<add>
<add> poll.WaitOn(t, serviceIsRemoved(client, serviceID2), pollSettings)
<add> poll.WaitOn(t, noTasks(client), pollSettings)
<add>
<add> err = client.NetworkRemove(context.Background(), overlayID)
<add> require.NoError(t, err)
<add>
<add> poll.WaitOn(t, networkIsRemoved(client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second))
<add>}
<add>
<add>func newSwarm(t *testing.T) *daemon.Swarm {
<add> d := &daemon.Swarm{
<add> Daemon: daemon.New(t, "", dockerdBinary, daemon.Config{
<add> Experimental: testEnv.DaemonInfo.ExperimentalBuild,
<add> }),
<add> // TODO: better method of finding an unused port
<add> Port: defaultSwarmPort,
<add> }
<add> // TODO: move to a NewSwarm constructor
<add> d.ListenAddr = fmt.Sprintf("0.0.0.0:%d", d.Port)
<add>
<add> // avoid networking conflicts
<add> args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"}
<add> d.StartWithBusybox(t, args...)
<add>
<add> require.NoError(t, d.Init(swarm.InitRequest{}))
<add> return d
<add>}
<add>
<add>func swarmServiceSpec(name string, replicas uint64) swarm.ServiceSpec {
<add> return swarm.ServiceSpec{
<add> Annotations: swarm.Annotations{
<add> Name: name,
<add> },
<add> TaskTemplate: swarm.TaskSpec{
<add> ContainerSpec: &swarm.ContainerSpec{
<add> Image: "busybox:latest",
<add> Command: []string{"/bin/top"},
<add> },
<add> },
<add> Mode: swarm.ServiceMode{
<add> Replicated: &swarm.ReplicatedService{
<add> Replicas: &replicas,
<add> },
<add> },
<add> }
<add>}
<add>
<add>func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result {
<add> return func(log poll.LogT) poll.Result {
<add> filter := filters.NewArgs()
<add> filter.Add("service", serviceID)
<add> tasks, err := client.TaskList(context.Background(), types.TaskListOptions{
<add> Filters: filter,
<add> })
<add> switch {
<add> case err != nil:
<add> return poll.Error(err)
<add> case len(tasks) == int(instances):
<add> for _, task := range tasks {
<add> if task.Status.State != swarm.TaskStateRunning {
<add> return poll.Continue("waiting for tasks to enter run state")
<add> }
<add> }
<add> return poll.Success()
<add> default:
<add> return poll.Continue("task count at %d waiting for %d", len(tasks), instances)
<add> }
<add> }
<add>}
<add>
<add>func networkIsRemoved(client client.NetworkAPIClient, networkID string) func(log poll.LogT) poll.Result {
<add> return func(log poll.LogT) poll.Result {
<add> _, err := client.NetworkInspect(context.Background(), networkID, types.NetworkInspectOptions{})
<add> if err == nil {
<add> return poll.Continue("waiting for network %s to be removed", networkID)
<add> }
<add> return poll.Success()
<add> }
<add>}
<add>
<add>func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log poll.LogT) poll.Result {
<add> return func(log poll.LogT) poll.Result {
<add> filter := filters.NewArgs()
<add> filter.Add("service", serviceID)
<add> _, err := client.TaskList(context.Background(), types.TaskListOptions{
<add> Filters: filter,
<add> })
<add> if err == nil {
<add> return poll.Continue("waiting for service %s to be deleted", serviceID)
<add> }
<add> return poll.Success()
<add> }
<add>}
<add>
<add>func noTasks(client client.ServiceAPIClient) func(log poll.LogT) poll.Result {
<add> return func(log poll.LogT) poll.Result {
<add> filter := filters.NewArgs()
<add> tasks, err := client.TaskList(context.Background(), types.TaskListOptions{
<add> Filters: filter,
<add> })
<add> switch {
<add> case err != nil:
<add> return poll.Error(err)
<add> case len(tasks) == 0:
<add> return poll.Success()
<add> default:
<add> return poll.Continue("task count at %d waiting for 0", len(tasks))
<add> }
<add> }
<add>}
<add>
<add>// Check to see if Service and Tasks info are part of the inspect verbose response
<add>func validNetworkVerbose(network types.NetworkResource, service string, instances uint64) bool {
<add> if service, ok := network.Services[service]; ok {
<add> if len(service.Tasks) == int(instances) {
<add> return true
<add> }
<add> }
<add> return false
<add>} | 2 |
Javascript | Javascript | prefer double-quotes over single | b9ffc537e66eddc460b5f0d4f7fbdb1880eac96c | <ide><path>lib/buffer.js
<ide> Buffer.prototype.readDoubleBE = function(offset, noAssert) {
<ide>
<ide> function checkInt(buffer, value, offset, ext, max, min) {
<ide> if ((value % 1) !== 0 || value > max || value < min)
<del> throw TypeError("value is out of bounds");
<add> throw TypeError('value is out of bounds');
<ide> if ((offset % 1) !== 0 || offset < 0)
<del> throw TypeError("offset is not uint");
<add> throw TypeError('offset is not uint');
<ide> if (offset + ext > buffer.length || buffer.length + offset < 0)
<del> throw RangeError("Trying to write outside buffer length");
<add> throw RangeError('Trying to write outside buffer length');
<ide> }
<ide>
<ide> | 1 |
Text | Text | add caveat for network plugins in swarm mode | 9ae64de6143451b0c3a3b2fe368b1c365b10e1a4 | <ide><path>docs/extend/plugins_network.md
<ide> LibNetwork, which shares plugin infrastructure with Engine. Effectively, network
<ide> driver plugins are activated in the same way as other plugins, and use the same
<ide> kind of protocol.
<ide>
<add>## Network driver plugins and swarm mode
<add>
<add>Docker 1.12 adds support for cluster management and orchestration called
<add>[swarm mode](../swarm/index.md). Docker Engine running in swarm mode currently
<add>only supports the built-in overlay driver for networking. Therefore existing
<add>networking plugins will not work in swarm mode.
<add>
<add>When you run Docker Engine outside of swarm mode, all networking plugins that
<add>worked in Docker 1.11 will continue to function normally. They do not require
<add>any modification.
<add>
<ide> ## Using network driver plugins
<ide>
<ide> The means of installing and running a network driver plugin depend on the | 1 |
Text | Text | remove outdated troubleshooting section | d6cc1d175534bc8659723f2e13df87d7f5974d2a | <ide><path>README.md
<ide> React is [BSD licensed](./LICENSE). We also provide an additional [patent grant]
<ide> React documentation is [Creative Commons licensed](./LICENSE-docs).
<ide>
<ide> Examples provided in this repository and in the documentation are [separately licensed](./LICENSE-examples).
<del>
<del>## Troubleshooting
<del>See the [Troubleshooting Guide](https://github.com/facebook/react/wiki/Troubleshooting) | 1 |
Go | Go | fix panic with unix socket | 9d3ec7b39fcf178eaa9aa1482f0a85c257df4408 | <ide><path>commands.go
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea
<ide> if in != nil {
<ide> io.Copy(rwc, in)
<ide> }
<del> if err := rwc.(*net.TCPConn).CloseWrite(); err != nil {
<del> utils.Debugf("Couldn't send EOF: %s\n", err)
<add> if tcpc, ok := rwc.(*net.TCPConn); ok {
<add> if err := tcpc.CloseWrite(); err != nil {
<add> utils.Debugf("Couldn't send EOF: %s\n", err)
<add> }
<add> } else if unixc, ok := rwc.(*net.UnixConn); ok {
<add> if err := unixc.CloseWrite(); err != nil {
<add> utils.Debugf("Couldn't send EOF: %s\n", err)
<add> }
<ide> }
<ide> // Discard errors due to pipe interruption
<ide> return nil | 1 |
PHP | PHP | remove reverse merged properties | d633532bfb392c9da8e8427d0d5fb708d4c32398 | <ide><path>Cake/Test/TestCase/Utility/MergeVariablesTraitTest.php
<ide> public function testMergeVarsWithBoolean() {
<ide> $this->assertEquals(['test'], $object->hasBoolean);
<ide> }
<ide>
<del>/**
<del> * Test that merging reversed works.
<del> *
<del> * @return void
<del> */
<del> public function testMergeVariablesReversed() {
<del> $object = new Grandchild();
<del> $object->mergeVars(['listProperty'], ['reverse' => ['listProperty']]);
<del> $expected = ['Four', 'Five', 'Two', 'Three', 'One'];
<del> $this->assertSame($expected, $object->listProperty);
<del> }
<ide> }
<ide><path>Cake/Utility/MergeVariablesTrait.php
<ide> trait MergeVariablesTrait {
<ide> *
<ide> * - `associative` - A list of properties that should be treated as associative arrays.
<ide> * Properties in this list will be passed through Hash::normalize() before merging.
<del> * - `reverse` - A list of properties that should be merged in reverse. Reverse merging
<del> * allows the parent properties to follow the child classes. Generally this option is only
<del> * useful when merging list properties that need to maintain the child property values
<del> * as the first elements in the merged list.
<ide> *
<ide> * @param array $properties An array of properties and the merge strategy for them.
<ide> * @param array $options The options to use when merging properties.
<ide> protected function _mergeVars($properties, $options = []) {
<ide> */
<ide> protected function _mergeProperty($property, $parentClasses, $options) {
<ide> $thisValue = $this->{$property};
<del> $isAssoc = $isReversed = false;
<add> $isAssoc = false;
<ide> if (
<ide> isset($options['associative']) &&
<ide> in_array($property, (array)$options['associative'])
<ide> ) {
<ide> $isAssoc = true;
<ide> }
<del> if (
<del> isset($options['reverse']) &&
<del> in_array($property, (array)$options['reverse'])
<del> ) {
<del> $isReversed = true;
<del> }
<ide>
<ide> if ($isAssoc) {
<ide> $thisValue = Hash::normalize($thisValue);
<ide> protected function _mergeProperty($property, $parentClasses, $options) {
<ide> if ($isAssoc) {
<ide> $parentProperty = Hash::normalize($parentProperty);
<ide> }
<del> if ($isReversed) {
<del> $thisValue = Hash::merge($thisValue, $parentProperty);
<del> } else {
<del> $thisValue = Hash::merge($parentProperty, $thisValue);
<del> }
<add> $thisValue = Hash::merge($parentProperty, $thisValue);
<ide> }
<ide> $this->{$property} = $thisValue;
<ide> } | 2 |
Text | Text | add 16.5.1 changelog | 7a5eecc07354b3aefc9abbf87df7f732a5160297 | <ide><path>CHANGELOG.md
<ide>
<ide> </details>
<ide>
<add>## 16.5.1 (September 13, 2018)
<add>
<add>### React
<add>
<add>* Improve the warning when `React.forwardRef` receives an unexpected number of arguments. ([@andresroberto](https://github.com/andresroberto) in [#13636](https://github.com/facebook/react/issues/13636))
<add>
<add>### React DOM
<add>
<add>* Fix a regression in unstable exports used by React Native Web. ([@aweary](https://github.com/aweary) in [#13598](https://github.com/facebook/react/issues/13598))
<add>* Fix a crash when component defines a method called `isReactComponent`. ([@gaearon](https://github.com/gaearon) in [#13608](https://github.com/facebook/react/issues/13608))
<add>* Fix a crash in development mode in IE9 when printing a warning. ([@link-alex](https://github.com/link-alex) in [#13620](https://github.com/facebook/react/issues/13620))
<add>* Provide a better error message when running `react-dom/profiling` with `schedule/tracking`. ([@bvaughn](https://github.com/bvaughn) in [#13605](https://github.com/facebook/react/issues/13605))
<add>* If a `ForwardRef` component defines a `displayName`, use it in warnings. ([@probablyup](https://github.com/probablyup) in [#13615](https://github.com/facebook/react/issues/13615))
<add>
<add>### Schedule (Experimental)
<add>
<add>* Add a separate profiling entry point at `schedule/tracking-profiling`. ([@bvaughn](https://github.com/bvaughn) in [#13605](https://github.com/facebook/react/issues/13605))
<add>
<ide> ## 16.5.0 (September 5, 2018)
<ide>
<ide> ### React | 1 |
PHP | PHP | remove unused method | aeac7a45b675810ea10bb419f402d89bdf938ece | <ide><path>src/Mailer/Message.php
<ide> public function getBody(?string $type = null)
<ide> return $this->message;
<ide> }
<ide>
<del> /**
<del> * Get generated message body.
<del> *
<del> * @param string|null $type Use MESSAGE_* constants or null to return the full message as array
<del> * @return string|array String if type is given, array if type is null
<del> * @internal This method is just for backwards compatibility. Use getBody() instead.
<del> */
<del> public function message(?string $type = null)
<del> {
<del> return $this->getBody();
<del> }
<del>
<ide> /**
<ide> * Create unique boundary identifier
<ide> * | 1 |
PHP | PHP | add missing params in docblocks | 3ade2155a2af35964ee99f583f0a30d8ce70cb23 | <ide><path>src/Illuminate/Database/PDO/Connection.php
<ide> public function lastInsertId($name = null)
<ide> /**
<ide> * Create a new statement instance.
<ide> *
<del> * @param \PDOStatement
<add> * @param \PDOStatement $stmt
<ide> * @return \Doctrine\DBAL\Driver\PDO\Statement
<ide> */
<ide> protected function createStatement(PDOStatement $stmt): Statement
<ide><path>src/Illuminate/Database/Schema/SqliteSchemaState.php
<ide> class SqliteSchemaState extends SchemaState
<ide> /**
<ide> * Dump the database's schema into a file.
<ide> *
<del> * @param \Illuminate\Database\Connection
<add> * @param \Illuminate\Database\Connection $connection
<ide> * @param string $path
<ide> * @return void
<ide> */
<ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> public function getApplication()
<ide> /**
<ide> * Set the Laravel application instance.
<ide> *
<del> * @param \Illuminate\Contracts\Foundation\Application
<add> * @param \Illuminate\Contracts\Foundation\Application $app
<ide> * @return $this
<ide> */
<ide> public function setApplication(Application $app)
<ide><path>src/Illuminate/Testing/ParallelConsoleOutput.php
<ide> class ParallelConsoleOutput extends ConsoleOutput
<ide> /**
<ide> * Create a new Parallel ConsoleOutput instance.
<ide> *
<del> * @param \Symfony\Component\Console\Output\OutputInterface
<add> * @param \Symfony\Component\Console\Output\OutputInterface $output
<ide> * @return void
<ide> */
<ide> public function __construct($output) | 4 |
Text | Text | add my weekly focus | c278224bea4c6239f5003953cc601b5af73353b7 | <ide><path>docs/focus/2018-03-12.md
<ide> - Teletype
<ide> - Released [Teletype 0.10.0](https://github.com/atom/teletype/releases/tag/v0.10.0), introducing a streamlined view of your collaborators' avatars inside the editor ([atom/teletype#332](https://github.com/atom/teletype/issues/332))
<ide> - Tree-sitter
<add> - Implemented some optimizations to make Tree-sitter parsers compile faster and produce smaller binaries (https://github.com/tree-sitter/tree-sitter/pull/137) (https://github.com/tree-sitter/tree-sitter/pull/140).
<ide> - Xray
<ide> - Engineering Improvements
<ide> - Begin a more robust solution to locating the correct Python binary [atom/atom#16885](https://github.com/atom/atom/pull/16885) [atom/apm#775](https://github.com/atom/apm/pull/775) [atom/dowsing-rod](https://github.com/atom/dowsing-rod)
<ide> - Open RFC for [streamlining collaboration set-up](https://github.com/atom/atom/blob/3752dca5b032e3b95bb480a6de73bbde41eb821c/docs/focus/README.md#2-streamline-collaboration-set-up)
<ide> - Begin adding support for joining a portal via URL ([atom/teletype#109](https://github.com/atom/teletype/issues/109))
<ide> - Tree-sitter
<add> - Work with Xray team to figure out how Tree-sitter will be used from Xray.
<ide> - Xray
<ide> - Engineering Improvements
<ide> - Reactor Duty | 1 |
Javascript | Javascript | remove debug code | 609842b76cad3e31f29d1c7fe41c116a8d6da81c | <ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide>
<ide> var fn = sh.get("Function");
<ide> fn = this.xref.fetchIfRef(fn);
<del>/*
<del> console.log("x0: "+ x0, "y0: "+ y0, "x1: "+ x1, "y1: "+ y1);
<del> console.log("size: "+ fn.dict.get("Size"));
<del> console.log("BPS: "+ fn.dict.get("BitsPerSample"));
<del> console.log(fn.dict.get("Encode"));
<del> console.log(fn.dict.get("Range"));
<del> console.log(fn.dict.get("Decode"));
<del>*/
<add>
<ide> var gradient = this.ctx.createLinearGradient(x0, y0, x1, y1);
<ide>
<ide> gradient.addColorStop(0, 'rgb(0,0,255)'); | 1 |
PHP | PHP | remove useless full namespace | c6dde96902deee084eb0f42927278efe4dd0e205 | <ide><path>src/Illuminate/Foundation/Providers/SimpleStructureServiceProvider.php
<ide>
<ide> use Illuminate\Support\ServiceProvider;
<ide>
<del>class SimpleStructureServiceProvider extends Illuminate\Support\ServiceProvider {
<add>class SimpleStructureServiceProvider extends ServiceProvider {
<ide>
<ide> /**
<ide> * Register the service provider. | 1 |
Mixed | Go | introduce sandbox entity | fd43ee13238c05266a2626a5281b699f78043a26 | <ide><path>libnetwork/README.md
<ide> There are many networking solutions available to suit a broad range of use-cases
<ide> driverOptions := options.Generic{}
<ide> genericOption := make(map[string]interface{})
<ide> genericOption[netlabel.GenericData] = driverOptions
<del> err := controller.ConfigureNetworkDriver(networkType, genericOption)
<add> err = controller.ConfigureNetworkDriver(networkType, genericOption)
<ide> if err != nil {
<ide> return
<ide> }
<ide>
<ide> // Create a network for containers to join.
<del> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
<add> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
<ide> network, err := controller.NewNetwork(networkType, "network1")
<ide> if err != nil {
<ide> return
<ide> There are many networking solutions available to suit a broad range of use-cases
<ide> return
<ide> }
<ide>
<del> // A container can join the endpoint by providing the container ID to the join
<del> // api.
<del> // Join accepts Variadic arguments which will be made use of by libnetwork and Drivers
<del> err = ep.Join("container1",
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"))
<add> // Create the sandbox for the containr.
<add> sbx, err := controller.NewSandbox("container1",
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"))
<add>
<add> // A sandbox can join the endpoint via the join api.
<add> // Join accepts Variadic arguments which libnetwork and Drivers can use.
<add> err = ep.Join(sbx)
<ide> if err != nil {
<ide> return
<ide> }
<ide><path>libnetwork/api/api.go
<ide> const (
<ide> epNameQr = "{" + urlEpName + ":" + qregx + "}"
<ide> epID = "{" + urlEpID + ":" + regex + "}"
<ide> epPIDQr = "{" + urlEpPID + ":" + qregx + "}"
<del> cnID = "{" + urlCnID + ":" + regex + "}"
<add> sbID = "{" + urlSbID + ":" + regex + "}"
<add> sbPIDQr = "{" + urlSbPID + ":" + qregx + "}"
<add> cnIDQr = "{" + urlCnID + ":" + qregx + "}"
<add> cnPIDQr = "{" + urlCnPID + ":" + qregx + "}"
<ide>
<ide> // Internal URL variable name.They can be anything as
<ide> // long as they do not collide with query fields.
<ide> const (
<ide> urlEpName = "endpoint-name"
<ide> urlEpID = "endpoint-id"
<ide> urlEpPID = "endpoint-partial-id"
<add> urlSbID = "sandbox-id"
<add> urlSbPID = "sandbox-partial-id"
<ide> urlCnID = "container-id"
<add> urlCnPID = "container-partial-id"
<ide>
<ide> // BridgeNetworkDriver is the built-in default for Network Driver
<ide> BridgeNetworkDriver = "bridge"
<ide> func (h *httpHandler) initRouter() {
<ide> {"/services", []string{"partial-id", epPIDQr}, procGetServices},
<ide> {"/services", nil, procGetServices},
<ide> {"/services/" + epID, nil, procGetService},
<del> {"/services/" + epID + "/backend", nil, procGetContainers},
<add> {"/services/" + epID + "/backend", nil, procGetSandbox},
<add> {"/sandboxes", []string{"partial-container-id", cnPIDQr}, procGetSandboxes},
<add> {"/sandboxes", []string{"container-id", cnIDQr}, procGetSandboxes},
<add> {"/sandboxes", []string{"partial-id", sbPIDQr}, procGetSandboxes},
<add> {"/sandboxes", nil, procGetSandboxes},
<add> {"/sandboxes/" + sbID, nil, procGetSandbox},
<ide> },
<ide> "POST": {
<ide> {"/networks", nil, procCreateNetwork},
<ide> {"/networks/" + nwID + "/endpoints", nil, procCreateEndpoint},
<del> {"/networks/" + nwID + "/endpoints/" + epID + "/containers", nil, procJoinEndpoint},
<add> {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes", nil, procJoinEndpoint},
<ide> {"/services", nil, procPublishService},
<ide> {"/services/" + epID + "/backend", nil, procAttachBackend},
<add> {"/sandboxes", nil, procCreateSandbox},
<ide> },
<ide> "DELETE": {
<ide> {"/networks/" + nwID, nil, procDeleteNetwork},
<ide> {"/networks/" + nwID + "/endpoints/" + epID, nil, procDeleteEndpoint},
<del> {"/networks/" + nwID + "/endpoints/" + epID + "/containers/" + cnID, nil, procLeaveEndpoint},
<add> {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes/" + sbID, nil, procLeaveEndpoint},
<ide> {"/services/" + epID, nil, procUnpublishService},
<del> {"/services/" + epID + "/backend/" + cnID, nil, procDetachBackend},
<add> {"/services/" + epID + "/backend/" + sbID, nil, procDetachBackend},
<add> {"/sandboxes/" + sbID, nil, procDeleteSandbox},
<ide> },
<ide> }
<ide>
<ide> func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
<ide> return r
<ide> }
<ide>
<del>func buildContainerResource(ci libnetwork.ContainerInfo) *containerResource {
<del> r := &containerResource{}
<del> if ci != nil {
<del> r.ID = ci.ID()
<add>func buildSandboxResource(sb libnetwork.Sandbox) *sandboxResource {
<add> r := &sandboxResource{}
<add> if sb != nil {
<add> r.ID = sb.ID()
<add> r.Key = sb.Key()
<add> r.ContainerID = sb.ContainerID()
<ide> }
<ide> return r
<ide> }
<ide> func (nc *networkCreate) parseOptions() []libnetwork.NetworkOption {
<ide> return setFctList
<ide> }
<ide>
<del>func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
<del> var setFctList []libnetwork.EndpointOption
<del> if ej.HostName != "" {
<del> setFctList = append(setFctList, libnetwork.JoinOptionHostname(ej.HostName))
<add>func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption {
<add> var setFctList []libnetwork.SandboxOption
<add> if sc.HostName != "" {
<add> setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName))
<ide> }
<del> if ej.DomainName != "" {
<del> setFctList = append(setFctList, libnetwork.JoinOptionDomainname(ej.DomainName))
<add> if sc.DomainName != "" {
<add> setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName))
<ide> }
<del> if ej.HostsPath != "" {
<del> setFctList = append(setFctList, libnetwork.JoinOptionHostsPath(ej.HostsPath))
<add> if sc.HostsPath != "" {
<add> setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath))
<ide> }
<del> if ej.ResolvConfPath != "" {
<del> setFctList = append(setFctList, libnetwork.JoinOptionResolvConfPath(ej.ResolvConfPath))
<add> if sc.ResolvConfPath != "" {
<add> setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath))
<ide> }
<del> if ej.UseDefaultSandbox {
<del> setFctList = append(setFctList, libnetwork.JoinOptionUseDefaultSandbox())
<del> }
<del> if ej.DNS != nil {
<del> for _, d := range ej.DNS {
<del> setFctList = append(setFctList, libnetwork.JoinOptionDNS(d))
<del> }
<add> if sc.UseDefaultSandbox {
<add> setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox())
<ide> }
<del> if ej.ExtraHosts != nil {
<del> for _, e := range ej.ExtraHosts {
<del> setFctList = append(setFctList, libnetwork.JoinOptionExtraHost(e.Name, e.Address))
<add> if sc.DNS != nil {
<add> for _, d := range sc.DNS {
<add> setFctList = append(setFctList, libnetwork.OptionDNS(d))
<ide> }
<ide> }
<del> if ej.ParentUpdates != nil {
<del> for _, p := range ej.ParentUpdates {
<del> setFctList = append(setFctList, libnetwork.JoinOptionParentUpdate(p.EndpointID, p.Name, p.Address))
<add> if sc.ExtraHosts != nil {
<add> for _, e := range sc.ExtraHosts {
<add> setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address))
<ide> }
<ide> }
<ide> return setFctList
<ide> }
<ide>
<add>func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
<add> // priority will go here
<add> return []libnetwork.EndpointOption{}
<add>}
<add>
<ide> /******************
<ide> Process functions
<ide> *******************/
<ide> func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, bod
<ide> return list, &successResponse
<ide> }
<ide>
<add>func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<add> var create sandboxCreate
<add>
<add> err := json.Unmarshal(body, &create)
<add> if err != nil {
<add> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
<add> }
<add>
<add> sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
<add> if err != nil {
<add> return "", convertNetworkError(err)
<add> }
<add>
<add> return sb.ID(), &createdResponse
<add>}
<add>
<ide> /******************
<ide> Network interface
<ide> *******************/
<ide> func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, bo
<ide> return nil, errRsp
<ide> }
<ide>
<del> err = ep.Join(ej.ContainerID, ej.parseOptions()...)
<add> sb, errRsp := findSandbox(c, ej.SandboxID, byID)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add>
<add> err = ep.Join(sb)
<ide> if err != nil {
<ide> return nil, convertNetworkError(err)
<ide> }
<del> return ep.Info().SandboxKey(), &successResponse
<add> return sb.Key(), &successResponse
<ide> }
<ide>
<ide> func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<ide> func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, b
<ide> return nil, errRsp
<ide> }
<ide>
<del> err := ep.Leave(vars[urlCnID])
<add> sb, errRsp := findSandbox(c, vars[urlSbID], byID)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add>
<add> err := ep.Leave(sb)
<ide> if err != nil {
<ide> return nil, convertNetworkError(err)
<ide> }
<ide> func procGetService(c libnetwork.NetworkController, vars map[string]string, body
<ide> return buildEndpointResource(sv), &successResponse
<ide> }
<ide>
<del>func procGetContainers(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<del> epT, epBy := detectEndpointTarget(vars)
<del> sv, errRsp := findService(c, epT, epBy)
<del> if !errRsp.isOK() {
<del> return nil, endpointToService(errRsp)
<del> }
<del> var list []*containerResource
<del> if sv.ContainerInfo() != nil {
<del> list = append(list, buildContainerResource(sv.ContainerInfo()))
<del> }
<del> return list, &successResponse
<del>}
<del>
<ide> func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<ide> var sp servicePublish
<ide>
<ide> func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, b
<ide> return nil, errRsp
<ide> }
<ide>
<del> err = sv.Join(bk.ContainerID, bk.parseOptions()...)
<add> sb, errRsp := findSandbox(c, bk.SandboxID, byID)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add>
<add> err = sv.Join(sb)
<ide> if err != nil {
<ide> return nil, convertNetworkError(err)
<ide> }
<del> return sv.Info().SandboxKey(), &successResponse
<add> return sb.Key(), &successResponse
<ide> }
<ide>
<ide> func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<ide> func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, b
<ide> return nil, errRsp
<ide> }
<ide>
<del> err := sv.Leave(vars[urlCnID])
<add> sb, errRsp := findSandbox(c, vars[urlSbID], byID)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add>
<add> err := sv.Leave(sb)
<add> if err != nil {
<add> return nil, convertNetworkError(err)
<add> }
<add>
<add> return nil, &successResponse
<add>}
<add>
<add>/******************
<add> Sandbox interface
<add>*******************/
<add>func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<add> if epT, ok := vars[urlEpID]; ok {
<add> sv, errRsp := findService(c, epT, byID)
<add> if !errRsp.isOK() {
<add> return nil, endpointToService(errRsp)
<add> }
<add> return buildSandboxResource(sv.Info().Sandbox()), &successResponse
<add> }
<add>
<add> sbT, by := detectSandboxTarget(vars)
<add> sb, errRsp := findSandbox(c, sbT, by)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add> return buildSandboxResource(sb), &successResponse
<add>}
<add>
<add>type cndFnMkr func(string) cndFn
<add>type cndFn func(libnetwork.Sandbox) bool
<add>
<add>// list of (query type, condition function makers) couples
<add>var cndMkrList = []struct {
<add> identifier string
<add> maker cndFnMkr
<add>}{
<add> {urlSbPID, func(id string) cndFn {
<add> return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
<add> }},
<add> {urlCnID, func(id string) cndFn {
<add> return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
<add> }},
<add> {urlCnPID, func(id string) cndFn {
<add> return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
<add> }},
<add>}
<add>
<add>func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
<add> for _, im := range cndMkrList {
<add> if val, ok := vars[im.identifier]; ok {
<add> return im.maker(val)
<add> }
<add> }
<add> return func(sb libnetwork.Sandbox) bool { return true }
<add>}
<add>
<add>func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
<add> return func(sb libnetwork.Sandbox) bool {
<add> if condition(sb) {
<add> *list = append(*list, buildSandboxResource(sb))
<add> }
<add> return false
<add> }
<add>}
<add>
<add>func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<add> var list []*sandboxResource
<add>
<add> cnd := getQueryCondition(vars)
<add> c.WalkSandboxes(sandboxWalker(cnd, &list))
<add>
<add> return list, &successResponse
<add>}
<add>
<add>func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
<add> sbT, by := detectSandboxTarget(vars)
<add>
<add> sb, errRsp := findSandbox(c, sbT, by)
<add> if !errRsp.isOK() {
<add> return nil, errRsp
<add> }
<add>
<add> err := sb.Delete()
<ide> if err != nil {
<ide> return nil, convertNetworkError(err)
<ide> }
<ide> func detectNetworkTarget(vars map[string]string) (string, int) {
<ide> panic("Missing URL variable parameter for network")
<ide> }
<ide>
<add>func detectSandboxTarget(vars map[string]string) (string, int) {
<add> if target, ok := vars[urlSbID]; ok {
<add> return target, byID
<add> }
<add> // vars are populated from the URL, following cannot happen
<add> panic("Missing URL variable parameter for sandbox")
<add>}
<add>
<ide> func detectEndpointTarget(vars map[string]string) (string, int) {
<ide> if target, ok := vars[urlEpName]; ok {
<ide> return target, byName
<ide> func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.N
<ide> return nw, &successResponse
<ide> }
<ide>
<add>func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
<add> var (
<add> sb libnetwork.Sandbox
<add> err error
<add> )
<add>
<add> switch by {
<add> case byID:
<add> sb, err = c.SandboxByID(s)
<add> default:
<add> panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
<add> }
<add> if err != nil {
<add> if _, ok := err.(types.NotFoundError); ok {
<add> return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
<add> }
<add> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
<add> }
<add> return sb, &successResponse
<add>}
<add>
<ide> func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
<ide> nw, errRsp := findNetwork(c, ns, nwBy)
<ide> if !errRsp.isOK() {
<ide><path>libnetwork/api/api_test.go
<ide> func i2nL(i interface{}) []*networkResource {
<ide> return s
<ide> }
<ide>
<del>func i2cL(i interface{}) []*containerResource {
<del> s, ok := i.([]*containerResource)
<add>func i2sb(i interface{}) *sandboxResource {
<add> s, ok := i.(*sandboxResource)
<ide> if !ok {
<del> panic(fmt.Sprintf("Failed i2cL for %v", i))
<add> panic(fmt.Sprintf("Failed i2sb for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2sbL(i interface{}) []*sandboxResource {
<add> s, ok := i.([]*sandboxResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2sbL for %v", i))
<ide> }
<ide> return s
<ide> }
<ide> func TestMain(m *testing.M) {
<ide> os.Exit(m.Run())
<ide> }
<ide>
<del>func TestJoinOptionParser(t *testing.T) {
<add>func TestSandboxOptionParser(t *testing.T) {
<ide> hn := "host1"
<ide> dn := "docker.com"
<ide> hp := "/etc/hosts"
<ide> rc := "/etc/resolv.conf"
<ide> dnss := []string{"8.8.8.8", "172.28.34.5"}
<del> ehs := []endpointExtraHost{endpointExtraHost{Name: "extra1", Address: "172.28.9.1"}, endpointExtraHost{Name: "extra2", Address: "172.28.9.2"}}
<del> pus := []endpointParentUpdate{endpointParentUpdate{EndpointID: "abc123def456", Name: "serv1", Address: "172.28.30.123"}}
<add> ehs := []extraHost{extraHost{Name: "extra1", Address: "172.28.9.1"}, extraHost{Name: "extra2", Address: "172.28.9.2"}}
<ide>
<del> ej := endpointJoin{
<add> sb := sandboxCreate{
<ide> HostName: hn,
<ide> DomainName: dn,
<ide> HostsPath: hp,
<ide> ResolvConfPath: rc,
<ide> DNS: dnss,
<ide> ExtraHosts: ehs,
<del> ParentUpdates: pus,
<ide> UseDefaultSandbox: true,
<ide> }
<ide>
<del> if len(ej.parseOptions()) != 10 {
<del> t.Fatalf("Failed to generate all libnetwork.EndpointJoinOption methods libnetwork.EndpointJoinOption method")
<add> if len(sb.parseOptions()) != 9 {
<add> t.Fatalf("Failed to generate all libnetwork.SandboxOption methods")
<ide> }
<del>
<ide> }
<ide>
<ide> func TestJson(t *testing.T) {
<ide> func TestJson(t *testing.T) {
<ide> t.Fatalf("Incorrect networkCreate after json encoding/deconding: %v", ncp)
<ide> }
<ide>
<del> jl := endpointJoin{ContainerID: "abcdef456789"}
<add> jl := endpointJoin{SandboxID: "abcdef456789"}
<ide> b, err = json.Marshal(jl)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestJson(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if jl.ContainerID != jld.ContainerID {
<add> if jl.SandboxID != jld.SandboxID {
<ide> t.Fatalf("Incorrect endpointJoin after json encoding/deconding: %v", jld)
<ide> }
<ide> }
<ide> func TestAttachDetachBackend(t *testing.T) {
<ide> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<ide> }
<ide>
<del> _, errRsp = procGetContainers(c, vars, nil)
<add> vars[urlEpID] = "db"
<add> _, errRsp = procGetSandbox(c, vars, nil)
<ide> if errRsp.isOK() {
<ide> t.Fatalf("Expected failure. Got %v", errRsp)
<ide> }
<ide> func TestAttachDetachBackend(t *testing.T) {
<ide> }
<ide>
<ide> cid := "abcdefghi"
<del> jl := endpointJoin{ContainerID: cid}
<add> sbox, err := c.NewSandbox(cid)
<add> sid := sbox.ID()
<add> defer sbox.Delete()
<add>
<add> jl := endpointJoin{SandboxID: sid}
<ide> jlb, err := json.Marshal(jl)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestAttachDetachBackend(t *testing.T) {
<ide> t.Fatalf("Unexpected failure, got: %v", errRsp)
<ide> }
<ide>
<del> cli, errRsp := procGetContainers(c, vars, nil)
<add> sli, errRsp := procGetSandboxes(c, vars, nil)
<ide> if errRsp != &successResponse {
<ide> t.Fatalf("Unexpected failure, got: %v", errRsp)
<ide> }
<del> cl := i2cL(cli)
<del> if len(cl) != 1 {
<del> t.Fatalf("Did not find expected number of containers attached to the service: %d", len(cl))
<add> sl := i2sbL(sli)
<add> if len(sl) != 1 {
<add> t.Fatalf("Did not find expected number of sandboxes attached to the service: %d", len(sl))
<ide> }
<del> if cl[0].ID != cid {
<del> t.Fatalf("Did not find expected container attached to the service: %v", cl[0])
<add> if sl[0].ContainerID != cid {
<add> t.Fatalf("Did not find expected sandbox attached to the service: %v", sl[0])
<ide> }
<ide>
<ide> _, errRsp = procUnpublishService(c, vars, nil)
<ide> func TestAttachDetachBackend(t *testing.T) {
<ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<ide> }
<ide>
<del> vars[urlCnID] = cid
<add> vars[urlSbID] = sid
<ide> _, errRsp = procDetachBackend(c, vars, nil)
<ide> if errRsp != &successResponse {
<ide> t.Fatalf("Unexpected failure, got: %v", errRsp)
<ide> }
<ide>
<del> cli, errRsp = procGetContainers(c, vars, nil)
<add> delete(vars, urlEpID)
<add> si, errRsp := procGetSandbox(c, vars, nil)
<ide> if errRsp != &successResponse {
<ide> t.Fatalf("Unexpected failure, got: %v", errRsp)
<ide> }
<del> cl = i2cL(cli)
<del> if len(cl) != 0 {
<del> t.Fatalf("Did not find expected number of containers attached to the service: %d", len(cl))
<add> sb := i2sb(si)
<add> if sb.ContainerID != cid {
<add> t.Fatalf("Did not find expected sandbox. Got %v", sb)
<ide> }
<ide>
<ide> err = ep1.Delete()
<ide> func TestJoinLeave(t *testing.T) {
<ide> }
<ide>
<ide> cid := "abcdefghi"
<del> jl := endpointJoin{ContainerID: cid}
<add> sb, err := c.NewSandbox(cid)
<add> defer sb.Delete()
<add>
<add> jl := endpointJoin{SandboxID: sb.ID()}
<ide> jlb, err := json.Marshal(jl)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestJoinLeave(t *testing.T) {
<ide> vars[urlEpName] = "endpoint"
<ide> key, errRsp := procJoinEndpoint(c, vars, jlb)
<ide> if errRsp != &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<add> t.Fatalf("Unexepected failure, got: %v", errRsp)
<ide> }
<ide>
<ide> keyStr := i2s(key)
<ide> func TestJoinLeave(t *testing.T) {
<ide> t.Fatalf("Expected failure, got: %v", errRsp)
<ide> }
<ide>
<del> vars[urlCnID] = cid
<add> vars[urlSbID] = sb.ID()
<ide> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<ide> if errRsp != &successResponse {
<ide> t.Fatalf("Unexepected failure: %v", errRsp)
<ide> func TestEndToEnd(t *testing.T) {
<ide> if epr.Name != "ep-TwentyTwo" || epr.ID != eid {
<ide> t.Fatalf("Incongruent resource found: %v", epr)
<ide> }
<add>
<add> // Store two container ids and one partial ids
<add> cid1 := "container10010000000"
<add> cid2 := "container20010000000"
<add> chars = []byte(cid1)
<add> cpid1 := string(chars[0 : len(chars)/2])
<add>
<add> // Create sandboxes
<add> sb1, err := json.Marshal(sandboxCreate{ContainerID: cid1})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> lr = newLocalReader(sb1)
<add> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatalf("Empty response body")
<add> }
<add> // Get sandbox id and partial id
<add> var sid1 string
<add> err = json.Unmarshal(rsp.body, &sid1)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> sb2, err := json.Marshal(sandboxCreate{ContainerID: cid2})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> lr = newLocalReader(sb2)
<add> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatalf("Empty response body")
<add> }
<add> // Get sandbox id and partial id
<add> var sid2 string
<add> err = json.Unmarshal(rsp.body, &sid2)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> chars = []byte(sid2)
<add> spid2 := string(chars[0 : len(chars)/2])
<add>
<add> // Query sandboxes
<add> req, err = http.NewRequest("GET", "/sandboxes", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var sbList []*sandboxResource
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) != 2 {
<add> t.Fatalf("Expected 2 elements in list. Got %v", sbList)
<add> }
<add>
<add> // Get sandbox by id
<add> req, err = http.NewRequest("GET", "/sandboxes/"+sid1, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var sbr sandboxResource
<add> err = json.Unmarshal(rsp.body, &sbr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if sbr.ContainerID != cid1 {
<add> t.Fatalf("Incongruent resource found: %v", sbr)
<add> }
<add>
<add> // Query sandbox by partial sandbox id
<add> req, err = http.NewRequest("GET", "/sandboxes?partial-id="+spid2, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatalf("Empty response body")
<add> }
<add> if sbList[0].ID != sid2 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<add>
<add> // Query sandbox by container id
<add> req, err = http.NewRequest("GET", "/sandboxes?container-id="+cid2, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatalf("Empty response body")
<add> }
<add> if sbList[0].ContainerID != cid2 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<add>
<add> // Query sandbox by partial container id
<add> req, err = http.NewRequest("GET", "/sandboxes?partial-container-id="+cpid1, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatalf("Empty response body")
<add> }
<add> if sbList[0].ContainerID != cid1 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<ide> }
<ide>
<ide> type bre struct{}
<ide><path>libnetwork/api/types.go
<ide> type endpointResource struct {
<ide> Network string `json:"network"`
<ide> }
<ide>
<del>// containerResource is the body of "get service backend" response message
<del>type containerResource struct {
<del> ID string `json:"id"`
<add>// sandboxResource is the body of "get service backend" response message
<add>type sandboxResource struct {
<add> ID string `json:"id"`
<add> Key string `json:"key"`
<add> ContainerID string `json:"container_id"`
<ide> // will add more fields once labels change is in
<ide> }
<ide>
<ide> type endpointCreate struct {
<ide> PortMapping []types.PortBinding `json:"port_mapping"`
<ide> }
<ide>
<add>// sandboxCreate is the expected body of the "create sandbox" http request message
<add>type sandboxCreate struct {
<add> ContainerID string `json:"container_id"`
<add> HostName string `json:"host_name"`
<add> DomainName string `json:"domain_name"`
<add> HostsPath string `json:"hosts_path"`
<add> ResolvConfPath string `json:"resolv_conf_path"`
<add> DNS []string `json:"dns"`
<add> ExtraHosts []extraHost `json:"extra_hosts"`
<add> UseDefaultSandbox bool `json:"use_default_sandbox"`
<add>}
<add>
<ide> // endpointJoin represents the expected body of the "join endpoint" or "leave endpoint" http request messages
<ide> type endpointJoin struct {
<del> ContainerID string `json:"container_id"`
<del> HostName string `json:"host_name"`
<del> DomainName string `json:"domain_name"`
<del> HostsPath string `json:"hosts_path"`
<del> ResolvConfPath string `json:"resolv_conf_path"`
<del> DNS []string `json:"dns"`
<del> ExtraHosts []endpointExtraHost `json:"extra_hosts"`
<del> ParentUpdates []endpointParentUpdate `json:"parent_updates"`
<del> UseDefaultSandbox bool `json:"use_default_sandbox"`
<add> SandboxID string `json:"sandbox_id"`
<ide> }
<ide>
<ide> // servicePublish represents the body of the "publish service" http request message
<ide> type servicePublish struct {
<ide> PortMapping []types.PortBinding `json:"port_mapping"`
<ide> }
<ide>
<del>// EndpointExtraHost represents the extra host object
<del>type endpointExtraHost struct {
<add>// extraHost represents the extra host object
<add>type extraHost struct {
<ide> Name string `json:"name"`
<ide> Address string `json:"address"`
<ide> }
<del>
<del>// EndpointParentUpdate is the object carrying the information about the
<del>// endpoint parent that needs to be updated
<del>type endpointParentUpdate struct {
<del> EndpointID string `json:"endpoint_id"`
<del> Name string `json:"name"`
<del> Address string `json:"address"`
<del>}
<ide><path>libnetwork/client/client_test.go
<ide> func TestMain(m *testing.M) {
<ide> }
<ide>
<ide> var callbackFunc func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error)
<del>var mockNwJSON, mockNwListJSON, mockServiceJSON, mockServiceListJSON []byte
<add>var mockNwJSON, mockNwListJSON, mockServiceJSON, mockServiceListJSON, mockSbJSON, mockSbListJSON []byte
<ide> var mockNwName = "test"
<ide> var mockNwID = "2a3456789"
<ide> var mockServiceName = "testSrv"
<ide> var mockServiceID = "2a3456789"
<ide> var mockContainerID = "2a3456789"
<add>var mockSandboxID = "2b3456789"
<ide>
<ide> func setupMockHTTPCallback() {
<ide> var list []networkResource
<ide> func setupMockHTTPCallback() {
<ide> srvList = append(srvList, ep)
<ide> mockServiceListJSON, _ = json.Marshal(srvList)
<ide>
<add> var sbxList []sandboxResource
<add> sb := sandboxResource{ID: mockSandboxID, ContainerID: mockContainerID}
<add> mockSbJSON, _ = json.Marshal(sb)
<add> sbxList = append(sbxList, sb)
<add> mockSbListJSON, _ = json.Marshal(sbxList)
<add>
<ide> dummyHTTPHdr := http.Header{}
<ide>
<ide> callbackFunc = func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
<ide> func setupMockHTTPCallback() {
<ide> rsp = string(mockServiceJSON)
<ide> } else if strings.Contains(path, "containers") {
<ide> return nopCloser{bytes.NewBufferString("")}, dummyHTTPHdr, 400, fmt.Errorf("Bad Request")
<add> } else if strings.Contains(path, fmt.Sprintf("sandboxes?container-id=%s", mockContainerID)) {
<add> rsp = string(mockSbListJSON)
<ide> }
<ide> case "POST":
<ide> var data []byte
<ide> func setupMockHTTPCallback() {
<ide> } else if strings.HasSuffix(path, "services") {
<ide> data, _ = json.Marshal(mockServiceID)
<ide> } else if strings.HasSuffix(path, "backend") {
<del> data, _ = json.Marshal(mockContainerID)
<add> data, _ = json.Marshal(mockSandboxID)
<ide> }
<ide> rsp = string(data)
<ide> case "PUT":
<ide><path>libnetwork/client/service.go
<ide> func lookupContainerID(cli *NetworkCli, cnNameID string) (string, error) {
<ide> return "", fmt.Errorf("Cannot find container ID in json response")
<ide> }
<ide>
<add>func lookupSandboxID(cli *NetworkCli, containerID string) (string, error) {
<add> obj, _, err := readBody(cli.call("GET", fmt.Sprintf("/sandboxes?container-id=%s", containerID), nil, nil))
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> var sandboxList []sandboxResource
<add> err = json.Unmarshal(obj, &sandboxList)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> if len(sandboxList) == 0 {
<add> return "", fmt.Errorf("cannot find sandbox for container: %s", containerID)
<add> }
<add>
<add> return sandboxList[0].ID, nil
<add>}
<add>
<ide> // CmdService handles the service UI
<ide> func (cli *NetworkCli) CmdService(chain string, args ...string) error {
<ide> cmd := cli.Subcmd(chain, "service", "COMMAND [OPTIONS] [arg...]", serviceUsage(chain), false)
<ide> func getBackendID(cli *NetworkCli, servID string) (string, error) {
<ide> )
<ide>
<ide> if obj, _, err = readBody(cli.call("GET", "/services/"+servID+"/backend", nil, nil)); err == nil {
<del> var bkl []backendResource
<add> var bkl []sandboxResource
<ide> if err := json.NewDecoder(bytes.NewReader(obj)).Decode(&bkl); err == nil {
<ide> if len(bkl) > 0 {
<ide> bk = bkl[0].ID
<ide> func (cli *NetworkCli) CmdServiceAttach(chain string, args ...string) error {
<ide> return err
<ide> }
<ide>
<add> sandboxID, err := lookupSandboxID(cli, containerID)
<add> if err != nil {
<add> return err
<add> }
<add>
<ide> sn, nn := parseServiceName(cmd.Arg(1))
<ide> serviceID, err := lookupServiceID(cli, nn, sn)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> nc := serviceAttach{ContainerID: containerID}
<add> nc := serviceAttach{SandboxID: sandboxID}
<ide>
<ide> _, _, err = readBody(cli.call("POST", "/services/"+serviceID+"/backend", nc, nil))
<ide>
<ide><path>libnetwork/client/types.go
<ide> type serviceResource struct {
<ide> Network string `json:"network"`
<ide> }
<ide>
<del>// backendResource is the body of "get service backend" response message
<del>type backendResource struct {
<del> ID string `json:"id"`
<add>// sandboxResource is the body of "get service backend" response message
<add>type sandboxResource struct {
<add> ID string `json:"id"`
<add> Key string `json:"key"`
<add> ContainerID string `json:"container_id"`
<ide> }
<ide>
<ide> /***********
<ide> type serviceCreate struct {
<ide> PortMapping []types.PortBinding `json:"port_mapping"`
<ide> }
<ide>
<del>// serviceAttach represents the expected body of the "attach/detach backend to/from service" http request messages
<add>// serviceAttach represents the expected body of the "attach/detach sandbox to/from service" http request messages
<ide> type serviceAttach struct {
<del> ContainerID string `json:"container_id"`
<del> HostName string `json:"host_name"`
<del> DomainName string `json:"domain_name"`
<del> HostsPath string `json:"hosts_path"`
<del> ResolvConfPath string `json:"resolv_conf_path"`
<del> DNS []string `json:"dns"`
<del> ExtraHosts []serviceExtraHost `json:"extra_hosts"`
<del> ParentUpdates []serviceParentUpdate `json:"parent_updates"`
<del> UseDefaultSandbox bool `json:"use_default_sandbox"`
<add> SandboxID string `json:"sandbox_id"`
<ide> }
<ide>
<del>// serviceExtraHost represents the extra host object
<del>type serviceExtraHost struct {
<add>type sandboxCreate struct {
<add> ContainerID string `json:"container_id"`
<add> HostName string `json:"host_name"`
<add> DomainName string `json:"domain_name"`
<add> HostsPath string `json:"hosts_path"`
<add> ResolvConfPath string `json:"resolv_conf_path"`
<add> DNS []string `json:"dns"`
<add> ExtraHosts []extraHost `json:"extra_hosts"`
<add> UseDefaultSandbox bool `json:"use_default_sandbox"`
<add>}
<add>
<add>// extraHost represents the extra host object
<add>type extraHost struct {
<ide> Name string `json:"name"`
<ide> Address string `json:"address"`
<ide> }
<ide>
<del>// EndpointParentUpdate is the object carrying the information about the
<del>// endpoint parent that needs to be updated
<del>type serviceParentUpdate struct {
<del> EndpointID string `json:"service_id"`
<del> Name string `json:"name"`
<del> Address string `json:"address"`
<add>// sandboxParentUpdate is the object carrying the information about the
<add>// sanbox parent that needs to be updated
<add>type sandboxParentUpdate struct {
<add> ContainerID string `json:"container_id"`
<add> Name string `json:"name"`
<add> Address string `json:"address"`
<ide> }
<ide><path>libnetwork/cmd/ovrouter/ovrouter.go
<ide> import (
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/drivers/overlay"
<ide> "github.com/docker/libnetwork/netlabel"
<del> "github.com/docker/libnetwork/types"
<ide> "github.com/vishvananda/netlink"
<ide> )
<ide>
<ide> func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int,
<ide> return nil
<ide> }
<ide>
<del>func (ep *endpoint) SetHostsPath(string) error {
<del> return nil
<del>}
<del>
<del>func (ep *endpoint) SetResolvConfPath(string) error {
<del> return nil
<del>}
<del>
<ide> func main() {
<ide> if reexec.Init() {
<ide> return
<ide> func main() {
<ide>
<ide> r.d.Config(opt)
<ide>
<del> if err := r.d.CreateNetwork(types.UUID("testnetwork"),
<add> if err := r.d.CreateNetwork("testnetwork",
<ide> map[string]interface{}{}); err != nil {
<ide> fmt.Printf("Failed to create network in the driver: %v\n", err)
<ide> os.Exit(1)
<ide> }
<ide>
<ide> ep := &endpoint{}
<del> if err := r.d.CreateEndpoint(types.UUID("testnetwork"), types.UUID("testep"),
<add> if err := r.d.CreateEndpoint("testnetwork", "testep",
<ide> ep, map[string]interface{}{}); err != nil {
<ide> fmt.Printf("Failed to create endpoint in the driver: %v\n", err)
<ide> os.Exit(1)
<ide> }
<ide>
<del> if err := r.d.Join(types.UUID("testnetwork"), types.UUID("testep"),
<add> if err := r.d.Join("testnetwork", "testep",
<ide> "", ep, map[string]interface{}{}); err != nil {
<ide> fmt.Printf("Failed to join an endpoint in the driver: %v\n", err)
<ide> os.Exit(1)
<ide> func main() {
<ide> for {
<ide> select {
<ide> case <-sigCh:
<del> r.d.Leave(types.UUID("testnetwork"), types.UUID("testep"))
<add> r.d.Leave("testnetwork", "testep")
<ide> overlay.Fini(r.d)
<ide> os.Exit(0)
<ide> }
<ide><path>libnetwork/cmd/readme_test/readme.go
<ide> func main() {
<ide> }
<ide>
<ide> // Create a network for containers to join.
<del> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
<add> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
<ide> network, err := controller.NewNetwork(networkType, "network1")
<ide> if err != nil {
<ide> return
<ide> func main() {
<ide> return
<ide> }
<ide>
<del> // A container can join the endpoint by providing the container ID to the join
<del> // api.
<del> // Join accepts Variadic arguments which will be made use of by libnetwork and Drivers
<del> err = ep.Join("container1",
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"))
<add> // Create the sandbox for the containr.
<add> sbx, err := controller.NewSandbox("container1",
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"))
<add>
<add> // A sandbox can join the endpoint via the join api.
<add> // Join accepts Variadic arguments which libnetwork and Drivers can use.
<add> err = ep.Join(sbx)
<ide> if err != nil {
<ide> return
<ide> }
<ide><path>libnetwork/controller.go
<ide> create network namespaces and allocate interfaces for containers to use.
<ide> package libnetwork
<ide>
<ide> import (
<add> "container/heap"
<ide> "fmt"
<ide> "net"
<ide> "strings"
<ide> import (
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/hostdiscovery"
<ide> "github.com/docker/libnetwork/netlabel"
<del> "github.com/docker/libnetwork/sandbox"
<add> "github.com/docker/libnetwork/osl"
<ide> "github.com/docker/libnetwork/types"
<ide> )
<ide>
<ide> type NetworkController interface {
<ide> // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
<ide> NetworkByID(id string) (Network, error)
<ide>
<del> // LeaveAll accepts a container id and attempts to leave all endpoints that the container has joined
<del> LeaveAll(id string) error
<add> // NewSandbox cretes a new network sandbox for the passed container id
<add> NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
<add>
<add> // Sandboxes returns the list of Sandbox(s) managed by this controller.
<add> Sandboxes() []Sandbox
<add>
<add> // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
<add> WalkSandboxes(walker SandboxWalker)
<add>
<add> // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
<add> SandboxByID(id string) (Sandbox, error)
<ide>
<ide> // GC triggers immediate garbage collection of resources which are garbage collected.
<ide> GC()
<ide> type NetworkController interface {
<ide> // When the function returns true, the walk will stop.
<ide> type NetworkWalker func(nw Network) bool
<ide>
<add>// SandboxWalker is a client provided function which will be used to walk the Sandboxes.
<add>// When the function returns true, the walk will stop.
<add>type SandboxWalker func(sb Sandbox) bool
<add>
<ide> type driverData struct {
<ide> driver driverapi.Driver
<ide> capability driverapi.Capability
<ide> }
<ide>
<ide> type driverTable map[string]*driverData
<del>type networkTable map[types.UUID]*network
<del>type endpointTable map[types.UUID]*endpoint
<del>type sandboxTable map[string]*sandboxData
<add>type networkTable map[string]*network
<add>type endpointTable map[string]*endpoint
<add>type sandboxTable map[string]*sandbox
<ide>
<ide> type controller struct {
<ide> networks networkTable
<ide> func (c *controller) NewNetwork(networkType, name string, options ...NetworkOpti
<ide> network := &network{
<ide> name: name,
<ide> networkType: networkType,
<del> id: types.UUID(stringid.GenerateRandomID()),
<add> id: stringid.GenerateRandomID(),
<ide> ctrlr: c,
<ide> endpoints: endpointTable{},
<ide> }
<ide> func (c *controller) NetworkByID(id string) (Network, error) {
<ide> }
<ide> c.Lock()
<ide> defer c.Unlock()
<del> if n, ok := c.networks[types.UUID(id)]; ok {
<add> if n, ok := c.networks[id]; ok {
<ide> return n, nil
<ide> }
<ide> return nil, ErrNoSuchNetwork(id)
<ide> }
<ide>
<add>// NewSandbox creates a new sandbox for the passed container id
<add>func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
<add> var err error
<add>
<add> if containerID == "" {
<add> return nil, types.BadRequestErrorf("invalid container ID")
<add> }
<add>
<add> var existing Sandbox
<add> look := SandboxContainerWalker(&existing, containerID)
<add> c.WalkSandboxes(look)
<add> if existing != nil {
<add> return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
<add> }
<add>
<add> // Create sandbox and process options first. Key generation depends on an option
<add> sb := &sandbox{
<add> id: stringid.GenerateRandomID(),
<add> containerID: containerID,
<add> endpoints: epHeap{},
<add> epPriority: map[string]int{},
<add> config: containerConfig{},
<add> controller: c,
<add> }
<add> // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
<add> var peerSb Sandbox
<add> c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
<add> if peerSb != nil {
<add> sb.osSbox = peerSb.(*sandbox).osSbox
<add> }
<add>
<add> heap.Init(&sb.endpoints)
<add>
<add> sb.processOptions(options...)
<add>
<add> err = sb.buildHostsFile()
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> err = sb.updateParentHosts()
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> err = sb.setupDNS()
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> if sb.osSbox == nil {
<add> if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
<add> return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
<add> }
<add> }
<add>
<add> c.Lock()
<add> c.sandboxes[sb.id] = sb
<add> c.Unlock()
<add>
<add> return sb, nil
<add>}
<add>
<add>func (c *controller) Sandboxes() []Sandbox {
<add> c.Lock()
<add> defer c.Unlock()
<add>
<add> list := make([]Sandbox, 0, len(c.sandboxes))
<add> for _, s := range c.sandboxes {
<add> list = append(list, s)
<add> }
<add>
<add> return list
<add>}
<add>
<add>func (c *controller) WalkSandboxes(walker SandboxWalker) {
<add> for _, sb := range c.Sandboxes() {
<add> if walker(sb) {
<add> return
<add> }
<add> }
<add>}
<add>
<add>func (c *controller) SandboxByID(id string) (Sandbox, error) {
<add> if id == "" {
<add> return nil, ErrInvalidID(id)
<add> }
<add> c.Lock()
<add> s, ok := c.sandboxes[id]
<add> c.Unlock()
<add> if !ok {
<add> return nil, types.NotFoundErrorf("sandbox %s not found", id)
<add> }
<add> return s, nil
<add>}
<add>
<add>// SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
<add>func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
<add> return func(sb Sandbox) bool {
<add> if sb.ContainerID() == containerID {
<add> *out = sb
<add> return true
<add> }
<add> return false
<add> }
<add>}
<add>
<add>// SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
<add>func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
<add> return func(sb Sandbox) bool {
<add> if sb.Key() == key {
<add> *out = sb
<add> return true
<add> }
<add> return false
<add> }
<add>}
<add>
<ide> func (c *controller) loadDriver(networkType string) (*driverData, error) {
<ide> // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
<ide> // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
<ide> func (c *controller) isDriverGlobalScoped(networkType string) (bool, error) {
<ide> }
<ide>
<ide> func (c *controller) GC() {
<del> sandbox.GC()
<add> osl.GC()
<ide> }
<ide><path>libnetwork/driverapi/driverapi.go
<ide> package driverapi
<ide>
<del>import (
<del> "net"
<del>
<del> "github.com/docker/libnetwork/types"
<del>)
<add>import "net"
<ide>
<ide> // NetworkPluginEndpointType represents the Endpoint Type used by Plugin system
<ide> const NetworkPluginEndpointType = "NetworkDriver"
<ide> type Driver interface {
<ide> // CreateNetwork invokes the driver method to create a network passing
<ide> // the network id and network specific config. The config mechanism will
<ide> // eventually be replaced with labels which are yet to be introduced.
<del> CreateNetwork(nid types.UUID, options map[string]interface{}) error
<add> CreateNetwork(nid string, options map[string]interface{}) error
<ide>
<ide> // DeleteNetwork invokes the driver method to delete network passing
<ide> // the network id.
<del> DeleteNetwork(nid types.UUID) error
<add> DeleteNetwork(nid string) error
<ide>
<ide> // CreateEndpoint invokes the driver method to create an endpoint
<ide> // passing the network id, endpoint id endpoint information and driver
<ide> // specific config. The endpoint information can be either consumed by
<ide> // the driver or populated by the driver. The config mechanism will
<ide> // eventually be replaced with labels which are yet to be introduced.
<del> CreateEndpoint(nid, eid types.UUID, epInfo EndpointInfo, options map[string]interface{}) error
<add> CreateEndpoint(nid, eid string, epInfo EndpointInfo, options map[string]interface{}) error
<ide>
<ide> // DeleteEndpoint invokes the driver method to delete an endpoint
<ide> // passing the network id and endpoint id.
<del> DeleteEndpoint(nid, eid types.UUID) error
<add> DeleteEndpoint(nid, eid string) error
<ide>
<ide> // EndpointOperInfo retrieves from the driver the operational data related to the specified endpoint
<del> EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error)
<add> EndpointOperInfo(nid, eid string) (map[string]interface{}, error)
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del> Join(nid, eid types.UUID, sboxKey string, jinfo JoinInfo, options map[string]interface{}) error
<add> Join(nid, eid string, sboxKey string, jinfo JoinInfo, options map[string]interface{}) error
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del> Leave(nid, eid types.UUID) error
<add> Leave(nid, eid string) error
<ide>
<ide> // Type returns the the type of this driver, the network type this driver manages
<ide> Type() string
<ide> type JoinInfo interface {
<ide> // AddStaticRoute adds a routes to the sandbox.
<ide> // It may be used in addtion to or instead of a default gateway (as above).
<ide> AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP, interfaceID int) error
<del>
<del> // SetHostsPath sets the overriding /etc/hosts path to use for the container.
<del> SetHostsPath(string) error
<del>
<del> // SetResolvConfPath sets the overriding /etc/resolv.conf path to use for the container.
<del> SetResolvConfPath(string) error
<ide> }
<ide>
<ide> // DriverCallback provides a Callback interface for Drivers into LibNetwork
<ide><path>libnetwork/drivers/bridge/bridge.go
<ide> type containerConfiguration struct {
<ide> }
<ide>
<ide> type bridgeEndpoint struct {
<del> id types.UUID
<add> id string
<ide> srcName string
<ide> addr *net.IPNet
<ide> addrv6 *net.IPNet
<ide> type bridgeEndpoint struct {
<ide> }
<ide>
<ide> type bridgeNetwork struct {
<del> id types.UUID
<add> id string
<ide> bridge *bridgeInterface // The bridge's L3 interface
<ide> config *networkConfiguration
<del> endpoints map[types.UUID]*bridgeEndpoint // key: endpoint id
<add> endpoints map[string]*bridgeEndpoint // key: endpoint id
<ide> portMapper *portmapper.PortMapper
<ide> driver *driver // The network's driver
<ide> sync.Mutex
<ide> type driver struct {
<ide> network *bridgeNetwork
<ide> natChain *iptables.ChainInfo
<ide> filterChain *iptables.ChainInfo
<del> networks map[types.UUID]*bridgeNetwork
<add> networks map[string]*bridgeNetwork
<ide> sync.Mutex
<ide> }
<ide>
<ide> func init() {
<ide>
<ide> // New constructs a new bridge driver
<ide> func newDriver() driverapi.Driver {
<del> return &driver{networks: map[types.UUID]*bridgeNetwork{}}
<add> return &driver{networks: map[string]*bridgeNetwork{}}
<ide> }
<ide>
<ide> // Init registers a new instance of bridge driver
<ide> func (n *bridgeNetwork) getNetworkBridgeName() string {
<ide> return config.BridgeName
<ide> }
<ide>
<del>func (n *bridgeNetwork) getEndpoint(eid types.UUID) (*bridgeEndpoint, error) {
<add>func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
<ide> n.Lock()
<ide> defer n.Unlock()
<ide>
<ide> func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) err
<ide> }
<ide>
<ide> // Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
<del>func (c *networkConfiguration) conflictsWithNetworks(id types.UUID, others []*bridgeNetwork) error {
<add>func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
<ide> for _, nw := range others {
<ide>
<ide> nw.Lock()
<ide> func (d *driver) Config(option map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) getNetwork(id types.UUID) (*bridgeNetwork, error) {
<add>func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
<ide> d.Lock()
<ide> defer d.Unlock()
<ide>
<ide> func (d *driver) getNetworks() []*bridgeNetwork {
<ide> }
<ide>
<ide> // Create a new network using bridge plugin
<del>func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
<ide> var err error
<ide>
<ide> // Sanity checks
<ide> func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) err
<ide> // Create and set network handler in driver
<ide> network := &bridgeNetwork{
<ide> id: id,
<del> endpoints: make(map[types.UUID]*bridgeEndpoint),
<add> endpoints: make(map[string]*bridgeEndpoint),
<ide> config: config,
<ide> portMapper: portmapper.New(),
<ide> driver: d,
<ide> func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) err
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<add>func (d *driver) DeleteNetwork(nid string) error {
<ide> var err error
<ide>
<ide> // Get network handler and remove it from driver
<ide> func setHairpinMode(link netlink.Link, enable bool) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<ide> var (
<ide> ipv6Addr *net.IPNet
<ide> err error
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> LinkAttrs: netlink.LinkAttrs{Name: hostIfName, TxQLen: 0},
<ide> PeerName: containerIfName}
<ide> if err = netlink.LinkAdd(veth); err != nil {
<del> return err
<add> return types.InternalErrorf("failed to add the host (%s) <=> sandbox (%s) pair interfaces: %v", hostIfName, containerIfName, err)
<ide> }
<ide>
<ide> // Get the host side pipe interface handler
<ide> host, err := netlink.LinkByName(hostIfName)
<ide> if err != nil {
<del> return err
<add> return types.InternalErrorf("failed to find host side interface %s: %v", hostIfName, err)
<ide> }
<ide> defer func() {
<ide> if err != nil {
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> // Get the sandbox side pipe interface handler
<ide> sbox, err := netlink.LinkByName(containerIfName)
<ide> if err != nil {
<del> return err
<add> return types.InternalErrorf("failed to find sandbox side interface %s: %v", containerIfName, err)
<ide> }
<ide> defer func() {
<ide> if err != nil {
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> if config.Mtu != 0 {
<ide> err = netlink.LinkSetMTU(host, config.Mtu)
<ide> if err != nil {
<del> return err
<add> return types.InternalErrorf("failed to set MTU on host interface %s: %v", hostIfName, err)
<ide> }
<ide> err = netlink.LinkSetMTU(sbox, config.Mtu)
<ide> if err != nil {
<del> return err
<add> return types.InternalErrorf("failed to set MTU on sandbox interface %s: %v", containerIfName, err)
<ide> }
<ide> }
<ide>
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> var err error
<ide>
<ide> // Get the network handler and make sure it exists
<ide> func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> // Get the network handler and make sure it exists
<ide> d.Lock()
<ide> n, ok := d.networks[nid]
<ide> func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{},
<ide> }
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<ide> network, err := d.getNetwork(nid)
<ide> if err != nil {
<ide> return err
<ide> func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinI
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> network, err := d.getNetwork(nid)
<ide> if err != nil {
<ide> return err
<ide> func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, options
<ide> if endpoint.config != nil && endpoint.config.ExposedPorts != nil {
<ide> for _, p := range cc.ParentEndpoints {
<ide> var parentEndpoint *bridgeEndpoint
<del> parentEndpoint, err = network.getEndpoint(types.UUID(p))
<add> parentEndpoint, err = network.getEndpoint(p)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, options
<ide>
<ide> for _, c := range cc.ChildEndpoints {
<ide> var childEndpoint *bridgeEndpoint
<del> childEndpoint, err = network.getEndpoint(types.UUID(c))
<add> childEndpoint, err = network.getEndpoint(c)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>libnetwork/drivers/bridge/bridge_test.go
<ide> func TestCreateMultipleNetworks(t *testing.T) {
<ide> verifyV4INCEntries(dd.networks, 0, t)
<ide> }
<ide>
<del>func verifyV4INCEntries(networks map[types.UUID]*bridgeNetwork, numEntries int, t *testing.T) {
<add>func verifyV4INCEntries(networks map[string]*bridgeNetwork, numEntries int, t *testing.T) {
<ide> out, err := iptables.Raw("-L", "FORWARD")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func (te *testEndpoint) SetGatewayIPv6(gw6 net.IP) error {
<ide> return nil
<ide> }
<ide>
<del>func (te *testEndpoint) SetHostsPath(path string) error {
<del> te.hostsPath = path
<del> return nil
<del>}
<del>
<del>func (te *testEndpoint) SetResolvConfPath(path string) error {
<del> te.resolvConfPath = path
<del> return nil
<del>}
<del>
<ide> func (te *testEndpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP, interfaceID int) error {
<ide> te.routes = append(te.routes, types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop, InterfaceID: interfaceID})
<ide> return nil
<ide><path>libnetwork/drivers/host/host.go
<ide> import (
<ide> const networkType = "host"
<ide>
<ide> type driver struct {
<del> network types.UUID
<add> network string
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (d *driver) Config(option map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
<ide> d.Lock()
<ide> defer d.Unlock()
<ide>
<ide> func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) err
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<add>func (d *driver) DeleteNetwork(nid string) error {
<ide> return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType)
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> return make(map[string]interface{}, 0), nil
<ide> }
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<del> if err := jinfo.SetHostsPath("/etc/hosts"); err != nil {
<del> return err
<del> }
<del>
<del> return jinfo.SetResolvConfPath("/etc/resolv.conf")
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add> return nil
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<ide><path>libnetwork/drivers/null/null.go
<ide> import (
<ide> const networkType = "null"
<ide>
<ide> type driver struct {
<del> network types.UUID
<add> network string
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (d *driver) Config(option map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
<ide> d.Lock()
<ide> defer d.Unlock()
<ide>
<ide> func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) err
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<add>func (d *driver) DeleteNetwork(nid string) error {
<ide> return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType)
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> return make(map[string]interface{}, 0), nil
<ide> }
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<ide><path>libnetwork/drivers/overlay/joinleave.go
<ide> import (
<ide> "fmt"
<ide>
<ide> "github.com/docker/libnetwork/driverapi"
<del> "github.com/docker/libnetwork/types"
<ide> "github.com/vishvananda/netlink"
<ide> )
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> }
<ide> func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinI
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_endpoint.go
<ide> import (
<ide>
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/netutils"
<del> "github.com/docker/libnetwork/types"
<ide> )
<ide>
<del>type endpointTable map[types.UUID]*endpoint
<add>type endpointTable map[string]*endpoint
<ide>
<ide> type endpoint struct {
<del> id types.UUID
<add> id string
<ide> mac net.HardwareAddr
<ide> addr *net.IPNet
<ide> }
<ide>
<del>func (n *network) endpoint(eid types.UUID) *endpoint {
<add>func (n *network) endpoint(eid string) *endpoint {
<ide> n.Lock()
<ide> defer n.Unlock()
<ide>
<ide> func (n *network) addEndpoint(ep *endpoint) {
<ide> n.Unlock()
<ide> }
<ide>
<del>func (n *network) deleteEndpoint(eid types.UUID) {
<add>func (n *network) deleteEndpoint(eid string) {
<ide> n.Lock()
<ide> delete(n.endpoints, eid)
<ide> n.Unlock()
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo,
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo,
<ide> epOptions map[string]interface{}) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> if err := validateID(nid, eid); err != nil {
<ide> return err
<ide> }
<ide> func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> return make(map[string]interface{}, 0), nil
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_network.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/libnetwork/datastore"
<ide> "github.com/docker/libnetwork/ipallocator"
<del> "github.com/docker/libnetwork/sandbox"
<del> "github.com/docker/libnetwork/types"
<add> "github.com/docker/libnetwork/osl"
<ide> "github.com/vishvananda/netlink"
<ide> "github.com/vishvananda/netlink/nl"
<ide> )
<ide>
<del>type networkTable map[types.UUID]*network
<add>type networkTable map[string]*network
<ide>
<ide> type network struct {
<del> id types.UUID
<add> id string
<ide> vni uint32
<ide> dbIndex uint64
<ide> dbExists bool
<del> sbox sandbox.Sandbox
<add> sbox osl.Sandbox
<ide> endpoints endpointTable
<ide> ipAllocator *ipallocator.IPAllocator
<ide> gw net.IP
<ide> type network struct {
<ide> sync.Mutex
<ide> }
<ide>
<del>func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
<ide> if id == "" {
<ide> return fmt.Errorf("invalid network id")
<ide> }
<ide> func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) err
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<add>func (d *driver) DeleteNetwork(nid string) error {
<ide> if nid == "" {
<ide> return fmt.Errorf("invalid network id")
<ide> }
<ide> func (n *network) initSandbox() error {
<ide> n.initEpoch++
<ide> n.Unlock()
<ide>
<del> sbox, err := sandbox.NewSandbox(
<del> sandbox.GenerateKey(fmt.Sprintf("%d-", n.initEpoch)+string(n.id)), true)
<add> sbox, err := osl.NewSandbox(
<add> osl.GenerateKey(fmt.Sprintf("%d-", n.initEpoch)+n.id), true)
<ide> if err != nil {
<ide> return fmt.Errorf("could not create network sandbox: %v", err)
<ide> }
<ide> func (n *network) watchMiss(nlSock *nl.NetlinkSocket) {
<ide> continue
<ide> }
<ide>
<del> if err := n.driver.peerAdd(n.id, types.UUID("dummy"), neigh.IP, mac, vtep, true); err != nil {
<add> if err := n.driver.peerAdd(n.id, "dummy", neigh.IP, mac, vtep, true); err != nil {
<ide> logrus.Errorf("could not add neighbor entry for missed peer: %v", err)
<ide> }
<ide> }
<ide> func (d *driver) addNetwork(n *network) {
<ide> d.Unlock()
<ide> }
<ide>
<del>func (d *driver) deleteNetwork(nid types.UUID) {
<add>func (d *driver) deleteNetwork(nid string) {
<ide> d.Lock()
<ide> delete(d.networks, nid)
<ide> d.Unlock()
<ide> }
<ide>
<del>func (d *driver) network(nid types.UUID) *network {
<add>func (d *driver) network(nid string) *network {
<ide> d.Lock()
<ide> defer d.Unlock()
<ide>
<ide> return d.networks[nid]
<ide> }
<ide>
<del>func (n *network) sandbox() sandbox.Sandbox {
<add>func (n *network) sandbox() osl.Sandbox {
<ide> n.Lock()
<ide> defer n.Unlock()
<ide>
<ide> return n.sbox
<ide> }
<ide>
<del>func (n *network) setSandbox(sbox sandbox.Sandbox) {
<add>func (n *network) setSandbox(sbox osl.Sandbox) {
<ide> n.Lock()
<ide> n.sbox = sbox
<ide> n.Unlock()
<ide> func (n *network) setVxlanID(vni uint32) {
<ide> }
<ide>
<ide> func (n *network) Key() []string {
<del> return []string{"overlay", "network", string(n.id)}
<add> return []string{"overlay", "network", n.id}
<ide> }
<ide>
<ide> func (n *network) KeyPrefix() []string {
<ide><path>libnetwork/drivers/overlay/ov_serf.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/libnetwork/types"
<ide> "github.com/hashicorp/serf/serf"
<ide> )
<ide>
<ide> type ovNotify struct {
<ide> action string
<del> eid types.UUID
<del> nid types.UUID
<add> eid string
<add> nid string
<ide> }
<ide>
<ide> type logWriter struct{}
<ide> func (d *driver) processEvent(u serf.UserEvent) {
<ide>
<ide> switch action {
<ide> case "join":
<del> if err := d.peerAdd(types.UUID(nid), types.UUID(eid), net.ParseIP(ipStr), mac,
<add> if err := d.peerAdd(nid, eid, net.ParseIP(ipStr), mac,
<ide> net.ParseIP(vtepStr), true); err != nil {
<ide> fmt.Printf("Peer add failed in the driver: %v\n", err)
<ide> }
<ide> case "leave":
<del> if err := d.peerDelete(types.UUID(nid), types.UUID(eid), net.ParseIP(ipStr), mac,
<add> if err := d.peerDelete(nid, eid, net.ParseIP(ipStr), mac,
<ide> net.ParseIP(vtepStr), true); err != nil {
<ide> fmt.Printf("Peer delete failed in the driver: %v\n", err)
<ide> }
<ide> func (d *driver) processQuery(q *serf.Query) {
<ide> fmt.Printf("Failed to scan query payload string: %v\n", err)
<ide> }
<ide>
<del> peerMac, vtep, err := d.peerDbSearch(types.UUID(nid), net.ParseIP(ipStr))
<add> peerMac, vtep, err := d.peerDbSearch(nid, net.ParseIP(ipStr))
<ide> if err != nil {
<ide> return
<ide> }
<ide>
<ide> q.Respond([]byte(fmt.Sprintf("%s %s", peerMac.String(), vtep.String())))
<ide> }
<ide>
<del>func (d *driver) resolvePeer(nid types.UUID, peerIP net.IP) (net.HardwareAddr, net.IP, error) {
<add>func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IP, error) {
<ide> qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
<ide> resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
<ide> if err != nil {
<ide><path>libnetwork/drivers/overlay/ov_utils.go
<ide> import (
<ide> "fmt"
<ide>
<ide> "github.com/docker/libnetwork/netutils"
<del> "github.com/docker/libnetwork/types"
<ide> "github.com/vishvananda/netlink"
<ide> "github.com/vishvananda/netlink/nl"
<ide> )
<ide>
<del>func validateID(nid, eid types.UUID) error {
<add>func validateID(nid, eid string) error {
<ide> if nid == "" {
<ide> return fmt.Errorf("invalid network id")
<ide> }
<ide><path>libnetwork/drivers/overlay/overlay.go
<ide> import (
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/idm"
<ide> "github.com/docker/libnetwork/netlabel"
<del> "github.com/docker/libnetwork/types"
<ide> "github.com/hashicorp/serf/serf"
<ide> )
<ide>
<ide> func Init(dc driverapi.DriverCallback) error {
<ide> return dc.RegisterDriver(networkType, &driver{
<ide> networks: networkTable{},
<ide> peerDb: peerNetworkMap{
<del> mp: map[types.UUID]peerMap{},
<add> mp: map[string]peerMap{},
<ide> },
<ide> }, c)
<ide> }
<ide><path>libnetwork/drivers/overlay/peerdb.go
<ide> import (
<ide> "net"
<ide> "sync"
<ide> "syscall"
<del>
<del> "github.com/docker/libnetwork/types"
<ide> )
<ide>
<ide> type peerKey struct {
<ide> type peerKey struct {
<ide> }
<ide>
<ide> type peerEntry struct {
<del> eid types.UUID
<add> eid string
<ide> vtep net.IP
<ide> inSandbox bool
<ide> isLocal bool
<ide> type peerMap struct {
<ide> }
<ide>
<ide> type peerNetworkMap struct {
<del> mp map[types.UUID]peerMap
<add> mp map[string]peerMap
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (pKey *peerKey) Scan(state fmt.ScanState, verb rune) error {
<ide>
<ide> var peerDbWg sync.WaitGroup
<ide>
<del>func (d *driver) peerDbWalk(nid types.UUID, f func(*peerKey, *peerEntry) bool) error {
<add>func (d *driver) peerDbWalk(nid string, f func(*peerKey, *peerEntry) bool) error {
<ide> d.peerDb.Lock()
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> func (d *driver) peerDbWalk(nid types.UUID, f func(*peerKey, *peerEntry) bool) e
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) peerDbSearch(nid types.UUID, peerIP net.IP) (net.HardwareAddr, net.IP, error) {
<add>func (d *driver) peerDbSearch(nid string, peerIP net.IP) (net.HardwareAddr, net.IP, error) {
<ide> var (
<ide> peerMac net.HardwareAddr
<ide> vtep net.IP
<ide> func (d *driver) peerDbSearch(nid types.UUID, peerIP net.IP) (net.HardwareAddr,
<ide> return peerMac, vtep, nil
<ide> }
<ide>
<del>func (d *driver) peerDbAdd(nid, eid types.UUID, peerIP net.IP,
<add>func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP,
<ide> peerMac net.HardwareAddr, vtep net.IP, isLocal bool) {
<ide>
<ide> peerDbWg.Wait()
<ide> func (d *driver) peerDbAdd(nid, eid types.UUID, peerIP net.IP,
<ide> pMap.Unlock()
<ide> }
<ide>
<del>func (d *driver) peerDbDelete(nid, eid types.UUID, peerIP net.IP,
<add>func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP,
<ide> peerMac net.HardwareAddr, vtep net.IP) {
<ide> peerDbWg.Wait()
<ide>
<ide> func (d *driver) peerDbDelete(nid, eid types.UUID, peerIP net.IP,
<ide> pMap.Unlock()
<ide> }
<ide>
<del>func (d *driver) peerDbUpdateSandbox(nid types.UUID) {
<add>func (d *driver) peerDbUpdateSandbox(nid string) {
<ide> d.peerDb.Lock()
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> func (d *driver) peerDbUpdateSandbox(nid types.UUID) {
<ide> peerDbWg.Done()
<ide> }
<ide>
<del>func (d *driver) peerAdd(nid, eid types.UUID, peerIP net.IP,
<add>func (d *driver) peerAdd(nid, eid string, peerIP net.IP,
<ide> peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
<ide>
<ide> if err := validateID(nid, eid); err != nil {
<ide> func (d *driver) peerAdd(nid, eid types.UUID, peerIP net.IP,
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) peerDelete(nid, eid types.UUID, peerIP net.IP,
<add>func (d *driver) peerDelete(nid, eid string, peerIP net.IP,
<ide> peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
<ide>
<ide> if err := validateID(nid, eid); err != nil {
<ide><path>libnetwork/drivers/remote/api/api.go
<ide> type JoinResponse struct {
<ide> InterfaceNames []*InterfaceName
<ide> Gateway string
<ide> GatewayIPv6 string
<del> HostsPath string
<del> ResolvConfPath string
<ide> StaticRoutes []StaticRoute
<ide> }
<ide>
<ide><path>libnetwork/drivers/remote/driver.go
<ide> func (d *driver) call(methodName string, arg interface{}, retVal maybeError) err
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateNetwork(id types.UUID, options map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, options map[string]interface{}) error {
<ide> create := &api.CreateNetworkRequest{
<del> NetworkID: string(id),
<add> NetworkID: id,
<ide> Options: options,
<ide> }
<ide> return d.call("CreateNetwork", create, &api.CreateNetworkResponse{})
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<del> delete := &api.DeleteNetworkRequest{NetworkID: string(nid)}
<add>func (d *driver) DeleteNetwork(nid string) error {
<add> delete := &api.DeleteNetworkRequest{NetworkID: nid}
<ide> return d.call("DeleteNetwork", delete, &api.DeleteNetworkResponse{})
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<ide> if epInfo == nil {
<ide> return fmt.Errorf("must not be called with nil EndpointInfo")
<ide> }
<ide> func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointIn
<ide> }
<ide> }
<ide> create := &api.CreateEndpointRequest{
<del> NetworkID: string(nid),
<del> EndpointID: string(eid),
<add> NetworkID: nid,
<add> EndpointID: eid,
<ide> Interfaces: reqIfaces,
<ide> Options: epOptions,
<ide> }
<ide> func errorWithRollback(msg string, err error) error {
<ide> return fmt.Errorf("%s; %s", msg, rollback)
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> delete := &api.DeleteEndpointRequest{
<del> NetworkID: string(nid),
<del> EndpointID: string(eid),
<add> NetworkID: nid,
<add> EndpointID: eid,
<ide> }
<ide> return d.call("DeleteEndpoint", delete, &api.DeleteEndpointResponse{})
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> info := &api.EndpointInfoRequest{
<del> NetworkID: string(nid),
<del> EndpointID: string(eid),
<add> NetworkID: nid,
<add> EndpointID: eid,
<ide> }
<ide> var res api.EndpointInfoResponse
<ide> if err := d.call("EndpointOperInfo", info, &res); err != nil {
<ide> func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{},
<ide> }
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<ide> join := &api.JoinRequest{
<del> NetworkID: string(nid),
<del> EndpointID: string(eid),
<add> NetworkID: nid,
<add> EndpointID: eid,
<ide> SandboxKey: sboxKey,
<ide> Options: options,
<ide> }
<ide> func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinI
<ide> }
<ide> }
<ide> }
<del> if jinfo.SetHostsPath(res.HostsPath) != nil {
<del> return errorWithRollback(fmt.Sprintf("failed to set hosts path: %s", res.HostsPath), d.Leave(nid, eid))
<del> }
<del> if jinfo.SetResolvConfPath(res.ResolvConfPath) != nil {
<del> return errorWithRollback(fmt.Sprintf("failed to set resolv.conf path: %s", res.ResolvConfPath), d.Leave(nid, eid))
<del> }
<ide> return nil
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> leave := &api.LeaveRequest{
<del> NetworkID: string(nid),
<del> EndpointID: string(eid),
<add> NetworkID: nid,
<add> EndpointID: eid,
<ide> }
<ide> return d.call("Leave", leave, &api.LeaveResponse{})
<ide> }
<ide><path>libnetwork/drivers/remote/driver_test.go
<ide> func (test *testEndpoint) SetGatewayIPv6(ipv6 net.IP) error {
<ide> return nil
<ide> }
<ide>
<del>func (test *testEndpoint) SetHostsPath(p string) error {
<del> if p != test.hostsPath {
<del> test.t.Fatalf(`Wrong HostsPath; expected "%s", got "%s"`, test.hostsPath, p)
<del> }
<del> return nil
<del>}
<del>
<del>func (test *testEndpoint) SetResolvConfPath(p string) error {
<del> if p != test.resolvConfPath {
<del> test.t.Fatalf(`Wrong ResolvConfPath; expected "%s", got "%s"`, test.resolvConfPath, p)
<del> }
<del> return nil
<del>}
<del>
<ide> func (test *testEndpoint) SetNames(src string, dst string) error {
<ide> if test.src != src {
<ide> test.t.Fatalf(`Wrong SrcName; expected "%s", got "%s"`, test.src, src)
<ide> func TestRemoteDriver(t *testing.T) {
<ide> t.Fatal("Driver type does not match that given")
<ide> }
<ide>
<del> netID := types.UUID("dummy-network")
<add> netID := "dummy-network"
<ide> err = driver.CreateNetwork(netID, map[string]interface{}{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> endID := types.UUID("dummy-endpoint")
<add> endID := "dummy-endpoint"
<ide> err = driver.CreateEndpoint(netID, endID, ep, map[string]interface{}{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestDriverError(t *testing.T) {
<ide>
<ide> driver := newDriver(plugin, p.Client)
<ide>
<del> if err := driver.CreateEndpoint(types.UUID("dummy"), types.UUID("dummy"), &testEndpoint{t: t}, map[string]interface{}{}); err == nil {
<add> if err := driver.CreateEndpoint("dummy", "dummy", &testEndpoint{t: t}, map[string]interface{}{}); err == nil {
<ide> t.Fatalf("Expected error from driver")
<ide> }
<ide> }
<ide> func TestMissingValues(t *testing.T) {
<ide> }
<ide> driver := newDriver(plugin, p.Client)
<ide>
<del> if err := driver.CreateEndpoint(types.UUID("dummy"), types.UUID("dummy"), ep, map[string]interface{}{}); err != nil {
<add> if err := driver.CreateEndpoint("dummy", "dummy", ep, map[string]interface{}{}); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }
<ide> func TestRollback(t *testing.T) {
<ide>
<ide> ep := &rollbackEndpoint{}
<ide>
<del> if err := driver.CreateEndpoint(types.UUID("dummy"), types.UUID("dummy"), ep, map[string]interface{}{}); err == nil {
<add> if err := driver.CreateEndpoint("dummy", "dummy", ep, map[string]interface{}{}); err == nil {
<ide> t.Fatalf("Expected error from driver")
<ide> }
<ide> if !rolledback {
<ide><path>libnetwork/drivers/windows/windows.go
<ide> package windows
<ide>
<del>import (
<del> "github.com/docker/libnetwork/driverapi"
<del> "github.com/docker/libnetwork/types"
<del>)
<add>import "github.com/docker/libnetwork/driverapi"
<ide>
<ide> const networkType = "windows"
<ide>
<ide> func (d *driver) Config(option map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
<add>func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteNetwork(nid types.UUID) error {
<add>func (d *driver) DeleteNetwork(nid string) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<add>func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
<add>func (d *driver) DeleteEndpoint(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
<add>func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
<ide> return make(map[string]interface{}, 0), nil
<ide> }
<ide>
<ide> // Join method is invoked when a Sandbox is attached to an endpoint.
<del>func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<add>func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
<ide> return nil
<ide> }
<ide>
<ide> // Leave method is invoked when a Sandbox detaches from an endpoint.
<del>func (d *driver) Leave(nid, eid types.UUID) error {
<add>func (d *driver) Leave(nid, eid string) error {
<ide> return nil
<ide> }
<ide>
<ide><path>libnetwork/endpoint.go
<ide> package libnetwork
<ide>
<ide> import (
<del> "bytes"
<ide> "encoding/json"
<ide> "fmt"
<del> "io/ioutil"
<del> "os"
<del> "path"
<del> "path/filepath"
<add> "net"
<ide> "sync"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/libnetwork/datastore"
<del> "github.com/docker/libnetwork/etchosts"
<ide> "github.com/docker/libnetwork/netlabel"
<del> "github.com/docker/libnetwork/resolvconf"
<del> "github.com/docker/libnetwork/sandbox"
<ide> "github.com/docker/libnetwork/types"
<ide> )
<ide>
<ide> type Endpoint interface {
<ide> // Network returns the name of the network to which this endpoint is attached.
<ide> Network() string
<ide>
<del> // Join creates a new sandbox for the given container ID and populates the
<del> // network resources allocated for the endpoint and joins the sandbox to
<del> // the endpoint.
<del> Join(containerID string, options ...EndpointOption) error
<add> // Join joins the sandbox to the endpoint and populates into the sandbox
<add> // the network resources allocated for the endpoint.
<add> Join(sandbox Sandbox, options ...EndpointOption) error
<ide>
<del> // Leave removes the sandbox associated with container ID and detaches
<del> // the network resources populated in the sandbox
<del> Leave(containerID string, options ...EndpointOption) error
<add> // Leave detaches the network resources populated in the sandbox.
<add> Leave(sandbox Sandbox, options ...EndpointOption) error
<ide>
<ide> // Return certain operational data belonging to this endpoint
<ide> Info() EndpointInfo
<ide>
<ide> // DriverInfo returns a collection of driver operational data related to this endpoint retrieved from the driver
<ide> DriverInfo() (map[string]interface{}, error)
<ide>
<del> // ContainerInfo returns the info available at the endpoint about the attached container
<del> ContainerInfo() ContainerInfo
<del>
<ide> // Delete and detaches this endpoint from the network.
<ide> Delete() error
<del>
<del> // Retrieve the interfaces' statistics from the sandbox
<del> Statistics() (map[string]*sandbox.InterfaceStatistics, error)
<ide> }
<ide>
<ide> // EndpointOption is a option setter function type used to pass varios options to Network
<ide> // and Endpoint interfaces methods. The various setter functions of type EndpointOption are
<ide> // provided by libnetwork, they look like <Create|Join|Leave>Option[...](...)
<ide> type EndpointOption func(ep *endpoint)
<ide>
<del>// ContainerData is a set of data returned when a container joins an endpoint.
<del>type ContainerData struct {
<del> SandboxKey string
<del>}
<del>
<del>// These are the container configs used to customize container /etc/hosts file.
<del>type hostsPathConfig struct {
<del> hostName string
<del> domainName string
<del> hostsPath string
<del> extraHosts []extraHost
<del> parentUpdates []parentUpdate
<del>}
<del>
<del>// These are the container configs used to customize container /etc/resolv.conf file.
<del>type resolvConfPathConfig struct {
<del> resolvConfPath string
<del> dnsList []string
<del> dnsSearchList []string
<del>}
<del>
<del>type containerConfig struct {
<del> hostsPathConfig
<del> resolvConfPathConfig
<del> generic map[string]interface{}
<del> useDefaultSandBox bool
<del> prio int // higher the value, more the priority
<del>}
<del>
<del>type extraHost struct {
<del> name string
<del> IP string
<del>}
<del>
<del>type parentUpdate struct {
<del> eid string
<del> name string
<del> ip string
<del>}
<del>
<del>type containerInfo struct {
<del> id string
<del> config containerConfig
<del> data ContainerData
<del> sync.Mutex
<del>}
<del>
<del>func (ci *containerInfo) ID() string {
<del> return ci.id
<del>}
<del>
<del>func (ci *containerInfo) Labels() map[string]interface{} {
<del> return ci.config.generic
<del>}
<del>
<ide> type endpoint struct {
<ide> name string
<del> id types.UUID
<add> id string
<ide> network *network
<ide> iFaces []*endpointInterface
<ide> joinInfo *endpointJoinInfo
<del> container *containerInfo
<add> sandboxID string
<ide> exposedPorts []types.TransportPort
<ide> generic map[string]interface{}
<ide> joinLeaveDone chan struct{}
<ide> type endpoint struct {
<ide> sync.Mutex
<ide> }
<ide>
<del>func (ci *containerInfo) MarshalJSON() ([]byte, error) {
<del> ci.Lock()
<del> defer ci.Unlock()
<del>
<del> // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
<del> return json.Marshal(ci.id)
<del>}
<del>
<del>func (ci *containerInfo) UnmarshalJSON(b []byte) (err error) {
<del> ci.Lock()
<del> defer ci.Unlock()
<del>
<del> var id string
<del> if err := json.Unmarshal(b, &id); err != nil {
<del> return err
<del> }
<del> ci.id = id
<del> return nil
<del>}
<del>
<ide> func (ep *endpoint) MarshalJSON() ([]byte, error) {
<ide> ep.Lock()
<ide> defer ep.Unlock()
<ide>
<ide> epMap := make(map[string]interface{})
<ide> epMap["name"] = ep.name
<del> epMap["id"] = string(ep.id)
<add> epMap["id"] = ep.id
<ide> epMap["ep_iface"] = ep.iFaces
<ide> epMap["exposed_ports"] = ep.exposedPorts
<ide> epMap["generic"] = ep.generic
<del> if ep.container != nil {
<del> epMap["container"] = ep.container
<del> }
<add> epMap["sandbox"] = ep.sandboxID
<ide> return json.Marshal(epMap)
<ide> }
<ide>
<ide> func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
<ide> return err
<ide> }
<ide> ep.name = epMap["name"].(string)
<del> ep.id = types.UUID(epMap["id"].(string))
<add> ep.id = epMap["id"].(string)
<ide>
<ide> ib, _ := json.Marshal(epMap["ep_iface"])
<ide> var ifaces []endpointInterface
<ide> func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
<ide> json.Unmarshal(tb, &tPorts)
<ide> ep.exposedPorts = tPorts
<ide>
<del> epc, ok := epMap["container"]
<del> if ok {
<del> cb, _ := json.Marshal(epc)
<del> var cInfo containerInfo
<del> json.Unmarshal(cb, &cInfo)
<del> ep.container = &cInfo
<del> }
<add> cb, _ := json.Marshal(epMap["sandbox"])
<add> json.Unmarshal(cb, &ep.sandboxID)
<ide>
<ide> if epMap["generic"] != nil {
<ide> ep.generic = epMap["generic"].(map[string]interface{})
<ide> }
<ide> return nil
<ide> }
<ide>
<del>const defaultPrefix = "/var/lib/docker/network/files"
<del>
<ide> func (ep *endpoint) ID() string {
<ide> ep.Lock()
<ide> defer ep.Unlock()
<ide>
<del> return string(ep.id)
<add> return ep.id
<ide> }
<ide>
<ide> func (ep *endpoint) Name() string {
<ide> func (ep *endpoint) Name() string {
<ide> }
<ide>
<ide> func (ep *endpoint) Network() string {
<del> ep.Lock()
<del> defer ep.Unlock()
<del>
<del> return ep.network.name
<add> return ep.getNetwork().name
<ide> }
<ide>
<ide> // endpoint Key structure : endpoint/network-id/endpoint-id
<ide> func (ep *endpoint) Key() []string {
<del> ep.Lock()
<del> n := ep.network
<del> defer ep.Unlock()
<del> return []string{datastore.EndpointKeyPrefix, string(n.id), string(ep.id)}
<add> return []string{datastore.EndpointKeyPrefix, ep.getNetwork().id, ep.id}
<ide> }
<ide>
<ide> func (ep *endpoint) KeyPrefix() []string {
<del> ep.Lock()
<del> n := ep.network
<del> defer ep.Unlock()
<del> return []string{datastore.EndpointKeyPrefix, string(n.id)}
<add> return []string{datastore.EndpointKeyPrefix, ep.getNetwork().id}
<ide> }
<ide>
<del>func (ep *endpoint) networkIDFromKey(key []string) (types.UUID, error) {
<add>func (ep *endpoint) networkIDFromKey(key []string) (string, error) {
<ide> // endpoint Key structure : endpoint/network-id/endpoint-id
<ide> // it's an invalid key if the key doesn't have all the 3 key elements above
<ide> if key == nil || len(key) < 3 || key[0] != datastore.EndpointKeyPrefix {
<del> return types.UUID(""), fmt.Errorf("invalid endpoint key : %v", key)
<add> return "", fmt.Errorf("invalid endpoint key : %v", key)
<ide> }
<ide>
<ide> // network-id is placed at index=1. pls refer to endpoint.Key() method
<del> return types.UUID(key[1]), nil
<add> return key[1], nil
<ide> }
<ide>
<ide> func (ep *endpoint) Value() []byte {
<ide> func (ep *endpoint) processOptions(options ...EndpointOption) {
<ide> }
<ide> }
<ide>
<del>func createBasePath(dir string) error {
<del> return os.MkdirAll(dir, 0644)
<del>}
<del>
<del>func createFile(path string) error {
<del> var f *os.File
<del>
<del> dir, _ := filepath.Split(path)
<del> err := createBasePath(dir)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> f, err = os.Create(path)
<del> if err == nil {
<del> f.Close()
<del> }
<del>
<del> return err
<del>}
<del>
<ide> // joinLeaveStart waits to ensure there are no joins or leaves in progress and
<ide> // marks this join/leave in progress without race
<ide> func (ep *endpoint) joinLeaveStart() {
<ide> func (ep *endpoint) joinLeaveEnd() {
<ide> }
<ide> }
<ide>
<del>func (ep *endpoint) Join(containerID string, options ...EndpointOption) error {
<add>func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error {
<ide> var err error
<ide>
<del> if containerID == "" {
<del> return InvalidContainerIDError(containerID)
<add> if sbox == nil {
<add> return types.BadRequestErrorf("endpoint cannot be joined by nil container")
<add> }
<add>
<add> sb, ok := sbox.(*sandbox)
<add> if !ok {
<add> return types.BadRequestErrorf("not a valid Sandbox interface")
<ide> }
<ide>
<ide> ep.joinLeaveStart()
<del> defer func() {
<del> ep.joinLeaveEnd()
<del> }()
<add> defer ep.joinLeaveEnd()
<ide>
<ide> ep.Lock()
<del> if ep.container != nil {
<add> if ep.sandboxID != "" {
<ide> ep.Unlock()
<del> return ErrInvalidJoin{}
<add> return types.ForbiddenErrorf("a sandbox has already joined the endpoint")
<ide> }
<ide>
<del> ep.container = &containerInfo{
<del> id: containerID,
<del> config: containerConfig{
<del> hostsPathConfig: hostsPathConfig{
<del> extraHosts: []extraHost{},
<del> parentUpdates: []parentUpdate{},
<del> },
<del> }}
<del>
<add> ep.sandboxID = sbox.ID()
<ide> ep.joinInfo = &endpointJoinInfo{}
<del>
<del> container := ep.container
<ide> network := ep.network
<ide> epid := ep.id
<del>
<ide> ep.Unlock()
<ide> defer func() {
<ide> if err != nil {
<ide> ep.Lock()
<del> ep.container = nil
<add> ep.sandboxID = ""
<ide> ep.Unlock()
<ide> }
<ide> }()
<ide>
<ide> network.Lock()
<ide> driver := network.driver
<ide> nid := network.id
<del> ctrlr := network.ctrlr
<ide> network.Unlock()
<ide>
<ide> ep.processOptions(options...)
<ide>
<del> sboxKey := sandbox.GenerateKey(containerID)
<del> if container.config.useDefaultSandBox {
<del> sboxKey = sandbox.GenerateKey("default")
<del> }
<del>
<del> err = driver.Join(nid, epid, sboxKey, ep, container.config.generic)
<add> err = driver.Join(nid, epid, sbox.Key(), ep, sbox.Labels())
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (ep *endpoint) Join(containerID string, options ...EndpointOption) error {
<ide> }
<ide> }()
<ide>
<del> err = ep.buildHostsFiles()
<del> if err != nil {
<add> address := ""
<add> if ip := ep.getFirstInterfaceAddress(); ip != nil {
<add> address = ip.String()
<add> }
<add> if err = sb.updateHostsFile(address, network.getSvcRecords()); err != nil {
<ide> return err
<ide> }
<ide>
<del> err = ep.updateParentHosts()
<del> if err != nil {
<add> if err = sb.updateDNS(ep.getNetwork().enableIPv6); err != nil {
<ide> return err
<ide> }
<ide>
<del> err = ep.setupDNS()
<del> if err != nil {
<add> if err = network.ctrlr.updateEndpointToStore(ep); err != nil {
<ide> return err
<ide> }
<ide>
<del> sb, err := ctrlr.sandboxAdd(sboxKey, !container.config.useDefaultSandBox, ep)
<del> if err != nil {
<del> return fmt.Errorf("failed sandbox add: %v", err)
<del> }
<del> defer func() {
<del> if err != nil {
<del> ctrlr.sandboxRm(sboxKey, ep)
<del> }
<del> }()
<del>
<del> if err := network.ctrlr.updateEndpointToStore(ep); err != nil {
<add> if err = sb.populateNetworkResources(ep); err != nil {
<ide> return err
<ide> }
<ide>
<del> container.data.SandboxKey = sb.Key()
<ide> return nil
<ide> }
<ide>
<ide> func (ep *endpoint) hasInterface(iName string) bool {
<ide> return false
<ide> }
<ide>
<del>func (ep *endpoint) Leave(containerID string, options ...EndpointOption) error {
<del> var err error
<del>
<add>func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
<ide> ep.joinLeaveStart()
<ide> defer ep.joinLeaveEnd()
<ide>
<del> ep.processOptions(options...)
<add> if sbox == nil || sbox.ID() == "" || sbox.Key() == "" {
<add> return types.BadRequestErrorf("invalid Sandbox passed to enpoint leave: %v", sbox)
<add> }
<ide>
<del> ep.Lock()
<del> container := ep.container
<del> n := ep.network
<add> sb, ok := sbox.(*sandbox)
<add> if !ok {
<add> return types.BadRequestErrorf("not a valid Sandbox interface")
<add> }
<ide>
<del> if container == nil || container.id == "" || container.data.SandboxKey == "" ||
<del> containerID == "" || container.id != containerID {
<del> if container == nil {
<del> err = ErrNoContainer{}
<del> } else {
<del> err = InvalidContainerIDError(containerID)
<del> }
<add> ep.Lock()
<add> sid := ep.sandboxID
<add> ep.Unlock()
<ide>
<del> ep.Unlock()
<del> return err
<add> if sid == "" {
<add> return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox")
<ide> }
<del> ep.container = nil
<add> if sid != sbox.ID() {
<add> return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sbox.ID())
<add> }
<add>
<add> ep.processOptions(options...)
<add>
<add> ep.Lock()
<add> ep.sandboxID = ""
<add> n := ep.network
<ide> ep.Unlock()
<ide>
<ide> n.Lock()
<del> driver := n.driver
<del> ctrlr := n.ctrlr
<add> c := n.ctrlr
<add> d := n.driver
<ide> n.Unlock()
<ide>
<del> if err := ctrlr.updateEndpointToStore(ep); err != nil {
<add> if err := c.updateEndpointToStore(ep); err != nil {
<ide> ep.Lock()
<del> ep.container = container
<add> ep.sandboxID = sid
<ide> ep.Unlock()
<ide> return err
<ide> }
<ide>
<del> err = driver.Leave(n.id, ep.id)
<del>
<del> ctrlr.sandboxRm(container.data.SandboxKey, ep)
<add> if err := d.Leave(n.id, ep.id); err != nil {
<add> return err
<add> }
<ide>
<del> return err
<add> return sb.clearNetworkResources(ep)
<ide> }
<ide>
<ide> func (ep *endpoint) Delete() error {
<ide> func (ep *endpoint) Delete() error {
<ide> epid := ep.id
<ide> name := ep.name
<ide> n := ep.network
<del> if ep.container != nil {
<add> if ep.sandboxID != "" {
<ide> ep.Unlock()
<del> return &ActiveContainerError{name: name, id: string(epid)}
<add> return &ActiveContainerError{name: name, id: epid}
<ide> }
<ide> n.Lock()
<ide> ctrlr := n.ctrlr
<ide> func (ep *endpoint) Delete() error {
<ide> return nil
<ide> }
<ide>
<del>func (ep *endpoint) Statistics() (map[string]*sandbox.InterfaceStatistics, error) {
<del> m := make(map[string]*sandbox.InterfaceStatistics)
<del>
<del> ep.Lock()
<del> n := ep.network
<del> skey := ep.container.data.SandboxKey
<del> ep.Unlock()
<del>
<del> n.Lock()
<del> c := n.ctrlr
<del> n.Unlock()
<del>
<del> sbox := c.sandboxGet(skey)
<del> if sbox == nil {
<del> return m, nil
<del> }
<del>
<del> var err error
<del> for _, i := range sbox.Info().Interfaces() {
<del> if m[i.DstName()], err = i.Statistics(); err != nil {
<del> return m, err
<del> }
<del> }
<del>
<del> return m, nil
<del>}
<del>
<ide> func (ep *endpoint) deleteEndpoint() error {
<ide> ep.Lock()
<ide> n := ep.network
<ide> func (ep *endpoint) deleteEndpoint() error {
<ide> return nil
<ide> }
<ide>
<del>func (ep *endpoint) addHostEntries(recs []etchosts.Record) {
<del> ep.Lock()
<del> container := ep.container
<del> ep.Unlock()
<del>
<del> if container == nil {
<del> return
<del> }
<del>
<del> if err := etchosts.Add(container.config.hostsPath, recs); err != nil {
<del> log.Warnf("Failed adding service host entries to the running container: %v", err)
<del> }
<del>}
<del>
<del>func (ep *endpoint) deleteHostEntries(recs []etchosts.Record) {
<add>func (ep *endpoint) getNetwork() *network {
<ide> ep.Lock()
<del> container := ep.container
<del> ep.Unlock()
<del>
<del> if container == nil {
<del> return
<del> }
<del>
<del> if err := etchosts.Delete(container.config.hostsPath, recs); err != nil {
<del> log.Warnf("Failed deleting service host entries to the running container: %v", err)
<del> }
<add> defer ep.Unlock()
<add> return ep.network
<ide> }
<ide>
<del>func (ep *endpoint) buildHostsFiles() error {
<del> var extraContent []etchosts.Record
<del>
<add>func (ep *endpoint) getSandbox() (*sandbox, bool) {
<ide> ep.Lock()
<del> container := ep.container
<del> joinInfo := ep.joinInfo
<del> ifaces := ep.iFaces
<del> n := ep.network
<add> c := ep.network.getController()
<add> sid := ep.sandboxID
<ide> ep.Unlock()
<ide>
<del> if container == nil {
<del> return ErrNoContainer{}
<del> }
<del>
<del> if container.config.hostsPath == "" {
<del> container.config.hostsPath = defaultPrefix + "/" + container.id + "/hosts"
<del> }
<del>
<del> dir, _ := filepath.Split(container.config.hostsPath)
<del> err := createBasePath(dir)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if joinInfo != nil && joinInfo.hostsPath != "" {
<del> content, err := ioutil.ReadFile(joinInfo.hostsPath)
<del> if err != nil && !os.IsNotExist(err) {
<del> return err
<del> }
<del>
<del> if err == nil {
<del> return ioutil.WriteFile(container.config.hostsPath, content, 0644)
<del> }
<del> }
<del>
<del> for _, extraHost := range container.config.extraHosts {
<del> extraContent = append(extraContent,
<del> etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
<del> }
<del>
<del> extraContent = append(extraContent, n.getSvcRecords()...)
<del>
<del> IP := ""
<del> if len(ifaces) != 0 && ifaces[0] != nil {
<del> IP = ifaces[0].addr.IP.String()
<del> }
<add> c.Lock()
<add> ps, ok := c.sandboxes[sid]
<add> c.Unlock()
<ide>
<del> return etchosts.Build(container.config.hostsPath, IP, container.config.hostName,
<del> container.config.domainName, extraContent)
<add> return ps, ok
<ide> }
<ide>
<del>func (ep *endpoint) updateParentHosts() error {
<add>func (ep *endpoint) getFirstInterfaceAddress() net.IP {
<ide> ep.Lock()
<del> container := ep.container
<del> network := ep.network
<del> ep.Unlock()
<del>
<del> if container == nil {
<del> return ErrNoContainer{}
<del> }
<del>
<del> for _, update := range container.config.parentUpdates {
<del> network.Lock()
<del> pep, ok := network.endpoints[types.UUID(update.eid)]
<del> if !ok {
<del> network.Unlock()
<del> continue
<del> }
<del> network.Unlock()
<del>
<del> pep.Lock()
<del> pContainer := pep.container
<del> pep.Unlock()
<add> defer ep.Unlock()
<ide>
<del> if pContainer != nil {
<del> if err := etchosts.Update(pContainer.config.hostsPath, update.ip, update.name); err != nil {
<del> return err
<del> }
<del> }
<add> if len(ep.iFaces) != 0 && ep.iFaces[0] != nil {
<add> return ep.iFaces[0].addr.IP
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<del>func (ep *endpoint) updateDNS(resolvConf []byte) error {
<del> ep.Lock()
<del> container := ep.container
<del> network := ep.network
<del> ep.Unlock()
<del>
<del> if container == nil {
<del> return ErrNoContainer{}
<del> }
<del>
<del> oldHash := []byte{}
<del> hashFile := container.config.resolvConfPath + ".hash"
<del>
<del> resolvBytes, err := ioutil.ReadFile(container.config.resolvConfPath)
<del> if err != nil {
<del> if !os.IsNotExist(err) {
<del> return err
<del> }
<del> } else {
<del> oldHash, err = ioutil.ReadFile(hashFile)
<del> if err != nil {
<del> if !os.IsNotExist(err) {
<del> return err
<del> }
<del>
<del> oldHash = []byte{}
<del> }
<del> }
<del>
<del> curHash, err := ioutils.HashData(bytes.NewReader(resolvBytes))
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if string(oldHash) != "" && curHash != string(oldHash) {
<del> // Seems the user has changed the container resolv.conf since the last time
<del> // we checked so return without doing anything.
<del> return nil
<del> }
<del>
<del> // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
<del> resolvConf, _ = resolvconf.FilterResolvDNS(resolvConf, network.enableIPv6)
<del>
<del> newHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
<del> if err != nil {
<del> return err
<del> }
<del>
<del> // for atomic updates to these files, use temporary files with os.Rename:
<del> dir := path.Dir(container.config.resolvConfPath)
<del> tmpHashFile, err := ioutil.TempFile(dir, "hash")
<del> if err != nil {
<del> return err
<del> }
<del> tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
<del> if err != nil {
<del> return err
<del> }
<del>
<del> // Change the perms to 0644 since ioutil.TempFile creates it by default as 0600
<del> if err := os.Chmod(tmpResolvFile.Name(), 0644); err != nil {
<del> return err
<del> }
<del>
<del> // write the updates to the temp files
<del> if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newHash), 0644); err != nil {
<del> return err
<del> }
<del> if err = ioutil.WriteFile(tmpResolvFile.Name(), resolvConf, 0644); err != nil {
<del> return err
<del> }
<del>
<del> // rename the temp files for atomic replace
<del> if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
<del> return err
<del> }
<del> return os.Rename(tmpResolvFile.Name(), container.config.resolvConfPath)
<del>}
<del>
<del>func copyFile(src, dst string) error {
<del> sBytes, err := ioutil.ReadFile(src)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> return ioutil.WriteFile(dst, sBytes, 0644)
<del>}
<del>
<del>func (ep *endpoint) setupDNS() error {
<del> ep.Lock()
<del> container := ep.container
<del> joinInfo := ep.joinInfo
<del> ep.Unlock()
<del>
<del> if container == nil {
<del> return ErrNoContainer{}
<del> }
<del>
<del> if container.config.resolvConfPath == "" {
<del> container.config.resolvConfPath = defaultPrefix + "/" + container.id + "/resolv.conf"
<del> }
<del>
<del> dir, _ := filepath.Split(container.config.resolvConfPath)
<del> err := createBasePath(dir)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if joinInfo.resolvConfPath != "" {
<del> if err := copyFile(joinInfo.resolvConfPath, container.config.resolvConfPath); err != nil {
<del> return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", joinInfo.resolvConfPath, container.config.resolvConfPath, err)
<del> }
<del>
<del> return nil
<del> }
<del>
<del> resolvConf, err := resolvconf.Get()
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if len(container.config.dnsList) > 0 ||
<del> len(container.config.dnsSearchList) > 0 {
<del> var (
<del> dnsList = resolvconf.GetNameservers(resolvConf)
<del> dnsSearchList = resolvconf.GetSearchDomains(resolvConf)
<del> )
<del>
<del> if len(container.config.dnsList) > 0 {
<del> dnsList = container.config.dnsList
<del> }
<del>
<del> if len(container.config.dnsSearchList) > 0 {
<del> dnsSearchList = container.config.dnsSearchList
<del> }
<del>
<del> return resolvconf.Build(container.config.resolvConfPath, dnsList, dnsSearchList)
<del> }
<del>
<del> return ep.updateDNS(resolvConf)
<del>}
<del>
<ide> // EndpointOptionGeneric function returns an option setter for a Generic option defined
<ide> // in a Dictionary of Key-Value pair
<ide> func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
<ide> func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
<ide> }
<ide> }
<ide>
<del>// JoinOptionPriority function returns an option setter for priority option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionPriority(prio int) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.prio = prio
<del> }
<del>}
<del>
<del>// JoinOptionHostname function returns an option setter for hostname option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionHostname(name string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.hostName = name
<del> }
<del>}
<del>
<del>// JoinOptionDomainname function returns an option setter for domainname option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionDomainname(name string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.domainName = name
<del> }
<del>}
<del>
<del>// JoinOptionHostsPath function returns an option setter for hostspath option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionHostsPath(path string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.hostsPath = path
<del> }
<del>}
<del>
<del>// JoinOptionExtraHost function returns an option setter for extra /etc/hosts options
<del>// which is a name and IP as strings.
<del>func JoinOptionExtraHost(name string, IP string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.extraHosts = append(ep.container.config.extraHosts, extraHost{name: name, IP: IP})
<del> }
<del>}
<del>
<del>// JoinOptionParentUpdate function returns an option setter for parent container
<del>// which needs to update the IP address for the linked container.
<del>func JoinOptionParentUpdate(eid string, name, ip string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.parentUpdates = append(ep.container.config.parentUpdates, parentUpdate{eid: eid, name: name, ip: ip})
<del> }
<del>}
<del>
<del>// JoinOptionResolvConfPath function returns an option setter for resolvconfpath option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionResolvConfPath(path string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.resolvConfPath = path
<del> }
<del>}
<del>
<del>// JoinOptionDNS function returns an option setter for dns entry option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionDNS(dns string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.dnsList = append(ep.container.config.dnsList, dns)
<del> }
<del>}
<del>
<del>// JoinOptionDNSSearch function returns an option setter for dns search entry option to
<del>// be passed to endpoint Join method.
<del>func JoinOptionDNSSearch(search string) EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.dnsSearchList = append(ep.container.config.dnsSearchList, search)
<del> }
<del>}
<del>
<del>// JoinOptionUseDefaultSandbox function returns an option setter for using default sandbox to
<del>// be passed to endpoint Join method.
<del>func JoinOptionUseDefaultSandbox() EndpointOption {
<del> return func(ep *endpoint) {
<del> ep.container.config.useDefaultSandBox = true
<del> }
<del>}
<del>
<ide> // CreateOptionExposedPorts function returns an option setter for the container exposed
<ide> // ports option to be passed to network.CreateEndpoint() method.
<ide> func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
<ide> func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
<ide> }
<ide> }
<ide>
<del>// JoinOptionGeneric function returns an option setter for Generic configuration
<del>// that is not managed by libNetwork but can be used by the Drivers during the call to
<del>// endpoint join method. Container Labels are a good example.
<del>func JoinOptionGeneric(generic map[string]interface{}) EndpointOption {
<add>// JoinOptionPriority function returns an option setter for priority option to
<add>// be passed to the endpoint.Join() method.
<add>func JoinOptionPriority(ep Endpoint, prio int) EndpointOption {
<ide> return func(ep *endpoint) {
<del> ep.container.config.generic = generic
<add> // ep lock already acquired
<add> c := ep.network.getController()
<add> c.Lock()
<add> sb, ok := c.sandboxes[ep.sandboxID]
<add> c.Unlock()
<add> if !ok {
<add> log.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
<add> return
<add> }
<add> sb.epPriority[ep.id] = prio
<ide> }
<ide> }
<ide><path>libnetwork/endpoint_info.go
<ide> type EndpointInfo interface {
<ide> // This will only return a valid value if a container has joined the endpoint.
<ide> GatewayIPv6() net.IP
<ide>
<del> // SandboxKey returns the sanbox key for the container which has joined
<del> // the endpoint. If there is no container joined then this will return an
<del> // empty string.
<del> SandboxKey() string
<add> // Sandbox returns the attached sandbox if there, nil otherwise.
<add> Sandbox() Sandbox
<ide> }
<ide>
<ide> // InterfaceInfo provides an interface to retrieve interface addresses bound to the endpoint.
<ide> type InterfaceInfo interface {
<ide> AddressIPv6() net.IPNet
<ide> }
<ide>
<del>// ContainerInfo provides an interface to retrieve the info about the container attached to the endpoint
<del>type ContainerInfo interface {
<del> // ID returns the ID of the container
<del> ID() string
<del> // Labels returns the container's labels
<del> Labels() map[string]interface{}
<del>}
<del>
<ide> type endpointInterface struct {
<ide> id int
<ide> mac net.HardwareAddr
<ide> func (epi *endpointInterface) UnmarshalJSON(b []byte) (err error) {
<ide> }
<ide>
<ide> type endpointJoinInfo struct {
<del> gw net.IP
<del> gw6 net.IP
<del> hostsPath string
<del> resolvConfPath string
<del> StaticRoutes []*types.StaticRoute
<del>}
<del>
<del>func (ep *endpoint) ContainerInfo() ContainerInfo {
<del> ep.Lock()
<del> ci := ep.container
<del> defer ep.Unlock()
<del>
<del> // Need this since we return the interface
<del> if ci == nil {
<del> return nil
<del> }
<del> return ci
<add> gw net.IP
<add> gw6 net.IP
<add> StaticRoutes []*types.StaticRoute
<ide> }
<ide>
<ide> func (ep *endpoint) Info() EndpointInfo {
<ide> func (ep *endpoint) addInterfaceRoute(route *types.StaticRoute) error {
<ide> route.InterfaceID)
<ide> }
<ide>
<del>func (ep *endpoint) SandboxKey() string {
<del> ep.Lock()
<del> defer ep.Unlock()
<del>
<del> if ep.container == nil {
<del> return ""
<add>func (ep *endpoint) Sandbox() Sandbox {
<add> cnt, ok := ep.getSandbox()
<add> if !ok {
<add> return nil
<ide> }
<del>
<del> return ep.container.data.SandboxKey
<add> return cnt
<ide> }
<ide>
<ide> func (ep *endpoint) Gateway() net.IP {
<ide> func (ep *endpoint) SetGatewayIPv6(gw6 net.IP) error {
<ide> ep.joinInfo.gw6 = types.GetIPCopy(gw6)
<ide> return nil
<ide> }
<del>
<del>func (ep *endpoint) SetHostsPath(path string) error {
<del> ep.Lock()
<del> defer ep.Unlock()
<del>
<del> ep.joinInfo.hostsPath = path
<del> return nil
<del>}
<del>
<del>func (ep *endpoint) SetResolvConfPath(path string) error {
<del> ep.Lock()
<del> defer ep.Unlock()
<del>
<del> ep.joinInfo.resolvConfPath = path
<del> return nil
<del>}
<ide><path>libnetwork/libnetwork_test.go
<ide> import (
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/netutils"
<ide> "github.com/docker/libnetwork/options"
<add> "github.com/docker/libnetwork/osl"
<ide> "github.com/docker/libnetwork/types"
<ide> "github.com/vishvananda/netlink"
<ide> "github.com/vishvananda/netns"
<ide> func getPortMapping() []types.PortBinding {
<ide> }
<ide>
<ide> func TestNull(t *testing.T) {
<add> cnt, err := controller.NewSandbox("null_container",
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> network, err := createTestNetwork("null", "testnull", options.Generic{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestNull(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep.Join("null_container",
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<add> err = ep.Join(cnt)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep.Leave("null_container")
<add> err = ep.Leave(cnt)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestNull(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> if err := cnt.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> // host type is special network. Cannot be removed.
<ide> err = network.Delete()
<ide> if err == nil {
<ide> func TestNull(t *testing.T) {
<ide> }
<ide>
<ide> func TestHost(t *testing.T) {
<add> sbx1, err := controller.NewSandbox("host_c1",
<add> libnetwork.OptionHostname("test1"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"),
<add> libnetwork.OptionUseDefaultSandbox())
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := sbx1.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> sbx2, err := controller.NewSandbox("host_c2",
<add> libnetwork.OptionHostname("test2"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"),
<add> libnetwork.OptionUseDefaultSandbox())
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := sbx2.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<ide> network, err := createTestNetwork("host", "testhost", options.Generic{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestHost(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep1.Join("host_container1",
<del> libnetwork.JoinOptionHostname("test1"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"),
<del> libnetwork.JoinOptionUseDefaultSandbox())
<del> if err != nil {
<add> if err := ep1.Join(sbx1); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestHost(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep2.Join("host_container2",
<del> libnetwork.JoinOptionHostname("test2"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"),
<del> libnetwork.JoinOptionUseDefaultSandbox())
<del> if err != nil {
<add> if err := ep2.Join(sbx2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep1.Leave("host_container1")
<del> if err != nil {
<add> if err := ep1.Leave(sbx1); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep2.Leave("host_container2")
<del> if err != nil {
<add> if err := ep2.Leave(sbx2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestHost(t *testing.T) {
<ide> }
<ide>
<ide> // Try to create another host endpoint and join/leave that.
<del> ep3, err := network.CreateEndpoint("testep3")
<add> cnt3, err := controller.NewSandbox("host_c3",
<add> libnetwork.OptionHostname("test3"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"),
<add> libnetwork.OptionUseDefaultSandbox())
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer func() {
<add> if err := cnt3.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<ide>
<del> err = ep3.Join("host_container3",
<del> libnetwork.JoinOptionHostname("test3"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"),
<del> libnetwork.JoinOptionUseDefaultSandbox())
<add> ep3, err := network.CreateEndpoint("testep3")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep3.Leave("host_container3")
<del> if err != nil {
<add> if err := ep3.Join(sbx2); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep3.Leave(sbx2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestNetworkQuery(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>const containerID = "valid_container"
<add>const containerID = "valid_c"
<ide>
<ide> func checkSandbox(t *testing.T, info libnetwork.EndpointInfo) {
<ide> origns, err := netns.Get()
<ide> func checkSandbox(t *testing.T, info libnetwork.EndpointInfo) {
<ide> }
<ide> defer origns.Close()
<ide>
<del> key := info.SandboxKey()
<add> key := info.Sandbox().Key()
<ide> f, err := os.OpenFile(key, os.O_RDONLY, 0)
<ide> if err != nil {
<ide> t.Fatalf("Failed to open network namespace path %q: %v", key, err)
<ide> func TestEndpointJoin(t *testing.T) {
<ide>
<ide> // Validate if ep.Info() only gives me IP address info and not names and gateway during CreateEndpoint()
<ide> info := ep1.Info()
<del>
<ide> for _, iface := range info.InterfaceList() {
<ide> if iface.Address().IP.To4() == nil {
<ide> t.Fatalf("Invalid IP address returned: %v", iface.Address())
<ide> func TestEndpointJoin(t *testing.T) {
<ide> t.Fatalf("Expected empty gateway for an empty endpoint. Instead found a gateway: %v", info.Gateway())
<ide> }
<ide>
<del> if info.SandboxKey() != "" {
<del> t.Fatalf("Expected an empty sandbox key for an empty endpoint. Instead found a non-empty sandbox key: %s", info.SandboxKey())
<add> if info.Sandbox() != nil {
<add> t.Fatalf("Expected an empty sandbox key for an empty endpoint. Instead found a non-empty sandbox key: %s", info.Sandbox().Key())
<ide> }
<ide>
<del> defer controller.LeaveAll(containerID)
<add> // test invalid joins
<add> err = ep1.Join(nil)
<add> if err == nil {
<add> t.Fatalf("Expected to fail join with nil Sandbox")
<add> }
<add> if _, ok := err.(types.BadRequestError); !ok {
<add> t.Fatalf("Unexpected error type returned: %T", err)
<add> }
<ide>
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<add> fsbx := &fakeSandbox{}
<add> if err = ep1.Join(fsbx); err == nil {
<add> t.Fatalf("Expected to fail join with invalid Sandbox")
<add> }
<add> if _, ok := err.(types.BadRequestError); !ok {
<add> t.Fatalf("Unexpected error type returned: %T", err)
<add> }
<add>
<add> sb, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> defer func() {
<add> if err := sb.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> err = ep1.Join(sb)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep1.Leave(containerID)
<add> err = ep1.Leave(sb)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestEndpointJoin(t *testing.T) {
<ide> t.Fatalf("Expected a valid gateway for a joined endpoint. Instead found an invalid gateway: %v", info.Gateway())
<ide> }
<ide>
<del> if info.SandboxKey() == "" {
<add> if info.Sandbox() == nil {
<ide> t.Fatalf("Expected an non-empty sandbox key for a joined endpoint. Instead found a empty sandbox key")
<ide> }
<ide>
<ide> // Check endpoint provided container information
<del> if ep1.ContainerInfo().ID() != containerID {
<del> t.Fatalf("Endpoint ContainerInfo returned unexpected id: %s", ep1.ContainerInfo().ID())
<add> if ep1.Info().Sandbox().Key() != sb.Key() {
<add> t.Fatalf("Endpoint Info returned unexpected sandbox key: %s", sb.Key())
<ide> }
<ide>
<ide> // Attempt retrieval of endpoint interfaces statistics
<del> stats, err := ep1.Statistics()
<add> stats, err := sb.Statistics()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestEndpointJoin(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> err = ep2.Join(containerID)
<add> err = ep2.Join(sb)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> runtime.LockOSThread()
<ide> defer func() {
<del> err = ep2.Leave(containerID)
<add> err = ep2.Leave(sb)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<del> if ep1.ContainerInfo().ID() != ep2.ContainerInfo().ID() {
<del> t.Fatalf("ep1 and ep2 returned different container info")
<add> if ep1.Info().Sandbox().Key() != ep2.Info().Sandbox().Key() {
<add> t.Fatalf("ep1 and ep2 returned different container sandbox key")
<ide> }
<ide>
<ide> checkSandbox(t, info)
<add>}
<ide>
<add>type fakeSandbox struct{}
<add>
<add>func (f *fakeSandbox) ID() string {
<add> return "fake sandbox"
<ide> }
<ide>
<del>func TestEndpointJoinInvalidContainerId(t *testing.T) {
<del> if !netutils.IsRunningInContainer() {
<del> defer netutils.SetupTestNetNS(t)()
<del> }
<add>func (f *fakeSandbox) ContainerID() string {
<add> return ""
<add>}
<ide>
<del> n, err := createTestNetwork(bridgeNetType, "testnetwork", options.Generic{
<del> netlabel.GenericData: options.Generic{
<del> "BridgeName": "testnetwork",
<del> "AllowNonDefaultBridge": true,
<del> },
<del> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer func() {
<del> if err := n.Delete(); err != nil {
<del> t.Fatal(err)
<del> }
<del> }()
<add>func (f *fakeSandbox) Key() string {
<add> return "fake key"
<add>}
<ide>
<del> ep, err := n.CreateEndpoint("ep1")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer func() {
<del> if err := ep.Delete(); err != nil {
<del> t.Fatal(err)
<del> }
<del> }()
<add>func (f *fakeSandbox) Labels() map[string]interface{} {
<add> return nil
<add>}
<ide>
<del> err = ep.Join("")
<del> if err == nil {
<del> t.Fatal("Expected to fail join with empty container id string")
<del> }
<add>func (f *fakeSandbox) Statistics() (map[string]*osl.InterfaceStatistics, error) {
<add> return nil, nil
<add>}
<ide>
<del> if _, ok := err.(libnetwork.InvalidContainerIDError); !ok {
<del> t.Fatalf("Failed for unexpected reason: %v", err)
<del> }
<add>func (f *fakeSandbox) Delete() error {
<add> return nil
<ide> }
<ide>
<ide> func TestEndpointDeleteWithActiveContainer(t *testing.T) {
<ide> func TestEndpointDeleteWithActiveContainer(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> defer controller.LeaveAll(containerID)
<add> cnt, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<add> defer func() {
<add> if err := cnt.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<ide>
<del> err = ep.Join(containerID,
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<add> err = ep.Join(cnt)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep.Leave(containerID)
<add> err = ep.Leave(cnt)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestEndpointMultipleJoins(t *testing.T) {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> }
<ide>
<del> n, err := createTestNetwork(bridgeNetType, "testnetwork", options.Generic{
<add> n, err := createTestNetwork(bridgeNetType, "testmultiple", options.Generic{
<ide> netlabel.GenericData: options.Generic{
<del> "BridgeName": "testnetwork",
<add> "BridgeName": "testmultiple",
<ide> "AllowNonDefaultBridge": true,
<ide> },
<ide> })
<ide> func TestEndpointMultipleJoins(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> defer controller.LeaveAll(containerID)
<add> sbx1, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<add> defer func() {
<add> if err := sbx1.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<ide>
<del> err = ep.Join(containerID,
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<add> sbx2, err := controller.NewSandbox("c2")
<add> defer func() {
<add> if err := sbx2.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> runtime.LockOSThread()
<add> }()
<add>
<add> err = ep.Join(sbx1)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep.Leave(containerID)
<add> err = ep.Leave(sbx1)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<del> err = ep.Join("container2")
<add> err = ep.Join(sbx2)
<ide> if err == nil {
<ide> t.Fatal("Expected to fail multiple joins for the same endpoint")
<ide> }
<ide>
<del> if _, ok := err.(libnetwork.ErrInvalidJoin); !ok {
<del> t.Fatalf("Failed for unexpected reason: %v", err)
<add> if _, ok := err.(types.ForbiddenError); !ok {
<add> t.Fatalf("Failed with unexpected error type: %T. Desc: %s", err, err.Error())
<ide> }
<add>
<ide> }
<ide>
<ide> func TestLeaveAll(t *testing.T) {
<ide> func TestLeaveAll(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<add> // If this goes through, it means cnt.Delete() effectively detached from all the endpoints
<ide> if err := n.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestLeaveAll(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> err = ep1.Join("leaveall")
<add> cnt, err := controller.NewSandbox("leaveall")
<ide> if err != nil {
<del> t.Fatalf("Failed to join ep1: %v", err)
<add> t.Fatal(err)
<ide> }
<del> runtime.LockOSThread()
<ide>
<del> err = ep2.Join("leaveall")
<add> err = ep1.Join(cnt)
<ide> if err != nil {
<del> t.Fatalf("Failed to join ep2: %v", err)
<add> t.Fatalf("Failed to join ep1: %v", err)
<ide> }
<ide> runtime.LockOSThread()
<ide>
<del> err = ep1.Leave("leaveall")
<add> err = ep2.Join(cnt)
<ide> if err != nil {
<del> t.Fatalf("Failed to leave ep1: %v", err)
<add> t.Fatalf("Failed to join ep2: %v", err)
<ide> }
<ide> runtime.LockOSThread()
<ide>
<del> err = controller.LeaveAll("leaveall")
<add> err = cnt.Delete()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> runtime.LockOSThread()
<ide> }
<ide>
<del>func TestEndpointInvalidLeave(t *testing.T) {
<add>func TestontainerInvalidLeave(t *testing.T) {
<ide> if !netutils.IsRunningInContainer() {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> }
<ide> func TestEndpointInvalidLeave(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> err = ep.Leave(containerID)
<del> if err == nil {
<del> t.Fatal("Expected to fail leave from an endpoint which has no active join")
<del> }
<del>
<del> if _, ok := err.(libnetwork.InvalidContainerIDError); !ok {
<del> if _, ok := err.(libnetwork.ErrNoContainer); !ok {
<del> t.Fatalf("Failed for unexpected reason: %v", err)
<del> }
<del> }
<del>
<del> defer controller.LeaveAll(containerID)
<del>
<del> err = ep.Join(containerID,
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<del> runtime.LockOSThread()
<add> cnt, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep.Leave(containerID)
<del> runtime.LockOSThread()
<del> if err != nil {
<add> if err := cnt.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<del> err = ep.Leave("")
<add> err = ep.Leave(cnt)
<ide> if err == nil {
<del> t.Fatal("Expected to fail leave with empty container id")
<add> t.Fatal("Expected to fail leave from an endpoint which has no active join")
<ide> }
<del>
<del> if _, ok := err.(libnetwork.InvalidContainerIDError); !ok {
<del> t.Fatalf("Failed for unexpected reason: %v", err)
<add> if _, ok := err.(types.ForbiddenError); !ok {
<add> t.Fatalf("Failed with unexpected error type: %T. Desc: %s", err, err.Error())
<ide> }
<ide>
<del> err = ep.Leave("container2")
<del> if err == nil {
<del> t.Fatal("Expected to fail leave with wrong container id")
<add> if err := ep.Leave(nil); err == nil {
<add> t.Fatalf("Expected to fail leave nil Sandbox")
<add> }
<add> if _, ok := err.(types.BadRequestError); !ok {
<add> t.Fatalf("Unexpected error type returned: %T", err)
<ide> }
<ide>
<del> if _, ok := err.(libnetwork.InvalidContainerIDError); !ok {
<del> t.Fatalf("Failed for unexpected reason: %v", err)
<add> fsbx := &fakeSandbox{}
<add> if err = ep.Leave(fsbx); err == nil {
<add> t.Fatalf("Expected to fail leave with invalid Sandbox")
<add> }
<add> if _, ok := err.(types.BadRequestError); !ok {
<add> t.Fatalf("Unexpected error type returned: %T", err)
<ide> }
<ide> }
<ide>
<ide> func TestEndpointUpdateParent(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> defer controller.LeaveAll(containerID)
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionHostname("test1"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionExtraHost("web", "192.168.0.1"))
<del> runtime.LockOSThread()
<add> ep2, err := n.CreateEndpoint("ep2")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep1.Leave(containerID)
<del> runtime.LockOSThread()
<del> if err != nil {
<add> if err := ep2.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<del> ep2, err := n.CreateEndpoint("ep2")
<add> sbx1, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.1"))
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> if err := ep2.Delete(); err != nil {
<add> if err := sbx1.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> sbx2, err := controller.NewSandbox("c2",
<add> libnetwork.OptionHostname("test2"),
<add> libnetwork.OptionDomainname("docker.io"),
<add> libnetwork.OptionHostsPath("/var/lib/docker/test_network/container2/hosts"),
<add> libnetwork.OptionExtraHost("web", "192.168.0.2"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := sbx2.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<del> defer controller.LeaveAll("container2")
<del> err = ep2.Join("container2",
<del> libnetwork.JoinOptionHostname("test2"),
<del> libnetwork.JoinOptionDomainname("docker.io"),
<del> libnetwork.JoinOptionHostsPath("/var/lib/docker/test_network/container2/hosts"),
<del> libnetwork.JoinOptionParentUpdate(ep1.ID(), "web", "192.168.0.2"))
<add> err = ep1.Join(sbx1)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep2.Leave("container2")
<add> err = ep2.Join(sbx2)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> err = ep2.Leave(sbx2)
<add> runtime.LockOSThread()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide> }
<ide>
<ide> func TestEnableIPv6(t *testing.T) {
<ide> if !netutils.IsRunningInContainer() {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> }
<ide>
<del> tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888")
<add> tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888\n")
<ide> //take a copy of resolv.conf for restoring after test completes
<ide> resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
<ide> if err != nil {
<ide> func TestEnableIPv6(t *testing.T) {
<ide> resolvConfPath := "/tmp/libnetwork_test/resolv.conf"
<ide> defer os.Remove(resolvConfPath)
<ide>
<del> defer controller.LeaveAll(containerID)
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<del> runtime.LockOSThread()
<add> sb, err := controller.NewSandbox(containerID, libnetwork.OptionResolvConfPath(resolvConfPath))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := sb.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> err = ep1.Join(sb)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep1.Leave(containerID)
<add> err = ep1.Leave(sb)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestEnableIPv6(t *testing.T) {
<ide> }
<ide>
<ide> if !bytes.Equal(content, tmpResolvConf) {
<del> t.Fatalf("Expected %s, Got %s", string(tmpResolvConf), string(content))
<add> t.Fatalf("Expected:\n%s\nGot:\n%s", string(tmpResolvConf), string(content))
<ide> }
<ide>
<ide> if err != nil {
<ide> func TestResolvConfHost(t *testing.T) {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> }
<ide>
<del> tmpResolvConf := []byte("search localhost.net\nnameserver 127.0.0.1\nnameserver 2001:4860:4860::8888")
<add> tmpResolvConf := []byte("search localhost.net\nnameserver 127.0.0.1\nnameserver 2001:4860:4860::8888\n")
<ide>
<ide> //take a copy of resolv.conf for restoring after test completes
<ide> resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
<ide> func TestResolvConfHost(t *testing.T) {
<ide> resolvConfPath := "/tmp/libnetwork_test/resolv.conf"
<ide> defer os.Remove(resolvConfPath)
<ide>
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<add> sb, err := controller.NewSandbox(containerID,
<add> libnetwork.OptionResolvConfPath(resolvConfPath),
<add> libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep1.Leave(containerID)
<add> if err := sb.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> err = ep1.Join(sb)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> err = ep1.Leave(sb)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestResolvConfHost(t *testing.T) {
<ide> }
<ide>
<ide> if !bytes.Equal(content, tmpResolvConf) {
<del> t.Fatalf("Expected %s, Got %s", string(tmpResolvConf), string(content))
<add> t.Fatalf("Expected:\n%s\nGot:\n%s", string(tmpResolvConf), string(content))
<ide> }
<ide> }
<ide>
<ide> func TestResolvConf(t *testing.T) {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> }
<ide>
<del> tmpResolvConf1 := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888")
<add> tmpResolvConf1 := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888\n")
<ide> expectedResolvConf1 := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n")
<del> tmpResolvConf2 := []byte("search pommesfrites.fr\nnameserver 112.34.56.78\nnameserver 2001:4860:4860::8888")
<add> tmpResolvConf2 := []byte("search pommesfrites.fr\nnameserver 112.34.56.78\nnameserver 2001:4860:4860::8888\n")
<ide> expectedResolvConf2 := []byte("search pommesfrites.fr\nnameserver 112.34.56.78\n")
<ide> tmpResolvConf3 := []byte("search pommesfrites.fr\nnameserver 113.34.56.78\n")
<ide>
<ide> func TestResolvConf(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> ep1, err := n.CreateEndpoint("ep1")
<add> ep, err := n.CreateEndpoint("ep")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> if err := ep1.Delete(); err != nil {
<add> if err := ep.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide> func TestResolvConf(t *testing.T) {
<ide> resolvConfPath := "/tmp/libnetwork_test/resolv.conf"
<ide> defer os.Remove(resolvConfPath)
<ide>
<del> defer controller.LeaveAll(containerID)
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<del> runtime.LockOSThread()
<add> sb1, err := controller.NewSandbox(containerID, libnetwork.OptionResolvConfPath(resolvConfPath))
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> defer func() {
<del> err = ep1.Leave(containerID)
<del> runtime.LockOSThread()
<del> if err != nil {
<add> if err := sb1.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<add> err = ep.Join(sb1)
<add> runtime.LockOSThread()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> finfo, err := os.Stat(resolvConfPath)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestResolvConf(t *testing.T) {
<ide> }
<ide>
<ide> if !bytes.Equal(content, expectedResolvConf1) {
<del> t.Fatalf("Expected %s, Got %s", string(expectedResolvConf1), string(content))
<add> fmt.Printf("\n%v\n%v\n", expectedResolvConf1, content)
<add> t.Fatalf("Expected:\n%s\nGot:\n%s", string(expectedResolvConf1), string(content))
<ide> }
<ide>
<del> err = ep1.Leave(containerID)
<add> err = ep.Leave(sb1)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestResolvConf(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<add> sb2, err := controller.NewSandbox(containerID+"_2", libnetwork.OptionResolvConfPath(resolvConfPath))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := sb2.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> err = ep.Join(sb2)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestResolvConf(t *testing.T) {
<ide> }
<ide>
<ide> if !bytes.Equal(content, expectedResolvConf2) {
<del> t.Fatalf("Expected %s, Got %s", string(expectedResolvConf2), string(content))
<add> t.Fatalf("Expected:\n%s\nGot:\n%s", string(expectedResolvConf2), string(content))
<ide> }
<ide>
<ide> if err := ioutil.WriteFile(resolvConfPath, tmpResolvConf3, 0644); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep1.Leave(containerID)
<add> err = ep.Leave(sb2)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = ep1.Join(containerID,
<del> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<add> err = ep.Join(sb2)
<ide> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestResolvConf(t *testing.T) {
<ide> }
<ide>
<ide> if !bytes.Equal(content, tmpResolvConf3) {
<del> t.Fatalf("Expected %s, Got %s", string(tmpResolvConf3), string(content))
<add> t.Fatalf("Expected:\n%s\nGot:\n%s", string(tmpResolvConf3), string(content))
<ide> }
<ide> }
<ide>
<ide> var (
<ide> done = make(chan chan struct{}, numThreads-1)
<ide> origns = netns.None()
<ide> testns = netns.None()
<add> sboxes = make([]libnetwork.Sandbox, numThreads)
<ide> )
<ide>
<ide> const (
<ide> func createGlobalInstance(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add>
<add> if sboxes[first-1], err = controller.NewSandbox(fmt.Sprintf("%drace", first), libnetwork.OptionUseDefaultSandbox()); err != nil {
<add> t.Fatal(err)
<add> }
<add> for thd := first + 1; thd <= last; thd++ {
<add> if sboxes[thd-1], err = controller.NewSandbox(fmt.Sprintf("%drace", thd)); err != nil {
<add> t.Fatal(err)
<add> }
<add> }
<ide> }
<ide>
<ide> func debugf(format string, a ...interface{}) (int, error) {
<ide> func debugf(format string, a ...interface{}) (int, error) {
<ide> return 0, nil
<ide> }
<ide>
<del>func parallelJoin(t *testing.T, ep libnetwork.Endpoint, thrNumber int) {
<add>func parallelJoin(t *testing.T, rc libnetwork.Sandbox, ep libnetwork.Endpoint, thrNumber int) {
<ide> debugf("J%d.", thrNumber)
<ide> var err error
<del> if thrNumber == first {
<del> err = ep.Join(fmt.Sprintf("%drace", thrNumber), libnetwork.JoinOptionUseDefaultSandbox())
<del> } else {
<del> err = ep.Join(fmt.Sprintf("%drace", thrNumber))
<del> }
<add>
<add> sb := sboxes[thrNumber-1]
<add> err = ep.Join(sb)
<ide>
<ide> runtime.LockOSThread()
<ide> if err != nil {
<del> if _, ok := err.(libnetwork.ErrNoContainer); !ok {
<del> if _, ok := err.(libnetwork.ErrInvalidJoin); !ok {
<del> t.Fatalf("thread %d: %v", thrNumber, err)
<del> }
<add> if _, ok := err.(types.ForbiddenError); !ok {
<add> t.Fatalf("thread %d: %v", thrNumber, err)
<ide> }
<ide> debugf("JE%d(%v).", thrNumber, err)
<ide> }
<ide> debugf("JD%d.", thrNumber)
<ide> }
<ide>
<del>func parallelLeave(t *testing.T, ep libnetwork.Endpoint, thrNumber int) {
<add>func parallelLeave(t *testing.T, rc libnetwork.Sandbox, ep libnetwork.Endpoint, thrNumber int) {
<ide> debugf("L%d.", thrNumber)
<ide> var err error
<add>
<add> cid := fmt.Sprintf("%drace", thrNumber)
<add> sb := sboxes[thrNumber-1]
<add>
<ide> if thrNumber == first {
<del> err = ep.Leave(fmt.Sprintf("%drace", thrNumber))
<add> err = ep.Leave(sb)
<ide> } else {
<del> err = controller.LeaveAll(fmt.Sprintf("%drace", thrNumber))
<add> err = sb.Delete()
<add> // re add sandbox
<add> defer func() {
<add> if err == nil {
<add> var e error
<add> if sboxes[thrNumber-1], e = controller.NewSandbox(cid); e != nil {
<add> t.Fatalf("Failed to recreate sandbox %s: %v", cid, e)
<add> }
<add> }
<add> }()
<ide> }
<ide>
<ide> runtime.LockOSThread()
<ide> if err != nil {
<del> if _, ok := err.(libnetwork.ErrNoContainer); !ok {
<del> if _, ok := err.(libnetwork.ErrInvalidJoin); !ok {
<del> t.Fatalf("thread %d: %v", thrNumber, err)
<del> }
<add> if _, ok := err.(types.ForbiddenError); !ok {
<add> t.Fatalf("thread %d: %v", thrNumber, err)
<ide> }
<ide> debugf("LE%d(%v).", thrNumber, err)
<ide> }
<ide> debugf("LD%d.", thrNumber)
<ide> }
<ide>
<ide> func runParallelTests(t *testing.T, thrNumber int) {
<del> var err error
<add> var (
<add> ep libnetwork.Endpoint
<add> sb libnetwork.Sandbox
<add> err error
<add> )
<ide>
<ide> t.Parallel()
<ide>
<ide> func runParallelTests(t *testing.T, thrNumber int) {
<ide> t.Fatal(err)
<ide> }
<ide> if net1 == nil {
<del> t.Fatal("Could not find network1")
<add> t.Fatal("Could not find testhost")
<ide> }
<ide>
<ide> net2, err := controller.NetworkByName("network2")
<ide> func runParallelTests(t *testing.T, thrNumber int) {
<ide>
<ide> epName := fmt.Sprintf("pep%d", thrNumber)
<ide>
<del> //var err error
<del> var ep libnetwork.Endpoint
<del>
<ide> if thrNumber == first {
<ide> ep, err = net1.EndpointByName(epName)
<ide> } else {
<ide> func runParallelTests(t *testing.T, thrNumber int) {
<ide> t.Fatal("Got nil ep with no error")
<ide> }
<ide>
<add> cid := fmt.Sprintf("%drace", thrNumber)
<add> controller.WalkSandboxes(libnetwork.SandboxContainerWalker(&sb, cid))
<add> if sb == nil {
<add> t.Fatalf("Got nil sandbox for container: %s", cid)
<add> }
<add>
<ide> for i := 0; i < iterCnt; i++ {
<del> parallelJoin(t, ep, thrNumber)
<del> parallelLeave(t, ep, thrNumber)
<add> parallelJoin(t, sb, ep, thrNumber)
<add> parallelLeave(t, sb, ep, thrNumber)
<ide> }
<ide>
<ide> debugf("\n")
<ide> func runParallelTests(t *testing.T, thrNumber int) {
<ide> }
<ide>
<ide> testns.Close()
<add> err = sb.Delete()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> ep.Delete()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<ide> if err := net2.Delete(); err != nil {
<ide> t.Fatal(err)
<ide><path>libnetwork/network.go
<ide> type network struct {
<ide> ctrlr *controller
<ide> name string
<ide> networkType string
<del> id types.UUID
<add> id string
<ide> driver driverapi.Driver
<ide> enableIPv6 bool
<ide> endpointCnt uint64
<ide> func (n *network) ID() string {
<ide> n.Lock()
<ide> defer n.Unlock()
<ide>
<del> return string(n.id)
<add> return n.id
<ide> }
<ide>
<ide> func (n *network) Type() string {
<ide> func (n *network) Type() string {
<ide> func (n *network) Key() []string {
<ide> n.Lock()
<ide> defer n.Unlock()
<del> return []string{datastore.NetworkKeyPrefix, string(n.id)}
<add> return []string{datastore.NetworkKeyPrefix, n.id}
<ide> }
<ide>
<ide> func (n *network) KeyPrefix() []string {
<ide> func (n *network) DecEndpointCnt() {
<ide> func (n *network) MarshalJSON() ([]byte, error) {
<ide> netMap := make(map[string]interface{})
<ide> netMap["name"] = n.name
<del> netMap["id"] = string(n.id)
<add> netMap["id"] = n.id
<ide> netMap["networkType"] = n.networkType
<ide> netMap["endpointCnt"] = n.endpointCnt
<ide> netMap["enableIPv6"] = n.enableIPv6
<ide> func (n *network) UnmarshalJSON(b []byte) (err error) {
<ide> return err
<ide> }
<ide> n.name = netMap["name"].(string)
<del> n.id = types.UUID(netMap["id"].(string))
<add> n.id = netMap["id"].(string)
<ide> n.networkType = netMap["networkType"].(string)
<ide> n.endpointCnt = uint64(netMap["endpointCnt"].(float64))
<ide> n.enableIPv6 = netMap["enableIPv6"].(bool)
<ide> func (n *network) Delete() error {
<ide> ctrlr.Unlock()
<ide>
<ide> if !ok {
<del> return &UnknownNetworkError{name: n.name, id: string(n.id)}
<add> return &UnknownNetworkError{name: n.name, id: n.id}
<ide> }
<ide>
<ide> numEps := n.EndpointCnt()
<ide> if numEps != 0 {
<del> return &ActiveEndpointsError{name: n.name, id: string(n.id)}
<add> return &ActiveEndpointsError{name: n.name, id: n.id}
<ide> }
<ide>
<ide> // deleteNetworkFromStore performs an atomic delete operation and the network.endpointCnt field will help
<ide> func (n *network) addEndpoint(ep *endpoint) error {
<ide>
<ide> err = d.CreateEndpoint(n.id, ep.id, ep, ep.generic)
<ide> if err != nil {
<del> return err
<add> return types.InternalErrorf("failed to create endpoint %s on network %s: %v", ep.Name(), n.Name(), err)
<ide> }
<ide>
<ide> n.updateSvcRecord(ep, true)
<ide> func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoi
<ide> ep := &endpoint{name: name,
<ide> iFaces: []*endpointInterface{},
<ide> generic: make(map[string]interface{})}
<del> ep.id = types.UUID(stringid.GenerateRandomID())
<add> ep.id = stringid.GenerateRandomID()
<ide> ep.network = n
<ide> ep.processOptions(options...)
<ide>
<ide> func (n *network) EndpointByID(id string) (Endpoint, error) {
<ide> }
<ide> n.Lock()
<ide> defer n.Unlock()
<del> if e, ok := n.endpoints[types.UUID(id)]; ok {
<add> if e, ok := n.endpoints[id]; ok {
<ide> return e, nil
<ide> }
<ide> return nil, ErrNoSuchEndpoint(id)
<ide> func (n *network) updateSvcRecord(ep *endpoint, isAdd bool) {
<ide> return
<ide> }
<ide>
<del> var epList []*endpoint
<add> var sbList []*sandbox
<ide> n.WalkEndpoints(func(e Endpoint) bool {
<del> cEp := e.(*endpoint)
<del> cEp.Lock()
<del> if cEp.container != nil {
<del> epList = append(epList, cEp)
<add> if sb, hasSandbox := e.(*endpoint).getSandbox(); hasSandbox {
<add> sbList = append(sbList, sb)
<ide> }
<del> cEp.Unlock()
<ide> return false
<ide> })
<ide>
<del> for _, cEp := range epList {
<add> for _, sb := range sbList {
<ide> if isAdd {
<del> cEp.addHostEntries(recs)
<add> sb.addHostsEntries(recs)
<ide> } else {
<del> cEp.deleteHostEntries(recs)
<add> sb.deleteHostsEntries(recs)
<ide> }
<ide> }
<ide> }
<ide> func (n *network) getSvcRecords() []etchosts.Record {
<ide>
<ide> return recs
<ide> }
<add>
<add>func (n *network) getController() *controller {
<add> n.Lock()
<add> defer n.Unlock()
<add> return n.ctrlr
<add>}
<add><path>libnetwork/osl/interface_freebsd.go
<del><path>libnetwork/sandbox/interface_freebsd.go
<del>package sandbox
<add>package osl
<ide>
<ide> // IfaceOption is a function option type to set interface options
<ide> type IfaceOption func()
<add><path>libnetwork/osl/interface_linux.go
<del><path>libnetwork/sandbox/interface_linux.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "fmt"
<add><path>libnetwork/osl/interface_windows.go
<del><path>libnetwork/sandbox/interface_windows.go
<del>package sandbox
<add>package osl
<ide>
<ide> // IfaceOption is a function option type to set interface options
<ide> type IfaceOption func()
<add><path>libnetwork/osl/namespace_linux.go
<del><path>libnetwork/sandbox/namespace_linux.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "fmt"
<add><path>libnetwork/osl/namespace_unsupported.go
<del><path>libnetwork/sandbox/namespace_unsupported.go
<ide> // +build !linux,!windows,!freebsd
<ide>
<del>package sandbox
<add>package osl
<ide>
<ide> // GC triggers garbage collection of namespace path right away
<ide> // and waits for it.
<add><path>libnetwork/osl/namespace_windows.go
<del><path>libnetwork/sandbox/namespace_windows.go
<del>package sandbox
<add>package osl
<ide>
<ide> // GenerateKey generates a sandbox key based on the passed
<ide> // container id.
<add><path>libnetwork/osl/neigh_freebsd.go
<del><path>libnetwork/sandbox/neigh_freebsd.go
<del>package sandbox
<add>package osl
<ide>
<ide> // NeighOption is a function option type to set neighbor options
<ide> type NeighOption func()
<add><path>libnetwork/osl/neigh_linux.go
<del><path>libnetwork/sandbox/neigh_linux.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "bytes"
<add><path>libnetwork/osl/neigh_windows.go
<del><path>libnetwork/sandbox/neigh_windows.go
<del>package sandbox
<add>package osl
<ide>
<ide> // NeighOption is a function option type to set neighbor options
<ide> type NeighOption func()
<add><path>libnetwork/osl/options_linux.go
<del><path>libnetwork/sandbox/options_linux.go
<del>package sandbox
<add>package osl
<ide>
<ide> import "net"
<ide>
<add><path>libnetwork/osl/route_linux.go
<del><path>libnetwork/sandbox/route_linux.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "fmt"
<add><path>libnetwork/osl/sandbox.go
<del><path>libnetwork/sandbox/sandbox.go
<del>package sandbox
<add>// Package osl describes structures and interfaces which abstract os entities
<add>package osl
<ide>
<ide> import (
<ide> "fmt"
<add><path>libnetwork/osl/sandbox_freebsd.go
<del><path>libnetwork/sandbox/sandbox_freebsd.go
<del>package sandbox
<add>package osl
<ide>
<ide> // GenerateKey generates a sandbox key based on the passed
<ide> // container id.
<add><path>libnetwork/osl/sandbox_linux_test.go
<del><path>libnetwork/sandbox/sandbox_linux_test.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "net"
<add><path>libnetwork/osl/sandbox_test.go
<del><path>libnetwork/sandbox/sandbox_test.go
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "os"
<add><path>libnetwork/osl/sandbox_unsupported.go
<del><path>libnetwork/sandbox/sandbox_unsupported.go
<ide> // +build !linux,!windows,!freebsd
<ide>
<del>package sandbox
<add>package osl
<ide>
<ide> import "errors"
<ide>
<add><path>libnetwork/osl/sandbox_unsupported_test.go
<del><path>libnetwork/sandbox/sandbox_unsupported_test.go
<ide> // +build !linux
<ide>
<del>package sandbox
<add>package osl
<ide>
<ide> import (
<ide> "errors"
<ide><path>libnetwork/resolvconf/resolvconf.go
<ide> func GetSearchDomains(resolvConf []byte) []string {
<ide> // Build writes a configuration file to path containing a "nameserver" entry
<ide> // for every element in dns, and a "search" entry for every element in
<ide> // dnsSearch.
<del>func Build(path string, dns, dnsSearch []string) error {
<add>func Build(path string, dns, dnsSearch []string) (string, error) {
<ide> content := bytes.NewBuffer(nil)
<del> for _, dns := range dns {
<del> if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
<del> return err
<del> }
<del> }
<ide> if len(dnsSearch) > 0 {
<ide> if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
<ide> if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
<del> return err
<add> return "", err
<ide> }
<ide> }
<ide> }
<add> for _, dns := range dns {
<add> if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
<add> return "", err
<add> }
<add> }
<add>
<add> hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
<add> if err != nil {
<add> return "", err
<add> }
<ide>
<del> return ioutil.WriteFile(path, content.Bytes(), 0644)
<add> return hash, ioutil.WriteFile(path, content.Bytes(), 0644)
<ide> }
<ide><path>libnetwork/resolvconf/resolvconf_test.go
<ide> func TestBuild(t *testing.T) {
<ide> }
<ide> defer os.Remove(file.Name())
<ide>
<del> err = Build(file.Name(), []string{"ns1", "ns2", "ns3"}, []string{"search1"})
<add> _, err = Build(file.Name(), []string{"ns1", "ns2", "ns3"}, []string{"search1"})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestBuild(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if expected := "nameserver ns1\nnameserver ns2\nnameserver ns3\nsearch search1\n"; !bytes.Contains(content, []byte(expected)) {
<add> if expected := "search search1\nnameserver ns1\nnameserver ns2\nnameserver ns3\n"; !bytes.Contains(content, []byte(expected)) {
<ide> t.Fatalf("Expected to find '%s' got '%s'", expected, content)
<ide> }
<ide> }
<ide> func TestBuildWithZeroLengthDomainSearch(t *testing.T) {
<ide> }
<ide> defer os.Remove(file.Name())
<ide>
<del> err = Build(file.Name(), []string{"ns1", "ns2", "ns3"}, []string{"."})
<add> _, err = Build(file.Name(), []string{"ns1", "ns2", "ns3"}, []string{"."})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>libnetwork/sandbox.go
<add>package libnetwork
<add>
<add>import (
<add> "bytes"
<add> "container/heap"
<add> "encoding/json"
<add> "fmt"
<add> "io/ioutil"
<add> "os"
<add> "path"
<add> "path/filepath"
<add> "sync"
<add>
<add> log "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/pkg/ioutils"
<add> "github.com/docker/libnetwork/etchosts"
<add> "github.com/docker/libnetwork/osl"
<add> "github.com/docker/libnetwork/resolvconf"
<add> "github.com/docker/libnetwork/types"
<add>)
<add>
<add>// Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
<add>type Sandbox interface {
<add> // ID returns the ID of the sandbox
<add> ID() string
<add> // Key returns the sandbox's key
<add> Key() string
<add> // ContainerID returns the container id associated to this sandbox
<add> ContainerID() string
<add> // Labels returns the sandbox's labels
<add> Labels() map[string]interface{}
<add> // Statistics retrieves the interfaces' statistics for the sandbox
<add> Statistics() (map[string]*osl.InterfaceStatistics, error)
<add> // Delete destroys this container after detaching it from all connected endpoints.
<add> Delete() error
<add>}
<add>
<add>// SandboxOption is a option setter function type used to pass varios options to
<add>// NewNetContainer method. The various setter functions of type SandboxOption are
<add>// provided by libnetwork, they look like ContainerOptionXXXX(...)
<add>type SandboxOption func(sb *sandbox)
<add>
<add>func (sb *sandbox) processOptions(options ...SandboxOption) {
<add> for _, opt := range options {
<add> if opt != nil {
<add> opt(sb)
<add> }
<add> }
<add>}
<add>
<add>type epHeap []*endpoint
<add>
<add>type sandbox struct {
<add> id string
<add> containerID string
<add> config containerConfig
<add> osSbox osl.Sandbox
<add> controller *controller
<add> refCnt int
<add> endpoints epHeap
<add> epPriority map[string]int
<add> //hostsPath string
<add> //resolvConfPath string
<add> joinLeaveDone chan struct{}
<add> sync.Mutex
<add>}
<add>
<add>// These are the container configs used to customize container /etc/hosts file.
<add>type hostsPathConfig struct {
<add> hostName string
<add> domainName string
<add> hostsPath string
<add> originHostsPath string
<add> extraHosts []extraHost
<add> parentUpdates []parentUpdate
<add>}
<add>
<add>type parentUpdate struct {
<add> cid string
<add> name string
<add> ip string
<add>}
<add>
<add>type extraHost struct {
<add> name string
<add> IP string
<add>}
<add>
<add>// These are the container configs used to customize container /etc/resolv.conf file.
<add>type resolvConfPathConfig struct {
<add> resolvConfPath string
<add> originResolvConfPath string
<add> resolvConfHashFile string
<add> dnsList []string
<add> dnsSearchList []string
<add>}
<add>
<add>type containerConfig struct {
<add> hostsPathConfig
<add> resolvConfPathConfig
<add> generic map[string]interface{}
<add> useDefaultSandBox bool
<add> prio int // higher the value, more the priority
<add>}
<add>
<add>func (sb *sandbox) ID() string {
<add> return sb.id
<add>}
<add>
<add>func (sb *sandbox) ContainerID() string {
<add> return sb.containerID
<add>}
<add>
<add>func (sb *sandbox) Key() string {
<add> if sb.config.useDefaultSandBox {
<add> return osl.GenerateKey("default")
<add> }
<add> return osl.GenerateKey(sb.id)
<add>}
<add>
<add>func (sb *sandbox) Labels() map[string]interface{} {
<add> return sb.config.generic
<add>}
<add>
<add>func (sb *sandbox) Statistics() (map[string]*osl.InterfaceStatistics, error) {
<add> m := make(map[string]*osl.InterfaceStatistics)
<add>
<add> if sb.osSbox == nil {
<add> return m, nil
<add> }
<add>
<add> var err error
<add> for _, i := range sb.osSbox.Info().Interfaces() {
<add> if m[i.DstName()], err = i.Statistics(); err != nil {
<add> return m, err
<add> }
<add> }
<add>
<add> return m, nil
<add>}
<add>
<add>func (sb *sandbox) Delete() error {
<add> sb.Lock()
<add> c := sb.controller
<add> eps := make([]*endpoint, len(sb.endpoints))
<add> for i, ep := range sb.endpoints {
<add> eps[i] = ep
<add> }
<add> sb.Unlock()
<add>
<add> // Detach from all containers
<add> for _, ep := range eps {
<add> if err := ep.Leave(sb); err != nil {
<add> log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
<add> }
<add> }
<add>
<add> if sb.osSbox != nil {
<add> sb.osSbox.Destroy()
<add> }
<add>
<add> c.Lock()
<add> delete(c.sandboxes, sb.ID())
<add> c.Unlock()
<add>
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) MarshalJSON() ([]byte, error) {
<add> sb.Lock()
<add> defer sb.Unlock()
<add>
<add> // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
<add> return json.Marshal(sb.id)
<add>}
<add>
<add>func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
<add> sb.Lock()
<add> defer sb.Unlock()
<add>
<add> var id string
<add> if err := json.Unmarshal(b, &id); err != nil {
<add> return err
<add> }
<add> sb.id = id
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) updateGateway(ep *endpoint) error {
<add> sb.osSbox.UnsetGateway()
<add> sb.osSbox.UnsetGatewayIPv6()
<add>
<add> if ep == nil {
<add> return nil
<add> }
<add>
<add> ep.Lock()
<add> joinInfo := ep.joinInfo
<add> ep.Unlock()
<add>
<add> if err := sb.osSbox.SetGateway(joinInfo.gw); err != nil {
<add> return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
<add> }
<add>
<add> if err := sb.osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
<add> return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
<add> ep.Lock()
<add> joinInfo := ep.joinInfo
<add> ifaces := ep.iFaces
<add> ep.Unlock()
<add>
<add> for _, i := range ifaces {
<add> var ifaceOptions []osl.IfaceOption
<add>
<add> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(&i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
<add> if i.addrv6.IP.To16() != nil {
<add> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(&i.addrv6))
<add> }
<add>
<add> if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
<add> return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
<add> }
<add> }
<add>
<add> if joinInfo != nil {
<add> // Set up non-interface routes.
<add> for _, r := range joinInfo.StaticRoutes {
<add> if err := sb.osSbox.AddStaticRoute(r); err != nil {
<add> return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
<add> }
<add> }
<add> }
<add>
<add> sb.Lock()
<add> heap.Push(&sb.endpoints, ep)
<add> highEp := sb.endpoints[0]
<add> sb.Unlock()
<add> if ep == highEp {
<add> if err := sb.updateGateway(ep); err != nil {
<add> return err
<add> }
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) clearNetworkResources(ep *endpoint) error {
<add>
<add> for _, i := range sb.osSbox.Info().Interfaces() {
<add> // Only remove the interfaces owned by this endpoint from the sandbox.
<add> if ep.hasInterface(i.SrcName()) {
<add> if err := i.Remove(); err != nil {
<add> log.Debugf("Remove interface failed: %v", err)
<add> }
<add> }
<add> }
<add>
<add> ep.Lock()
<add> joinInfo := ep.joinInfo
<add> ep.Unlock()
<add>
<add> // Remove non-interface routes.
<add> for _, r := range joinInfo.StaticRoutes {
<add> if err := sb.osSbox.RemoveStaticRoute(r); err != nil {
<add> log.Debugf("Remove route failed: %v", err)
<add> }
<add> }
<add>
<add> sb.Lock()
<add> if len(sb.endpoints) == 0 {
<add> // sb.endpoints should never be empty and this is unexpected error condition
<add> // We log an error message to note this down for debugging purposes.
<add> log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
<add> sb.Unlock()
<add> return nil
<add> }
<add>
<add> highEpBefore := sb.endpoints[0]
<add> var (
<add> i int
<add> e *endpoint
<add> )
<add> for i, e = range sb.endpoints {
<add> if e == ep {
<add> break
<add> }
<add> }
<add> heap.Remove(&sb.endpoints, i)
<add> var highEpAfter *endpoint
<add> if len(sb.endpoints) > 0 {
<add> highEpAfter = sb.endpoints[0]
<add> }
<add> delete(sb.epPriority, ep.ID())
<add> sb.Unlock()
<add>
<add> if highEpBefore != highEpAfter {
<add> sb.updateGateway(highEpAfter)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>const (
<add> defaultPrefix = "/var/lib/docker/network/files"
<add> filePerm = 0644
<add>)
<add>
<add>func (sb *sandbox) buildHostsFile() error {
<add> if sb.config.hostsPath == "" {
<add> sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
<add> }
<add>
<add> dir, _ := filepath.Split(sb.config.hostsPath)
<add> if err := createBasePath(dir); err != nil {
<add> return err
<add> }
<add>
<add> // This is for the host mode networking
<add> if sb.config.originHostsPath != "" {
<add> if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
<add> return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
<add> }
<add> return nil
<add> }
<add>
<add> extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
<add> for _, extraHost := range sb.config.extraHosts {
<add> extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
<add> }
<add>
<add> return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
<add>}
<add>
<add>func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
<add> // Rebuild the hosts file accounting for the passed interface IP and service records
<add> extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts)+len(svcRecords))
<add>
<add> for _, extraHost := range sb.config.extraHosts {
<add> extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
<add> }
<add>
<add> for _, svc := range svcRecords {
<add> extraContent = append(extraContent, svc)
<add> }
<add>
<add> return etchosts.Build(sb.config.hostsPath, ifaceIP, sb.config.hostName, sb.config.domainName, extraContent)
<add>}
<add>
<add>func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
<add> if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
<add> log.Warnf("Failed adding service host entries to the running container: %v", err)
<add> }
<add>}
<add>
<add>func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
<add> if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
<add> log.Warnf("Failed deleting service host entries to the running container: %v", err)
<add> }
<add>}
<add>
<add>func (sb *sandbox) updateParentHosts() error {
<add> var pSb Sandbox
<add>
<add> for _, update := range sb.config.parentUpdates {
<add> sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
<add> if pSb == nil {
<add> continue
<add> }
<add> if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
<add> return err
<add> }
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) setupDNS() error {
<add> if sb.config.resolvConfPath == "" {
<add> sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
<add> }
<add>
<add> sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
<add>
<add> dir, _ := filepath.Split(sb.config.resolvConfPath)
<add> if err := createBasePath(dir); err != nil {
<add> return err
<add> }
<add>
<add> // This is for the host mode networking
<add> if sb.config.originResolvConfPath != "" {
<add> if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
<add> return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
<add> }
<add> return nil
<add> }
<add>
<add> resolvConf, err := resolvconf.Get()
<add> if err != nil {
<add> return err
<add> }
<add> dnsList := resolvconf.GetNameservers(resolvConf)
<add> dnsSearchList := resolvconf.GetSearchDomains(resolvConf)
<add>
<add> if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 {
<add> if len(sb.config.dnsList) > 0 {
<add> dnsList = sb.config.dnsList
<add> }
<add> if len(sb.config.dnsSearchList) > 0 {
<add> dnsSearchList = sb.config.dnsSearchList
<add> }
<add> }
<add>
<add> hash, err := resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> // write hash
<add> if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(hash), filePerm); err != nil {
<add> return types.InternalErrorf("failed to write resol.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
<add> var oldHash []byte
<add> hashFile := sb.config.resolvConfHashFile
<add>
<add> resolvConf, err := ioutil.ReadFile(sb.config.resolvConfPath)
<add> if err != nil {
<add> if !os.IsNotExist(err) {
<add> return err
<add> }
<add> } else {
<add> oldHash, err = ioutil.ReadFile(hashFile)
<add> if err != nil {
<add> if !os.IsNotExist(err) {
<add> return err
<add> }
<add>
<add> oldHash = []byte{}
<add> }
<add> }
<add>
<add> curHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if string(oldHash) != "" && curHash != string(oldHash) {
<add> // Seems the user has changed the container resolv.conf since the last time
<add> // we checked so return without doing anything.
<add> log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
<add> return nil
<add> }
<add>
<add> // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
<add> resolvConf, _ = resolvconf.FilterResolvDNS(resolvConf, ipv6Enabled)
<add>
<add> newHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
<add> if err != nil {
<add> return err
<add> }
<add>
<add> // for atomic updates to these files, use temporary files with os.Rename:
<add> dir := path.Dir(sb.config.resolvConfPath)
<add> tmpHashFile, err := ioutil.TempFile(dir, "hash")
<add> if err != nil {
<add> return err
<add> }
<add> tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
<add> if err != nil {
<add> return err
<add> }
<add>
<add> // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
<add> if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
<add> return err
<add> }
<add>
<add> // write the updates to the temp files
<add> if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newHash), filePerm); err != nil {
<add> return err
<add> }
<add> if err = ioutil.WriteFile(tmpResolvFile.Name(), resolvConf, filePerm); err != nil {
<add> return err
<add> }
<add>
<add> // rename the temp files for atomic replace
<add> if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
<add> return err
<add> }
<add> return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
<add>}
<add>
<add>// OptionHostname function returns an option setter for hostname option to
<add>// be passed to NewSandbox method.
<add>func OptionHostname(name string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.hostName = name
<add> }
<add>}
<add>
<add>// OptionDomainname function returns an option setter for domainname option to
<add>// be passed to NewSandbox method.
<add>func OptionDomainname(name string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.domainName = name
<add> }
<add>}
<add>
<add>// OptionHostsPath function returns an option setter for hostspath option to
<add>// be passed to NewSandbox method.
<add>func OptionHostsPath(path string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.hostsPath = path
<add> }
<add>}
<add>
<add>// OptionOriginHostsPath function returns an option setter for origin hosts file path
<add>// tbeo passed to NewSandbox method.
<add>func OptionOriginHostsPath(path string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.originHostsPath = path
<add> }
<add>}
<add>
<add>// OptionExtraHost function returns an option setter for extra /etc/hosts options
<add>// which is a name and IP as strings.
<add>func OptionExtraHost(name string, IP string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
<add> }
<add>}
<add>
<add>// OptionParentUpdate function returns an option setter for parent container
<add>// which needs to update the IP address for the linked container.
<add>func OptionParentUpdate(cid string, name, ip string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
<add> }
<add>}
<add>
<add>// OptionResolvConfPath function returns an option setter for resolvconfpath option to
<add>// be passed to net container methods.
<add>func OptionResolvConfPath(path string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.resolvConfPath = path
<add> }
<add>}
<add>
<add>// OptionOriginResolvConfPath function returns an option setter to set the path to the
<add>// origin resolv.conf file to be passed to net container methods.
<add>func OptionOriginResolvConfPath(path string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.originResolvConfPath = path
<add> }
<add>}
<add>
<add>// OptionDNS function returns an option setter for dns entry option to
<add>// be passed to container Create method.
<add>func OptionDNS(dns string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.dnsList = append(sb.config.dnsList, dns)
<add> }
<add>}
<add>
<add>// OptionDNSSearch function returns an option setter for dns search entry option to
<add>// be passed to container Create method.
<add>func OptionDNSSearch(search string) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
<add> }
<add>}
<add>
<add>// OptionUseDefaultSandbox function returns an option setter for using default sandbox to
<add>// be passed to container Create method.
<add>func OptionUseDefaultSandbox() SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.useDefaultSandBox = true
<add> }
<add>}
<add>
<add>// OptionGeneric function returns an option setter for Generic configuration
<add>// that is not managed by libNetwork but can be used by the Drivers during the call to
<add>// net container creation method. Container Labels are a good example.
<add>func OptionGeneric(generic map[string]interface{}) SandboxOption {
<add> return func(sb *sandbox) {
<add> sb.config.generic = generic
<add> }
<add>}
<add>
<add>func (eh epHeap) Len() int { return len(eh) }
<add>
<add>func (eh epHeap) Less(i, j int) bool {
<add> ci, _ := eh[i].getSandbox()
<add> cj, _ := eh[j].getSandbox()
<add>
<add> cip, ok := ci.epPriority[eh[i].ID()]
<add> if !ok {
<add> cip = 0
<add> }
<add> cjp, ok := cj.epPriority[eh[j].ID()]
<add> if !ok {
<add> cjp = 0
<add> }
<add> if cip == cjp {
<add> return eh[i].getNetwork().Name() < eh[j].getNetwork().Name()
<add> }
<add>
<add> return cip > cjp
<add>}
<add>
<add>func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
<add>
<add>func (eh *epHeap) Push(x interface{}) {
<add> *eh = append(*eh, x.(*endpoint))
<add>}
<add>
<add>func (eh *epHeap) Pop() interface{} {
<add> old := *eh
<add> n := len(old)
<add> x := old[n-1]
<add> *eh = old[0 : n-1]
<add> return x
<add>}
<add>
<add>func createBasePath(dir string) error {
<add> return os.MkdirAll(dir, filePerm)
<add>}
<add>
<add>func createFile(path string) error {
<add> var f *os.File
<add>
<add> dir, _ := filepath.Split(path)
<add> err := createBasePath(dir)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> f, err = os.Create(path)
<add> if err == nil {
<add> f.Close()
<add> }
<add>
<add> return err
<add>}
<add>
<add>func copyFile(src, dst string) error {
<add> sBytes, err := ioutil.ReadFile(src)
<add> if err != nil {
<add> return err
<add> }
<add> return ioutil.WriteFile(dst, sBytes, filePerm)
<add>}
<ide><path>libnetwork/sandbox_test.go
<add>package libnetwork
<add>
<add>import (
<add> "testing"
<add>
<add> "github.com/docker/libnetwork/netlabel"
<add> "github.com/docker/libnetwork/netutils"
<add> "github.com/docker/libnetwork/options"
<add> "github.com/docker/libnetwork/osl"
<add>)
<add>
<add>func createEmptyCtrlr() *controller {
<add> return &controller{sandboxes: sandboxTable{}}
<add>}
<add>
<add>func createEmptyEndpoint() *endpoint {
<add> return &endpoint{
<add> joinInfo: &endpointJoinInfo{},
<add> iFaces: []*endpointInterface{},
<add> }
<add>}
<add>
<add>func getTestEnv(t *testing.T) (NetworkController, Network, Network) {
<add> c, err := New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> option := options.Generic{
<add> "EnableIPForwarding": true,
<add> }
<add> genericOption := make(map[string]interface{})
<add> genericOption[netlabel.GenericData] = option
<add> if err := c.ConfigureNetworkDriver("bridge", genericOption); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> netType := "bridge"
<add> name1 := "test_nw_1"
<add> netOption1 := options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": name1,
<add> "AllowNonDefaultBridge": true,
<add> },
<add> }
<add> n1, err := c.NewNetwork(netType, name1, NetworkOptionGeneric(netOption1))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> name2 := "test_nw_2"
<add> netOption2 := options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": name2,
<add> "AllowNonDefaultBridge": true,
<add> },
<add> }
<add> n2, err := c.NewNetwork(netType, name2, NetworkOptionGeneric(netOption2))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> return c, n1, n2
<add>}
<add>
<add>func TestSandboxAddEmpty(t *testing.T) {
<add> ctrlr := createEmptyCtrlr()
<add>
<add> sbx, err := ctrlr.NewSandbox("sandbox0")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := sbx.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if len(ctrlr.sandboxes) != 0 {
<add> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<add> }
<add>
<add> osl.GC()
<add>}
<add>
<add>func TestSandboxAddMultiPrio(t *testing.T) {
<add> if !netutils.IsRunningInContainer() {
<add> defer netutils.SetupTestNetNS(t)()
<add> }
<add>
<add> c, nw, _ := getTestEnv(t)
<add> ctrlr := c.(*controller)
<add>
<add> sbx, err := ctrlr.NewSandbox("sandbox1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> sid := sbx.ID()
<add>
<add> ep1, err := nw.CreateEndpoint("ep1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep2, err := nw.CreateEndpoint("ep2")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep3, err := nw.CreateEndpoint("ep3")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep1.Join(sbx, JoinOptionPriority(ep1, 1)); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep2.Join(sbx, JoinOptionPriority(ep2, 2)); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep3.Join(sbx, JoinOptionPriority(ep3, 3)); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep3 {
<add> t.Fatal("Expected ep3 to be at the top of the heap. But did not find ep3 at the top of the heap")
<add> }
<add>
<add> if err := ep3.Leave(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep2 {
<add> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<add> }
<add>
<add> if err := ep2.Leave(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep1 {
<add> t.Fatal("Expected ep1 to be at the top of the heap after removing ep2. But did not find ep1 at the top of the heap")
<add> }
<add>
<add> // Re-add ep3 back
<add> if err := ep3.Join(sbx, JoinOptionPriority(ep3, 3)); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep3 {
<add> t.Fatal("Expected ep3 to be at the top of the heap after adding ep3 back. But did not find ep3 at the top of the heap")
<add> }
<add>
<add> if err := sbx.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if len(ctrlr.sandboxes) != 0 {
<add> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<add> }
<add>
<add> osl.GC()
<add>}
<add>
<add>func TestSandboxAddSamePrio(t *testing.T) {
<add> if !netutils.IsRunningInContainer() {
<add> defer netutils.SetupTestNetNS(t)()
<add> }
<add>
<add> c, nw1, nw2 := getTestEnv(t)
<add>
<add> ctrlr := c.(*controller)
<add>
<add> sbx, err := ctrlr.NewSandbox("sandbox1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> sid := sbx.ID()
<add>
<add> ep1, err := nw1.CreateEndpoint("ep1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep2, err := nw2.CreateEndpoint("ep2")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep1.Join(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := ep2.Join(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep1 {
<add> t.Fatal("Expected ep1 to be at the top of the heap. But did not find ep1 at the top of the heap")
<add> }
<add>
<add> if err := ep1.Leave(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if ctrlr.sandboxes[sid].endpoints[0] != ep2 {
<add> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<add> }
<add>
<add> if err := ep2.Leave(sbx); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := sbx.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if len(ctrlr.sandboxes) != 0 {
<add> t.Fatalf("controller containers is not empty. len = %d", len(ctrlr.sandboxes))
<add> }
<add>
<add> osl.GC()
<add>}
<ide><path>libnetwork/sandboxdata.go
<del>package libnetwork
<del>
<del>import (
<del> "container/heap"
<del> "fmt"
<del> "sync"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/libnetwork/sandbox"
<del>)
<del>
<del>type epHeap []*endpoint
<del>
<del>type sandboxData struct {
<del> sbox sandbox.Sandbox
<del> refCnt int
<del> endpoints epHeap
<del> sync.Mutex
<del>}
<del>
<del>func (eh epHeap) Len() int { return len(eh) }
<del>
<del>func (eh epHeap) Less(i, j int) bool {
<del> eh[i].Lock()
<del> eh[j].Lock()
<del> defer eh[j].Unlock()
<del> defer eh[i].Unlock()
<del>
<del> if eh[i].container.config.prio == eh[j].container.config.prio {
<del> return eh[i].network.Name() < eh[j].network.Name()
<del> }
<del>
<del> return eh[i].container.config.prio > eh[j].container.config.prio
<del>}
<del>
<del>func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
<del>
<del>func (eh *epHeap) Push(x interface{}) {
<del> *eh = append(*eh, x.(*endpoint))
<del>}
<del>
<del>func (eh *epHeap) Pop() interface{} {
<del> old := *eh
<del> n := len(old)
<del> x := old[n-1]
<del> *eh = old[0 : n-1]
<del> return x
<del>}
<del>
<del>func (s *sandboxData) updateGateway(ep *endpoint) error {
<del> sb := s.sandbox()
<del>
<del> sb.UnsetGateway()
<del> sb.UnsetGatewayIPv6()
<del>
<del> if ep == nil {
<del> return nil
<del> }
<del>
<del> ep.Lock()
<del> joinInfo := ep.joinInfo
<del> ep.Unlock()
<del>
<del> if err := sb.SetGateway(joinInfo.gw); err != nil {
<del> return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
<del> }
<del>
<del> if err := sb.SetGatewayIPv6(joinInfo.gw6); err != nil {
<del> return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (s *sandboxData) addEndpoint(ep *endpoint) error {
<del> ep.Lock()
<del> joinInfo := ep.joinInfo
<del> ifaces := ep.iFaces
<del> ep.Unlock()
<del>
<del> sb := s.sandbox()
<del> for _, i := range ifaces {
<del> var ifaceOptions []sandbox.IfaceOption
<del>
<del> ifaceOptions = append(ifaceOptions, sb.InterfaceOptions().Address(&i.addr),
<del> sb.InterfaceOptions().Routes(i.routes))
<del> if i.addrv6.IP.To16() != nil {
<del> ifaceOptions = append(ifaceOptions,
<del> sb.InterfaceOptions().AddressIPv6(&i.addrv6))
<del> }
<del>
<del> if err := sb.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
<del> return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
<del> }
<del> }
<del>
<del> if joinInfo != nil {
<del> // Set up non-interface routes.
<del> for _, r := range ep.joinInfo.StaticRoutes {
<del> if err := sb.AddStaticRoute(r); err != nil {
<del> return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
<del> }
<del> }
<del> }
<del>
<del> s.Lock()
<del> heap.Push(&s.endpoints, ep)
<del> highEp := s.endpoints[0]
<del> s.Unlock()
<del>
<del> if ep == highEp {
<del> if err := s.updateGateway(ep); err != nil {
<del> return err
<del> }
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (s *sandboxData) rmEndpoint(ep *endpoint) {
<del> ep.Lock()
<del> joinInfo := ep.joinInfo
<del> ep.Unlock()
<del>
<del> sb := s.sandbox()
<del> for _, i := range sb.Info().Interfaces() {
<del> // Only remove the interfaces owned by this endpoint from the sandbox.
<del> if ep.hasInterface(i.SrcName()) {
<del> if err := i.Remove(); err != nil {
<del> logrus.Debugf("Remove interface failed: %v", err)
<del> }
<del> }
<del> }
<del>
<del> // Remove non-interface routes.
<del> for _, r := range joinInfo.StaticRoutes {
<del> if err := sb.RemoveStaticRoute(r); err != nil {
<del> logrus.Debugf("Remove route failed: %v", err)
<del> }
<del> }
<del>
<del> s.Lock()
<del> if len(s.endpoints) == 0 {
<del> // s.endpoints should never be empty and this is unexpected error condition
<del> // We log an error message to note this down for debugging purposes.
<del> logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
<del> s.Unlock()
<del> return
<del> }
<del>
<del> highEpBefore := s.endpoints[0]
<del> var (
<del> i int
<del> e *endpoint
<del> )
<del> for i, e = range s.endpoints {
<del> if e == ep {
<del> break
<del> }
<del> }
<del> heap.Remove(&s.endpoints, i)
<del> var highEpAfter *endpoint
<del> if len(s.endpoints) > 0 {
<del> highEpAfter = s.endpoints[0]
<del> }
<del>
<del> s.Unlock()
<del>
<del> if highEpBefore != highEpAfter {
<del> s.updateGateway(highEpAfter)
<del> }
<del>}
<del>
<del>func (s *sandboxData) sandbox() sandbox.Sandbox {
<del> s.Lock()
<del> defer s.Unlock()
<del>
<del> return s.sbox
<del>}
<del>
<del>func (c *controller) sandboxAdd(key string, create bool, ep *endpoint) (sandbox.Sandbox, error) {
<del> c.Lock()
<del> sData, ok := c.sandboxes[key]
<del> c.Unlock()
<del>
<del> if !ok {
<del> sb, err := sandbox.NewSandbox(key, create)
<del> if err != nil {
<del> return nil, fmt.Errorf("failed to create new sandbox: %v", err)
<del> }
<del>
<del> sData = &sandboxData{
<del> sbox: sb,
<del> endpoints: epHeap{},
<del> }
<del>
<del> heap.Init(&sData.endpoints)
<del> c.Lock()
<del> c.sandboxes[key] = sData
<del> c.Unlock()
<del> }
<del>
<del> if err := sData.addEndpoint(ep); err != nil {
<del> return nil, err
<del> }
<del>
<del> return sData.sandbox(), nil
<del>}
<del>
<del>func (c *controller) sandboxRm(key string, ep *endpoint) {
<del> c.Lock()
<del> sData := c.sandboxes[key]
<del> c.Unlock()
<del>
<del> sData.rmEndpoint(ep)
<del>}
<del>
<del>func (c *controller) sandboxGet(key string) sandbox.Sandbox {
<del> c.Lock()
<del> sData, ok := c.sandboxes[key]
<del> c.Unlock()
<del>
<del> if !ok {
<del> return nil
<del> }
<del>
<del> return sData.sandbox()
<del>}
<del>
<del>func (c *controller) LeaveAll(id string) error {
<del> c.Lock()
<del> sData, ok := c.sandboxes[sandbox.GenerateKey(id)]
<del> c.Unlock()
<del>
<del> if !ok {
<del> return fmt.Errorf("could not find sandbox for container id %s", id)
<del> }
<del>
<del> sData.Lock()
<del> eps := make([]*endpoint, len(sData.endpoints))
<del> for i, ep := range sData.endpoints {
<del> eps[i] = ep
<del> }
<del> sData.Unlock()
<del>
<del> for _, ep := range eps {
<del> if err := ep.Leave(id); err != nil {
<del> logrus.Warnf("Failed leaving endpoint id %s: %v\n", ep.ID(), err)
<del> }
<del> }
<del>
<del> sData.sandbox().Destroy()
<del>
<del> c.Lock()
<del> delete(c.sandboxes, sandbox.GenerateKey(id))
<del> c.Unlock()
<del>
<del> return nil
<del>}
<ide><path>libnetwork/sandboxdata_test.go
<del>package libnetwork
<del>
<del>import (
<del> "testing"
<del>
<del> "github.com/docker/libnetwork/sandbox"
<del>)
<del>
<del>func createEmptyCtrlr() *controller {
<del> return &controller{sandboxes: sandboxTable{}}
<del>}
<del>
<del>func createEmptyEndpoint() *endpoint {
<del> return &endpoint{
<del> container: &containerInfo{},
<del> joinInfo: &endpointJoinInfo{},
<del> iFaces: []*endpointInterface{},
<del> }
<del>}
<del>
<del>func TestSandboxAddEmpty(t *testing.T) {
<del> ctrlr := createEmptyCtrlr()
<del> ep := createEmptyEndpoint()
<del>
<del> if _, err := ctrlr.sandboxAdd(sandbox.GenerateKey("sandbox1"), true, ep); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> ctrlr.sandboxRm(sandbox.GenerateKey("sandbox1"), ep)
<del>
<del> ctrlr.LeaveAll("sandbox1")
<del> if len(ctrlr.sandboxes) != 0 {
<del> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<del> }
<del>
<del> sandbox.GC()
<del>}
<del>
<del>func TestSandboxAddMultiPrio(t *testing.T) {
<del> ctrlr := createEmptyCtrlr()
<del> ep1 := createEmptyEndpoint()
<del> ep2 := createEmptyEndpoint()
<del> ep3 := createEmptyEndpoint()
<del>
<del> ep1.container.config.prio = 1
<del> ep2.container.config.prio = 2
<del> ep3.container.config.prio = 3
<del>
<del> sKey := sandbox.GenerateKey("sandbox1")
<del>
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep1); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep2); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep3); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep3 {
<del> t.Fatal("Expected ep3 to be at the top of the heap. But did not find ep3 at the top of the heap")
<del> }
<del>
<del> ctrlr.sandboxRm(sKey, ep3)
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep2 {
<del> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<del> }
<del>
<del> ctrlr.sandboxRm(sKey, ep2)
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep1 {
<del> t.Fatal("Expected ep1 to be at the top of the heap after removing ep2. But did not find ep1 at the top of the heap")
<del> }
<del>
<del> // Re-add ep3 back
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep3); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep3 {
<del> t.Fatal("Expected ep3 to be at the top of the heap after adding ep3 back. But did not find ep3 at the top of the heap")
<del> }
<del>
<del> ctrlr.sandboxRm(sKey, ep3)
<del> ctrlr.sandboxRm(sKey, ep1)
<del>
<del> if err := ctrlr.LeaveAll("sandbox1"); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if len(ctrlr.sandboxes) != 0 {
<del> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<del> }
<del>
<del> sandbox.GC()
<del>}
<del>
<del>func TestSandboxAddSamePrio(t *testing.T) {
<del> ctrlr := createEmptyCtrlr()
<del> ep1 := createEmptyEndpoint()
<del> ep2 := createEmptyEndpoint()
<del>
<del> ep1.network = &network{name: "aaa"}
<del> ep2.network = &network{name: "bbb"}
<del>
<del> sKey := sandbox.GenerateKey("sandbox1")
<del>
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep1); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if _, err := ctrlr.sandboxAdd(sKey, true, ep2); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep1 {
<del> t.Fatal("Expected ep1 to be at the top of the heap. But did not find ep1 at the top of the heap")
<del> }
<del>
<del> ctrlr.sandboxRm(sKey, ep1)
<del>
<del> if ctrlr.sandboxes[sKey].endpoints[0] != ep2 {
<del> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<del> }
<del>
<del> ctrlr.sandboxRm(sKey, ep2)
<del>
<del> if err := ctrlr.LeaveAll("sandbox1"); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if len(ctrlr.sandboxes) != 0 {
<del> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<del> }
<del>
<del> sandbox.GC()
<del>}
<ide><path>libnetwork/store.go
<ide> import (
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/libkv/store"
<ide> "github.com/docker/libnetwork/datastore"
<del> "github.com/docker/libnetwork/types"
<ide> )
<ide>
<ide> func (c *controller) validateDatastoreConfig() bool {
<ide> func (c *controller) deleteNetworkFromStore(n *network) error {
<ide> return nil
<ide> }
<ide>
<del>func (c *controller) getNetworkFromStore(nid types.UUID) (*network, error) {
<add>func (c *controller) getNetworkFromStore(nid string) (*network, error) {
<ide> n := network{id: nid}
<ide> if err := c.store.GetObject(datastore.Key(n.Key()...), &n); err != nil {
<ide> return nil, err
<ide> func (c *controller) newEndpointFromStore(key string, ep *endpoint) error {
<ide> id := ep.id
<ide> ep.Unlock()
<ide>
<del> _, err := n.EndpointByID(string(id))
<add> _, err := n.EndpointByID(id)
<ide> if err != nil {
<ide> if _, ok := err.(ErrNoSuchEndpoint); ok {
<ide> return n.addEndpoint(ep)
<ide> func (c *controller) updateEndpointToStore(ep *endpoint) error {
<ide> return cs.PutObjectAtomic(ep)
<ide> }
<ide>
<del>func (c *controller) getEndpointFromStore(eid types.UUID) (*endpoint, error) {
<add>func (c *controller) getEndpointFromStore(eid string) (*endpoint, error) {
<ide> ep := endpoint{id: eid}
<ide> if err := c.store.GetObject(datastore.Key(ep.Key()...), &ep); err != nil {
<ide> return nil, err
<ide> func (c *controller) processEndpointUpdate(ep *endpoint) bool {
<ide> if !ok {
<ide> return true
<ide> }
<del> existing, _ := n.EndpointByID(string(ep.id))
<add> existing, _ := n.EndpointByID(ep.id)
<ide> if existing == nil {
<ide> return true
<ide> }
<ide> func (c *controller) processEndpointUpdate(ep *endpoint) bool {
<ide> // Can't use SetIndex() because ee is locked.
<ide> ee.dbIndex = ep.Index()
<ide> ee.dbExists = true
<del> if ee.container != nil && ep.container != nil {
<del> // we care only about the container id
<del> ee.container.id = ep.container.id
<del> } else {
<del> // we still care only about the container id, but this is a short-cut to communicate join or leave operation
<del> ee.container = ep.container
<del> }
<add> ee.sandboxID = ep.sandboxID
<ide> }
<ide> ee.Unlock()
<ide> | 54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.