Add code and examples (#1)

This commit is contained in:
Carmi Grushko 2018-04-26 13:52:06 -04:00 committed by GitHub
parent f0eea1b63e
commit 5fda9e82bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 636 additions and 0 deletions

8
.bazelci/config.yaml Normal file
View File

@ -0,0 +1,8 @@
---
platforms:
ubuntu1604:
build_targets:
- "//examples/..."
macos:
build_targets:
- "//examples/..."

6
AUTHORS Normal file
View File

@ -0,0 +1,6 @@
# This is the list of Bazel authors for copyright purposes.
#
# This does not necessarily list everyone who has contributed code, since in
# some cases, their employer may be the copyright holder. To see the full list
# of contributors, see the revision history in source control.
Google Inc.

28
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,28 @@
# How to Contribute
We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.
## Contributor License Agreement
Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution,
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.
## Code reviews
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
## Community Guidelines
This project follows [Google's Open Source Community
Guidelines](https://opensource.google.com/conduct/).

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1 +1,54 @@
# rules_foreign_cc
Rules for building projects using foreign build systems inside Bazel projects.
* Experimental - API will most definitely change.
* This is not an officially supported Google product
(meaning, support and/or new releases may be limited.)
## ./configure && make
**NOTE**: this requires building Bazel from head after https://github.com/bazelbuild/bazel/commit/060b1624e4d64dbdbeb375f9a55a3da9bd055a54
Example:
* In `WORKSPACE`, we use a `new_http_archive` to download tarballs with the libraries we use.
* In `BUILD`, we instantiate a `cc_configure_make_library` macro which behaves similarly to a `cc_library`, which can then be used in a C++ rule (`cc_binary` in this case).
In `WORKSPACE`, put
```python
new_http_archive(
name = "libevent",
build_file_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])""",
strip_prefix = "libevent-2.1.8-stable",
urls = ["https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz"],
)
```
and in `BUILD`, put
```python
cc_configure_make(
name = "libevent",
src = "@libevent//:all",
configure_flags = [
"--enable-shared=no",
"--disable-libevent-regress",
"--disable-openssl",
],
out_lib_path = "lib/libevent.a",
)
cc_binary(
name = "libevent_echosrv1",
srcs = ["libevent_echosrv1.c"],
deps = [":libevent"],
)
```
then build as usual:
```bash
$ devbazel build //:libevent_echosrv1
```

8
WORKSPACE Normal file
View File

@ -0,0 +1,8 @@
# These repositories are used in the BUILD files in examples/, which are also used in CI.
new_http_archive(
name = "libevent",
build_file_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])""",
strip_prefix = "libevent-2.1.8-stable",
urls = ["https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz"],
)

0
cc_configure_make/BUILD Normal file
View File

98
cc_configure_make/def.bzl Normal file
View File

@ -0,0 +1,98 @@
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def _cc_configure_make_impl(ctx):
out_includes = ctx.actions.declare_directory(ctx.attr.name + "-includes.h")
out_lib = ctx.actions.declare_file("{}.a".format(ctx.attr.name))
outputs = [out_includes, out_lib]
cpp_fragment = ctx.fragments.cpp
compiler_options = [] # cpp_fragment.compiler_options(ctx.features)
c_options = compiler_options + cpp_fragment.c_options
cxx_options = compiler_options + cpp_fragment.cxx_options(ctx.features)
CFLAGS = "\"{}\"".format(' '.join(c_options))
CXXFLAGS = "\"{}\"".format(' '.join(cxx_options))
# Run ./configure && make from a temporary directory, and install into another temporary directory.
# Finally, copy the results into the directory artifact declared in out_includes.
ctx.actions.run_shell(
mnemonic="ConfigureMake",
inputs = ctx.attr.src.files,
outputs = outputs,
command = '\n'.join([
"set -e",
"P=$(pwd)",
"tmpdir=$(mktemp -d)",
"tmpinstalldir=$(mktemp -d)",
"trap \"{ rm -rf $tmpdir $tmpinstalldir; }\" EXIT",
"pushd $tmpdir",
"CFLAGS={} CXXFLAGS={} $P/{}/configure --prefix=$tmpinstalldir {}".format(
CFLAGS, CXXFLAGS, ctx.attr.src.label.workspace_root, ' '.join(ctx.attr.configure_flags)),
"CFLAGS={} CXXFLAGS={} make install".format(CFLAGS, CXXFLAGS),
"popd",
"cp $tmpinstalldir/{} {}".format(ctx.attr.out_lib_path, out_lib.path),
"cp -R $tmpinstalldir/include/ {}".format(out_includes.path)]),
execution_requirements = {"block-network": ""}
)
return [DefaultInfo(files = depset(direct=outputs)),
OutputGroupInfo(headers = depset([out_includes]),
libfile = depset([out_lib]))]
_cc_configure_make_rule = rule(
attrs = {
"configure_flags": attr.string_list(),
"src": attr.label(mandatory = True),
"out_lib_path": attr.string(mandatory = True),
},
fragments = ["cpp"],
output_to_genfiles = True,
implementation = _cc_configure_make_impl,
)
def cc_configure_make(name, configure_flags, src, out_lib_path):
name_cmr = '_{}_cc_configure_make_rule'.format(name)
_cc_configure_make_rule(
name = name_cmr,
configure_flags = configure_flags,
src = src,
out_lib_path = out_lib_path
)
name_libfile_fg = '_{}_libfile_fg'.format(name)
native.filegroup(
name = name_libfile_fg,
srcs = [name_cmr],
output_group = "libfile",
)
name_libfile_import = '_{}_libfile_import'.format(name)
native.cc_import(
name = name_libfile_import,
static_library = name_libfile_fg,
)
name_headers_fg = '_{}_headers_fg'.format(name)
native.filegroup(
name = name_headers_fg,
srcs = [name_cmr],
output_group = "headers",
)
native.cc_library(
name = name,
hdrs = [name_headers_fg],
includes = [name_cmr + "-includes.h"],
deps = [name_libfile_import],
)

View File

@ -0,0 +1,20 @@
load("//cc_configure_make:def.bzl", "cc_configure_make")
cc_configure_make(
name = "libevent",
src = "@libevent//:all",
configure_flags = [
"--enable-shared=no",
"--disable-libevent-regress",
"--disable-openssl",
],
out_lib_path = "lib/libevent.a",
)
cc_binary(
name = "libevent_echosrv1",
srcs = ["libevent_echosrv1.c"],
deps = [
"libevent",
],
)

View File

@ -0,0 +1,213 @@
// Copied from
// https://github.com/jasonish/libevent-examples/blob/6d20f0d86c2cd263f5edff28862bc09ce4a3220f/echo-server/libevent_echosrv1.c
// for testing purposes only.
/*
* Copyright (c) 2011, Jason Ish
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* libevent echo server example.
*/
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
/* For inet_ntoa. */
#include <arpa/inet.h>
/* Required by event.h. */
#include <sys/time.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Libevent. */
#include <event.h>
/* Port to listen on. */
#define SERVER_PORT 5555
/**
* A struct for client specific data, in this simple case the only
* client specific data is the read event.
*/
struct client {
struct event ev_read;
};
/**
* Set a socket to non-blocking mode.
*/
int setnonblock(int fd) {
int flags;
flags = fcntl(fd, F_GETFL);
if (flags < 0)
return flags;
flags |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0)
return -1;
return 0;
}
/**
* This function will be called by libevent when the client socket is
* ready for reading.
*/
void on_read(int fd, short ev, void *arg) {
struct client *client = (struct client *)arg;
u_char buf[8196];
int len, wlen;
len = read(fd, buf, sizeof(buf));
if (len == 0) {
/* Client disconnected, remove the read event and the
* free the client structure. */
printf("Client disconnected.\n");
close(fd);
event_del(&client->ev_read);
free(client);
return;
} else if (len < 0) {
/* Some other error occurred, close the socket, remove
* the event and free the client structure. */
printf("Socket failure, disconnecting client: %s", strerror(errno));
close(fd);
event_del(&client->ev_read);
free(client);
return;
}
/* XXX For the sake of simplicity we'll echo the data write
* back to the client. Normally we shouldn't do this in a
* non-blocking app, we should queue the data and wait to be
* told that we can write.
*/
wlen = write(fd, buf, len);
if (wlen < len) {
/* We didn't write all our data. If we had proper
* queueing/buffering setup, we'd finish off the write
* when told we can write again. For this simple case
* we'll just lose the data that didn't make it in the
* write.
*/
printf("Short write, not all data echoed back to client.\n");
}
}
/**
* This function will be called by libevent when there is a connection
* ready to be accepted.
*/
void on_accept(int fd, short ev, void *arg) {
int client_fd;
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
struct client *client;
/* Accept the new connection. */
client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1) {
warn("accept failed");
return;
}
/* Set the client socket to non-blocking mode. */
if (setnonblock(client_fd) < 0)
warn("failed to set client socket non-blocking");
/* We've accepted a new client, allocate a client object to
* maintain the state of this client. */
client = calloc(1, sizeof(*client));
if (client == NULL)
err(1, "malloc failed");
/* Setup the read event, libevent will call on_read() whenever
* the clients socket becomes read ready. We also make the
* read event persistent so we don't have to re-add after each
* read. */
event_set(&client->ev_read, client_fd, EV_READ | EV_PERSIST, on_read, client);
/* Setting up the event does not activate, add the event so it
* becomes active. */
event_add(&client->ev_read, NULL);
printf("Accepted connection from %s\n", inet_ntoa(client_addr.sin_addr));
}
int main(int argc, char **argv) {
int listen_fd;
struct sockaddr_in listen_addr;
int reuseaddr_on = 1;
/* The socket accept event. */
struct event ev_accept;
/* Initialize libevent. */
event_init();
/* Create our listening socket. This is largely boiler plate
* code that I'll abstract away in the future. */
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0)
err(1, "listen failed");
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on,
sizeof(reuseaddr_on)) == -1)
err(1, "setsockopt failed");
memset(&listen_addr, 0, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = INADDR_ANY;
listen_addr.sin_port = htons(SERVER_PORT);
if (bind(listen_fd, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0)
err(1, "bind failed");
if (listen(listen_fd, 5) < 0)
err(1, "listen failed");
/* Set the socket to non-blocking, this is essential in event
* based programming with libevent. */
if (setnonblock(listen_fd) < 0)
err(1, "failed to set server socket to non-blocking");
/* We now have a listening socket, we create a read event to
* be notified when a client connects. */
event_set(&ev_accept, listen_fd, EV_READ | EV_PERSIST, on_accept, NULL);
event_add(&ev_accept, NULL);
/* Start the libevent event loop. */
event_dispatch();
return 0;
}