mesh-rb 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile.lock +1 -1
  3. data/ext/mesh/extconf.rb +22 -4
  4. data/ext/mesh/mesh.tar.gz +0 -0
  5. data/lib/mesh/version.rb +1 -1
  6. data/mesh.gemspec +3 -2
  7. metadata +4 -120
  8. data/ext/mesh/mesh/.bazelrc +0 -20
  9. data/ext/mesh/mesh/.bazelversion +0 -1
  10. data/ext/mesh/mesh/.clang-format +0 -15
  11. data/ext/mesh/mesh/.dockerignore +0 -5
  12. data/ext/mesh/mesh/.editorconfig +0 -16
  13. data/ext/mesh/mesh/.gitattributes +0 -4
  14. data/ext/mesh/mesh/.github/workflows/main.yml +0 -144
  15. data/ext/mesh/mesh/.gitignore +0 -51
  16. data/ext/mesh/mesh/AUTHORS +0 -5
  17. data/ext/mesh/mesh/CMakeLists.txt +0 -270
  18. data/ext/mesh/mesh/CODE_OF_CONDUCT.md +0 -77
  19. data/ext/mesh/mesh/Dockerfile +0 -30
  20. data/ext/mesh/mesh/LICENSE +0 -201
  21. data/ext/mesh/mesh/Makefile +0 -81
  22. data/ext/mesh/mesh/README.md +0 -97
  23. data/ext/mesh/mesh/WORKSPACE +0 -50
  24. data/ext/mesh/mesh/bazel +0 -350
  25. data/ext/mesh/mesh/mesh-pldi19-powers.pdf +0 -0
  26. data/ext/mesh/mesh/src/BUILD +0 -222
  27. data/ext/mesh/mesh/src/CMakeLists.txt +0 -85
  28. data/ext/mesh/mesh/src/bitmap.h +0 -590
  29. data/ext/mesh/mesh/src/cheap_heap.h +0 -170
  30. data/ext/mesh/mesh/src/common.h +0 -377
  31. data/ext/mesh/mesh/src/copts.bzl +0 -31
  32. data/ext/mesh/mesh/src/d_assert.cc +0 -75
  33. data/ext/mesh/mesh/src/fixed_array.h +0 -124
  34. data/ext/mesh/mesh/src/global_heap.cc +0 -547
  35. data/ext/mesh/mesh/src/global_heap.h +0 -569
  36. data/ext/mesh/mesh/src/gnu_wrapper.cc +0 -75
  37. data/ext/mesh/mesh/src/internal.h +0 -356
  38. data/ext/mesh/mesh/src/libmesh.cc +0 -239
  39. data/ext/mesh/mesh/src/mac_wrapper.cc +0 -528
  40. data/ext/mesh/mesh/src/measure_rss.cc +0 -44
  41. data/ext/mesh/mesh/src/measure_rss.h +0 -20
  42. data/ext/mesh/mesh/src/meshable_arena.cc +0 -776
  43. data/ext/mesh/mesh/src/meshable_arena.h +0 -309
  44. data/ext/mesh/mesh/src/meshing.h +0 -60
  45. data/ext/mesh/mesh/src/mini_heap.h +0 -532
  46. data/ext/mesh/mesh/src/mmap_heap.h +0 -104
  47. data/ext/mesh/mesh/src/one_way_mmap_heap.h +0 -77
  48. data/ext/mesh/mesh/src/partitioned_heap.h +0 -111
  49. data/ext/mesh/mesh/src/plasma/mesh.h +0 -33
  50. data/ext/mesh/mesh/src/real.cc +0 -52
  51. data/ext/mesh/mesh/src/real.h +0 -36
  52. data/ext/mesh/mesh/src/rng/mwc.h +0 -296
  53. data/ext/mesh/mesh/src/rng/mwc64.h +0 -58
  54. data/ext/mesh/mesh/src/rpl_printf.c +0 -1991
  55. data/ext/mesh/mesh/src/runtime.cc +0 -393
  56. data/ext/mesh/mesh/src/runtime.h +0 -114
  57. data/ext/mesh/mesh/src/shuffle_vector.h +0 -287
  58. data/ext/mesh/mesh/src/size_classes.def +0 -251
  59. data/ext/mesh/mesh/src/static/if.h +0 -36
  60. data/ext/mesh/mesh/src/static/log.h +0 -43
  61. data/ext/mesh/mesh/src/testing/benchmark/local_refill.cc +0 -103
  62. data/ext/mesh/mesh/src/testing/big-alloc.c +0 -28
  63. data/ext/mesh/mesh/src/testing/fragmenter.cc +0 -128
  64. data/ext/mesh/mesh/src/testing/global-large-stress.cc +0 -25
  65. data/ext/mesh/mesh/src/testing/local-alloc.c +0 -16
  66. data/ext/mesh/mesh/src/testing/meshing_benchmark.cc +0 -189
  67. data/ext/mesh/mesh/src/testing/thread.cc +0 -35
  68. data/ext/mesh/mesh/src/testing/unit/alignment.cc +0 -56
  69. data/ext/mesh/mesh/src/testing/unit/bitmap_test.cc +0 -274
  70. data/ext/mesh/mesh/src/testing/unit/concurrent_mesh_test.cc +0 -185
  71. data/ext/mesh/mesh/src/testing/unit/mesh_test.cc +0 -143
  72. data/ext/mesh/mesh/src/testing/unit/rng_test.cc +0 -22
  73. data/ext/mesh/mesh/src/testing/unit/size_class_test.cc +0 -66
  74. data/ext/mesh/mesh/src/testing/unit/triple_mesh_test.cc +0 -285
  75. data/ext/mesh/mesh/src/testing/userfaultfd-kernel-copy.cc +0 -164
  76. data/ext/mesh/mesh/src/thread_local_heap.cc +0 -163
  77. data/ext/mesh/mesh/src/thread_local_heap.h +0 -268
  78. data/ext/mesh/mesh/src/wrapper.cc +0 -433
  79. data/ext/mesh/mesh/support/export_mesh.cmake +0 -28
  80. data/ext/mesh/mesh/support/gen-size-classes +0 -57
  81. data/ext/mesh/mesh/support/install_all_configs +0 -33
  82. data/ext/mesh/mesh/support/remove_export_mesh.cmake +0 -48
  83. data/ext/mesh/mesh/support/update-bazelisk +0 -8
  84. data/ext/mesh/mesh/theory/32m80.png +0 -0
  85. data/ext/mesh/mesh/theory/64m80ind.png +0 -0
  86. data/ext/mesh/mesh/theory/bound_comparison.py +0 -67
  87. data/ext/mesh/mesh/theory/bounds/impdeg+1 +0 -135
  88. data/ext/mesh/mesh/theory/choose.py +0 -43
  89. data/ext/mesh/mesh/theory/common.py +0 -42
  90. data/ext/mesh/mesh/theory/compute_exp_Y.py +0 -134
  91. data/ext/mesh/mesh/theory/createRandomString.py +0 -69
  92. data/ext/mesh/mesh/theory/deg_bound_check.py +0 -100
  93. data/ext/mesh/mesh/theory/degcheck.py +0 -47
  94. data/ext/mesh/mesh/theory/dumps/32,1,80,dumb.txt +0 -81
  95. data/ext/mesh/mesh/theory/dumps/32,2,80,dumb.txt +0 -81
  96. data/ext/mesh/mesh/theory/dumps/32,3,80,dumb.txt +0 -81
  97. data/ext/mesh/mesh/theory/dumps/32,4,80,dumb.txt +0 -81
  98. data/ext/mesh/mesh/theory/dumps/32,5,80,dumb.txt +0 -81
  99. data/ext/mesh/mesh/theory/dumps/32,6,80,dumb.txt +0 -81
  100. data/ext/mesh/mesh/theory/dumps/32,7,80,dumb.txt +0 -81
  101. data/ext/mesh/mesh/theory/dumps/32,8,80,dumb.txt +0 -81
  102. data/ext/mesh/mesh/theory/dumps/32,9,80,dumb.txt +0 -81
  103. data/ext/mesh/mesh/theory/experiment.py +0 -303
  104. data/ext/mesh/mesh/theory/experiment_raw_results/.gitignore +0 -0
  105. data/ext/mesh/mesh/theory/greedy_experiment.py +0 -66
  106. data/ext/mesh/mesh/theory/greedy_experiment_copy.py +0 -46
  107. data/ext/mesh/mesh/theory/greedy_experiment_q.py +0 -75
  108. data/ext/mesh/mesh/theory/makeGraph.py +0 -64
  109. data/ext/mesh/mesh/theory/manyreps.png +0 -0
  110. data/ext/mesh/mesh/theory/manystrings.png +0 -0
  111. data/ext/mesh/mesh/theory/match_vs_color_experiment.py +0 -94
  112. data/ext/mesh/mesh/theory/maxmatch_vs_E[Y].py +0 -162
  113. data/ext/mesh/mesh/theory/maxmatch_vs_greedymatch.py +0 -96
  114. data/ext/mesh/mesh/theory/maxvdeg+1imp++32,80.png +0 -0
  115. data/ext/mesh/mesh/theory/mesh_util.py +0 -322
  116. data/ext/mesh/mesh/theory/meshers.py +0 -452
  117. data/ext/mesh/mesh/theory/meshingBenchmark.py +0 -96
  118. data/ext/mesh/mesh/theory/occupancyComparison.py +0 -133
  119. data/ext/mesh/mesh/theory/randmatch_vs_greedymatch.py +0 -97
  120. data/ext/mesh/mesh/theory/randmatch_vs_greedymatch_q.py +0 -103
  121. data/ext/mesh/mesh/theory/randmatch_vs_greedymatch_time.py +0 -117
  122. data/ext/mesh/mesh/theory/read_mesh_dump.py +0 -82
  123. data/ext/mesh/mesh/theory/test.py +0 -70
  124. data/ext/mesh/mesh/tools/bazel +0 -1
@@ -1,81 +0,0 @@
1
- # Copyright 2020 The Mesh Authors. All rights reserved.
2
- # Use of this source code is governed by the Apache License,
3
- # Version 2.0, that can be found in the LICENSE file.
4
-
5
- PREFIX = /usr
6
- BAZEL_CONFIG = --config=modern-amd64
7
- LIB_SUFFIX =
8
-
9
- UNAME_S = $(shell uname -s)
10
- ifeq ($(UNAME_S),Darwin)
11
- LIB_EXT = dylib
12
- BAZEL_PREFIX = darwin
13
- LDCONFIG =
14
- PREFIX = /usr/local
15
- else
16
- LIB_EXT = so
17
- BAZEL_PREFIX = k8
18
- LDCONFIG = ldconfig
19
- endif
20
-
21
- LIB = mesh
22
- FS_LIB = libmesh.so
23
- INSTALL_LIB = libmesh$(LIB_SUFFIX).$(LIB_EXT)
24
-
25
- COV_DIR = coverage
26
- CONFIG = Makefile
27
-
28
- # quiet output, but allow us to look at what commands are being
29
- # executed by passing 'V=1' to make, without requiring temporarily
30
- # editing the Makefile.
31
- ifneq ($V, 1)
32
- MAKEFLAGS += -s
33
- endif
34
-
35
- .SUFFIXES:
36
- .SUFFIXES: .cc .c .o .d .test
37
-
38
- all: test build
39
-
40
- build lib:
41
- ./bazel build $(BAZEL_CONFIG) -c opt //src:$(LIB)
42
-
43
- test check:
44
- ./bazel test $(BAZEL_CONFIG) //src:unit-tests --test_output=all --action_env="GTEST_COLOR=1"
45
-
46
- install:
47
- install -c -m 0755 bazel-out/$(BAZEL_PREFIX)-opt/bin/src/$(FS_LIB) $(PREFIX)/lib/$(INSTALL_LIB)
48
- $(LDCONFIG)
49
- mkdir -p $(PREFIX)/include/plasma
50
- install -c -m 0755 src/plasma/mesh.h $(PREFIX)/include/plasma/mesh.h
51
-
52
- clang-coverage: $(UNIT_BIN) $(LIB) $(CONFIG)
53
- mkdir -p "$(COV_DIR)"
54
- rm -f "$(COV_DIR)/unit.test.profdata"
55
- cd "$(COV_DIR)" && llvm-profdata merge -sparse ../default.profraw -o unit.test.profdata
56
- cd "$(COV_DIR)" && llvm-cov show -format=html -instr-profile=unit.test.profdata ../unit.test -ignore-filename-regex='.*(vendor|unit)/.*' >index.html
57
- cd "$(COV_DIR)" && llvm-cov report -instr-profile=unit.test.profdata ../unit.test -ignore-filename-regex='.*(vendor|unit)/.*' -use-color
58
- rm -f default.profraw
59
-
60
- benchmark:
61
- ./bazel build $(BAZEL_CONFIG) --config=disable-meshing --config=debugsymbols -c opt //src:local-refill-benchmark
62
- ./bazel-bin/src/local-refill-benchmark
63
-
64
- format:
65
- clang-format -i src/*.cc src/*.c src/*.h src/plasma/*.h src/rng/*.h src/static/*.h src/testing/unit/*.cc src/testing/*.cc src/testing/benchmark/*.cc
66
-
67
- clean:
68
- find . -name '*~' -print0 | xargs -0 rm -f
69
- ./bazel clean
70
- ./bazel shutdown
71
-
72
-
73
- distclean: clean
74
- ./bazel clean --expunge
75
-
76
- # double $$ in egrep pattern is because we're embedding this shell command in a Makefile
77
- TAGS:
78
- @echo " TAGS"
79
- find . -type f | egrep '\.(cpp|h|cc|hh)$$' | grep -v google | xargs etags -l c++
80
-
81
- .PHONY: all clean distclean format test test_frag check build benchmark install TAGS
@@ -1,97 +0,0 @@
1
- Mesh: Compacting Memory Management for C/C++
2
- ============================================
3
-
4
- Mesh is a drop in replacement for
5
- [malloc(3)](http://man7.org/linux/man-pages/man3/malloc.3.html)
6
- that can transparently recover from memory fragmentation without any changes
7
- to application code.
8
-
9
- Mesh is described in detail in a [paper (PDF)](https://github.com/plasma-umass/Mesh/raw/master/mesh-pldi19-powers.pdf) that appeared at PLDI 2019.
10
-
11
- Or watch this talk by Bobby Powers at Strange Loop:
12
-
13
- [![Compacting the Uncompactable](https://img.youtube.com/vi/c1UBJbfR-H0/0.jpg)](https://www.youtube.com/watch?v=c1UBJbfR-H0)
14
-
15
- Mesh runs on Linux and macOS. Windows is a work in progress.
16
-
17
- Mesh uses [bazel](https://bazel.build/) as a build system, but wraps it in a Makefile, and has no runtime dependencies
18
- other than libc:
19
-
20
- ```
21
- $ git clone https://github.com/plasma-umass/mesh
22
- $ cd mesh
23
- $ make; sudo make install
24
- # example: run git with mesh as its allocator:
25
- $ LD_PRELOAD=libmesh.so git status
26
- ```
27
-
28
- Please open an issue if you have questions (or issues)!
29
-
30
-
31
- But will it blend?
32
- ------------------
33
-
34
- If you run a program linked against mesh (or with Mesh `LD_PRELOAD`ed), setting the variable `MALLOCSTATS=1` will instruct mesh to print a summary at exit:
35
-
36
- ```
37
- $ MALLOCSTATS=1 ./bin/redis-server-mesh ./redis.conf
38
- 25216:C 11 Mar 20:27:12.050 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
39
- 25216:C 11 Mar 20:27:12.050 # Redis version=4.0.2, bits=64, commit=dfe0d212, modified=0, pid=25216, just started
40
- 25216:C 11 Mar 20:27:12.050 # Configuration loaded
41
- [...]
42
- ^C25216:signal-handler (1583983641) Received SIGINT scheduling shutdown...
43
- 25216:M 11 Mar 20:27:21.945 # User requested shutdown...
44
- 25216:M 11 Mar 20:27:21.945 * Removing the pid file.
45
- 25216:M 11 Mar 20:27:21.945 * Removing the unix socket file.
46
- 25216:M 11 Mar 20:27:21.945 # Redis is now ready to exit, bye bye...
47
- MESH COUNT: 25918
48
- Meshed MB (total): 101.2
49
- Meshed pages HWM: 25918
50
- Meshed MB HWM: 101.2
51
- MH Alloc Count: 56775
52
- MH Free Count: 17
53
- MH High Water Mark: 82687
54
- ```
55
-
56
- Not all workloads experience fragmentation, so its possible that Mesh will have a small 'Meshed MB (total' number!
57
-
58
-
59
- Implementation Overview
60
- -----------------------
61
-
62
- Mesh is built on [Heap Layers](http://heaplayers.org/), an
63
- infrastructure for building high performance memory allocators in C++
64
- (see the
65
- [paper](https://people.cs.umass.edu/~emery/pubs/berger-pldi2001.pdf)
66
- for details.)
67
-
68
- The entry point of the library is [`libmesh.cc`](src/libmesh.cc).
69
- This file is where `malloc`, `free` and the instantiations of the
70
- Heap used for allocating program memory lives.
71
-
72
-
73
- DEFINITIONS
74
- -----------
75
-
76
- - **Page**: The smallest block of memory managed by the operating
77
- system, 4Kb on most architectures. Memory given to the allocator by
78
- the operating system is always in multiples of the page size, and
79
- aligned to the page size.
80
- - **Span**: A contiguous run of 1 or more pages. It is often larger
81
- than the page size to account for large allocations and amortize the
82
- cost of heap metadata.
83
- - **Arena**: A contiguous range of virtual address space we allocate
84
- out of. All allocations returned by
85
- [`malloc(3)`](http://man7.org/linux/man-pages/man3/malloc.3.html)
86
- reside within the arena.
87
- - [**GlobalHeap**](src/global_heap.h): The global heap carves out the
88
- Arena into Spans and performs meshing.
89
- - [**MiniHeap**](src/mini_heap.h): Metadata for a Span -- at any time
90
- a live Span has a single MiniHeap owner. For small objects,
91
- MiniHeaps have a bitmap to track whether an allocation is live or
92
- freed.
93
- - [**ThreadLocalHeap**](src/thread_local_heap.h): A collections of
94
- MiniHeaps and a ShuffleVector so that most allocations and
95
- `free(3)`s can be fast and lock-free.
96
- - [**ShuffleVector**](src/shuffle_vector.h): A novel data structure
97
- that enables randomized allocation with bump-pointer-like speed.
@@ -1,50 +0,0 @@
1
- # Copyright 2020 The Mesh Authors. All rights reserved.
2
- # Use of this source code is governed by the Apache License,
3
- # Version 2.0, that can be found in the LICENSE file.
4
-
5
- workspace(name = "org_libmesh")
6
-
7
- load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
8
-
9
- commit = {
10
- "rules_cc": "5cbd3dfbd1613f71ef29bbb7b10310b81e272975",
11
- "googletest": "c6e309b268d4fb9138bed7d0f56b7709c29f102f",
12
- "benchmark": "15e6dfd7182b74b4fb6860f52fe314d0654307fb",
13
- "heap_layers": "08ca96cfe11b1dd1c504fb7be613ad00756d568f",
14
- }
15
-
16
- http_archive(
17
- name = "rules_cc",
18
- sha256 = "d6775fe03da086dfe47c668f54e77e220aa6e601a66a4517eaf19fa1d9fda309",
19
- strip_prefix = "rules_cc-{}".format(commit["rules_cc"]),
20
- urls = [
21
- "https://github.com/bazelbuild/rules_cc/archive/{}.zip".format(commit["rules_cc"]),
22
- ],
23
- )
24
-
25
- http_archive(
26
- name = "com_google_googletest",
27
- sha256 = "ac0b859e4c28af555657c7702523465756eb56f8606bf53e62fd934c86b5fa5f",
28
- strip_prefix = "googletest-{}".format(commit["googletest"]),
29
- urls = [
30
- "https://github.com/google/googletest/archive/{}.zip".format(commit["googletest"]),
31
- ],
32
- )
33
-
34
- http_archive(
35
- name = "com_google_benchmark",
36
- # sha256 = "",
37
- strip_prefix = "benchmark-{}".format(commit["benchmark"]),
38
- urls = [
39
- "https://github.com/google/benchmark/archive/{}.zip".format(commit["benchmark"]),
40
- ],
41
- )
42
-
43
- http_archive(
44
- name = "org_heaplayers",
45
- sha256 = "c8a9f7589e13112515ba1ac8647b4e80462f18a6773f7f5f132a7d7602fe2aec",
46
- strip_prefix = "Heap-Layers-{}".format(commit["heap_layers"]),
47
- urls = [
48
- "https://github.com/emeryberger/Heap-Layers/archive/{}.zip".format(commit["heap_layers"]),
49
- ],
50
- )
data/ext/mesh/mesh/bazel DELETED
@@ -1,350 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Copyright 2018 Google Inc. All rights reserved.
4
-
5
- Licensed under the Apache License, Version 2.0 (the "License");
6
- you may not use this file except in compliance with the License.
7
- You may obtain a copy of the License at
8
-
9
- http://www.apache.org/licenses/LICENSE-2.0
10
-
11
- Unless required by applicable law or agreed to in writing, software
12
- distributed under the License is distributed on an "AS IS" BASIS,
13
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- See the License for the specific language governing permissions and
15
- limitations under the License.
16
- """
17
-
18
- from contextlib import closing
19
- from distutils.version import LooseVersion
20
- import json
21
- import os
22
- import os.path
23
- import platform
24
- import re
25
- import shutil
26
- import subprocess
27
- import sys
28
- import tempfile
29
- import time
30
-
31
- try:
32
- from urllib.request import urlopen
33
- except ImportError:
34
- # Python 2.x compatibility hack.
35
- from urllib2 import urlopen
36
-
37
- ONE_HOUR = 1 * 60 * 60
38
-
39
- LATEST_PATTERN = re.compile(r"latest(-(?P<offset>\d+))?$")
40
-
41
- LAST_GREEN_COMMIT_BASE_PATH = (
42
- "https://storage.googleapis.com/bazel-untrusted-builds/last_green_commit/"
43
- )
44
-
45
- LAST_GREEN_COMMIT_PATH_SUFFIXES = {
46
- "last_green": "github.com/bazelbuild/bazel.git/bazel-bazel",
47
- "last_downstream_green": "downstream_pipeline",
48
- }
49
-
50
- BAZEL_GCS_PATH_PATTERN = (
51
- "https://storage.googleapis.com/bazel-builds/artifacts/{platform}/{commit}/bazel"
52
- )
53
-
54
- SUPPORTED_PLATFORMS = {"linux": "ubuntu1404", "windows": "windows", "darwin": "macos"}
55
-
56
- TOOLS_BAZEL_PATH = "./tools/bazel"
57
-
58
- BAZEL_REAL = "BAZEL_REAL"
59
-
60
-
61
- def decide_which_bazel_version_to_use():
62
- # Check in this order:
63
- # - env var "USE_BAZEL_VERSION" is set to a specific version.
64
- # - env var "USE_NIGHTLY_BAZEL" or "USE_BAZEL_NIGHTLY" is set -> latest
65
- # nightly. (TODO)
66
- # - env var "USE_CANARY_BAZEL" or "USE_BAZEL_CANARY" is set -> latest
67
- # rc. (TODO)
68
- # - the file workspace_root/tools/bazel exists -> that version. (TODO)
69
- # - workspace_root/.bazelversion exists -> read contents, that version.
70
- # - workspace_root/WORKSPACE contains a version -> that version. (TODO)
71
- # - fallback: latest release
72
- if "USE_BAZEL_VERSION" in os.environ:
73
- return os.environ["USE_BAZEL_VERSION"]
74
-
75
- workspace_root = find_workspace_root()
76
- if workspace_root:
77
- bazelversion_path = os.path.join(workspace_root, ".bazelversion")
78
- if os.path.exists(bazelversion_path):
79
- with open(bazelversion_path, "r") as f:
80
- return f.read().strip()
81
-
82
- return "latest"
83
-
84
-
85
- def find_workspace_root(root=None):
86
- if root is None:
87
- root = os.getcwd()
88
- if os.path.exists(os.path.join(root, "WORKSPACE")):
89
- return root
90
- new_root = os.path.dirname(root)
91
- return find_workspace_root(new_root) if new_root != root else None
92
-
93
-
94
- def resolve_version_label_to_number_or_commit(bazelisk_directory, version):
95
- """Resolves the given label to a released version of Bazel or a commit.
96
-
97
- Args:
98
- bazelisk_directory: string; path to a directory that can store
99
- temporary data for Bazelisk.
100
- version: string; the version label that should be resolved.
101
- Returns:
102
- A (string, bool) tuple that consists of two parts:
103
- 1. the resolved number of a Bazel release (candidate), or the commit
104
- of an unreleased Bazel binary,
105
- 2. An indicator for whether the returned version refers to a commit.
106
- """
107
- suffix = LAST_GREEN_COMMIT_PATH_SUFFIXES.get(version)
108
- if suffix:
109
- return get_last_green_commit(suffix), True
110
-
111
- if "latest" in version:
112
- match = LATEST_PATTERN.match(version)
113
- if not match:
114
- raise Exception(
115
- 'Invalid version "{}". In addition to using a version '
116
- 'number such as "0.20.0", you can use values such as '
117
- '"latest" and "latest-N", with N being a non-negative '
118
- "integer.".format(version)
119
- )
120
-
121
- history = get_version_history(bazelisk_directory)
122
- offset = int(match.group("offset") or "0")
123
- return resolve_latest_version(history, offset), False
124
-
125
- return version, False
126
-
127
-
128
- def get_last_green_commit(path_suffix):
129
- return read_remote_text_file(LAST_GREEN_COMMIT_BASE_PATH + path_suffix).strip()
130
-
131
-
132
- def get_releases_json(bazelisk_directory):
133
- """Returns the most recent versions of Bazel, in descending order."""
134
- releases = os.path.join(bazelisk_directory, "releases.json")
135
-
136
- # Use a cached version if it's fresh enough.
137
- if os.path.exists(releases):
138
- if abs(time.time() - os.path.getmtime(releases)) < ONE_HOUR:
139
- with open(releases, "rb") as f:
140
- try:
141
- return json.loads(f.read().decode("utf-8"))
142
- except ValueError:
143
- print("WARN: Could not parse cached releases.json.")
144
- pass
145
-
146
- with open(releases, "wb") as f:
147
- body = read_remote_text_file("https://api.github.com/repos/bazelbuild/bazel/releases")
148
- f.write(body.encode("utf-8"))
149
- return json.loads(body)
150
-
151
-
152
- def read_remote_text_file(url):
153
- with closing(urlopen(url)) as res:
154
- body = res.read()
155
- try:
156
- return body.decode(res.info().get_content_charset("iso-8859-1"))
157
- except AttributeError:
158
- # Python 2.x compatibility hack
159
- return body.decode(res.info().getparam("charset") or "iso-8859-1")
160
-
161
-
162
- def get_version_history(bazelisk_directory):
163
- ordered = sorted(
164
- (
165
- LooseVersion(release["tag_name"])
166
- for release in get_releases_json(bazelisk_directory)
167
- if not release["prerelease"]
168
- ),
169
- reverse=True,
170
- )
171
- return [str(v) for v in ordered]
172
-
173
-
174
- def resolve_latest_version(version_history, offset):
175
- if offset >= len(version_history):
176
- version = "latest-{}".format(offset) if offset else "latest"
177
- raise Exception(
178
- 'Cannot resolve version "{}": There are only {} Bazel '
179
- "releases.".format(version, len(version_history))
180
- )
181
-
182
- # This only works since we store the history in descending order.
183
- return version_history[offset]
184
-
185
-
186
- def get_operating_system():
187
- operating_system = platform.system().lower()
188
- if operating_system not in ("linux", "darwin", "windows"):
189
- raise Exception(
190
- 'Unsupported operating system "{}". '
191
- "Bazel currently only supports Linux, macOS and Windows.".format(operating_system)
192
- )
193
- return operating_system
194
-
195
-
196
- def determine_bazel_filename(version):
197
- machine = normalized_machine_arch_name()
198
- if machine != "x86_64":
199
- raise Exception(
200
- 'Unsupported machine architecture "{}". Bazel currently only supports x86_64.'.format(
201
- machine
202
- )
203
- )
204
-
205
- operating_system = get_operating_system()
206
-
207
- filename_ending = ".exe" if operating_system == "windows" else ""
208
- return "bazel-{}-{}-{}{}".format(version, operating_system, machine, filename_ending)
209
-
210
-
211
- def normalized_machine_arch_name():
212
- machine = platform.machine().lower()
213
- if machine == "amd64":
214
- machine = "x86_64"
215
- return machine
216
-
217
-
218
- def determine_url(version, is_commit, bazel_filename):
219
- if is_commit:
220
- sys.stderr.write("Using unreleased version at commit {}\n".format(version))
221
- # No need to validate the platform thanks to determine_bazel_filename().
222
- return BAZEL_GCS_PATH_PATTERN.format(
223
- platform=SUPPORTED_PLATFORMS[platform.system().lower()], commit=version
224
- )
225
-
226
- # Split version into base version and optional additional identifier.
227
- # Example: '0.19.1' -> ('0.19.1', None), '0.20.0rc1' -> ('0.20.0', 'rc1')
228
- (version, rc) = re.match(r"(\d*\.\d*(?:\.\d*)?)(rc\d+)?", version).groups()
229
- return "https://releases.bazel.build/{}/{}/{}".format(
230
- version, rc if rc else "release", bazel_filename
231
- )
232
-
233
-
234
- def download_bazel_into_directory(version, is_commit, directory):
235
- bazel_filename = determine_bazel_filename(version)
236
- url = determine_url(version, is_commit, bazel_filename)
237
- destination_path = os.path.join(directory, bazel_filename)
238
- if not os.path.exists(destination_path):
239
- sys.stderr.write("Downloading {}...\n".format(url))
240
- with tempfile.NamedTemporaryFile(prefix="bazelisk", dir=directory, delete=False) as t:
241
- with closing(urlopen(url)) as response:
242
- shutil.copyfileobj(response, t)
243
- t.flush()
244
- os.fsync(t.fileno())
245
- os.rename(t.name, destination_path)
246
- os.chmod(destination_path, 0o755)
247
- return destination_path
248
-
249
-
250
- def get_bazelisk_directory():
251
- bazelisk_home = os.environ.get("BAZELISK_HOME")
252
- if bazelisk_home is not None:
253
- return bazelisk_home
254
-
255
- operating_system = get_operating_system()
256
-
257
- base_dir = None
258
-
259
- if operating_system == "windows":
260
- base_dir = os.environ.get("LocalAppData")
261
- if base_dir is None:
262
- raise Exception("%LocalAppData% is not defined")
263
- elif operating_system == "darwin":
264
- base_dir = os.environ.get("HOME")
265
- if base_dir is None:
266
- raise Exception("$HOME is not defined")
267
- base_dir = os.path.join(base_dir, "Library/Caches")
268
- elif operating_system == "linux":
269
- base_dir = os.environ.get("XDG_CACHE_HOME")
270
- if base_dir is None:
271
- base_dir = os.environ.get("HOME")
272
- if base_dir is None:
273
- raise Exception("neither $XDG_CACHE_HOME nor $HOME are defined")
274
- base_dir = os.path.join(base_dir, ".cache")
275
- else:
276
- raise Exception("Unsupported operating system '{}'".format(operating_system))
277
-
278
- return os.path.join(base_dir, "bazelisk")
279
-
280
-
281
- def maybe_makedirs(path):
282
- """
283
- Creates a directory and its parents if necessary.
284
- """
285
- try:
286
- os.makedirs(path)
287
- except OSError as e:
288
- if not os.path.isdir(path):
289
- raise e
290
-
291
-
292
- def delegate_tools_bazel(bazel_path):
293
- """Match Bazel's own delegation behavior in the builds distributed by most
294
- package managers: use tools/bazel if it's present, executable, and not this
295
- script.
296
- """
297
- root = find_workspace_root()
298
- if root:
299
- wrapper = os.path.join(root, TOOLS_BAZEL_PATH)
300
- if os.path.exists(wrapper) and os.access(wrapper, os.X_OK):
301
- try:
302
- if not os.path.samefile(wrapper, __file__):
303
- return wrapper
304
- except AttributeError:
305
- # Python 2 on Windows does not support os.path.samefile
306
- if os.path.abspath(wrapper) != os.path.abspath(__file__):
307
- return wrapper
308
- return None
309
-
310
-
311
- def execute_bazel(bazel_path, argv):
312
- wrapper = delegate_tools_bazel(bazel_path)
313
- if wrapper:
314
- os.putenv(BAZEL_REAL, bazel_path)
315
- bazel_path = wrapper
316
-
317
- # We cannot use close_fds on Windows, so disable it there.
318
- p = subprocess.Popen([bazel_path] + argv, close_fds=os.name != "nt")
319
- while True:
320
- try:
321
- return p.wait()
322
- except KeyboardInterrupt:
323
- # Bazel will also get the signal and terminate.
324
- # We should continue waiting until it does so.
325
- pass
326
-
327
-
328
- def get_bazel_path():
329
- bazelisk_directory = get_bazelisk_directory()
330
- maybe_makedirs(bazelisk_directory)
331
-
332
- bazel_version = decide_which_bazel_version_to_use()
333
- bazel_version, is_commit = resolve_version_label_to_number_or_commit(
334
- bazelisk_directory, bazel_version
335
- )
336
-
337
- bazel_directory = os.path.join(bazelisk_directory, "bin")
338
- maybe_makedirs(bazel_directory)
339
- return download_bazel_into_directory(bazel_version, is_commit, bazel_directory)
340
-
341
-
342
- def main(argv=None):
343
- if argv is None:
344
- argv = sys.argv
345
-
346
- return execute_bazel(get_bazel_path(), argv[1:])
347
-
348
-
349
- if __name__ == "__main__":
350
- sys.exit(main())